- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/news-stream.test.ts?version=299&format=json
225 linesbox-grants 100%Last change box-grants in version 299, 6 versions changed it
You're reading version 299. The newest is 318, and no version since then changed this file.
1// abso news --stream and --follow (abso 690): the Monitor call, and holding the stream through closes and refusals.
3import assert from "node:assert/strict";
4import { test } from "node:test";
5import {
6 expiresAtMs,
7 type FollowDeps,
8 follow,
9 isRefusal,
10 MONITOR_TIMEOUT_MS,
11 monitorArgs,
12 NEWS_PROTOCOL,
13 type NewsTicket,
14 nextWait,
15 PING,
16 PING_MS,
17 PONG,
18 type Socket,
19 STREAM_MARK,
20 streamMarkUntil,
21 streamText,
22} from "../src/news-stream.ts";
24const NOW = 1_800_000_000_000;
25const ticket = (n: number): NewsTicket => ({
26 url: "wss://api.abso.dev/p/abso/a/fe/news/stream",
27 protocols: [NEWS_PROTOCOL, `abso-ticket.t${n}`],
28 expiresAt: NOW + 60_000,
29});
31test("--stream prints the Monitor call: the URL and protocols as the server gave them, 30 minutes, named for the seat", () => {
32 const args = monitorArgs(ticket(1), "abso", "fe");
33 assert.deepEqual(args, {
34 ws: { url: "wss://api.abso.dev/p/abso/a/fe/news/stream", protocols: ["abso-news.1", "abso-ticket.t1"] },
35 description: "abso news for fe in abso",
36 timeout_ms: MONITOR_TIMEOUT_MS,
37 });
38 assert.equal(MONITOR_TIMEOUT_MS, 30 * 60_000);
39 // The ticket never goes in the URL.
40 assert.doesNotMatch(args.ws.url, /t1/);
41 const text = streamText(ticket(1), "abso", "fe", NOW + 15_000).split("\n");
42 assert.match(text[0]!, /within 45 seconds/);
43 assert.match(text[0]!, /run abso news --stream again/);
44 assert.deepEqual(JSON.parse(text[1]!), args);
45 // The server sends the expiry as an ISO time (staging 1418); the countdown and the stream mark read it the same.
46 const iso = { ...ticket(1), expiresAt: new Date(NOW + 60_000).toISOString() };
47 assert.match(streamText(iso, "abso", "fe", NOW + 15_000), /within 45 seconds/);
48 assert.equal(streamMarkUntil(iso, NOW), NOW + 60_000 + MONITOR_TIMEOUT_MS);
49 assert.equal(expiresAtMs({ ...ticket(1), expiresAt: "soon" }, NOW), NOW);
50});
52test("a refusal close stops --follow; any other close opens again, waiting 1 s doubling to a minute", () => {
53 // 1008: a revoked key, or a fifth socket for the agent. A bad ticket is refused before the upgrade, so it closes 1006
54 // and is tried again with a new ticket; a refused key then fails the mint.
55 assert.equal(isRefusal(1008), true);
56 assert.equal(isRefusal(1006), false);
57 assert.equal(isRefusal(1001), false);
58 assert.equal(nextWait(1_000, 0), 2_000);
59 assert.equal(nextWait(32_000, 5_000), 60_000);
60 assert.equal(nextWait(60_000, 5_000), 60_000);
61 // A socket that lived a minute starts the wait over.
62 assert.equal(nextWait(60_000, 60_000), 1_000);
63});
65/** A world for follow(): each connect gets the next script of frames and a close. */
66function world(scripts: { frames: string[]; close: { code: number; reason?: string }; livedMs?: number }[]) {
67 let now = NOW;
68 let n = 0;
69 const lines: string[] = [];
70 const notes: string[] = [];
71 const sent: string[] = [];
72 const slept: number[] = [];
73 const opened: { url: string; protocols: readonly string[] }[] = [];
74 const pings: (() => void)[] = [];
75 let stop = false;
76 const deps: FollowDeps = {
77 mint: async () => ticket(++n),
78 connect: (url, protocols) => {
79 opened.push({ url, protocols });
80 const script = scripts[opened.length - 1];
81 const socket: Socket = {
82 onopen: null,
83 onmessage: null,
84 onclose: null,
85 onerror: null,
86 send: (text) => sent.push(text),
87 close: () => {},
88 };
89 queueMicrotask(() => {
90 socket.onopen?.();
91 if (script === undefined) {
92 stop = true;
93 socket.onclose?.({ code: 1000, reason: "" });
94 return;
95 }
96 for (const pinged of pings.splice(0)) pinged();
97 for (const data of script.frames) socket.onmessage?.({ data });
98 now += script.livedMs ?? 1_000;
99 socket.onclose?.({ code: script.close.code, reason: script.close.reason ?? "" });
100 });
101 return socket;
102 },
103 write: (line) => lines.push(line),
104 note: (line) => notes.push(line),
105 sleep: async (ms) => {
106 slept.push(ms);
107 },
108 now: () => now,
109 every: (ms, fn) => {
110 assert.equal(ms, PING_MS);
111 pings.push(fn);
112 return () => {};
113 },
114 stopped: () => stop,
115 };
116 return { deps, lines, notes, sent, slept, opened };
117}
119test("--follow prints each item once, skips the server's pongs, and opens a new socket with a new ticket after a close", async () => {
120 const w = world([
121 { frames: ["fe told you: hello", PONG, "an ask from cloud: ship it?"], close: { code: 1006 } },
122 { frames: ["second socket's item"], close: { code: 1001 }, livedMs: 120_000 },
123 ]);
124 const ended = await follow(w.deps);
125 assert.deepEqual(ended, { ended: "stopped", reason: "stopped" });
126 assert.deepEqual(w.lines, ["fe told you: hello", "an ask from cloud: ship it?", "second socket's item"]);
127 // Each socket used its own ticket; each ticket was used once.
128 assert.deepEqual(
129 w.opened.map((o) => o.protocols[1]),
130 ["abso-ticket.t1", "abso-ticket.t2", "abso-ticket.t3"],
131 );
132 // The first socket lived a second: wait 2 s. The second lived two minutes: start over at 1 s.
133 assert.deepEqual(w.slept, [2_000, 1_000]);
134 assert.equal(w.notes.length, 0);
135});
137test("a frame is a wake: --follow reads the news and prints that once; an empty read prints the frames", async () => {
138 // The server's frames don't count as heard (abso 690): the read takes them, so each item prints once.
139 const w = world([{ frames: ["fe told you: hello", "cloud asks: ship it?"], close: { code: 1006 } }]);
140 const reads: string[][] = [["fe told you: hello", "cloud asks: ship it?"], []];
141 let calls = 0;
142 w.deps.take = async () => {
143 calls++;
144 return reads.shift() ?? [];
145 };
146 await follow(w.deps);
147 // Two frames, one read in flight: the second folds into one more read, which finds nothing new; its frame was
148 // already printed by the first read, so nothing prints twice.
149 assert.equal(calls, 2);
150 assert.deepEqual(w.lines, ["fe told you: hello", "cloud asks: ship it?"]);
152 // A server that counts a frame as heard already (staging 1418): the read is empty, so the frame is what shows.
153 const old = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]);
154 old.deps.take = async () => [];
155 await follow(old.deps);
156 assert.deepEqual(old.lines, ["fe told you: hello"]);
158 // On that server a read can find other news waiting: the frame's own item still shows (Code Review, 291).
159 const mixed = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]);
160 mixed.deps.take = async () => ["cloud: an older item"];
161 await follow(mixed.deps);
162 assert.deepEqual(mixed.lines, ["cloud: an older item", "fe told you: hello"]);
164 // A catch-up frame names the first few waiting items and how many more: the read shows them all, the frame adds nothing.
165 const catchUp = world([{ frames: ["fe told you: hello\ncloud: ship it?\nand 1 more"], close: { code: 1006 } }]);
166 catchUp.deps.take = async () => ["fe told you: hello", "cloud: ship it?", "desk: a third"];
167 await follow(catchUp.deps);
168 assert.deepEqual(catchUp.lines, ["fe told you: hello", "cloud: ship it?", "desk: a third"]);
170 // A read that fails shows the frames and says why.
171 const down = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]);
172 down.deps.take = async () => {
173 throw new Error("could not reach the server");
174 };
175 await follow(down.deps);
176 assert.deepEqual(down.lines, ["fe told you: hello"]);
177 assert.match(down.notes[0]!, /couldn't read the news: could not reach the server/);
178});
180test("--follow keeps an idle socket open with a ping the object answers without waking", async () => {
181 const w = world([{ frames: [], close: { code: 1006 } }]);
182 const held: number[] = [];
183 w.deps.held = (until) => held.push(until);
184 await follow(w.deps);
185 assert.deepEqual(w.sent, [PING]);
186 // The stream mark is renewed on open and at each ping, two pings ahead, so the mod's poll stands down meanwhile.
187 // The first socket opens and pings; the second opens a second later.
188 assert.deepEqual(held, [NOW + 2 * PING_MS, NOW + 2 * PING_MS, NOW + 1_000 + 2 * PING_MS]);
189});
191test("--stream's mark holds for the Monitor's 30 minutes after the ticket's minute", () => {
192 assert.equal(streamMarkUntil(ticket(1), NOW), NOW + 60_000 + MONITOR_TIMEOUT_MS);
193 assert.equal(STREAM_MARK, "news-stream.json");
194});
196test("a refused ticket or a refusal close ends --follow; a ticket that can't be had is tried again", async () => {
197 const refusedClose = world([{ frames: ["one item"], close: { code: 1008, reason: "key revoked" } }]);
198 assert.deepEqual(await follow(refusedClose.deps), { ended: "refused", reason: "key revoked" });
199 assert.deepEqual(refusedClose.lines, ["one item"]);
201 const w = world([{ frames: [], close: { code: 1000 } }]);
202 let tries = 0;
203 const mint = w.deps.mint;
204 w.deps.mint = async () => {
205 tries++;
206 if (tries === 1) throw Object.assign(new Error("could not reach the server"), { status: undefined });
207 if (tries === 3)
208 throw Object.assign(new Error("POST /a/fe/news/ticket answered 401: no such key"), { status: 401 });
209 return mint();
210 };
211 const ended = await follow(w.deps);
212 assert.equal(ended.ended, "refused");
213 assert.match(ended.reason, /401/);
214 assert.equal(w.notes.length, 1);
215 assert.match(w.notes[0]!, /no ticket: could not reach the server; trying again in 1 s/);
216 assert.deepEqual(w.lines, []);
218 // A server without the stream (before abso 690) answers the ticket 404: stop, don't retry.
219 const old = world([]);
220 old.deps.mint = async () => {
221 throw Object.assign(new Error("POST /a/fe/news/ticket answered 404: not found"), { status: 404 });
222 };
223 assert.equal((await follow(old.deps)).ended, "refused");
224 assert.deepEqual(old.slept, []);
225});