Open History to see the last commit
1import type {
2 EnvironmentId,
3 OrchestrationShellSnapshot,
4 OrchestrationShellStreamEvent,
5 ServerConfig,
6 ServerLifecycleWelcomePayload,
7 TerminalEvent,
8} from "@t3tools/contracts";
9import type { KnownEnvironment } from "@t3tools/client-runtime";
10
11import type { WsRpcClient } from "~/rpc/wsRpcClient";
12
13export interface EnvironmentConnection {
14 readonly kind: "primary" | "saved";
15 readonly environmentId: EnvironmentId;
16 readonly knownEnvironment: KnownEnvironment;
17 readonly client: WsRpcClient;
18 readonly ensureBootstrapped: () => Promise<void>;
19 readonly reconnect: () => Promise<void>;
20 readonly dispose: () => Promise<void>;
21}
22
23interface OrchestrationHandlers {
24 readonly applyShellEvent: (
25 event: OrchestrationShellStreamEvent,
26 environmentId: EnvironmentId,
27 ) => void;
28 readonly syncShellSnapshot: (
29 snapshot: OrchestrationShellSnapshot,
30 environmentId: EnvironmentId,
31 ) => void;
32 readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void;
33}
34
35interface EnvironmentConnectionInput extends OrchestrationHandlers {
36 readonly kind: "primary" | "saved";
37 readonly knownEnvironment: KnownEnvironment;
38 readonly client: WsRpcClient;
39 readonly refreshMetadata?: () => Promise<void>;
40 readonly onConfigSnapshot?: (config: ServerConfig) => void;
41 readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
42}
43
44function createBootstrapGate() {
45 let resolve: (() => void) | null = null;
46 let reject: ((error: unknown) => void) | null = null;
47 let promise = new Promise<void>((nextResolve, nextReject) => {
48 resolve = nextResolve;
49 reject = nextReject;
50 });
51
52 return {
53 wait: () => promise,
54 resolve: () => {
55 resolve?.();
56 resolve = null;
57 reject = null;
58 },
59 reject: (error: unknown) => {
60 reject?.(error);
61 resolve = null;
62 reject = null;
63 },
64 reset: () => {
65 promise = new Promise<void>((nextResolve, nextReject) => {
66 resolve = nextResolve;
67 reject = nextReject;
68 });
69 },
70 };
71}
72
73export function createEnvironmentConnection(
74 input: EnvironmentConnectionInput,
75): EnvironmentConnection {
76 const environmentId = input.knownEnvironment.environmentId;
77
78 if (!environmentId) {
79 throw new Error(
80 `Known environment ${input.knownEnvironment.label} is missing its environmentId.`,
81 );
82 }
83
84 let disposed = false;
85 const bootstrapGate = createBootstrapGate();
86 const shouldObserveLifecycle = input.kind === "saved" || input.onWelcome !== undefined;
87 const shouldObserveConfig = input.kind === "saved" || input.onConfigSnapshot !== undefined;
88
89 const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
90 if (environmentId !== nextEnvironmentId) {
91 throw new Error(
92 `Environment connection ${environmentId} changed identity to ${nextEnvironmentId} via ${source}.`,
93 );
94 }
95 };
96
97 const unsubLifecycle = shouldObserveLifecycle
98 ? input.client.server.subscribeLifecycle(
99 (event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
100 if (event.type !== "welcome") {
101 return;
102 }
103 observeEnvironmentIdentity(
104 event.payload.environment.environmentId,
105 "server lifecycle welcome",
106 );
107 input.onWelcome?.(event.payload);
108 },
109 )
110 : () => undefined;
111
112 const unsubConfig = shouldObserveConfig
113 ? input.client.server.subscribeConfig(
114 (event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
115 if (event.type !== "snapshot") {
116 return;
117 }
118 observeEnvironmentIdentity(
119 event.config.environment.environmentId,
120 "server config snapshot",
121 );
122 input.onConfigSnapshot?.(event.config);
123 },
124 )
125 : () => undefined;
126
127 const unsubShell = input.client.orchestration.subscribeShell(
128 (item: Parameters<Parameters<WsRpcClient["orchestration"]["subscribeShell"]>[0]>[0]) => {
129 if (item.kind === "snapshot") {
130 input.syncShellSnapshot(item.snapshot, environmentId);
131 bootstrapGate.resolve();
132 return;
133 }
134 input.applyShellEvent(item, environmentId);
135 },
136 {
137 onResubscribe: () => {
138 if (disposed) {
139 return;
140 }
141 bootstrapGate.reset();
142 },
143 },
144 );
145
146 const unsubTerminalEvent = input.client.terminal.onEvent(
147 (event: Parameters<Parameters<WsRpcClient["terminal"]["onEvent"]>[0]>[0]) => {
148 input.applyTerminalEvent(event, environmentId);
149 },
150 );
151
152 const cleanup = () => {
153 disposed = true;
154 unsubShell();
155 unsubTerminalEvent();
156 unsubLifecycle();
157 unsubConfig();
158 };
159
160 return {
161 kind: input.kind,
162 environmentId,
163 knownEnvironment: input.knownEnvironment,
164 client: input.client,
165 ensureBootstrapped: () => bootstrapGate.wait(),
166 reconnect: async () => {
167 bootstrapGate.reset();
168 try {
169 await input.client.reconnect();
170 await input.refreshMetadata?.();
171 await bootstrapGate.wait();
172 } catch (error) {
173 bootstrapGate.reject(error);
174 throw error;
175 }
176 },
177 dispose: async () => {
178 cleanup();
179 await input.client.dispose();
180 },
181 };
182}