Wire environment runtime through atom RPC

- Add environment and server atom RPC clients
- Split websocket lifecycle handlers for primary and saved environments
- Reset and dispose atom registries alongside websocket reconnects
This commit is contained in:
Julius Marminge committed 2026-05-05 20:40:10 -07:00
1 parent 0e38870647
commit 6f585399bd
5 files changed
+309 -65

No files matched your search

@@ -9,12 +9,14 @@ import type {
import type { KnownEnvironment } from "@t3tools/client-runtime";
import type { WsRpcClient } from "~/rpc/wsRpcClient";
import type { EnvironmentAtomRpcClient } from "~/rpc/environmentAtomRpc";
export interface EnvironmentConnection {
readonly kind: "primary" | "saved";
readonly environmentId: EnvironmentId;
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly atomRpc?: EnvironmentAtomRpcClient;
readonly ensureBootstrapped: () => Promise<void>;
readonly reconnect: () => Promise<void>;
readonly dispose: () => Promise<void>;
@@ -36,6 +38,7 @@ interface EnvironmentConnectionInput extends OrchestrationHandlers {
readonly kind: "primary" | "saved";
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly atomRpc?: EnvironmentAtomRpcClient;
readonly refreshMetadata?: () => Promise<void>;
readonly onConfigSnapshot?: (config: ServerConfig) => void;
readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
@@ -162,9 +165,11 @@ export function createEnvironmentConnection(
environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
...(input.atomRpc ? { atomRpc: input.atomRpc } : {}),
ensureBootstrapped: () => bootstrapGate.wait(),
reconnect: async () => {
bootstrapGate.reset();
input.atomRpc?.reset();
try {
await input.client.reconnect();
await input.refreshMetadata?.();
@@ -176,7 +181,11 @@ export function createEnvironmentConnection(
},
dispose: async () => {
cleanup();
await input.client.dispose();
try {
await input.client.dispose();
} finally {
input.atomRpc?.dispose();
}
},
};
}
@@ -28,3 +28,4 @@ export {
startEnvironmentConnectionService,
subscribeEnvironmentConnections,
} from "./service";
export type { EnvironmentConnection } from "./connection";
+121 -64
View File
@@ -63,10 +63,15 @@ import {
} from "~/store";
import { useTerminalStateStore } from "~/terminalStateStore";
import { useUiStateStore } from "~/uiStateStore";
import type { WsProtocolCloseContext } from "../../rpc/protocol";
import type {
WsProtocolCloseContext,
WsProtocolLifecycleHandlers,
WsRpcProtocolSocketUrlProvider,
} from "../../rpc/protocol";
import { getServerConfig } from "../../rpc/serverState";
import { WsTransport } from "../../rpc/wsTransport";
import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
import { createEnvironmentAtomRpcClient } from "../../rpc/environmentAtomRpc";
import { appendVersionMismatchHint, resolveServerConfigVersionMismatch } from "../../versionSkew";
import {
deriveLogicalProjectKeyFromSettings,
@@ -1130,17 +1135,40 @@ function createPrimaryEnvironmentClient(
`Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
);
}
const connectionLabel = knownEnvironment?.label ?? null;
return createWsRpcClient(
new WsTransport(wsBaseUrl, {
getConnectionLabel: () => connectionLabel,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(getServerConfig())?.hint ?? null,
}),
new WsTransport(wsBaseUrl, createPrimaryEnvironmentLifecycleHandlers(knownEnvironment)),
);
}
function createPrimaryEnvironmentAtomRpcClient(
knownEnvironment: ReturnType<typeof getPrimaryKnownEnvironment>,
) {
const wsBaseUrl = getKnownEnvironmentWsBaseUrl(knownEnvironment);
if (!wsBaseUrl || !knownEnvironment?.environmentId) {
throw new Error(
`Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
);
}
return createEnvironmentAtomRpcClient({
environmentId: knownEnvironment.environmentId,
url: wsBaseUrl,
lifecycleHandlers: createPrimaryEnvironmentLifecycleHandlers(knownEnvironment),
});
}
function createPrimaryEnvironmentLifecycleHandlers(
knownEnvironment: ReturnType<typeof getPrimaryKnownEnvironment>,
): WsProtocolLifecycleHandlers {
const connectionLabel = knownEnvironment?.label ?? null;
return {
getConnectionLabel: () => connectionLabel,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(getServerConfig())?.hint ?? null,
};
}
function createSavedEnvironmentClient(
environmentId: EnvironmentId,
bearerToken: string,
@@ -1149,67 +1177,90 @@ function createSavedEnvironmentClient(
return createWsRpcClient(
new WsTransport(
async () => {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
return record.desktopSsh
? await resolveDesktopSshWebSocketConnectionUrl(
record.wsBaseUrl,
record.httpBaseUrl,
bearerToken,
)
: await resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
});
},
{
getConnectionLabel: () => getSavedEnvironmentRecord(environmentId)?.label ?? null,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
)?.hint ?? null,
onAttempt: () => {
setRuntimeConnecting(environmentId);
},
onOpen: () => {
setRuntimeConnected(environmentId);
},
onError: (message: string) => {
const mismatch = resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
);
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "error",
lastError: appendVersionMismatchHint(message, mismatch),
lastErrorAt: isoNow(),
});
},
onClose: (
details: { readonly code: number; readonly reason: string },
context: WsProtocolCloseContext,
) => {
if (context.intentional) {
return;
}
setRuntimeDisconnected(
environmentId,
appendVersionMismatchHint(
details.reason,
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
),
),
);
},
},
createSavedEnvironmentSocketUrlProvider(environmentId, bearerToken),
createSavedEnvironmentLifecycleHandlers(environmentId),
),
);
}
function createSavedEnvironmentAtomRpcClient(environmentId: EnvironmentId, bearerToken: string) {
useSavedEnvironmentRuntimeStore.getState().ensure(environmentId);
return createEnvironmentAtomRpcClient({
environmentId,
url: createSavedEnvironmentSocketUrlProvider(environmentId, bearerToken),
lifecycleHandlers: createSavedEnvironmentLifecycleHandlers(environmentId),
});
}
function createSavedEnvironmentSocketUrlProvider(
environmentId: EnvironmentId,
bearerToken: string,
): WsRpcProtocolSocketUrlProvider {
return async () => {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
return record.desktopSsh
? await resolveDesktopSshWebSocketConnectionUrl(
record.wsBaseUrl,
record.httpBaseUrl,
bearerToken,
)
: await resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
});
};
}
function createSavedEnvironmentLifecycleHandlers(
environmentId: EnvironmentId,
): WsProtocolLifecycleHandlers {
return {
getConnectionLabel: () => getSavedEnvironmentRecord(environmentId)?.label ?? null,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
)?.hint ?? null,
onAttempt: () => {
setRuntimeConnecting(environmentId);
},
onOpen: () => {
setRuntimeConnected(environmentId);
},
onError: (message: string) => {
const mismatch = resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
);
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "error",
lastError: appendVersionMismatchHint(message, mismatch),
lastErrorAt: isoNow(),
});
},
onClose: (
details: { readonly code: number; readonly reason: string },
context: WsProtocolCloseContext,
) => {
if (context.intentional) {
return;
}
setRuntimeDisconnected(
environmentId,
appendVersionMismatchHint(
details.reason,
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
),
),
);
},
};
}
async function refreshSavedEnvironmentMetadata(
environmentId: EnvironmentId,
bearerToken: string,
@@ -1284,6 +1335,7 @@ function createPrimaryEnvironmentConnection(): EnvironmentConnection {
kind: "primary",
knownEnvironment,
client: createPrimaryEnvironmentClient(knownEnvironment),
atomRpc: createPrimaryEnvironmentAtomRpcClient(knownEnvironment),
...createEnvironmentConnectionHandlers(),
}),
);
@@ -1344,6 +1396,10 @@ async function ensureSavedEnvironmentConnection(
const client =
options?.client ??
createSavedEnvironmentClient(activeRecord.environmentId, activeBearerToken);
const atomRpc =
options?.client === undefined
? createSavedEnvironmentAtomRpcClient(activeRecord.environmentId, activeBearerToken)
: undefined;
const initialConfigSnapshot = createDeferredPromise<ServerConfig>();
const knownEnvironment = createKnownEnvironment({
id: activeRecord.environmentId,
@@ -1361,6 +1417,7 @@ async function ensureSavedEnvironmentConnection(
environmentId: activeRecord.environmentId,
},
client,
...(atomRpc ? { atomRpc } : {}),
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(
activeRecord.environmentId,
+65
View File
@@ -0,0 +1,65 @@
import { WsRpcGroup, type EnvironmentId } from "@t3tools/contracts";
import { Layer } from "effect";
import { Atom, AtomRegistry, AtomRpc } from "effect/unstable/reactivity";
import type * as Rpc from "effect/unstable/rpc/Rpc";
import type * as RpcGroup from "effect/unstable/rpc/RpcGroup";
import {
createWsRpcProtocolLayer,
type WsProtocolLifecycleHandlers,
type WsRpcProtocolSocketUrlProvider,
} from "./protocol";
import { createServerAtomRpc, type ServerAtomRpc } from "./serverAtomRpc";
type WsRpcGroupRpcs =
typeof WsRpcGroup extends RpcGroup.RpcGroup<infer Rpcs extends Rpc.Any> ? Rpcs : never;
export interface WsAtomRpcService extends AtomRpc.AtomRpcClient<
WsAtomRpcService,
string,
WsRpcGroupRpcs
> {}
export interface EnvironmentAtomRpcClient {
readonly environmentId: EnvironmentId;
readonly registry: AtomRegistry.AtomRegistry;
readonly service: WsAtomRpcService;
readonly server: ServerAtomRpc;
readonly reset: () => void;
readonly dispose: () => void;
}
export interface EnvironmentAtomRpcClientInput {
readonly environmentId: EnvironmentId;
readonly url: WsRpcProtocolSocketUrlProvider;
readonly lifecycleHandlers?: WsProtocolLifecycleHandlers;
}
export function createEnvironmentAtomRpcClient(
input: EnvironmentAtomRpcClientInput,
): EnvironmentAtomRpcClient {
const registry = AtomRegistry.make();
const runtime = Atom.context({ memoMap: Layer.makeMemoMapUnsafe() });
const service = AtomRpc.Service<WsAtomRpcService>()(
`t3tools/web/environment-rpc/${input.environmentId}`,
{
group: WsRpcGroup,
protocol: createWsRpcProtocolLayer(input.url, input.lifecycleHandlers),
runtime,
spanPrefix: `EnvironmentRpc:${input.environmentId}`,
},
);
return {
environmentId: input.environmentId,
registry,
service,
server: createServerAtomRpc({ registry, service }),
reset: () => {
registry.reset();
},
dispose: () => {
registry.dispose();
},
};
}
+112
View File
@@ -0,0 +1,112 @@
import {
WS_METHODS,
type ServerConfig,
type ServerSettings,
type ServerSettingsPatch,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { AtomRegistry } from "effect/unstable/reactivity";
import type { WsAtomRpcService } from "./environmentAtomRpc";
const SERVER_CONFIG_REACTIVITY_KEY = ["server", "config"] as const;
const SERVER_SETTINGS_REACTIVITY_KEY = ["server", "settings"] as const;
export interface ServerAtomRpcInput {
readonly registry: AtomRegistry.AtomRegistry;
readonly service: WsAtomRpcService;
}
export interface ServerAtomRpc {
readonly atoms: {
readonly config: ReturnType<WsAtomRpcService["query"]>;
readonly settings: ReturnType<WsAtomRpcService["query"]>;
};
readonly mutations: {
readonly updateSettings: ReturnType<WsAtomRpcService["mutation"]>;
};
readonly getConfig: Effect.Effect<ServerConfig, ServerAtomRpcError>;
readonly getSettings: Effect.Effect<ServerSettings, ServerAtomRpcError>;
readonly updateSettings: (
patch: ServerSettingsPatch,
) => Effect.Effect<ServerSettings, ServerAtomRpcError>;
}
export type ServerAtomRpcError =
| AtomFailure<typeof WS_METHODS.serverGetConfig>
| AtomFailure<typeof WS_METHODS.serverGetSettings>
| MutationFailure<typeof WS_METHODS.serverUpdateSettings>;
type QueryAtom<_Tag extends Parameters<WsAtomRpcService["query"]>[0]> = ReturnType<
WsAtomRpcService["query"]
>;
type MutationAtom<_Tag extends Parameters<WsAtomRpcService["mutation"]>[0]> = ReturnType<
WsAtomRpcService["mutation"]
>;
type AtomFailure<Tag extends Parameters<WsAtomRpcService["query"]>[0]> =
QueryAtom<Tag> extends import("effect/unstable/reactivity").Atom.Atom<
import("effect/unstable/reactivity").AsyncResult.AsyncResult<unknown, infer E>
>
? E
: never;
type MutationFailure<Tag extends Parameters<WsAtomRpcService["mutation"]>[0]> =
MutationAtom<Tag> extends import("effect/unstable/reactivity").Atom.AtomResultFn<
unknown,
unknown,
infer E
>
? E
: never;
export function createServerAtomRpc(input: ServerAtomRpcInput): ServerAtomRpc {
const config = input.service.query(
WS_METHODS.serverGetConfig,
{},
{
reactivityKeys: SERVER_CONFIG_REACTIVITY_KEY,
serializationKey: "server.getConfig",
timeToLive: Infinity,
},
);
const settings = input.service.query(
WS_METHODS.serverGetSettings,
{},
{
reactivityKeys: SERVER_SETTINGS_REACTIVITY_KEY,
serializationKey: "server.getSettings",
timeToLive: Infinity,
},
);
const updateSettings = input.service.mutation(WS_METHODS.serverUpdateSettings);
return {
atoms: {
config,
settings,
},
mutations: {
updateSettings,
},
getConfig: AtomRegistry.getResult(input.registry, config, { suspendOnWaiting: true }),
getSettings: AtomRegistry.getResult(input.registry, settings, { suspendOnWaiting: true }),
updateSettings: (patch) =>
Effect.gen(function* () {
yield* Effect.sync(() => {
input.registry.set(updateSettings, {
payload: { patch },
reactivityKeys: {
config: SERVER_CONFIG_REACTIVITY_KEY,
settings: SERVER_SETTINGS_REACTIVITY_KEY,
},
});
});
return yield* AtomRegistry.getResult(input.registry, updateSettings, {
suspendOnWaiting: true,
});
}),
};
}