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
This commit is contained in:
Julius Marminge committed 2026-05-05 21:00:42 -07:00
1 parent 8c48db4409
commit fd4c354212
5 files changed
+148 -26

No files matched your search

+47 -18
View File
@@ -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<T = UnifiedSettings>(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<UnifiedSettings>(
() => ({
@@ -193,25 +203,44 @@ export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings)
* persisted via RPC. Client keys go through client persistence.
*/
export function useUpdateSettings() {
const updateSettings = useCallback((patch: Partial<UnifiedSettings>) => {
const { serverPatch, clientPatch } = splitPatch(patch);
const updatePrimaryServerSettingsRpc = useUpdatePrimaryServerSettingsRpc();
const updateSettings = useCallback(
(patch: Partial<UnifiedSettings>) => {
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);
+4
View File
@@ -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 <RegistryContext.Provider value={appAtomRegistry}>{children}</RegistryContext.Provider>;
}
+2
View File
@@ -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}`,
});
@@ -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<ServerSettings, ServerSettingsRpcAtomError>;
const missingServerSettingsAtom = Atom.make(
AsyncResult.initial<ServerSettings, ServerSettingsRpcAtomError>(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<ServerSettings, ServerSettingsRpcAtomError>
>,
[runtime],
);
return useAtomValue(atom);
}
export function useUpdatePrimaryServerSettingsRpc(): UpdatePrimaryServerSettingsRpc {
const runtime = usePrimaryEnvironmentRpcAtomRuntime();
const mutation = useMemo(
() => (runtime ? updateServerSettingsMutation(runtime) : null),
[runtime],
);
return useCallback<UpdatePrimaryServerSettingsRpc>(
(patch: ServerSettingsPatch) => {
if (!runtime || !mutation) {
return Effect.fail(
new RpcAtomRuntimeUnavailableError({
environmentId: getPrimaryKnownEnvironment()?.environmentId ?? null,
}),
);
}
return runtime.runMutation(mutation, updateServerSettingsArg(patch), {
suspendOnWaiting: true,
});
},
[mutation, runtime],
);
}
@@ -18,7 +18,6 @@ export type T3RpcAtomProtocol = Layer.Layer<RpcClient.Protocol, never, never>;
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<T3RpcAtomService>()(
`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.
},
};
}