diff --git a/apps/web/src/environments/runtime/connection.ts b/apps/web/src/environments/runtime/connection.ts index beacf6144d..1ce4e5d0ad 100644 --- a/apps/web/src/environments/runtime/connection.ts +++ b/apps/web/src/environments/runtime/connection.ts @@ -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; readonly reconnect: () => Promise; readonly dispose: () => Promise; @@ -36,6 +38,7 @@ interface EnvironmentConnectionInput extends OrchestrationHandlers { readonly kind: "primary" | "saved"; readonly knownEnvironment: KnownEnvironment; readonly client: WsRpcClient; + readonly atomRpc?: EnvironmentAtomRpcClient; readonly refreshMetadata?: () => Promise; 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(); + } }, }; } diff --git a/apps/web/src/environments/runtime/index.ts b/apps/web/src/environments/runtime/index.ts index 0192fb6026..d5a49b94c0 100644 --- a/apps/web/src/environments/runtime/index.ts +++ b/apps/web/src/environments/runtime/index.ts @@ -28,3 +28,4 @@ export { startEnvironmentConnectionService, subscribeEnvironmentConnections, } from "./service"; +export type { EnvironmentConnection } from "./connection"; diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 60c05fc217..ebe32f5147 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -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, +) { + 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, +): 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(); 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, diff --git a/apps/web/src/rpc/environmentAtomRpc.ts b/apps/web/src/rpc/environmentAtomRpc.ts new file mode 100644 index 0000000000..97b2f87e4d --- /dev/null +++ b/apps/web/src/rpc/environmentAtomRpc.ts @@ -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 ? 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()( + `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(); + }, + }; +} diff --git a/apps/web/src/rpc/serverAtomRpc.ts b/apps/web/src/rpc/serverAtomRpc.ts new file mode 100644 index 0000000000..39da0b9cf5 --- /dev/null +++ b/apps/web/src/rpc/serverAtomRpc.ts @@ -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; + readonly settings: ReturnType; + }; + readonly mutations: { + readonly updateSettings: ReturnType; + }; + readonly getConfig: Effect.Effect; + readonly getSettings: Effect.Effect; + readonly updateSettings: ( + patch: ServerSettingsPatch, + ) => Effect.Effect; +} + +export type ServerAtomRpcError = + | AtomFailure + | AtomFailure + | MutationFailure; + +type QueryAtom<_Tag extends Parameters[0]> = ReturnType< + WsAtomRpcService["query"] +>; + +type MutationAtom<_Tag extends Parameters[0]> = ReturnType< + WsAtomRpcService["mutation"] +>; + +type AtomFailure[0]> = + QueryAtom extends import("effect/unstable/reactivity").Atom.Atom< + import("effect/unstable/reactivity").AsyncResult.AsyncResult + > + ? E + : never; + +type MutationFailure[0]> = + MutationAtom 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, + }); + }), + }; +}