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