Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off - The probe fixture uses a Node macrotask boundary.
2import * as NodeTimersPromises from "node:timers/promises";
3import {
4 EnvironmentId,
5 EventId,
6 type OrchestrationV2ThreadHistoryPage,
7 type OrchestrationV2ThreadStreamItem,
8 type PeerLinkClientPairingResult,
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 Fiber from "effect/Fiber";
14import * as Queue from "effect/Queue";
15import * as Stream from "effect/Stream";
16import { TestClock } from "effect/testing";
17
18import {
19 connectLinkedEnvironment,
20 followLinkedThread,
21 keepLinkedThreadView,
22 LINKED_THREAD_RETRY_MS,
23 type LinkedThreadView,
24} from "./linkedThread.ts";
25import { v2MessageRow, v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts";
26
27const snapshot = (
28 snapshotSequence: number,
29 historyCursor: string | null = null,
30): OrchestrationV2ThreadStreamItem => ({
31 kind: "snapshot",
32 snapshotSequence,
33 projection: v2Projection,
34 historyCursor,
35 hasMoreHistory: historyCursor !== null,
36});
37
38const retitled = (sequence: number, title: string): OrchestrationV2ThreadStreamItem => ({
39 kind: "event",
40 sequence,
41 event: {
42 id: EventId.make(`event:${sequence}`),
43 type: "thread.metadata-updated",
44 threadId: v2Projection.thread.id,
45 occurredAt: v2Now,
46 payload: { ...v2Projection.thread, title },
47 },
48});
49
50const failure = (reason: string) => ({ _tag: "PeerLinkThreadReadError", reason });
51const titleOf = (view: LinkedThreadView) => view.thread.projection?.thread.title ?? null;
52
53it.effect("keeps what it read while a linked environment is out of reach, and asks it again", () =>
54 Effect.gen(function* () {
55 const attempts = [
56 Stream.make(snapshot(1), retitled(2, "Renamed")).pipe(
57 Stream.concat(Stream.fail(failure("unreachable"))),
58 ),
59 Stream.make(snapshot(5)).pipe(Stream.concat(Stream.fail(failure("expired")))),
60 ];
61 let opened = 0;
62 const views = yield* Queue.unbounded<LinkedThreadView>();
63 const following = yield* followLinkedThread({
64 items: Stream.suspend(() => attempts[opened++]!),
65 historyPage: () => Effect.die("unused"),
66 }).pipe(
67 Stream.runForEach((view) => Queue.offer(views, view)),
68 Effect.flip,
69 Effect.forkChild,
70 );
71
72 expect(titleOf(yield* Queue.take(views))).toBe(v2Projection.thread.title);
73 expect(titleOf(yield* Queue.take(views))).toBe("Renamed");
74 // Out of reach: the thread stays as read, with the reason beside it.
75 const waiting = yield* Queue.take(views);
76 expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]);
77 expect(opened).toBe(1);
78
79 yield* TestClock.adjust(LINKED_THREAD_RETRY_MS);
80 // It answers again: its snapshot replaces the thread and clears the reason.
81 const back = yield* Queue.take(views);
82 expect([titleOf(back), back.error, back.thread.sequence]).toEqual([
83 v2Projection.thread.title,
84 null,
85 5,
86 ]);
87 // A link that expired cannot come back by waiting, so the stream ends with it.
88 expect(yield* Fiber.join(following)).toEqual(failure("expired"));
89 expect(opened).toBe(2);
90 }),
91);
92
93it.effect("keeps the thread a view showed while its reopened stream has read nothing", () =>
94 Effect.gen(function* () {
95 const attempts = [
96 Stream.make(snapshot(1, "cursor-1"), retitled(2, "Renamed")),
97 // The view closed and opened again while the linked environment was out of reach.
98 Stream.fail(failure("unreachable")),
99 Stream.make(snapshot(5)).pipe(Stream.concat(Stream.never)),
100 ];
101 let opened = 0;
102 const follow = () =>
103 followLinkedThread({
104 items: Stream.suspend(() => attempts[opened++]!),
105 historyPage: () => Effect.die("unused"),
106 });
107 let kept: LinkedThreadView | null = null;
108 yield* follow().pipe(
109 Stream.runForEach((view) => Effect.sync(() => (kept = keepLinkedThreadView(kept, view)))),
110 );
111
112 const views = yield* Queue.unbounded<LinkedThreadView>();
113 yield* follow().pipe(
114 Stream.runForEach((view) => Queue.offer(views, keepLinkedThreadView(kept, view))),
115 Effect.forkScoped,
116 );
117 const waiting = yield* Queue.take(views);
118 expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]);
119 // Earlier turns belong to a stream that is gone, so none are offered until one is back.
120 expect(waiting.thread.historyCursor).toBeNull();
121
122 yield* TestClock.adjust(LINKED_THREAD_RETRY_MS);
123 const back = yield* Queue.take(views);
124 expect([titleOf(back), back.error, back.thread.sequence]).toEqual([
125 v2Projection.thread.title,
126 null,
127 5,
128 ]);
129 }).pipe(Effect.scoped),
130);
131
132it.effect("loads the turns before a snapshot's window once per request", () =>
133 Effect.gen(function* () {
134 const asked: string[] = [];
135 const page: OrchestrationV2ThreadHistoryPage = {
136 snapshotSequence: 1,
137 items: [],
138 nextCursor: null,
139 hasMoreHistory: false,
140 };
141 const views = yield* Queue.unbounded<LinkedThreadView>();
142 yield* followLinkedThread({
143 items: Stream.make(snapshot(1, "cursor-1")).pipe(Stream.concat(Stream.never)),
144 historyPage: (cursor) =>
145 Effect.sync(() => {
146 asked.push(cursor);
147 return page;
148 }),
149 }).pipe(
150 Stream.runForEach((view) => Queue.offer(views, view)),
151 Effect.forkScoped,
152 );
153
154 const shown = yield* Queue.take(views);
155 expect(shown.thread.historyCursor).toBe("cursor-1");
156 shown.loadEarlier();
157 // A second tap while the page loads asks for nothing more.
158 shown.loadEarlier();
159 expect((yield* Queue.take(views)).history).toEqual({ loading: true, failed: false });
160 const loaded = yield* Queue.take(views);
161 expect([loaded.history.loading, loaded.thread.historyCursor]).toEqual([false, null]);
162 // Nothing is left to load.
163 loaded.loadEarlier();
164 expect(asked).toEqual(["cursor-1"]);
165 }).pipe(Effect.scoped),
166);
167
168it.effect("brings back the turns a closed view had loaded when it opens again", () =>
169 Effect.gen(function* () {
170 const older = v2MessageRow("Older", 1);
171 const recent = v2MessageRow("Recent", 2);
172 const latest = v2MessageRow("Latest", 3);
173 const window = (
174 snapshotSequence: number,
175 historyCursor: string,
176 row: typeof recent,
177 ): OrchestrationV2ThreadStreamItem => ({
178 kind: "snapshot",
179 snapshotSequence,
180 projection: { ...v2Projection, turnItems: [row.item], visibleTurnItems: [row] },
181 historyCursor,
182 hasMoreHistory: true,
183 });
184 const pages: Record<string, Pick<OrchestrationV2ThreadHistoryPage, "items" | "nextCursor">> = {
185 "before-recent": { items: [older], nextCursor: "before-older" },
186 "before-latest": { items: [recent], nextCursor: "before-recent" },
187 };
188 const asked: string[] = [];
189 const follow = (
190 items: ReadonlyArray<OrchestrationV2ThreadStreamItem>,
191 previous: LinkedThreadView | null,
192 ) =>
193 Effect.gen(function* () {
194 const views = yield* Queue.unbounded<LinkedThreadView>();
195 yield* followLinkedThread({
196 items: Stream.fromIterable(items).pipe(Stream.concat(Stream.never)),
197 historyPage: (cursor) =>
198 Effect.sync(() => {
199 asked.push(cursor);
200 return { ...pages[cursor]!, snapshotSequence: 3, hasMoreHistory: true };
201 }),
202 previous,
203 }).pipe(
204 Stream.runForEach((view) => Queue.offer(views, view)),
205 Effect.forkScoped,
206 );
207 return views;
208 });
209 const settled = Effect.fnUntraced(function* (views: Queue.Queue<LinkedThreadView>) {
210 let view = yield* Queue.take(views);
211 while (view.history.loading) view = yield* Queue.take(views);
212 return view;
213 });
214 const rows = (view: LinkedThreadView) =>
215 view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId);
216
217 const first = yield* follow([window(1, "before-recent", recent), retitled(2, "Renamed")], null);
218 (yield* Queue.take(first)).loadEarlier();
219 yield* Queue.take(first); // Loading.
220 yield* Queue.take(first); // The earlier page.
221 const closed = yield* Queue.take(first);
222 expect([rows(closed), closed.thread.sequence]).toEqual([
223 [older.sourceItemId, recent.sourceItemId],
224 2,
225 ]);
226
227 // Nothing changed while the view was closed: the rows it held are shown as they were.
228 const same = yield* settled(yield* follow([window(2, "before-recent", recent)], closed));
229 expect([rows(same), same.thread.historyCursor]).toEqual([
230 [older.sourceItemId, recent.sourceItemId],
231 "before-older",
232 ]);
233 expect(asked).toEqual(["before-recent"]);
234
235 // The thread moved on: pages are read again until the oldest row it showed is back.
236 const moved = yield* settled(yield* follow([window(3, "before-latest", latest)], closed));
237 expect([rows(moved), moved.thread.historyCursor]).toEqual([
238 [older.sourceItemId, recent.sourceItemId, latest.sourceItemId],
239 "before-older",
240 ]);
241 expect(asked).toEqual(["before-recent", "before-latest", "before-recent"]);
242 }).pipe(Effect.scoped),
243);
244
245describe("connectLinkedEnvironment", () => {
246 const lan = "http://192.168.1.20:3773";
247 const tailnet = "https://vm.tail.ts.net";
248 const target = {
249 environmentId: EnvironmentId.make("environment-vm"),
250 label: "VM",
251 urls: [lan, tailnet],
252 };
253 const credential: PeerLinkClientPairingResult = {
254 type: "credential",
255 ...target,
256 credential: "ONE-TIME",
257 expiresAt: DateTime.makeUnsafe(0),
258 };
259 const unsupported: PeerLinkClientPairingResult = {
260 type: "unsupported",
261 reason: "link_access",
262 ...target,
263 };
264 const connect = (
265 pairing: PeerLinkClientPairingResult | null,
266 reachable: ReadonlyArray<string> | ((host: string) => Promise<boolean>),
267 paired = true,
268 ) => {
269 const pairs: Array<{ host: string; pairingCode: string }> = [];
270 return connectLinkedEnvironment({
271 label: "vm (saved name)",
272 requestPairing: async () => pairing,
273 reaches:
274 typeof reachable === "function" ? reachable : async (host) => reachable.includes(host),
275 pair: async (input) => {
276 pairs.push(input);
277 return paired;
278 },
279 }).then((outcome) => ({ outcome, pairs }));
280 };
281
282 it("redeems the pairing at the first address this device reaches", async () => {
283 expect(await connect(credential, [tailnet])).toEqual({
284 outcome: { type: "connected" },
285 pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }],
286 });
287 expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan);
288 });
289
290 it.each([
291 {
292 name: "redeems at an alternate after the preferred probe fails",
293 pairing: credential,
294 preferredReachable: false,
295 expected: {
296 outcome: { type: "connected" },
297 pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }],
298 },
299 },
300 {
301 name: "prefills the preferred address even when an alternate answers first",
302 pairing: unsupported,
303 preferredReachable: true,
304 expected: { outcome: { type: "manual", label: "VM", host: lan }, pairs: [] },
305 },
306 ])("$name without waiting for a silent last address", async (row) => {
307 const last = "https://other.example.test";
308 const preferred = Promise.withResolvers<boolean>();
309 const silent = Promise.withResolvers<boolean>();
310 const connecting = connect({ ...row.pairing, urls: [lan, tailnet, last] }, (host) => {
311 if (host === lan) return preferred.promise;
312 if (host === last) return silent.promise;
313 queueMicrotask(() => preferred.resolve(row.preferredReachable));
314 return Promise.resolve(true);
315 });
316 try {
317 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Let the already runnable probe continuations finish while the last probe stays pending.
318 const pending = NodeTimersPromises.setImmediate("still waiting for an address");
319 expect(await Promise.race([connecting, pending])).toEqual(row.expected);
320 } finally {
321 silent.resolve(false);
322 preferred.resolve(false);
323 }
324 });
325
326 it("says the machine is out of reach, and spends nothing, when no address answers", async () => {
327 expect(await connect(credential, [])).toEqual({
328 outcome: { type: "unreachable", label: "VM" },
329 pairs: [],
330 });
331 });
332
333 it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => {
334 const manual = (host: string | null) => ({
335 outcome: { type: "manual", label: "VM", host },
336 pairs: [],
337 });
338 expect(await connect(unsupported, [tailnet])).toEqual(manual(tailnet));
339 // An address the user can correct beats an empty field.
340 expect(await connect(unsupported, [])).toEqual(manual(lan));
341 expect(await connect({ ...unsupported, urls: [] }, [])).toEqual(manual(null));
342 // The linking environment never answered, so only the client's own name is known.
343 expect((await connect(null, [lan])).outcome).toEqual({
344 type: "manual",
345 label: "vm (saved name)",
346 host: null,
347 });
348 // The one-time pairing was refused where it was redeemed.
349 expect((await connect(credential, [lan], false)).outcome).toEqual({
350 type: "manual",
351 label: "VM",
352 host: lan,
353 });
354 });
355});