Open History to see the last commit
1import type {
2 EnvironmentId,
3 OrchestrationEvent,
4 OrchestrationReadModel,
5 ServerConfig,
6 ServerLifecycleWelcomePayload,
7 TerminalEvent,
8} from "@t3tools/contracts";
9import type { KnownEnvironment } from "@t3tools/client-runtime";
10
11import {
12 deriveReplayRetryDecision,
13 type OrchestrationRecoveryReason,
14} from "../../orchestrationRecovery";
15import {
16 createOrchestrationRecoveryCoordinator,
17 type ReplayRetryTracker,
18} from "../../orchestrationRecovery";
19import { isTransportConnectionErrorMessage } from "~/rpc/transportError";
20import type { WsRpcClient } from "~/rpc/wsRpcClient";
21
22const REPLAY_RECOVERY_RETRY_DELAY_MS = 100;
23const MAX_NO_PROGRESS_REPLAY_RETRIES = 3;
24const RECOVERY_TRANSPORT_RETRY_DELAY_MS = 250;
25const MAX_RECOVERY_TRANSPORT_RETRIES = 20;
26
27export interface EnvironmentConnection {
28 readonly kind: "primary" | "saved";
29 readonly environmentId: EnvironmentId;
30 readonly knownEnvironment: KnownEnvironment;
31 readonly client: WsRpcClient;
32 readonly ensureBootstrapped: () => Promise<void>;
33 readonly reconnect: () => Promise<void>;
34 readonly dispose: () => Promise<void>;
35}
36
37interface OrchestrationHandlers {
38 readonly applyEventBatch: (
39 events: ReadonlyArray<OrchestrationEvent>,
40 environmentId: EnvironmentId,
41 ) => void;
42 readonly syncSnapshot: (snapshot: OrchestrationReadModel, environmentId: EnvironmentId) => void;
43 readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void;
44}
45
46interface EnvironmentConnectionInput extends OrchestrationHandlers {
47 readonly kind: "primary" | "saved";
48 readonly knownEnvironment: KnownEnvironment;
49 readonly client: WsRpcClient;
50 readonly refreshMetadata?: () => Promise<void>;
51 readonly onConfigSnapshot?: (config: ServerConfig) => void;
52 readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
53}
54
55function createSnapshotBootstrapController(input: {
56 readonly isBootstrapped: () => boolean;
57 readonly runSnapshotRecovery: (
58 reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
59 ) => Promise<void>;
60}) {
61 let inFlight: Promise<void> | null = null;
62
63 return {
64 ensureSnapshotRecovery(
65 reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
66 ): Promise<void> {
67 if (input.isBootstrapped()) {
68 return Promise.resolve();
69 }
70
71 if (inFlight !== null) {
72 return inFlight;
73 }
74
75 const nextInFlight = input.runSnapshotRecovery(reason).finally(() => {
76 if (inFlight === nextInFlight) {
77 inFlight = null;
78 }
79 });
80 inFlight = nextInFlight;
81 return inFlight;
82 },
83 };
84}
85
86export function createEnvironmentConnection(
87 input: EnvironmentConnectionInput,
88): EnvironmentConnection {
89 const recovery = createOrchestrationRecoveryCoordinator();
90 let replayRetryTracker: ReplayRetryTracker | null = null;
91 const pendingDomainEvents: OrchestrationEvent[] = [];
92 let flushPendingDomainEventsScheduled = false;
93 const environmentId = input.knownEnvironment.environmentId;
94
95 if (!environmentId) {
96 throw new Error(
97 `Known environment ${input.knownEnvironment.label} is missing its environmentId.`,
98 );
99 }
100
101 let disposed = false;
102
103 const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
104 if (environmentId !== nextEnvironmentId) {
105 throw new Error(
106 `Environment connection ${environmentId} changed identity to ${nextEnvironmentId} via ${source}.`,
107 );
108 }
109 };
110
111 const flushPendingDomainEvents = () => {
112 flushPendingDomainEventsScheduled = false;
113 if (disposed || pendingDomainEvents.length === 0) {
114 return;
115 }
116
117 const events = pendingDomainEvents.splice(0, pendingDomainEvents.length);
118 const nextEvents = recovery.markEventBatchApplied(events);
119 if (nextEvents.length === 0) {
120 return;
121 }
122 input.applyEventBatch(nextEvents, environmentId);
123 };
124
125 const schedulePendingDomainEventFlush = () => {
126 if (flushPendingDomainEventsScheduled) {
127 return;
128 }
129
130 flushPendingDomainEventsScheduled = true;
131 queueMicrotask(flushPendingDomainEvents);
132 };
133
134 const retryTransportRecoveryOperation = async <T>(operation: () => Promise<T>): Promise<T> => {
135 for (let attempt = 0; ; attempt += 1) {
136 try {
137 return await operation();
138 } catch (error) {
139 const message = error instanceof Error ? error.message : String(error);
140 if (
141 disposed ||
142 !isTransportConnectionErrorMessage(message) ||
143 attempt >= MAX_RECOVERY_TRANSPORT_RETRIES - 1
144 ) {
145 throw error;
146 }
147
148 await new Promise<void>((resolve) => {
149 setTimeout(resolve, RECOVERY_TRANSPORT_RETRY_DELAY_MS);
150 });
151
152 if (disposed) {
153 throw error;
154 }
155 }
156 }
157 };
158 const scheduleReplayRecovery = (reason: "sequence-gap" | "resubscribe") => {
159 void runReplayRecovery(reason).catch(() => undefined);
160 };
161
162 const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise<void> => {
163 if (!recovery.beginReplayRecovery(reason)) {
164 return;
165 }
166
167 const fromSequenceExclusive = recovery.getState().latestSequence;
168 try {
169 const events = await retryTransportRecoveryOperation(() =>
170 input.client.orchestration.replayEvents({ fromSequenceExclusive }),
171 );
172 if (!disposed) {
173 const nextEvents = recovery.markEventBatchApplied(events);
174 if (nextEvents.length > 0) {
175 input.applyEventBatch(nextEvents, environmentId);
176 }
177 }
178 } catch {
179 replayRetryTracker = null;
180 recovery.failReplayRecovery();
181 if (disposed) {
182 return;
183 }
184 await snapshotBootstrap.ensureSnapshotRecovery("replay-failed");
185 return;
186 }
187
188 if (disposed) {
189 return;
190 }
191
192 const replayCompletion = recovery.completeReplayRecovery();
193 const retryDecision = deriveReplayRetryDecision({
194 previousTracker: replayRetryTracker,
195 completion: replayCompletion,
196 recoveryState: recovery.getState(),
197 baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS,
198 maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES,
199 });
200 replayRetryTracker = retryDecision.tracker;
201
202 if (retryDecision.shouldRetry) {
203 if (retryDecision.delayMs > 0) {
204 await new Promise<void>((resolve) => {
205 setTimeout(resolve, retryDecision.delayMs);
206 });
207 if (disposed) {
208 return;
209 }
210 }
211 scheduleReplayRecovery(reason);
212 } else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") {
213 console.warn(
214 "[orchestration-recovery]",
215 "Stopping replay recovery after no-progress retries.",
216 {
217 environmentId,
218 state: recovery.getState(),
219 },
220 );
221 }
222 };
223
224 const runSnapshotRecovery = async (
225 reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
226 ): Promise<void> => {
227 const started = recovery.beginSnapshotRecovery(reason);
228 if (!started) {
229 return;
230 }
231
232 try {
233 const snapshot = await retryTransportRecoveryOperation(() =>
234 input.client.orchestration.getSnapshot(),
235 );
236 if (!disposed) {
237 input.syncSnapshot(snapshot, environmentId);
238 if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
239 scheduleReplayRecovery("sequence-gap");
240 }
241 }
242 } catch (error) {
243 recovery.failSnapshotRecovery();
244 throw error;
245 }
246 };
247
248 const snapshotBootstrap = createSnapshotBootstrapController({
249 isBootstrapped: () => recovery.getState().bootstrapped,
250 runSnapshotRecovery,
251 });
252
253 const unsubLifecycle = input.client.server.subscribeLifecycle(
254 (event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
255 if (event.type !== "welcome") {
256 return;
257 }
258 observeEnvironmentIdentity(
259 event.payload.environment.environmentId,
260 "server lifecycle welcome",
261 );
262 input.onWelcome?.(event.payload);
263 },
264 );
265
266 const unsubConfig = input.client.server.subscribeConfig(
267 (event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
268 if (event.type !== "snapshot") {
269 return;
270 }
271 observeEnvironmentIdentity(event.config.environment.environmentId, "server config snapshot");
272 input.onConfigSnapshot?.(event.config);
273 },
274 );
275
276 const unsubDomainEvent = input.client.orchestration.onDomainEvent(
277 (event: Parameters<Parameters<WsRpcClient["orchestration"]["onDomainEvent"]>[0]>[0]) => {
278 const action = recovery.classifyDomainEvent(event.sequence);
279 if (action === "apply") {
280 pendingDomainEvents.push(event);
281 schedulePendingDomainEventFlush();
282 return;
283 }
284 if (action === "recover") {
285 flushPendingDomainEvents();
286 scheduleReplayRecovery("sequence-gap");
287 }
288 },
289 {
290 onResubscribe: () => {
291 if (disposed) {
292 return;
293 }
294 flushPendingDomainEvents();
295 scheduleReplayRecovery("resubscribe");
296 },
297 },
298 );
299
300 const unsubTerminalEvent = input.client.terminal.onEvent(
301 (event: Parameters<Parameters<WsRpcClient["terminal"]["onEvent"]>[0]>[0]) => {
302 input.applyTerminalEvent(event, environmentId);
303 },
304 );
305
306 void snapshotBootstrap.ensureSnapshotRecovery("bootstrap").catch(() => undefined);
307
308 const cleanup = () => {
309 disposed = true;
310 flushPendingDomainEventsScheduled = false;
311 pendingDomainEvents.length = 0;
312 unsubDomainEvent();
313 unsubTerminalEvent();
314 unsubLifecycle();
315 unsubConfig();
316 };
317
318 return {
319 kind: input.kind,
320 environmentId,
321 knownEnvironment: input.knownEnvironment,
322 client: input.client,
323 ensureBootstrapped: () => snapshotBootstrap.ensureSnapshotRecovery("bootstrap"),
324 reconnect: async () => {
325 await input.client.reconnect();
326 await input.refreshMetadata?.();
327 await snapshotBootstrap.ensureSnapshotRecovery("bootstrap");
328 },
329 dispose: async () => {
330 cleanup();
331 await input.client.dispose();
332 },
333 };
334}