Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell-sync.test.ts

328 lines12.7 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_WS_METHODS,
4 type OrchestrationShellSnapshot,
5 type OrchestrationShellStreamItem,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Ref from "effect/Ref";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14​
15import {
16 AVAILABLE_CONNECTION_STATE,
17 PrimaryConnectionTarget,
18 type PreparedConnection,
19} from "../connection/model.ts";
20import * as EnvironmentSupervisor from "../connection/supervisor.ts";
21import * as ConnectionWakeups from "../connection/wakeups.ts";
22import * as Persistence from "../platform/persistence.ts";
23import * as RpcSession from "../rpc/session.ts";
24import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
25import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
26​
27const TARGET = new PrimaryConnectionTarget({
28 environmentId: EnvironmentId.make("environment-1"),
29 label: "Test environment",
30 httpBaseUrl: "https://environment.example.test",
31 wsBaseUrl: "wss://environment.example.test",
32});
33​
34const PREPARED: PreparedConnection = {
35 environmentId: TARGET.environmentId,
36 label: TARGET.label,
37 httpBaseUrl: TARGET.httpBaseUrl,
38 socketUrl: TARGET.wsBaseUrl,
39 httpAuthorization: null,
40 target: TARGET,
41};
42​
43const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
44 snapshotSequence: 1,
45 projects: [],
46 threads: [],
47 updatedAt: "2026-06-06T00:00:00.000Z",
48};
49​
50function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
51 return {
52 client,
53 initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never),
54 ready: Effect.void,
55 probe: Effect.void,
56 closed: Effect.never,
57 };
59​
60describe("environment shell synchronization", () => {
61 it.effect("publishes live state before persistence and preserves it when ready", () =>
62 Effect.gen(function* () {
63 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
64 const client = {
65 [ORCHESTRATION_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
66 } as unknown as WsRpcProtocolClient;
67 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
68 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
69 Option.some(session(client)),
70 );
71 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
72 target: TARGET,
73 state: supervisorState,
74 session: activeSession,
75 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
76 connect: Effect.void,
77 disconnect: Effect.void,
78 retryNow: Effect.void,
79 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
80 const cache = Persistence.EnvironmentCacheStore.of({
81 loadShell: () => Effect.succeed(Option.none()),
82 saveShell: () => Effect.never,
83 loadThread: () => Effect.succeed(Option.none()),
84 saveThread: () => Effect.void,
85 removeThread: () => Effect.void,
86 loadServerConfig: () => Effect.succeed(Option.none()),
87 saveServerConfig: () => Effect.void,
88 loadVcsRefs: () => Effect.succeed(Option.none()),
89 saveVcsRefs: () => Effect.void,
90 clear: () => Effect.void,
91 });
92 // Cold cache with no HTTP snapshot available → falls back to the
93 // socket-embedded snapshot.
94 const snapshotLoader = ShellSnapshotLoader.of({
95 load: () => Effect.succeed(Option.none()),
96 });
97 const shellState = yield* makeEnvironmentShellState().pipe(
98 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
99 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
100 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
101 );
102​
103 yield* SubscriptionRef.set(supervisorState, {
104 desired: true,
105 network: "online",
106 phase: "connecting",
107 stage: "synchronizing",
108 attempt: 1,
109 generation: 0,
110 lastFailure: null,
111 retryAt: null,
112 });
113 yield* Queue.offer(events, {
114 kind: "snapshot",
115 snapshot: LIVE_SHELL_SNAPSHOT,
116 });
117 const synchronizing = yield* SubscriptionRef.changes(shellState).pipe(
118 Stream.filter((state) => state.status === "synchronizing" && Option.isSome(state.snapshot)),
119 Stream.runHead,
120 );
121 expect(Option.getOrThrow(Option.getOrThrow(synchronizing).snapshot)).toEqual(
122 LIVE_SHELL_SNAPSHOT,
123 );
124​
125 yield* Queue.offer(events, { kind: "synchronized" });
126 yield* SubscriptionRef.changes(shellState).pipe(
127 Stream.filter((state) => state.status === "live"),
128 Stream.runHead,
129 );
130​
131 yield* SubscriptionRef.set(supervisorState, {
132 desired: true,
133 network: "online",
134 phase: "connected",
135 stage: null,
136 attempt: 1,
137 generation: 1,
138 lastFailure: null,
139 retryAt: null,
140 });
141 for (let index = 0; index < 10; index += 1) {
142 yield* Effect.yieldNow;
143 }
144​
145 const state = yield* SubscriptionRef.get(shellState);
146 expect(state.status).toBe("live");
147 expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
148 }),
149 );
150​
151 it.effect("replaces a warm shell cache with an authoritative HTTP snapshot", () =>
152 Effect.gen(function* () {
153 const cachedSnapshot: OrchestrationShellSnapshot = {
154 snapshotSequence: 5,
155 projects: [],
156 threads: [{ id: "stale-thread" } as never],
157 updatedAt: "2026-06-06T00:00:00.000Z",
158 };
159 const httpSnapshot: OrchestrationShellSnapshot = {
160 ...cachedSnapshot,
161 snapshotSequence: 9,
162 threads: [],
163 updatedAt: "2026-06-07T00:00:00.000Z",
164 };
165 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
166 const capturedAfterSequence = yield* SubscriptionRef.make<number | undefined>(undefined);
167 const capturedCompletionMarker = yield* Ref.make<boolean | undefined>(undefined);
168 const loaderCalls = yield* SubscriptionRef.make(0);
169 const client = {
170 [ORCHESTRATION_WS_METHODS.subscribeShell]: (input: {
171 readonly afterSequence?: number;
172 readonly requestCompletionMarker?: boolean;
173 }) =>
174 Stream.unwrap(
175 Ref.set(capturedCompletionMarker, input.requestCompletionMarker).pipe(
176 Effect.andThen(SubscriptionRef.set(capturedAfterSequence, input.afterSequence)),
177 Effect.as(Stream.fromQueue(events)),
178 ),
179 ),
180 } as unknown as WsRpcProtocolClient;
181 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
182 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
183 Option.some(session(client)),
184 );
185 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
186 target: TARGET,
187 state: supervisorState,
188 session: activeSession,
189 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
190 connect: Effect.void,
191 disconnect: Effect.void,
192 retryNow: Effect.void,
193 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
194 const cache = Persistence.EnvironmentCacheStore.of({
195 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
196 saveShell: () => Effect.void,
197 loadThread: () => Effect.succeed(Option.none()),
198 saveThread: () => Effect.void,
199 removeThread: () => Effect.void,
200 loadServerConfig: () => Effect.succeed(Option.none()),
201 saveServerConfig: () => Effect.void,
202 loadVcsRefs: () => Effect.succeed(Option.none()),
203 saveVcsRefs: () => Effect.void,
204 clear: () => Effect.void,
205 });
206 const snapshotLoader = ShellSnapshotLoader.of({
207 load: () =>
208 SubscriptionRef.update(loaderCalls, (count) => count + 1).pipe(
209 Effect.as(Option.some(httpSnapshot)),
210 ),
211 });
212 const shellState = yield* makeEnvironmentShellState().pipe(
213 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
214 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
215 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
216 );
217​
218 // Wait until the subscription is established from the warm cache.
219 yield* SubscriptionRef.changes(capturedAfterSequence).pipe(
220 Stream.filter((value) => value !== undefined),
221 Stream.runHead,
222 );
223​
224 expect(yield* SubscriptionRef.get(capturedAfterSequence)).toBe(9);
225 expect(yield* Ref.get(capturedCompletionMarker)).toBe(true);
226 expect(yield* SubscriptionRef.get(loaderCalls)).toBe(1);
227 const synchronizing = yield* SubscriptionRef.get(shellState);
228 expect(synchronizing.status).toBe("synchronizing");
229 expect(Option.getOrThrow(synchronizing.snapshot)).toEqual(httpSnapshot);
230​
231 yield* Queue.offer(events, { kind: "synchronized" });
232 yield* SubscriptionRef.changes(shellState).pipe(
233 Stream.filter((value) => value.status === "live"),
234 Stream.runHead,
235 );
236 }),
237 );
238​
239 it.effect("refreshes the authoritative shell snapshot when the app becomes active", () =>
240 Effect.gen(function* () {
241 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
242 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
243 const loaderCalls = yield* Ref.make(0);
244 const subscriptionCount = yield* Ref.make(0);
245 const client = {
246 [ORCHESTRATION_WS_METHODS.subscribeShell]: () =>
247 Stream.unwrap(
248 Ref.update(subscriptionCount, (count) => count + 1).pipe(
249 Effect.as(Stream.fromQueue(events)),
250 ),
251 ),
252 } as unknown as WsRpcProtocolClient;
253 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
254 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
255 target: TARGET,
256 state: supervisorState,
257 session: yield* SubscriptionRef.make(Option.some(session(client))),
258 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
259 connect: Effect.void,
260 disconnect: Effect.void,
261 retryNow: Effect.void,
262 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
263 const cache = Persistence.EnvironmentCacheStore.of({
264 loadShell: () => Effect.succeed(Option.some(LIVE_SHELL_SNAPSHOT)),
265 saveShell: () => Effect.void,
266 loadThread: () => Effect.succeed(Option.none()),
267 saveThread: () => Effect.void,
268 removeThread: () => Effect.void,
269 loadServerConfig: () => Effect.succeed(Option.none()),
270 saveServerConfig: () => Effect.void,
271 loadVcsRefs: () => Effect.succeed(Option.none()),
272 saveVcsRefs: () => Effect.void,
273 clear: () => Effect.void,
274 });
275 const snapshotLoader = ShellSnapshotLoader.of({
276 load: () =>
277 Ref.updateAndGet(loaderCalls, (count) => count + 1).pipe(
278 Effect.map((count) =>
279 Option.some({ ...LIVE_SHELL_SNAPSHOT, snapshotSequence: count * 10 }),
280 ),
281 ),
282 });
283 const shellState = yield* makeEnvironmentShellState().pipe(
284 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
285 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
286 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
287 Effect.provideService(
288 ConnectionWakeups.ConnectionWakeups,
289 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
290 ),
291 );
292​
293 yield* SubscriptionRef.changes(shellState).pipe(
294 Stream.filter(
295 (value) =>
296 value.status === "synchronizing" &&
297 Option.isSome(value.snapshot) &&
298 value.snapshot.value.snapshotSequence === 10,
299 ),
300 Stream.runHead,
301 );
302 yield* Queue.offer(events, { kind: "synchronized" });
303 yield* SubscriptionRef.changes(shellState).pipe(
304 Stream.filter((value) => value.status === "live"),
305 Stream.runHead,
306 );
307​
308 yield* Queue.offer(wakeups, "application-active");
309 yield* SubscriptionRef.changes(shellState).pipe(
310 Stream.filter(
311 (value) =>
312 value.status === "synchronizing" &&
313 Option.isSome(value.snapshot) &&
314 value.snapshot.value.snapshotSequence === 20,
315 ),
316 Stream.runHead,
317 );
318​
319 for (let attempt = 0; attempt < 100; attempt += 1) {
320 if ((yield* Ref.get(subscriptionCount)) >= 2) break;
321 yield* Effect.yieldNow;
322 }
323​
324 expect(yield* Ref.get(loaderCalls)).toBe(2);
325 expect(yield* Ref.get(subscriptionCount)).toBe(2);
326 }),
327 );
328});