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

threadFamilies.test.ts

193 lines7.8 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_V2_WS_METHODS,
4 OrchestrationV2GetShellSnapshotError,
5 ThreadId,
6 type OrchestrationV2ShellSnapshot,
7 type OrchestrationV2ThreadFamily,
8 type OrchestrationV2ThreadShell,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "@effect/vitest";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Stream from "effect/Stream";
16import * as SubscriptionRef from "effect/SubscriptionRef";
17import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
18​
19import {
20 AVAILABLE_CONNECTION_STATE,
21 PrimaryConnectionTarget,
22 type PreparedConnection,
23 type SupervisorConnectionState,
24} from "../connection/model.ts";
25import * as EnvironmentRegistry from "../connection/registry.ts";
26import * as EnvironmentSupervisor from "../connection/supervisor.ts";
27import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
28import type * as RpcSession from "../rpc/session.ts";
29import { EMPTY_SHELL_STATE, type EnvironmentShellState } from "./shell.ts";
30import {
31 createThreadFamilyAtoms,
32 threadFamilyRead,
33 threadFamilyRowsMissingFromShell,
34} from "./threadFamilies.ts";
35​
36const row = (id: string, title = id) =>
37 ({ id: ThreadId.make(id), title }) as unknown as OrchestrationV2ThreadShell;
38​
39describe("threadFamilyRowsMissingFromShell", () => {
40 it("adds only the rows the shell left out, once, with shell rows winning", () => {
41 const missing = threadFamilyRowsMissingFromShell({
42 shellThreads: [row("parent"), row("live", "live from shell")],
43 families: [
44 { snapshotSequence: 4, threads: [row("live", "stale family copy"), row("idle")] },
45 { snapshotSequence: 4, threads: [row("idle"), row("other")] },
46 ],
47 removedAt: new Map(),
48 });
49 expect(missing.map((thread) => thread.id)).toEqual(["idle", "other"]);
50 });
51​
52 it("drops a family copy read before the shell removed that thread", () => {
53 const missing = threadFamilyRowsMissingFromShell({
54 shellThreads: [],
55 families: [
56 {
57 snapshotSequence: 5,
58 threads: [row("archived-after-read"), row("removed-before-read")],
59 },
60 ],
61 removedAt: new Map([
62 [ThreadId.make("archived-after-read"), 7],
63 [ThreadId.make("removed-before-read"), 3],
64 ]),
65 });
66 expect(missing.map((thread) => thread.id)).toEqual(["removed-before-read"]);
67 });
68});
69​
70const TARGET = new PrimaryConnectionTarget({
71 environmentId: EnvironmentId.make("environment-family"),
72 label: "Family environment",
73 httpBaseUrl: "https://family.example.test",
74 wsBaseUrl: "wss://family.example.test",
75});
76​
77describe("createThreadFamilyAtoms", () => {
78 it.effect("reads a family per shell generation and retries a failed read", () =>
79 Effect.scoped(
80 Effect.gen(function* () {
81 const replies =
82 yield* Queue.unbounded<
83 Effect.Effect<OrchestrationV2ThreadFamily, OrchestrationV2GetShellSnapshotError>
84 >();
85 const client = {
86 [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: () => Effect.flatten(Queue.take(replies)),
87 } as unknown as WsRpcProtocolClient;
88 const session = {
89 client,
90 initialConfig: Effect.succeed({ shellThreadFamilies: true } as never),
91 ready: Effect.void,
92 probe: Effect.void,
93 closed: Effect.never,
94 } as unknown as RpcSession.RpcSession;
95 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
96 target: TARGET,
97 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
98 ...AVAILABLE_CONNECTION_STATE,
99 desired: true,
100 network: "online",
101 phase: "connected",
102 attempt: 1,
103 generation: 1,
104 }),
105 session: yield* SubscriptionRef.make(Option.some(session)),
106 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
107 connect: Effect.void,
108 disconnect: Effect.void,
109 retryNow: Effect.void,
110 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
111 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
112 _environmentId,
113 effect,
114 ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
115 const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
116 _environmentId,
117 stream,
118 ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
119 const runtime = Atom.runtime(
120 Layer.succeed(
121 EnvironmentRegistry.EnvironmentRegistry,
122 EnvironmentRegistry.EnvironmentRegistry.of({
123 run,
124 followStream,
125 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
126 ),
127 );
128 const parent = row("parent");
129 const child = row("idle-child");
130 const shellSnapshot = {
131 schemaVersion: 1,
132 snapshotSequence: 3,
133 projects: [],
134 threads: [parent],
135 archivedThreads: [],
136 } as OrchestrationV2ShellSnapshot;
137 const shellAt = (generation: number): EnvironmentShellState => ({
138 ...EMPTY_SHELL_STATE,
139 status: "live",
140 snapshot: Option.some(shellSnapshot),
141 generation,
142 });
143 const shellState = Atom.make<AsyncResult.AsyncResult<EnvironmentShellState>>(
144 AsyncResult.success(shellAt(0)),
145 );
146 const families = createThreadFamilyAtoms(runtime, () => shellState);
147 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
148 Effect.sync(() => registry.dispose()),
149 );
150 const family = families.familyAtom(TARGET.environmentId, parent.id);
151 const mergedIds = () =>
152 registry.get(families.snapshotAtom(TARGET.environmentId))?.threads.map(({ id }) => id);
153 // Waits for the read to finish either way; the assertions read its outcome.
154 const settle = AtomRegistry.getResult(registry, family, { suspendOnWaiting: true }).pipe(
155 Effect.ignore,
156 Effect.tap(() => Effect.yieldNow),
157 );
158 registry.mount(families.snapshotAtom(TARGET.environmentId));
159 families.mount(registry, TARGET.environmentId, parent.id);
160​
161 // A cached shell from before this session's first snapshot reads nothing.
162 expect(threadFamilyRead(registry.get(family))).toBe("pending");
163 expect(yield* Queue.size(replies)).toBe(0);
164​
165 registry.set(shellState, AsyncResult.success(shellAt(1)));
166 yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 3, threads: [child] }));
167 yield* settle;
168 expect(threadFamilyRead(registry.get(family))).toBe("settled");
169 expect(mergedIds()).toEqual(["parent", "idle-child"]);
170​
171 // A new authoritative snapshot never reuses the old read, even while the next one waits
172 // or fails.
173 registry.set(shellState, AsyncResult.success(shellAt(2)));
174 expect(threadFamilyRead(registry.get(family))).toBe("pending");
175 expect(mergedIds()).toEqual(["parent"]);
176 yield* Queue.offer(
177 replies,
178 Effect.fail(new OrchestrationV2GetShellSnapshotError({ message: "read failed" })),
179 );
180 yield* settle;
181 expect(threadFamilyRead(registry.get(family))).toBe("failed");
182 expect(mergedIds()).toEqual(["parent"]);
183​
184 families.refresh(registry, TARGET.environmentId, parent.id);
185 expect(threadFamilyRead(registry.get(family))).toBe("pending");
186 yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 5, threads: [child] }));
187 yield* settle;
188 expect(threadFamilyRead(registry.get(family))).toBe("settled");
189 expect(mergedIds()).toEqual(["parent", "idle-child"]);
190 }),
191 ),
192 );
193});