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";
9
10import type { KnownEnvironment } from "./knownEnvironment.ts";
11import type { WsRpcClient } from "./wsRpcClient.ts";
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
35export interface 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 readonly onShellResubscribe?: (environmentId: EnvironmentId) => void;
43}
44
45export interface EnvironmentConnectionAttempt {
46 readonly environmentId: EnvironmentId;
47 readonly isCurrent: () => boolean;
48}
49
50export class EnvironmentConnectionAttemptCancelledError extends Error {
51 constructor(environmentId: EnvironmentId) {
52 super(`Environment connection attempt ${environmentId} was cancelled.`);
53 this.name = "EnvironmentConnectionAttemptCancelledError";
54 }
55}
56
57export function createEnvironmentConnectionAttemptRegistry() {
58 const attempts = new Map<EnvironmentId, symbol>();
59
60 return {
61 begin: (environmentId: EnvironmentId): EnvironmentConnectionAttempt => {
62 const id = Symbol(environmentId);
63 attempts.set(environmentId, id);
64 return {
65 environmentId,
66 isCurrent: () => attempts.get(environmentId) === id,
67 };
68 },
69 cancel: (environmentId: EnvironmentId): void => {
70 attempts.delete(environmentId);
71 },
72 clear: (): void => {
73 attempts.clear();
74 },
75 };
76}
77
78export class EnvironmentConnectionDisposedError extends Error {
79 constructor(environmentId: EnvironmentId) {
80 super(`Environment connection ${environmentId} was disposed before it finished bootstrapping.`);
81 this.name = "EnvironmentConnectionDisposedError";
82 }
83}
84
85function createBootstrapGate() {
86 let resolve: (() => void) | null = null;
87 let reject: ((error: unknown) => void) | null = null;
88 const makePromise = () => {
89 const nextPromise = new Promise<void>((nextResolve, nextReject) => {
90 resolve = nextResolve;
91 reject = nextReject;
92 });
93 void nextPromise.catch(() => undefined);
94 return nextPromise;
95 };
96 let promise = makePromise();
97
98 return {
99 wait: () => promise,
100 resolve: () => {
101 resolve?.();
102 resolve = null;
103 reject = null;
104 },
105 reject: (error: unknown) => {
106 reject?.(error);
107 resolve = null;
108 reject = null;
109 },
110 reset: () => {
111 promise = makePromise();
112 },
113 };
114}
115
116export function createEnvironmentConnection(
117 input: EnvironmentConnectionInput,
118): EnvironmentConnection {
119 const environmentId = input.knownEnvironment.environmentId;
120
121 if (!environmentId) {
122 throw new Error(
123 `Known environment ${input.knownEnvironment.label} is missing its environmentId.`,
124 );
125 }
126
127 let disposed = false;
128 const bootstrapGate = createBootstrapGate();
129 const shouldObserveLifecycle = input.kind === "saved" || input.onWelcome !== undefined;
130 const shouldObserveConfig = input.kind === "saved" || input.onConfigSnapshot !== undefined;
131
132 const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
133 if (environmentId !== nextEnvironmentId) {
134 throw new Error(
135 `Environment connection ${environmentId} changed identity to ${nextEnvironmentId} via ${source}.`,
136 );
137 }
138 };
139
140 const unsubLifecycle = shouldObserveLifecycle
141 ? input.client.server.subscribeLifecycle((event) => {
142 if (disposed || event.type !== "welcome") {
143 return;
144 }
145
146 observeEnvironmentIdentity(
147 event.payload.environment.environmentId,
148 "server lifecycle welcome",
149 );
150 input.onWelcome?.(event.payload);
151 })
152 : () => undefined;
153
154 const unsubConfig = shouldObserveConfig
155 ? input.client.server.subscribeConfig((event) => {
156 if (disposed || event.type !== "snapshot") {
157 return;
158 }
159
160 observeEnvironmentIdentity(
161 event.config.environment.environmentId,
162 "server config snapshot",
163 );
164 input.onConfigSnapshot?.(event.config);
165 })
166 : () => undefined;
167
168 const unsubShell = input.client.orchestration.subscribeShell(
169 (item) => {
170 if (disposed) {
171 return;
172 }
173
174 if (item.kind === "snapshot") {
175 input.syncShellSnapshot(item.snapshot, environmentId);
176 bootstrapGate.resolve();
177 return;
178 }
179
180 input.applyShellEvent(item, environmentId);
181 },
182 {
183 onResubscribe: () => {
184 if (disposed) {
185 return;
186 }
187
188 bootstrapGate.reset();
189 input.onShellResubscribe?.(environmentId);
190 },
191 },
192 );
193
194 const unsubTerminalEvent = input.applyTerminalEvent
195 ? input.client.terminal.onEvent((event) => {
196 if (!disposed) {
197 input.applyTerminalEvent?.(event, environmentId);
198 }
199 })
200 : () => undefined;
201
202 const cleanup = () => {
203 if (disposed) {
204 return;
205 }
206
207 disposed = true;
208 bootstrapGate.reject(new EnvironmentConnectionDisposedError(environmentId));
209 unsubShell();
210 unsubTerminalEvent();
211 unsubLifecycle();
212 unsubConfig();
213 };
214
215 return {
216 kind: input.kind,
217 environmentId,
218 knownEnvironment: input.knownEnvironment,
219 client: input.client,
220 ensureBootstrapped: () =>
221 disposed
222 ? Promise.reject(new EnvironmentConnectionDisposedError(environmentId))
223 : bootstrapGate.wait(),
224 reconnect: async () => {
225 if (disposed) {
226 throw new EnvironmentConnectionDisposedError(environmentId);
227 }
228
229 bootstrapGate.reset();
230 try {
231 await input.client.reconnect();
232 await input.refreshMetadata?.();
233 await bootstrapGate.wait();
234 } catch (error) {
235 bootstrapGate.reject(error);
236 throw error;
237 }
238 },
239 dispose: async () => {
240 cleanup();
241 await input.client.dispose();
242 },
243 };
244}