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

shell-sync.test.ts

334 lines13.0 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 removeVcsRefs: () => Effect.void,
91 clearVcsRefs: () => Effect.void,
92 clear: () => Effect.void,
93 });
94 // Cold cache with no HTTP snapshot available → falls back to the
95 // socket-embedded snapshot.
96 const snapshotLoader = ShellSnapshotLoader.of({
97 load: () => Effect.succeed(Option.none()),
98 });
99 const shellState = yield* makeEnvironmentShellState().pipe(
100 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
101 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
102 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
103 );
104​
105 yield* SubscriptionRef.set(supervisorState, {
106 desired: true,
107 network: "online",
108 phase: "connecting",
109 stage: "synchronizing",
110 attempt: 1,
111 generation: 0,
112 lastFailure: null,
113 retryAt: null,
114 });
115 yield* Queue.offer(events, {
116 kind: "snapshot",
117 snapshot: LIVE_SHELL_SNAPSHOT,
118 });
119 const synchronizing = yield* SubscriptionRef.changes(shellState).pipe(
120 Stream.filter((state) => state.status === "synchronizing" && Option.isSome(state.snapshot)),
121 Stream.runHead,
122 );
123 expect(Option.getOrThrow(Option.getOrThrow(synchronizing).snapshot)).toEqual(
124 LIVE_SHELL_SNAPSHOT,
125 );
126​
127 yield* Queue.offer(events, { kind: "synchronized" });
128 yield* SubscriptionRef.changes(shellState).pipe(
129 Stream.filter((state) => state.status === "live"),
130 Stream.runHead,
131 );
132​
133 yield* SubscriptionRef.set(supervisorState, {
134 desired: true,
135 network: "online",
136 phase: "connected",
137 stage: null,
138 attempt: 1,
139 generation: 1,
140 lastFailure: null,
141 retryAt: null,
142 });
143 for (let index = 0; index < 10; index += 1) {
144 yield* Effect.yieldNow;
145 }
146​
147 const state = yield* SubscriptionRef.get(shellState);
148 expect(state.status).toBe("live");
149 expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
150 }),
151 );
152​
153 it.effect("replaces a warm shell cache with an authoritative HTTP snapshot", () =>
154 Effect.gen(function* () {
155 const cachedSnapshot: OrchestrationShellSnapshot = {
156 snapshotSequence: 5,
157 projects: [],
158 threads: [{ id: "stale-thread" } as never],
159 updatedAt: "2026-06-06T00:00:00.000Z",
160 };
161 const httpSnapshot: OrchestrationShellSnapshot = {
162 ...cachedSnapshot,
163 snapshotSequence: 9,
164 threads: [],
165 updatedAt: "2026-06-07T00:00:00.000Z",
166 };
167 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
168 const capturedAfterSequence = yield* SubscriptionRef.make<number | undefined>(undefined);
169 const capturedCompletionMarker = yield* Ref.make<boolean | undefined>(undefined);
170 const loaderCalls = yield* SubscriptionRef.make(0);
171 const client = {
172 [ORCHESTRATION_WS_METHODS.subscribeShell]: (input: {
173 readonly afterSequence?: number;
174 readonly requestCompletionMarker?: boolean;
175 }) =>
176 Stream.unwrap(
177 Ref.set(capturedCompletionMarker, input.requestCompletionMarker).pipe(
178 Effect.andThen(SubscriptionRef.set(capturedAfterSequence, input.afterSequence)),
179 Effect.as(Stream.fromQueue(events)),
180 ),
181 ),
182 } as unknown as WsRpcProtocolClient;
183 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
184 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
185 Option.some(session(client)),
186 );
187 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
188 target: TARGET,
189 state: supervisorState,
190 session: activeSession,
191 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
192 connect: Effect.void,
193 disconnect: Effect.void,
194 retryNow: Effect.void,
195 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
196 const cache = Persistence.EnvironmentCacheStore.of({
197 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
198 saveShell: () => Effect.void,
199 loadThread: () => Effect.succeed(Option.none()),
200 saveThread: () => Effect.void,
201 removeThread: () => Effect.void,
202 loadServerConfig: () => Effect.succeed(Option.none()),
203 saveServerConfig: () => Effect.void,
204 loadVcsRefs: () => Effect.succeed(Option.none()),
205 saveVcsRefs: () => Effect.void,
206 removeVcsRefs: () => Effect.void,
207 clearVcsRefs: () => Effect.void,
208 clear: () => Effect.void,
209 });
210 const snapshotLoader = ShellSnapshotLoader.of({
211 load: () =>
212 SubscriptionRef.update(loaderCalls, (count) => count + 1).pipe(
213 Effect.as(Option.some(httpSnapshot)),
214 ),
215 });
216 const shellState = yield* makeEnvironmentShellState().pipe(
217 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
218 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
219 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
220 );
221​
222 // Wait until the subscription is established from the warm cache.
223 yield* SubscriptionRef.changes(capturedAfterSequence).pipe(
224 Stream.filter((value) => value !== undefined),
225 Stream.runHead,
226 );
227​
228 expect(yield* SubscriptionRef.get(capturedAfterSequence)).toBe(9);
229 expect(yield* Ref.get(capturedCompletionMarker)).toBe(true);
230 expect(yield* SubscriptionRef.get(loaderCalls)).toBe(1);
231 const synchronizing = yield* SubscriptionRef.get(shellState);
232 expect(synchronizing.status).toBe("synchronizing");
233 expect(Option.getOrThrow(synchronizing.snapshot)).toEqual(httpSnapshot);
234​
235 yield* Queue.offer(events, { kind: "synchronized" });
236 yield* SubscriptionRef.changes(shellState).pipe(
237 Stream.filter((value) => value.status === "live"),
238 Stream.runHead,
239 );
240 }),
241 );
242​
243 it.effect("refreshes the authoritative shell snapshot when the app becomes active", () =>
244 Effect.gen(function* () {
245 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
246 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
247 const loaderCalls = yield* Ref.make(0);
248 const subscriptionCount = yield* Ref.make(0);
249 const client = {
250 [ORCHESTRATION_WS_METHODS.subscribeShell]: () =>
251 Stream.unwrap(
252 Ref.update(subscriptionCount, (count) => count + 1).pipe(
253 Effect.as(Stream.fromQueue(events)),
254 ),
255 ),
256 } as unknown as WsRpcProtocolClient;
257 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
258 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
259 target: TARGET,
260 state: supervisorState,
261 session: yield* SubscriptionRef.make(Option.some(session(client))),
262 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
263 connect: Effect.void,
264 disconnect: Effect.void,
265 retryNow: Effect.void,
266 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
267 const cache = Persistence.EnvironmentCacheStore.of({
268 loadShell: () => Effect.succeed(Option.some(LIVE_SHELL_SNAPSHOT)),
269 saveShell: () => Effect.void,
270 loadThread: () => Effect.succeed(Option.none()),
271 saveThread: () => Effect.void,
272 removeThread: () => Effect.void,
273 loadServerConfig: () => Effect.succeed(Option.none()),
274 saveServerConfig: () => Effect.void,
275 loadVcsRefs: () => Effect.succeed(Option.none()),
276 saveVcsRefs: () => Effect.void,
277 removeVcsRefs: () => Effect.void,
278 clearVcsRefs: () => Effect.void,
279 clear: () => Effect.void,
280 });
281 const snapshotLoader = ShellSnapshotLoader.of({
282 load: () =>
283 Ref.updateAndGet(loaderCalls, (count) => count + 1).pipe(
284 Effect.map((count) =>
285 Option.some({ ...LIVE_SHELL_SNAPSHOT, snapshotSequence: count * 10 }),
286 ),
287 ),
288 });
289 const shellState = yield* makeEnvironmentShellState().pipe(
290 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
291 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
292 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
293 Effect.provideService(
294 ConnectionWakeups.ConnectionWakeups,
295 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
296 ),
297 );
298​
299 yield* SubscriptionRef.changes(shellState).pipe(
300 Stream.filter(
301 (value) =>
302 value.status === "synchronizing" &&
303 Option.isSome(value.snapshot) &&
304 value.snapshot.value.snapshotSequence === 10,
305 ),
306 Stream.runHead,
307 );
308 yield* Queue.offer(events, { kind: "synchronized" });
309 yield* SubscriptionRef.changes(shellState).pipe(
310 Stream.filter((value) => value.status === "live"),
311 Stream.runHead,
312 );
313​
314 yield* Queue.offer(wakeups, "application-active");
315 yield* SubscriptionRef.changes(shellState).pipe(
316 Stream.filter(
317 (value) =>
318 value.status === "synchronizing" &&
319 Option.isSome(value.snapshot) &&
320 value.snapshot.value.snapshotSequence === 20,
321 ),
322 Stream.runHead,
323 );
324​
325 for (let attempt = 0; attempt < 100; attempt += 1) {
326 if ((yield* Ref.get(subscriptionCount)) >= 2) break;
327 yield* Effect.yieldNow;
328 }
329​
330 expect(yield* Ref.get(loaderCalls)).toBe(2);
331 expect(yield* Ref.get(subscriptionCount)).toBe(2);
332 }),
333 );
334});