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
87 const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
88 if (environmentId !== nextEnvironmentId) {
89 throw new Error(
90 `Environment connection ${environmentId} changed identity to ${nextEnvironmentId} via ${source}.`,
91 );
92 }
93 };
94
95 const unsubLifecycle = input.client.server.subscribeLifecycle(
96 (event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
97 if (event.type !== "welcome") {
98 return;
99 }
100 observeEnvironmentIdentity(
101 event.payload.environment.environmentId,
102 "server lifecycle welcome",
103 );
104 input.onWelcome?.(event.payload);
105 },
106 );
107
108 const unsubConfig = input.client.server.subscribeConfig(
109 (event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
110 if (event.type !== "snapshot") {
111 return;
112 }
113 observeEnvironmentIdentity(event.config.environment.environmentId, "server config snapshot");
114 input.onConfigSnapshot?.(event.config);
115 },
116 );
117
118 const unsubShell = input.client.orchestration.subscribeShell(
119 (item: Parameters<Parameters<WsRpcClient["orchestration"]["subscribeShell"]>[0]>[0]) => {
120 if (item.kind === "snapshot") {
121 input.syncShellSnapshot(item.snapshot, environmentId);
122 bootstrapGate.resolve();
123 return;
124 }
125 input.applyShellEvent(item, environmentId);
126 },
127 {
128 onResubscribe: () => {
129 if (disposed) {
130 return;
131 }
132 bootstrapGate.reset();
133 },
134 },
135 );
136
137 const unsubTerminalEvent = input.client.terminal.onEvent(
138 (event: Parameters<Parameters<WsRpcClient["terminal"]["onEvent"]>[0]>[0]) => {
139 input.applyTerminalEvent(event, environmentId);
140 },
141 );
142
143 const cleanup = () => {
144 disposed = true;
145 unsubShell();
146 unsubTerminalEvent();
147 unsubLifecycle();
148 unsubConfig();
149 };
150
151 return {
152 kind: input.kind,
153 environmentId,
154 knownEnvironment: input.knownEnvironment,
155 client: input.client,
156 ensureBootstrapped: () => bootstrapGate.wait(),
157 reconnect: async () => {
158 bootstrapGate.reset();
159 try {
160 await input.client.reconnect();
161 await input.refreshMetadata?.();
162 await bootstrapGate.wait();
163 } catch (error) {
164 bootstrapGate.reject(error);
165 throw error;
166 }
167 },
168 dispose: async () => {
169 cleanup();
170 await input.client.dispose();
171 },
172 };
173}