From fd4c3542121233dc3d6172a0d37bbfb4d9d55a82 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 5 May 2026 21:00:42 -0700 Subject: [PATCH] Route environment RPC through shared atom registry - Reuse the app atom registry for environment RPC atoms - Add a fallback path for server settings updates when the runtime is unavailable - Remove per-runtime registry ownership from the client runtime --- apps/web/src/hooks/useSettings.ts | 65 ++++++++++---- apps/web/src/rpc/atomRegistry.tsx | 4 + apps/web/src/rpc/environmentAtomRpc.ts | 2 + apps/web/src/rpc/useEnvironmentRpcAtoms.ts | 88 +++++++++++++++++++ packages/client-runtime/src/rpcAtomRuntime.ts | 15 ++-- 5 files changed, 148 insertions(+), 26 deletions(-) create mode 100644 apps/web/src/rpc/useEnvironmentRpcAtoms.ts diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 6541bb7a82..6fffa62570 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -19,9 +19,14 @@ import { UnifiedSettings, } from "@t3tools/contracts/settings"; import { ensureLocalApi } from "~/localApi"; -import { Struct } from "effect"; +import { Cause, Effect, Exit, Option, Struct } from "effect"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState"; +import { + RpcAtomRuntimeUnavailableError, + usePrimaryServerSettingsRpcResult, + useUpdatePrimaryServerSettingsRpc, +} from "~/rpc/useEnvironmentRpcAtoms"; const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]"; @@ -168,12 +173,17 @@ export function useClientSettingsHydrated(): boolean { } export function useSettings(selector?: (s: UnifiedSettings) => T): T { - const serverSettings = useServerSettings(); + const legacyServerSettings = useServerSettings(); + const serverSettingsRpcResult = usePrimaryServerSettingsRpcResult(); const clientSettings = useSyncExternalStore( subscribeClientSettings, getClientSettingsSnapshot, () => DEFAULT_CLIENT_SETTINGS, ); + const serverSettings = + serverSettingsRpcResult._tag === "Success" + ? serverSettingsRpcResult.value + : legacyServerSettings; const merged = useMemo( () => ({ @@ -193,25 +203,44 @@ export function useSettings(selector?: (s: UnifiedSettings) * persisted via RPC. Client keys go through client persistence. */ export function useUpdateSettings() { - const updateSettings = useCallback((patch: Partial) => { - const { serverPatch, clientPatch } = splitPatch(patch); + const updatePrimaryServerSettingsRpc = useUpdatePrimaryServerSettingsRpc(); + const updateSettings = useCallback( + (patch: Partial) => { + const { serverPatch, clientPatch } = splitPatch(patch); - if (Object.keys(serverPatch).length > 0) { - const currentServerConfig = getServerConfig(); - if (currentServerConfig) { - applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch)); + if (Object.keys(serverPatch).length > 0) { + const currentServerConfig = getServerConfig(); + if (currentServerConfig) { + applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch)); + } + void Effect.runPromiseExit(updatePrimaryServerSettingsRpc(serverPatch)).then((exit) => { + if (Exit.isSuccess(exit)) { + applySettingsUpdated(exit.value); + return; + } + + const typedError = Cause.findErrorOption(exit.cause); + if ( + Option.isSome(typedError) && + typedError.value instanceof RpcAtomRuntimeUnavailableError + ) { + void ensureLocalApi().server.updateSettings(serverPatch); + return; + } + + console.error("[SERVER_SETTINGS] AtomRpc update failed", Cause.pretty(exit.cause)); + }); } - // Fire-and-forget RPC — push will reconcile on success - void ensureLocalApi().server.updateSettings(serverPatch); - } - if (Object.keys(clientPatch).length > 0) { - persistClientSettings({ - ...getClientSettingsSnapshot(), - ...clientPatch, - }); - } - }, []); + if (Object.keys(clientPatch).length > 0) { + persistClientSettings({ + ...getClientSettingsSnapshot(), + ...clientPatch, + }); + } + }, + [updatePrimaryServerSettingsRpc], + ); const resetSettings = useCallback(() => { updateSettings(DEFAULT_UNIFIED_SETTINGS); diff --git a/apps/web/src/rpc/atomRegistry.tsx b/apps/web/src/rpc/atomRegistry.tsx index 89385c9a75..da44872f7c 100644 --- a/apps/web/src/rpc/atomRegistry.tsx +++ b/apps/web/src/rpc/atomRegistry.tsx @@ -4,6 +4,10 @@ import type { ReactNode } from "react"; export let appAtomRegistry = AtomRegistry.make(); +export function getAppAtomRegistry(): AtomRegistry.AtomRegistry { + return appAtomRegistry; +} + export function AppAtomRegistryProvider({ children }: { readonly children: ReactNode }) { return {children}; } diff --git a/apps/web/src/rpc/environmentAtomRpc.ts b/apps/web/src/rpc/environmentAtomRpc.ts index 53507c363d..40ce814622 100644 --- a/apps/web/src/rpc/environmentAtomRpc.ts +++ b/apps/web/src/rpc/environmentAtomRpc.ts @@ -6,6 +6,7 @@ import { type WsProtocolLifecycleHandlers, type WsRpcProtocolSocketUrlProvider, } from "./protocol"; +import { getAppAtomRegistry } from "./atomRegistry"; export type EnvironmentAtomRpcClient = T3RpcAtomRuntime; @@ -20,6 +21,7 @@ export function createEnvironmentAtomRpcClient( ): EnvironmentAtomRpcClient { return createT3RpcAtomRuntime({ environmentId: input.environmentId, + getRegistry: getAppAtomRegistry, protocol: createWsRpcProtocolLayer(input.url, input.lifecycleHandlers), spanPrefix: `EnvironmentRpc:${input.environmentId}`, }); diff --git a/apps/web/src/rpc/useEnvironmentRpcAtoms.ts b/apps/web/src/rpc/useEnvironmentRpcAtoms.ts new file mode 100644 index 0000000000..0e8546de36 --- /dev/null +++ b/apps/web/src/rpc/useEnvironmentRpcAtoms.ts @@ -0,0 +1,88 @@ +import { + serverSettingsAtom, + updateServerSettingsArg, + updateServerSettingsMutation, + type T3RpcAtomRuntime, +} from "@t3tools/client-runtime"; +import { + ServerSettingsError, + type ServerSettings, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { Data, Effect } from "effect"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; +import type { RpcClientError } from "effect/unstable/rpc/RpcClientError"; +import { useCallback, useEffect, useMemo, useState } from "react"; + +import { getPrimaryKnownEnvironment } from "../environments/primary"; +import { + readEnvironmentConnection, + subscribeEnvironmentConnections, +} from "../environments/runtime"; + +export class RpcAtomRuntimeUnavailableError extends Data.TaggedError( + "RpcAtomRuntimeUnavailableError", +)<{ + readonly environmentId: string | null; +}> {} + +export type ServerSettingsRpcAtomError = + | ServerSettingsError + | RpcClientError + | RpcAtomRuntimeUnavailableError; + +export type UpdatePrimaryServerSettingsRpc = ( + patch: ServerSettingsPatch, +) => Effect.Effect; + +const missingServerSettingsAtom = Atom.make( + AsyncResult.initial(true), +).pipe(Atom.keepAlive, Atom.withLabel("rpc:server-settings:missing-runtime")); + +export function usePrimaryEnvironmentRpcAtomRuntime(): T3RpcAtomRuntime | null { + const [, forceSync] = useState(0); + + useEffect(() => subscribeEnvironmentConnections(() => forceSync((version) => version + 1)), []); + + const environmentId = getPrimaryKnownEnvironment()?.environmentId ?? null; + return environmentId ? (readEnvironmentConnection(environmentId)?.atomRpc ?? null) : null; +} + +export function usePrimaryServerSettingsRpcResult() { + const runtime = usePrimaryEnvironmentRpcAtomRuntime(); + const atom = useMemo( + () => + (runtime ? serverSettingsAtom(runtime) : missingServerSettingsAtom) as Atom.Atom< + AsyncResult.AsyncResult + >, + [runtime], + ); + + return useAtomValue(atom); +} + +export function useUpdatePrimaryServerSettingsRpc(): UpdatePrimaryServerSettingsRpc { + const runtime = usePrimaryEnvironmentRpcAtomRuntime(); + const mutation = useMemo( + () => (runtime ? updateServerSettingsMutation(runtime) : null), + [runtime], + ); + + return useCallback( + (patch: ServerSettingsPatch) => { + if (!runtime || !mutation) { + return Effect.fail( + new RpcAtomRuntimeUnavailableError({ + environmentId: getPrimaryKnownEnvironment()?.environmentId ?? null, + }), + ); + } + + return runtime.runMutation(mutation, updateServerSettingsArg(patch), { + suspendOnWaiting: true, + }); + }, + [mutation, runtime], + ); +} diff --git a/packages/client-runtime/src/rpcAtomRuntime.ts b/packages/client-runtime/src/rpcAtomRuntime.ts index 1417cad30e..dc7c7cf2a5 100644 --- a/packages/client-runtime/src/rpcAtomRuntime.ts +++ b/packages/client-runtime/src/rpcAtomRuntime.ts @@ -18,7 +18,6 @@ export type T3RpcAtomProtocol = Layer.Layer; export interface T3RpcAtomRuntime { readonly environmentId: EnvironmentId; - readonly registry: AtomRegistry.AtomRegistry; readonly rpc: T3RpcAtomService; readonly query: T3RpcAtomService["query"]; readonly mutation: T3RpcAtomService["mutation"]; @@ -42,11 +41,11 @@ export interface T3RpcAtomRuntime { export interface T3RpcAtomRuntimeInput { readonly environmentId: EnvironmentId; readonly protocol: T3RpcAtomProtocol; + readonly getRegistry: () => AtomRegistry.AtomRegistry; readonly spanPrefix?: string; } export function createT3RpcAtomRuntime(input: T3RpcAtomRuntimeInput): T3RpcAtomRuntime { - const registry = AtomRegistry.make(); const runtime = Atom.context({ memoMap: Layer.makeMemoMapUnsafe() }); const rpc = AtomRpc.Service()( `t3tools/runtime/environment-rpc/${input.environmentId}`, @@ -60,24 +59,24 @@ export function createT3RpcAtomRuntime(input: T3RpcAtomRuntimeInput): T3RpcAtomR return { environmentId: input.environmentId, - registry, rpc, query: rpc.query, mutation: rpc.mutation, - getResult: (atom, options) => AtomRegistry.getResult(registry, atom, options), + getResult: (atom, options) => AtomRegistry.getResult(input.getRegistry(), atom, options), runMutation: (atom, arg, options) => Effect.gen(function* () { yield* Effect.sync(() => { - registry.set(atom, arg); + input.getRegistry().set(atom, arg); }); - return yield* AtomRegistry.getResult(registry, atom, options); + return yield* AtomRegistry.getResult(input.getRegistry(), atom, options); }), reset: () => { - registry.reset(); + // Registry ownership stays with the host app. Environment teardown can + // invalidate specific atoms, but it must not reset the app registry. }, dispose: () => { - registry.dispose(); + // Registry ownership stays with the host app. }, }; }