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

threads-sync.test.ts

603 lines21.4 KB

1import {
2 EnvironmentId,
3 EventId,
4 ORCHESTRATION_V2_WS_METHODS,
5 ThreadId,
6 type OrchestrationV2ThreadDetailSnapshot,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2ThreadStreamItem,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "@effect/vitest";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Ref from "effect/Ref";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import * as TestClock from "effect/testing/TestClock";
19​
20import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
21import {
22 AVAILABLE_CONNECTION_STATE,
23 PrimaryConnectionTarget,
24 type PreparedConnection,
25 type SupervisorConnectionState,
26} from "../connection/model.ts";
27import * as ConnectionWakeups from "../connection/wakeups.ts";
28import * as EnvironmentSupervisor from "../connection/supervisor.ts";
29import * as Persistence from "../platform/persistence.ts";
30import * as RpcSession from "../rpc/session.ts";
31import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
32import {
33 EMPTY_ENVIRONMENT_THREAD_STATE,
34 makeEnvironmentThreadState,
35 ThreadSnapshotLoader,
36 type EnvironmentThreadState,
37} from "./threads.ts";
38​
39const TARGET = new PrimaryConnectionTarget({
40 environmentId: EnvironmentId.make("environment-1"),
41 label: "Test environment",
42 httpBaseUrl: "https://environment.example.test",
43 wsBaseUrl: "wss://environment.example.test",
44});
45const THREAD_ID = v2ThreadId;
46const CACHED_SNAPSHOT_SEQUENCE = 7;
47const PREPARED: PreparedConnection = {
48 environmentId: TARGET.environmentId,
49 label: TARGET.label,
50 httpBaseUrl: TARGET.httpBaseUrl,
51 socketUrl: TARGET.wsBaseUrl,
52 httpAuthorization: null,
53 target: TARGET,
54};
55const BASE_PROJECTION: OrchestrationV2ThreadProjection = {
56 ...v2Projection,
57 thread: { ...v2Projection.thread, title: "Cached thread" },
58};
59​
60type TestThreadInput = OrchestrationV2ThreadStreamItem | Error;
61​
62function testSession(
63 client: WsRpcProtocolClient,
64 config?: { readonly completionMarker?: boolean },
65): RpcSession.RpcSession {
66 return {
67 client,
68 initialConfig: Effect.succeed({
69 threadResumeCompletionMarker: config?.completionMarker === true,
70 } as never),
71 ready: Effect.void,
72 probe: Effect.void,
73 closed: Effect.never,
74 };
76​
77function awaitThreadState(
78 observed: Queue.Queue<EnvironmentThreadState>,
79 predicate: (state: EnvironmentThreadState) => boolean,
80) {
81 return Queue.take(observed).pipe(
82 Effect.repeat({
83 until: predicate,
84 }),
85 );
87​
88const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: {
89 readonly cached?: OrchestrationV2ThreadProjection;
90 readonly httpSnapshot?: Option.Option<OrchestrationV2ThreadDetailSnapshot>;
91 readonly completionMarker?: boolean;
92}) {
93 const inputs = yield* Queue.unbounded<TestThreadInput>();
94 const observed = yield* Queue.unbounded<EnvironmentThreadState>();
95 const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
96 const retryCount = yield* Ref.make(0);
97 const subscriptionCount = yield* Ref.make(0);
98 const loaderCalls = yield* Ref.make(0);
99 const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
100 const lastRequestCompletionMarker = yield* Ref.make(false);
101 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
102 const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationV2ThreadDetailSnapshot>>([]);
103 const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
104 const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
105 AVAILABLE_CONNECTION_STATE,
106 );
107 const streamFrom = (queue: Queue.Queue<TestThreadInput>) =>
108 Stream.fromQueue(queue).pipe(
109 Stream.mapEffect((input) =>
110 input instanceof Error ? Effect.fail(input) : Effect.succeed(input),
111 ),
112 );
113 const client = {
114 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: {
115 readonly afterSequence?: number;
116 readonly requestCompletionMarker?: true;
117 }) =>
118 Stream.unwrap(
119 Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
120 Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
121 Effect.andThen(
122 Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker === true),
123 ),
124 Effect.as(streamFrom(inputs)),
125 ),
126 ),
127 } as unknown as WsRpcProtocolClient;
128 const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
129 Option.some(testSession(client, options)),
130 );
131 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
132 Option.some(PREPARED),
133 );
134 const snapshotLoader = ThreadSnapshotLoader.of({
135 load: (_prepared, threadId) =>
136 Ref.update(loaderCalls, (count) => count + 1).pipe(
137 Effect.as(
138 threadId === THREAD_ID
139 ? (options?.httpSnapshot ?? Option.none<OrchestrationV2ThreadDetailSnapshot>())
140 : Option.none<OrchestrationV2ThreadDetailSnapshot>(),
141 ),
142 ),
143 });
144 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
145 target: TARGET,
146 state: supervisorState,
147 session: supervisorSession,
148 prepared,
149 connect: Effect.void,
150 disconnect: Effect.void,
151 retryNow: Ref.update(retryCount, (count) => count + 1),
152 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
153 const cache = Persistence.EnvironmentCacheStore.of({
154 loadShell: () => Effect.succeed(Option.none()),
155 saveShell: () => Effect.void,
156 loadThread: (_environmentId, threadId) =>
157 Effect.succeed(
158 threadId === THREAD_ID && options?.cached !== undefined
159 ? Option.some({
160 snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
161 projection: options.cached,
162 })
163 : Option.none(),
164 ),
165 saveThread: (_environmentId, snapshot) =>
166 Ref.update(savedThreads, (current) => [...current, snapshot]),
167 removeThread: (_environmentId, threadId) =>
168 Ref.update(removedThreads, (current) => [...current, threadId]),
169 loadServerConfig: () => Effect.succeed(Option.none()),
170 saveServerConfig: () => Effect.void,
171 loadVcsRefs: () => Effect.succeed(Option.none()),
172 saveVcsRefs: () => Effect.void,
173 removeVcsRefs: () => Effect.void,
174 clearVcsRefs: () => Effect.void,
175 clear: () => Effect.void,
176 });
177 const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
178 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
179 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
180 Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
181 Effect.provideService(
182 ConnectionWakeups.ConnectionWakeups,
183 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
184 ),
185 );
186 yield* SubscriptionRef.changes(threadState).pipe(
187 Stream.runForEach((state) =>
188 Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))),
189 ),
190 Effect.forkScoped,
191 );
192​
193 return {
194 inputs,
195 observed,
196 latest,
197 retryCount,
198 subscriptionCount,
199 loaderCalls,
200 lastSubscribeAfterSequence,
201 lastRequestCompletionMarker,
202 supervisorState,
203 supervisorSession,
204 savedThreads,
205 removedThreads,
206 wakeups,
207 replaceSession: SubscriptionRef.set(
208 supervisorSession,
209 Option.some(testSession(client, options)),
210 ),
211 };
212});
213​
214const snapshot = (
215 projection: OrchestrationV2ThreadProjection,
216 snapshotSequence = 1,
217): OrchestrationV2ThreadStreamItem => ({
218 kind: "snapshot",
219 snapshotSequence,
220 projection,
221});
222​
223const synchronized = (): OrchestrationV2ThreadStreamItem => ({ kind: "synchronized" });
224​
225const titleUpdated = (title: string, sequence = 2): OrchestrationV2ThreadStreamItem => {
226 const occurredAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
227 return {
228 kind: "event",
229 sequence,
230 event: {
231 id: EventId.make("event-title"),
232 type: "thread.metadata-updated",
233 threadId: THREAD_ID,
234 occurredAt,
235 payload: { ...v2Projection.thread, title, updatedAt: occurredAt },
236 },
237 };
238};
239​
240const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => {
241 const occurredAt = DateTime.makeUnsafe("2026-06-20T02:00:00.000Z");
242 return {
243 kind: "event",
244 sequence,
245 event: {
246 id: EventId.make("event-deleted"),
247 type: "thread.deleted",
248 threadId: THREAD_ID,
249 occurredAt,
250 payload: { ...v2Projection.thread, updatedAt: occurredAt, deletedAt: occurredAt },
251 },
252 };
253};
254​
255describe("EnvironmentThreads", () => {
256 it.effect("publishes cached data immediately from a warm cache", () =>
257 Effect.gen(function* () {
258 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
259 const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
260​
261 expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
262 expect(Option.isNone(state.error)).toBe(true);
263 }),
264 );
265​
266 it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
267 Effect.gen(function* () {
268 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
269​
270 // The warm cache reaches live from the cached data, and a live event
271 // applies on top of it.
272 yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
273 yield* awaitThreadState(
274 harness.observed,
275 (value) =>
276 value.status === "live" &&
277 Option.isSome(value.data) &&
278 value.data.value.thread.title === "Live title",
279 );
280​
281 // The subscription resumed from the cached sequence and never fetched the
282 // full snapshot over HTTP.
283 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
284 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
285 }),
286 );
287​
288 it.effect("reduces live events and persists the latest thread", () =>
289 Effect.gen(function* () {
290 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
291 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
292 yield* Queue.offer(harness.inputs, titleUpdated("Live title"));
293​
294 const state = yield* awaitThreadState(
295 harness.observed,
296 (value) =>
297 value.status === "live" &&
298 Option.isSome(value.data) &&
299 value.data.value.thread.title === "Live title",
300 );
301 yield* TestClock.adjust("500 millis");
302 yield* Effect.yieldNow;
303​
304 expect(Option.getOrThrow(state.data).thread.title).toBe("Live title");
305 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.projection.thread.title).toBe(
306 "Live title",
307 );
308 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2);
309 }),
310 );
311​
312 it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
313 Effect.gen(function* () {
314 const httpProjection: OrchestrationV2ThreadProjection = {
315 ...BASE_PROJECTION,
316 thread: { ...BASE_PROJECTION.thread, title: "HTTP title" },
317 };
318 const harness = yield* makeHarness({
319 httpSnapshot: Option.some({ snapshotSequence: 1, projection: httpProjection }),
320 });
321 // No socket snapshot is pushed; only a live event arrives over the socket.
322 // It can only be applied if the HTTP snapshot already seeded the thread.
323 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
324​
325 const state = yield* awaitThreadState(
326 harness.observed,
327 (value) =>
328 value.status === "live" &&
329 Option.isSome(value.data) &&
330 value.data.value.thread.title === "Live title",
331 );
332​
333 expect(Option.getOrThrow(state.data).thread.title).toBe("Live title");
334 // Cold cache: the full snapshot was loaded over HTTP and the socket
335 // resumed from that snapshot's sequence.
336 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
337 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1);
338 }),
339 );
340​
341 it.effect("ignores replayed thread events at or below the snapshot sequence", () =>
342 Effect.gen(function* () {
343 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
344 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
345 yield* Queue.offer(harness.inputs, titleUpdated("Replayed title", 1));
346 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
347​
348 const state = yield* awaitThreadState(
349 harness.observed,
350 (value) =>
351 value.status === "live" &&
352 Option.isSome(value.data) &&
353 value.data.value.thread.title === "Live title",
354 );
355​
356 expect(Option.getOrThrow(state.data).thread.title).toBe("Live title");
357 }),
358 );
359​
360 it.effect("removes cached data when the thread is deleted", () =>
361 Effect.gen(function* () {
362 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
363 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
364 yield* Queue.offer(harness.inputs, deleted());
365​
366 const state = yield* awaitThreadState(
367 harness.observed,
368 (value) => value.status === "deleted",
369 );
370​
371 expect(Option.isNone(state.data)).toBe(true);
372 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
373 }),
374 );
375​
376 it.effect("preserves data after a domain failure and resumes on a replacement session", () =>
377 Effect.gen(function* () {
378 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
379 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
380 yield* Queue.offer(harness.inputs, new Error("stream failed"));
381​
382 const state = yield* awaitThreadState(harness.observed, (value) =>
383 Option.isSome(value.error),
384 );
385​
386 expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
387 expect(Option.getOrThrow(state.error)).toBe("stream failed");
388 expect(yield* Ref.get(harness.retryCount)).toBe(0);
389​
390 yield* harness.replaceSession;
391 for (let attempt = 0; attempt < 100; attempt += 1) {
392 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
393 break;
394 }
395 yield* Effect.yieldNow;
396 }
397 yield* Queue.offer(
398 harness.inputs,
399 snapshot({
400 ...BASE_PROJECTION,
401 thread: { ...BASE_PROJECTION.thread, title: "Recovered thread" },
402 }),
403 );
404 const recovered = yield* awaitThreadState(
405 harness.observed,
406 (value) =>
407 value.status === "live" &&
408 Option.isSome(value.data) &&
409 value.data.value.thread.title === "Recovered thread",
410 );
411​
412 expect(Option.isNone(recovered.error)).toBe(true);
413 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
414 }),
415 );
416​
417 it.effect("recovers from a transient domain failure without replacing the session", () =>
418 Effect.gen(function* () {
419 const harness = yield* makeHarness();
420 yield* Queue.offer(harness.inputs, new Error("thread not found yet"));
421​
422 const failed = yield* awaitThreadState(harness.observed, (value) =>
423 Option.isSome(value.error),
424 );
425 expect(Option.getOrThrow(failed.error)).toBe("thread not found yet");
426 expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
427​
428 yield* TestClock.adjust("250 millis");
429 for (let attempt = 0; attempt < 100; attempt += 1) {
430 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
431 break;
432 }
433 yield* Effect.yieldNow;
434 }
435 yield* Queue.offer(
436 harness.inputs,
437 snapshot({
438 ...BASE_PROJECTION,
439 thread: { ...BASE_PROJECTION.thread, title: "Materialized thread" },
440 }),
441 );
442​
443 const recovered = yield* awaitThreadState(
444 harness.observed,
445 (value) =>
446 value.status === "live" &&
447 Option.isSome(value.data) &&
448 value.data.value.thread.title === "Materialized thread",
449 );
450​
451 expect(Option.isNone(recovered.error)).toBe(true);
452 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
453 expect(yield* Ref.get(harness.retryCount)).toBe(0);
454 }),
455 );
456​
457 it.effect("does not overwrite a live snapshot when the supervisor becomes ready", () =>
458 Effect.gen(function* () {
459 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
460 yield* SubscriptionRef.set(harness.supervisorState, {
461 desired: true,
462 network: "online",
463 phase: "connecting",
464 stage: "synchronizing",
465 attempt: 1,
466 generation: 0,
467 lastFailure: null,
468 retryAt: null,
469 });
470 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
471 yield* awaitThreadState(harness.observed, (value) => value.status === "live");
472​
473 yield* SubscriptionRef.set(harness.supervisorState, {
474 desired: true,
475 network: "online",
476 phase: "connected",
477 stage: null,
478 attempt: 1,
479 generation: 1,
480 lastFailure: null,
481 retryAt: null,
482 });
483 for (let index = 0; index < 10; index += 1) {
484 yield* Effect.yieldNow;
485 }
486​
487 expect((yield* Ref.get(harness.latest)).status).toBe("live");
488 }),
489 );
490​
491 it.effect("keeps replayed updates synchronizing until the completion marker arrives", () =>
492 Effect.gen(function* () {
493 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
494 yield* awaitThreadState(
495 harness.observed,
496 (value) => value.status === "synchronizing" && Option.isSome(value.data),
497 );
498 expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true);
499​
500 yield* Queue.offer(
501 harness.inputs,
502 titleUpdated("Caught-up title", CACHED_SNAPSHOT_SEQUENCE + 1),
503 );
504 const catchingUp = yield* awaitThreadState(
505 harness.observed,
506 (value) =>
507 value.status === "synchronizing" &&
508 Option.isSome(value.data) &&
509 value.data.value.thread.title === "Caught-up title",
510 );
511 expect(catchingUp.status).toBe("synchronizing");
512​
513 yield* Queue.offer(harness.inputs, synchronized());
514 const live = yield* awaitThreadState(
515 harness.observed,
516 (value) => value.status === "live" && Option.isSome(value.data),
517 );
518 expect(Option.getOrThrow(live.data).thread.title).toBe("Caught-up title");
519 }),
520 );
521​
522 it.effect("resumes replacement sessions from the latest applied sequence", () =>
523 Effect.gen(function* () {
524 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
525 yield* Queue.offer(
526 harness.inputs,
527 titleUpdated("Latest title", CACHED_SNAPSHOT_SEQUENCE + 1),
528 );
529 yield* Queue.offer(harness.inputs, synchronized());
530 yield* awaitThreadState(
531 harness.observed,
532 (value) =>
533 value.status === "live" &&
534 Option.isSome(value.data) &&
535 value.data.value.thread.title === "Latest title",
536 );
537​
538 yield* harness.replaceSession;
539 for (let attempt = 0; attempt < 100; attempt += 1) {
540 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
541 yield* Effect.yieldNow;
542 }
543​
544 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
545 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);
546 expect((yield* Ref.get(harness.latest)).status).toBe("synchronizing");
547 }),
548 );
549​
550 it.effect("resubscribes on app foreground from the latest applied sequence", () =>
551 Effect.gen(function* () {
552 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
553 yield* Queue.offer(
554 harness.inputs,
555 titleUpdated("Latest title", CACHED_SNAPSHOT_SEQUENCE + 1),
556 );
557 yield* Queue.offer(harness.inputs, synchronized());
558 yield* awaitThreadState(
559 harness.observed,
560 (value) =>
561 value.status === "live" &&
562 Option.isSome(value.data) &&
563 value.data.value.thread.title === "Latest title",
564 );
565​
566 yield* Queue.offer(harness.wakeups, "application-active");
567 const synchronizing = yield* awaitThreadState(
568 harness.observed,
569 (value) => value.status === "synchronizing" && Option.isSome(value.data),
570 );
571 for (let attempt = 0; attempt < 100; attempt += 1) {
572 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
573 yield* Effect.yieldNow;
574 }
575​
576 expect(synchronizing.status).toBe("synchronizing");
577 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
578 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);
579 expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true);
580 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
581​
582 yield* Queue.offer(harness.inputs, synchronized());
583 const live = yield* awaitThreadState(
584 harness.observed,
585 (value) => value.status === "live" && Option.isSome(value.data),
586 );
587 expect(Option.getOrThrow(live.data).thread.title).toBe("Latest title");
588​
589 yield* Queue.offer(harness.wakeups, "application-active-probe");
590 for (let attempt = 0; attempt < 100; attempt += 1) {
591 if ((yield* Ref.get(harness.subscriptionCount)) >= 3) break;
592 yield* Effect.yieldNow;
593 }
594 expect(yield* Ref.get(harness.subscriptionCount)).toBe(3);
595​
596 yield* Queue.offer(harness.wakeups, "application-active-reconnect");
597 for (let attempt = 0; attempt < 10; attempt += 1) {
598 yield* Effect.yieldNow;
599 }
600 expect(yield* Ref.get(harness.subscriptionCount)).toBe(3);
601 }),
602 );
603});