@notation/factory 0.2.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,10 +2,15 @@ import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import type { OutpostConfig } from "../contracts/outpost.ts";
4
4
  import type { Delivery, Received, RemoteChannel } from "./channel.ts";
5
- import { handle, type RemoteDeployer, type RouterStore } from "./handle.ts";
6
- import { type Run, signBuildReport, signTicket, signTokenTicket } from "./run.ts";
5
+ import { BUILD_POLL_MS, BUILD_WAIT_MS, type DeliveryRecord, failedDelivery, type Inbox, replayRecord } from "./deliveries.ts";
6
+ import { type RepoDeploy, signSession, verifySession } from "./admin.ts";
7
+ import { advance, handle, type RemoteDeployer, type RouterStore } from "./handle.ts";
8
+ import { type Run, signBuildReport, signMessage, signTicket, signTokenTicket } from "./run.ts";
9
+ import { SYNC_HEADER, signSync } from "./sync.ts";
7
10
 
8
11
  const ROOT_KEY = "root";
12
+ const SYNC_KEY = "sync";
13
+ const ORIGIN = "https://router.test";
9
14
 
10
15
  type FakeEvent = { allow: boolean };
11
16
 
@@ -22,9 +27,18 @@ const fake = (
22
27
  read: async () => ({ ref: "c0ffee", files: {} }),
23
28
  writeStatus: async () => {},
24
29
  writeCheck: async () => {},
25
- conversation: async (delivery) => ({ id: `fake:${delivery.repo}`, prompt: "do it", thread: { repo: delivery.repo } }),
26
- reply: async () => {},
30
+ conversation: async (delivery) => ({ id: `fake:${delivery.repo}`, message: "p1", thread: { repo: delivery.repo } }),
31
+ messages: async () => [],
32
+ acknowledge: async () => {},
33
+ reply: async () => undefined,
27
34
  token: async (repo, permissions) => `token:${repo}:${JSON.stringify(permissions)}`,
35
+ repos: async () => [],
36
+ signInUrl: async (state) => `https://sign-in.test/?state=${state}`,
37
+ // A code of `code-<login>-<id>` signs in as that user.
38
+ signIn: async (code) => {
39
+ const [login = "", id = "0"] = code.replace(/^code-/, "").split("-");
40
+ return { login, id };
41
+ },
28
42
  });
29
43
 
30
44
  const accepted = (over: Partial<Delivery<FakeEvent>> = {}) =>
@@ -61,6 +75,16 @@ const outpost: OutpostConfig = {
61
75
  },
62
76
  };
63
77
 
78
+ /** The store of the last `call`, which `atOnce` dispatches against. */
79
+ let calling: RouterStore;
80
+
81
+ /** An inbox that dispatches each delivery once, as soon as the router saves it. */
82
+ const atOnce: Inbox = {
83
+ receive: async (record) => (await advance(record, calling), true),
84
+ failed: async () => [],
85
+ replay: async () => false,
86
+ };
87
+
64
88
  const entry = (channel: string) => ({ provider: "fake", source: "1", credentials: {}, channel });
65
89
 
66
90
  const store = (
@@ -78,6 +102,7 @@ const store = (
78
102
  | undefined,
79
103
  outpost: async (repo) => outposts[repo],
80
104
  rootKey: async () => ROOT_KEY,
105
+ inbox: atOnce,
81
106
  });
82
107
 
83
108
  /** The matches without their runs' random ids. */
@@ -86,6 +111,7 @@ const matched = (matches: { run?: string }[]) => matches.map(({ run, ...m }) =>
86
111
  const post = (path: string) => new Request(`https://router.test${path}`, { method: "POST" });
87
112
 
88
113
  const call = async (s: RouterStore, path = "/webhook/fake/main") => {
114
+ calling = s;
89
115
  const response = await handle(post(path), s);
90
116
  return { status: response.status, body: await response.json() };
91
117
  };
@@ -116,20 +142,43 @@ test("a delivery to a connection with no channel is a 404", async () => {
116
142
  assert.equal((await call(store({ main: accepted() }), "/webhook/fake/unknown")).status, 404);
117
143
  });
118
144
 
145
+ const syncCall = async (s: RouterStore, header?: string) => {
146
+ const response = await handle(
147
+ new Request("https://router.test/sync", { method: "POST", ...(header && { headers: { [SYNC_HEADER]: header } }) }),
148
+ s,
149
+ );
150
+ return { status: response.status, body: await response.json() };
151
+ };
152
+
119
153
  test("sync gives each channel its connection's webhook URL, and reports failures", async () => {
120
154
  const urls: string[] = [];
121
- const s = store({
122
- main: fake({ status: "ignored", reason: "" }, async (url) => void urls.push(url)),
123
- second: fake({ status: "ignored", reason: "" }, async () => {
124
- throw new Error("no access");
155
+ const s: RouterStore = {
156
+ ...store({
157
+ main: fake({ status: "ignored", reason: "" }, async (url) => void urls.push(url)),
158
+ second: fake({ status: "ignored", reason: "" }, async () => {
159
+ throw new Error("no access");
160
+ }),
125
161
  }),
126
- });
127
- const { status, body } = await call(s, "/sync");
162
+ syncKey: async () => SYNC_KEY,
163
+ };
164
+ const { status, body } = await syncCall(s, await signSync(SYNC_KEY, ORIGIN));
128
165
  assert.equal(status, 502);
129
166
  assert.deepEqual(urls, ["https://router.test/webhook/fake/main"]);
130
167
  assert.deepEqual(body.connections, { "fake/main": "ok", "fake/second": "no access" });
131
168
  });
132
169
 
170
+ test("sync takes only a recent request signed with the sync key", async () => {
171
+ const urls: string[] = [];
172
+ const s: RouterStore = { ...store({ main: fake({ status: "ignored", reason: "" }, async (url) => void urls.push(url)) }), syncKey: async () => SYNC_KEY };
173
+ assert.equal((await syncCall(s)).status, 401);
174
+ assert.equal((await syncCall(s, await signSync("other", ORIGIN))).status, 401);
175
+ assert.equal((await syncCall(s, await signSync(SYNC_KEY, "https://other-router.test"))).status, 401);
176
+ assert.equal((await syncCall(s, await signSync(SYNC_KEY, ORIGIN, Date.now() - 10 * 60 * 1000))).status, 401);
177
+ assert.equal((await syncCall(s, (await signSync(SYNC_KEY, ORIGIN)).replace(/^\d+/, (at) => String(Number(at) + 1)))).status, 401);
178
+ assert.equal((await syncCall({ ...s, syncKey: undefined }, await signSync(SYNC_KEY, ORIGIN))).status, 501);
179
+ assert.deepEqual(urls, []);
180
+ });
181
+
133
182
  const sourceStore = (
134
183
  channel: RemoteChannel<FakeEvent>,
135
184
  calls: string[],
@@ -142,9 +191,10 @@ const sourceStore = (
142
191
  channel: (binding) => (binding === "CHANNEL_MAIN" ? (channel as RemoteChannel) : undefined),
143
192
  outpost: async () => undefined,
144
193
  rootKey: async () => ROOT_KEY,
194
+ inbox: atOnce,
145
195
  deployer: {
146
196
  worktree: async () => undefined,
147
- run: async () => {},
197
+ run: async () => "queued",
148
198
  deploy: async (repo, source) => {
149
199
  calls.push(`deploy ${repo} ${source.ref}`);
150
200
  return { state: "deployed", ref: source.ref, at: "now" };
@@ -306,12 +356,12 @@ const runStore = (channel: RemoteChannel<FakeEvent>, deployer: Partial<RemoteDep
306
356
  deploy: async () => ({ state: "deployed", at: "now" }),
307
357
  remove: async () => {},
308
358
  worktree: async () => undefined,
309
- run: async () => {},
359
+ run: async () => "queued",
310
360
  ...deployer,
311
361
  },
312
362
  });
313
363
 
314
- test("a match whose author may start a run hands the deployer a run, with its branch, tokens and a reply ticket", async () => {
364
+ test("a match whose author may start a run hands the deployer a run, with its branch, tokens and a ticket for its thread", async () => {
315
365
  const runs: Run[] = [];
316
366
  const worktrees: unknown[] = [];
317
367
  const s = runStore(accepted(), {
@@ -319,7 +369,7 @@ test("a match whose author may start a run hands the deployer a run, with its br
319
369
  worktrees.push([repo, trigger, payload]);
320
370
  return "issue-1";
321
371
  },
322
- run: async (run) => void runs.push(run),
372
+ run: async (run) => (runs.push(run), "queued" as const),
323
373
  });
324
374
  const { body } = await call(s);
325
375
  assert.equal(runs.length, 1);
@@ -330,7 +380,7 @@ test("a match whose author may start a run hands the deployer a run, with its br
330
380
  assert.equal(run!.container, "dev");
331
381
  assert.deepEqual(run!.runtimes, ["claude"]);
332
382
  assert.deepEqual(run!.agent, { id: "coder", runtime: "claude", model: "m" });
333
- assert.deepEqual(run!.conversation, { id: "fake:acme/api", prompt: "do it" });
383
+ assert.deepEqual(run!.conversation, { id: "fake:acme/api", message: "p1" });
334
384
  assert.equal(run!.cloneToken, 'token:acme/api:{"contents":"read"}');
335
385
  assert.deepEqual(run!.tokens, [
336
386
  { policy: "code", repo: "acme/api", token: 'token:acme/api:{"contents":"write"}' },
@@ -347,7 +397,7 @@ test("a match whose author may start a run hands the deployer a run, with its br
347
397
 
348
398
  test("a worktree function that names no branch runs in a scratch worktree", async () => {
349
399
  const runs: Run[] = [];
350
- await call(runStore(accepted(), { run: async (run) => void runs.push(run) }));
400
+ await call(runStore(accepted(), { run: async (run) => (runs.push(run), "queued" as const) }));
351
401
  assert.equal(runs[0]!.worktree, undefined);
352
402
  });
353
403
 
@@ -355,7 +405,7 @@ test("a run that can't start replies with the error", async () => {
355
405
  const replies: unknown[] = [];
356
406
  const runs: Run[] = [];
357
407
  const channel = { ...accepted(), reply: async (thread: unknown, text: string) => void replies.push([thread, text]) };
358
- await call(runStore(channel, { worktree: async () => "../etc", run: async (run) => void runs.push(run) }));
408
+ await call(runStore(channel, { worktree: async () => "../etc", run: async (run) => (runs.push(run), "queued" as const) }));
359
409
  assert.equal(runs.length, 0);
360
410
  assert.equal(replies.length, 1);
361
411
  assert.match((replies[0] as string[])[1]!, /returned "\.\.\/etc", which isn't a branch name/);
@@ -363,9 +413,31 @@ test("a run that can't start replies with the error", async () => {
363
413
 
364
414
  test("a denied author starts no run", async () => {
365
415
  const runs: Run[] = [];
366
- const { body } = await call(runStore(accepted({ data: { allow: false } }), { run: async (run) => void runs.push(run) }));
416
+ const acknowledged: unknown[] = [];
417
+ const channel = { ...accepted({ data: { allow: false } }), acknowledge: async (d: Delivery<FakeEvent>) => void acknowledged.push(d.id) };
418
+ const { body } = await call(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
367
419
  assert.deepEqual(body.matches, [{ trigger: "mention", author: { result: "denied" } }]);
368
420
  assert.equal(runs.length, 0);
421
+ assert.deepEqual(acknowledged, []);
422
+ });
423
+
424
+ test("a delivery that starts a run is acknowledged once, before the run is handed to the deployer", async () => {
425
+ const events: string[] = [];
426
+ const channel = { ...accepted(), acknowledge: async (d: Delivery<FakeEvent>) => void events.push(`acknowledge ${d.id}`) };
427
+ await call(runStore(channel, { run: async () => (events.push("run"), "queued" as const) }));
428
+ assert.deepEqual(events, ["acknowledge d1", "run"]);
429
+ });
430
+
431
+ test("a run starts even if the channel can't acknowledge its delivery", async () => {
432
+ const runs: Run[] = [];
433
+ const channel = {
434
+ ...accepted(),
435
+ acknowledge: async () => {
436
+ throw new Error("no reactions");
437
+ },
438
+ };
439
+ await call(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
440
+ assert.equal(runs.length, 1);
369
441
  });
370
442
 
371
443
  const relay = (s: RouterStore, body: unknown) =>
@@ -387,6 +459,74 @@ test("relay posts a reply with a ticket the router signed through the ticket's c
387
459
  assert.equal(replies.length, 1);
388
460
  });
389
461
 
462
+ test("relay answers with the message it posted, signed, and a reply with that message replaces it", async () => {
463
+ const replies: unknown[] = [];
464
+ const channel = {
465
+ ...accepted(),
466
+ reply: async (thread: unknown, text: string, message?: string) => {
467
+ replies.push([text, message]);
468
+ return message ?? "m1";
469
+ },
470
+ };
471
+ const s = runStore(channel, {});
472
+ const ticket = { connection: "fake/main", thread: { repo: "acme/api" }, expires: Date.now() + 60_000 };
473
+ const signature = await signTicket(ROOT_KEY, ticket);
474
+
475
+ const first = await (await relay(s, { ticket, signature, text: "working" })).json();
476
+ assert.deepEqual(first, { ok: true, message: { id: "m1", signature: await signMessage(ROOT_KEY, signature, "m1") } });
477
+ assert.equal((await relay(s, { ticket, signature, text: "done", message: first.message })).status, 200);
478
+ assert.deepEqual(replies, [["working", undefined], ["done", "m1"]]);
479
+
480
+ // A run can't replace a message that it didn't post.
481
+ const other = { id: "m2", signature: first.message.signature };
482
+ assert.equal((await relay(s, { ticket, signature, text: "x", message: other })).status, 401);
483
+ const otherTicket = { ...ticket, expires: ticket.expires + 1 };
484
+ const otherSignature = await signTicket(ROOT_KEY, otherTicket);
485
+ assert.equal((await relay(s, { ticket: otherTicket, signature: otherSignature, text: "x", message: first.message })).status, 401);
486
+ assert.equal((await relay(s, { ticket, signature, text: "x", message: { id: 1 } })).status, 400);
487
+ assert.equal(replies.length, 2);
488
+ });
489
+
490
+ const readMessages = (s: RouterStore, body: unknown) =>
491
+ handle(new Request("https://router.test/messages", { method: "POST", body: JSON.stringify(body) }), s);
492
+
493
+ test("messages answers a thread's messages for a reply ticket the router signed, through the ticket's channel", async () => {
494
+ const reads: unknown[] = [];
495
+ const message = { id: "1", author: "@alice", body: "fix it", role: "write", canTrigger: true };
496
+ const channel = {
497
+ ...accepted(),
498
+ messages: async (thread: unknown) => {
499
+ reads.push(thread);
500
+ return [message];
501
+ },
502
+ };
503
+ const s = runStore(channel, {});
504
+ const ticket = { connection: "fake/main", thread: { repo: "acme/api" }, expires: Date.now() + 60_000 };
505
+ const signature = await signTicket(ROOT_KEY, ticket);
506
+
507
+ const response = await readMessages(s, { ticket, signature });
508
+ assert.equal(response.status, 200);
509
+ assert.deepEqual(await response.json(), { messages: [message] });
510
+ assert.deepEqual(reads, [{ repo: "acme/api" }]);
511
+
512
+ // A run can't read another thread.
513
+ assert.equal((await readMessages(s, { ticket: { ...ticket, thread: { repo: "acme/other" } }, signature })).status, 401);
514
+ assert.equal(reads.length, 1);
515
+ });
516
+
517
+ test("messages reports a channel that can't read the thread", async () => {
518
+ const channel = {
519
+ ...accepted(),
520
+ messages: async () => {
521
+ throw new Error("GitHub is down");
522
+ },
523
+ };
524
+ const ticket = { connection: "fake/main", thread: { repo: "acme/api" }, expires: Date.now() + 60_000 };
525
+ const response = await readMessages(runStore(channel, {}), { ticket, signature: await signTicket(ROOT_KEY, ticket) });
526
+ assert.equal(response.status, 502);
527
+ assert.deepEqual(await response.json(), { error: "GitHub is down" });
528
+ });
529
+
390
530
  const refresh = (s: RouterStore, body: unknown) =>
391
531
  handle(new Request("https://router.test/tokens", { method: "POST", body: JSON.stringify(body) }), s);
392
532
 
@@ -417,3 +557,458 @@ test("tokens refuses a container that the repo's outpost no longer has", async (
417
557
  assert.equal(response.status, 404);
418
558
  assert.match((await response.json()).error, /no container gone/);
419
559
  });
560
+
561
+ /** An inbox that keeps records in memory, by connection and id. It dispatches only when a test calls `advance`. */
562
+ const memoryInbox = () => {
563
+ const records = new Map<string, DeliveryRecord>();
564
+ const inbox: Inbox = {
565
+ receive: async (record) => {
566
+ const key = `${record.connection}/${record.id}`;
567
+ if (records.has(key)) return false;
568
+ records.set(key, structuredClone(record));
569
+ return true;
570
+ },
571
+ failed: async () => [],
572
+ replay: async () => false,
573
+ };
574
+ return { inbox, records };
575
+ };
576
+
577
+ test("with an inbox, a delivery is saved before the router answers, and a second delivery with its id is a duplicate", async () => {
578
+ const runs: Run[] = [];
579
+ const { inbox, records } = memoryInbox();
580
+ const s = { ...runStore(accepted(), { run: async (run) => (runs.push(run), "queued" as const) }), inbox };
581
+ const first = await call(s);
582
+ assert.equal(first.status, 202);
583
+ assert.deepEqual([...records.keys()], ["fake/main/d1"]);
584
+ const [record] = records.values();
585
+ assert.deepEqual(record!.dispatches, [{ trigger: "mention", run: first.body.matches[0].run, state: "pending" }]);
586
+ assert.equal(runs.length, 0);
587
+
588
+ const second = await call(s);
589
+ assert.equal(second.status, 200);
590
+ assert.equal(second.body.duplicate, true);
591
+ assert.equal(records.size, 1);
592
+
593
+ assert.equal(await advance(record!, s), undefined);
594
+ assert.equal(runs.length, 1);
595
+ assert.equal(record!.dispatches[0]!.state, "dispatched");
596
+ });
597
+
598
+ test("a delivery with no id isn't taken for a duplicate", async () => {
599
+ const { inbox, records } = memoryInbox();
600
+ const s = { ...runStore(accepted({ id: "" }), {}), inbox };
601
+ await call(s);
602
+ await call(s);
603
+ assert.equal(records.size, 2);
604
+ });
605
+
606
+ const memoryDeploys = (): NonNullable<RouterStore["deploys"]> & { saved: Map<string, unknown> } => {
607
+ const saved = new Map<string, RepoDeploy>();
608
+ return {
609
+ saved,
610
+ put: async (repo, status) => void saved.set(repo.toLowerCase(), { repo, status, builds: saved.get(repo.toLowerCase())?.builds ?? {} }),
611
+ remove: async (repo) => void saved.delete(repo.toLowerCase()),
612
+ build: async (repo, container) => saved.get(repo.toLowerCase())?.builds[container],
613
+ putBuild: async (repo, container, build) => {
614
+ const deploy = saved.get(repo.toLowerCase()) ?? { repo, status: { state: "deployed", at: "" }, builds: {} };
615
+ saved.set(repo.toLowerCase(), { ...deploy, builds: { ...deploy.builds, [container]: build } });
616
+ },
617
+ pruneBuilds: async (repo, containers) => {
618
+ const deploy = saved.get(repo.toLowerCase());
619
+ if (deploy) deploy.builds = Object.fromEntries(Object.entries(deploy.builds).filter(([c]) => containers.includes(c)));
620
+ },
621
+ list: async () => structuredClone([...saved.values()]),
622
+ repos: async () => [...saved.keys()],
623
+ };
624
+ };
625
+
626
+ const savedRecord = async (s: RouterStore) => {
627
+ const { inbox, records } = memoryInbox();
628
+ await call({ ...s, inbox });
629
+ return { record: [...records.values()][0]!, store: { ...s, inbox } };
630
+ };
631
+
632
+ test("a dispatch whose container's first image build hasn't finished waits for it, and its run replaces the waiting message", async () => {
633
+ const replies: unknown[][] = [];
634
+ const results = ["building", "building", "queued"] as const;
635
+ const runs: Run[] = [];
636
+ const channel = {
637
+ ...accepted(),
638
+ reply: async (_thread: unknown, text: string, message?: string) => {
639
+ replies.push([text, message]);
640
+ return "w1";
641
+ },
642
+ };
643
+ const { record, store } = await savedRecord(runStore(channel, { run: async (run) => (runs.push(run), results[runs.length - 1]!) }));
644
+ const start = 1_000_000;
645
+
646
+ assert.equal(await advance(record, store, start), start + BUILD_POLL_MS);
647
+ assert.deepEqual(replies, [["> Booting container `dev`...", undefined]]);
648
+
649
+ // Not due yet.
650
+ assert.equal(await advance(record, store, start + 1_000), start + BUILD_POLL_MS);
651
+ assert.equal(runs.length, 1);
652
+
653
+ assert.equal(await advance(record, store, start + BUILD_POLL_MS), start + 2 * BUILD_POLL_MS);
654
+ assert.equal(replies.length, 1);
655
+
656
+ assert.equal(await advance(record, store, start + 2 * BUILD_POLL_MS), undefined);
657
+ assert.equal(record.dispatches[0]!.state, "dispatched");
658
+ const run = runs[2]!;
659
+ assert.equal(run.id, runs[0]!.id);
660
+ assert.deepEqual(run.reply.message, { id: "w1", signature: await signMessage(ROOT_KEY, run.reply.signature, "w1") });
661
+ assert.equal(replies.length, 1);
662
+ });
663
+
664
+ test("a dispatch whose container's build fails replaces the waiting message with the build's error", async () => {
665
+ const replies: unknown[][] = [];
666
+ const channel = {
667
+ ...accepted(),
668
+ reply: async (_thread: unknown, text: string, message?: string) => {
669
+ replies.push([text, message]);
670
+ return "w1";
671
+ },
672
+ };
673
+ const deploys = memoryDeploys();
674
+ const { record, store } = await savedRecord({ ...runStore(channel, { run: async () => "building" }), deploys });
675
+ await deploys.putBuild("acme/api", "dev", { state: "in_progress", ref: "abc", url: "https://builds/1", at: "now" });
676
+ assert.equal(await advance(record, store, 0), BUILD_POLL_MS);
677
+
678
+ await deploys.putBuild("acme/api", "dev", { state: "failure", ref: "abc", url: "https://builds/1", summary: "Workers Builds: fail.", at: "now" });
679
+ assert.equal(await advance(record, store, BUILD_POLL_MS), undefined);
680
+ assert.equal(record.dispatches[0]!.state, "failed");
681
+ assert.equal(replies.length, 2);
682
+ assert.equal(replies[1]![1], "w1");
683
+ assert.match(replies[1]![0] as string, /`mention`: The first image build of container `dev` failed\. Workers Builds: fail\. The build's log: https:\/\/builds\/1/);
684
+ assert.match(replies[1]![0] as string, /`factory infra replay`/);
685
+
686
+ // A settled delivery posts nothing more.
687
+ await advance(record, store, BUILD_POLL_MS + 1);
688
+ assert.equal(replies.length, 2);
689
+ });
690
+
691
+ test("a dispatch isn't tried again while the deploy log says its container's build is queued or in progress", async () => {
692
+ const runs: Run[] = [];
693
+ const deploys = memoryDeploys();
694
+ const { record, store } = await savedRecord({
695
+ ...runStore(accepted(), { run: async (run) => (runs.push(run), runs.length === 1 ? "building" : "queued") }),
696
+ deploys,
697
+ });
698
+ await deploys.putBuild("acme/api", "dev", { state: "queued", ref: "abc", at: "now" });
699
+ assert.equal(await advance(record, store, 0), BUILD_POLL_MS);
700
+ await deploys.putBuild("acme/api", "dev", { state: "in_progress", ref: "abc", at: "now" });
701
+ assert.equal(await advance(record, store, BUILD_POLL_MS), 2 * BUILD_POLL_MS);
702
+ assert.equal(runs.length, 1);
703
+
704
+ await deploys.putBuild("acme/api", "dev", { state: "success", ref: "abc", at: "now" });
705
+ assert.equal(await advance(record, store, 2 * BUILD_POLL_MS), undefined);
706
+ assert.equal(runs.length, 2);
707
+ assert.equal(record.dispatches[0]!.state, "dispatched");
708
+ });
709
+
710
+ test("a dispatch stops waiting for a build that never reports", async () => {
711
+ const { record, store } = await savedRecord(runStore(accepted(), { run: async () => "building" }));
712
+ let now = 0;
713
+ let wake: number | undefined = 0;
714
+ while (wake !== undefined) {
715
+ now = wake;
716
+ wake = await advance(record, store, now);
717
+ }
718
+ assert.equal(now, BUILD_WAIT_MS);
719
+ assert.equal(record.dispatches[0]!.state, "failed");
720
+ assert.match(record.dispatches[0]!.error!, /didn't finish within 3 hours/);
721
+ });
722
+
723
+ test("an error from the deployer fails the dispatch without a retry, since the run may have been queued", async () => {
724
+ const replies: unknown[][] = [];
725
+ const channel = { ...accepted(), reply: async (_thread: unknown, text: string) => void replies.push([text]) };
726
+ const { record, store } = await savedRecord(
727
+ runStore(channel, {
728
+ run: async () => {
729
+ throw new Error("status 502: bad gateway");
730
+ },
731
+ }),
732
+ );
733
+ assert.equal(await advance(record, store, 0), undefined);
734
+ assert.equal(record.dispatches[0]!.state, "failed");
735
+ assert.equal(replies.length, 1);
736
+ assert.deepEqual(failedDelivery(record, 5)?.triggers, [{ trigger: "mention", error: "status 502: bad gateway" }]);
737
+ });
738
+
739
+ test("each failed trigger of a delivery replaces its own waiting message", async () => {
740
+ const replies: unknown[][] = [];
741
+ let posted = 0;
742
+ const channel = {
743
+ ...accepted(),
744
+ reply: async (_thread: unknown, text: string, message?: string) => {
745
+ replies.push([text, message]);
746
+ return message ?? `w${++posted}`;
747
+ },
748
+ };
749
+ const twoTriggers: OutpostConfig = {
750
+ ...runOutpost,
751
+ triggers: { mention: runOutpost.triggers.mention!, again: runOutpost.triggers.mention! },
752
+ };
753
+ const s: RouterStore = { ...runStore(channel, { run: async () => "building" }), outpost: async () => twoTriggers };
754
+ const { record, store } = await savedRecord(s);
755
+ await advance(record, store, 0);
756
+ assert.equal(replies.length, 2);
757
+ const waiting = Object.fromEntries(record.dispatches.map((d) => [d.trigger, d.waiting]));
758
+ assert.deepEqual(Object.values(waiting).sort(), ["w1", "w2"]);
759
+ store.outpost = async () => ({ ...twoTriggers, triggers: {} });
760
+ await advance(record, store, BUILD_POLL_MS);
761
+ const notices = Object.fromEntries(replies.slice(2).map(([text, message]) => [(text as string).match(/`(\w+)`/)![1], message]));
762
+ assert.deepEqual(notices, waiting);
763
+ });
764
+
765
+ test("a failed dispatch posts its notice without waiting for a sibling that waits for a build", async () => {
766
+ const replies: string[] = [];
767
+ const channel = { ...accepted(), reply: async (_thread: unknown, text: string) => void replies.push(text) };
768
+ const twoTriggers: OutpostConfig = {
769
+ ...runOutpost,
770
+ triggers: { mention: runOutpost.triggers.mention!, other: { ...runOutpost.triggers.mention!, container: "missing" } },
771
+ };
772
+ const s: RouterStore = { ...runStore(channel, { run: async () => "building" }), outpost: async () => twoTriggers };
773
+ const { record, store } = await savedRecord(s);
774
+ assert.equal(await advance(record, store, 0), BUILD_POLL_MS);
775
+ assert.deepEqual(record.dispatches.map((d) => d.state).sort(), ["failed", "pending"]);
776
+ assert.ok(replies.some((text) => text.includes("`other`")));
777
+ });
778
+
779
+ test("a replay dispatches the failed triggers again as new runs, against the outpost config the repo has now", async () => {
780
+ const runs: Run[] = [];
781
+ let ok = false;
782
+ const outposts: Record<string, OutpostConfig> = { "acme/api": runOutpost };
783
+ const s: RouterStore = {
784
+ ...runStore(accepted(), {
785
+ run: async (run) => {
786
+ runs.push(run);
787
+ if (!ok) throw new Error("refused");
788
+ return "queued";
789
+ },
790
+ }),
791
+ outpost: async (repo) => outposts[repo],
792
+ };
793
+ const { record, store } = await savedRecord(s);
794
+ await advance(record, store, 0);
795
+ const failedRun = record.dispatches[0]!.run;
796
+ assert.equal(record.dispatches[0]!.state, "failed");
797
+
798
+ ok = true;
799
+ assert.equal(replayRecord(record, "https://router.new"), true);
800
+ await advance(record, store, 1);
801
+ assert.equal(record.dispatches[0]!.state, "dispatched");
802
+ assert.notEqual(runs[1]!.id, failedRun);
803
+ assert.equal(runs[1]!.reply.url, "https://router.new/relay");
804
+ assert.equal(replayRecord(record, "https://router.new"), false);
805
+
806
+ // A trigger that the outpost no longer has fails.
807
+ outposts["acme/api"] = { ...runOutpost, triggers: {} };
808
+ record.dispatches[0]!.state = "failed";
809
+ replayRecord(record, "https://router.new");
810
+ await advance(record, store, 2);
811
+ assert.equal(record.dispatches[0]!.state, "failed");
812
+ assert.match(record.dispatches[0]!.error!, /no longer has the trigger `mention`/);
813
+ assert.equal(runs.length, 2);
814
+ });
815
+
816
+ const adminStore = (channel: RemoteChannel<FakeEvent>, calls: string[] = []): RouterStore => ({
817
+ ...sourceStore(channel, calls),
818
+ config: {
819
+ // Operator auth signs in through a connection of its own provider.
820
+ connections: { "fake/main": entry("CHANNEL_MAIN"), "github/main": { ...entry("CHANNEL_MAIN"), provider: "github" } },
821
+ codeHost: { provider: "fake", connection: "main", allow: [{ owner: "acme" }] },
822
+ operators: { provider: "github", connection: "main", users: ["Alice"] },
823
+ },
824
+ channel: (binding) => (binding === "CHANNEL_MAIN" ? (channel as RemoteChannel) : undefined),
825
+ });
826
+
827
+ const adminCall = async (s: RouterStore, method: string, path: string, { body, session }: { body?: unknown; session?: string } = {}) => {
828
+ const response = await handle(
829
+ new Request(`https://router.test${path}`, {
830
+ method,
831
+ ...(body !== undefined && { body: JSON.stringify(body) }),
832
+ ...(session && { headers: { authorization: `Bearer ${session}` } }),
833
+ }),
834
+ s,
835
+ );
836
+ return { status: response.status, body: await response.json() };
837
+ };
838
+
839
+ const adminChannel = () => sourceChannel([], []);
840
+
841
+ test("an operator signs in through the operator auth's channel, and gets a session that the admin routes take", async () => {
842
+ const s = adminStore(adminChannel());
843
+ const signIn = await adminCall(s, "POST", "/admin/sign-in", { body: { state: "s1" } });
844
+ assert.equal(signIn.status, 200);
845
+ assert.equal(signIn.body.url, "https://sign-in.test/?state=s1");
846
+ assert.equal((await adminCall(s, "POST", "/admin/sign-in")).status, 400);
847
+
848
+ const signed = await adminCall(s, "POST", "/admin/session", { body: { code: "code-alice-1" } });
849
+ assert.equal(signed.status, 200);
850
+ assert.equal(signed.body.operator, "alice");
851
+ assert.ok(signed.body.expires > Date.now());
852
+ assert.equal((await verifySession(ROOT_KEY, signed.body.session))?.login, "alice");
853
+ assert.equal(signed.body.session.split(".").slice(0, 3).join("."), `alice.1.${signed.body.expires}`);
854
+ // A token whose operator or expiry is changed fails its signature.
855
+ assert.equal(await verifySession(ROOT_KEY, signed.body.session.replace(/^alice\.1\.\d+/, `alice.1.${signed.body.expires + 1}`)), undefined);
856
+ assert.equal(await verifySession(ROOT_KEY, signed.body.session.replace(/^alice\.1\./, "alice.2.")), undefined);
857
+
858
+ assert.equal((await adminCall(s, "GET", "/admin/deliveries", { session: signed.body.session })).status, 200);
859
+ assert.equal((await adminCall(s, "GET", "/admin/deliveries")).status, 401);
860
+ assert.equal((await adminCall(s, "GET", "/admin/deliveries", { session: `${signed.body.session}0` })).status, 401);
861
+ });
862
+
863
+ test("a sign-in by someone outside the operator auth gets no session", async () => {
864
+ const s = adminStore(adminChannel());
865
+ const { status, body } = await adminCall(s, "POST", "/admin/session", { body: { code: "code-mallory" } });
866
+ assert.equal(status, 403);
867
+ assert.equal(body.session, undefined);
868
+ });
869
+
870
+ test("an operator listed by account id signs in under any login, and a login of digits is not an id", async () => {
871
+ const s = adminStore(adminChannel());
872
+ s.config.operators = { provider: "github", connection: "main", users: [7, "8"] };
873
+ assert.equal((await adminCall(s, "POST", "/admin/session", { body: { code: "code-renamed-7" } })).status, 200);
874
+ assert.equal((await adminCall(s, "POST", "/admin/session", { body: { code: "code-mallory-8" } })).status, 403);
875
+ // A session keeps working after its operator's rename, since the id still matches.
876
+ const session = await signSession(ROOT_KEY, { login: "old-name", id: "7", expires: Date.now() + 60_000 });
877
+ assert.equal((await adminCall(s, "GET", "/admin/deliveries", { session })).status, 200);
878
+ });
879
+
880
+ test("a session keeps a login with dots in it", async () => {
881
+ const session = await signSession(ROOT_KEY, { login: "a.b", id: "1.5", expires: Date.now() + 60_000 });
882
+ assert.equal(session.split(".").length, 4);
883
+ const found = await verifySession(ROOT_KEY, session);
884
+ assert.equal(found?.login, "a.b");
885
+ assert.equal(found?.id, "1.5");
886
+ });
887
+
888
+ test("a session stops working when it expires, or when its operator leaves the operator auth", async () => {
889
+ const s = adminStore(adminChannel());
890
+ const expired = await signSession(ROOT_KEY, { login: "alice", id: "1", expires: Date.now() - 1 });
891
+ assert.equal((await adminCall(s, "GET", "/admin/deliveries", { session: expired })).status, 401);
892
+ const session = await signSession(ROOT_KEY, { login: "alice", id: "1", expires: Date.now() + 60_000 });
893
+ s.config.operators = { provider: "github", connection: "main", users: ["bob"] };
894
+ assert.equal((await adminCall(s, "GET", "/admin/deliveries", { session })).status, 401);
895
+ });
896
+
897
+ test("a deploy is logged with a queued build for each container it builds, and build reports update the build", async () => {
898
+ const calls: string[] = [];
899
+ const deploys = memoryDeploys();
900
+ await deploys.putBuild("acme/api", "ci", { state: "success", ref: "old", at: "then" });
901
+ const s: RouterStore = { ...sourceStore(sourceChannel([{ repo: "acme/api", ref: "abc" }], calls), calls), deploys };
902
+ s.deployer!.deploy = async (_repo, source) => ({ state: "deployed", ref: source.ref, at: "now", builds: ["dev"] });
903
+ await call(s);
904
+ assert.deepEqual(await deploys.list(), [
905
+ {
906
+ repo: "acme/api",
907
+ status: { state: "deployed", ref: "abc", at: "now", builds: ["dev"] },
908
+ // A container that this deploy didn't build keeps its last build.
909
+ builds: { ci: { state: "success", ref: "old", at: "then" }, dev: { state: "queued", ref: "abc", at: "now" } },
910
+ },
911
+ ]);
912
+
913
+ const report = { repo: "acme/api", ref: "abc", container: "dev", state: "success" as const, url: "https://dash.test/b", expires: Date.now() + 60_000 };
914
+ await buildReport(s, { report, signature: await signBuildReport(ROOT_KEY, report) });
915
+ const build = (await deploys.build("acme/api", "dev"))!;
916
+ assert.equal(build.state, "success");
917
+ assert.equal(build.url, "https://dash.test/b");
918
+ });
919
+
920
+ test("a late report of an older commit's build doesn't replace the newer build in the log", async () => {
921
+ const deploys = memoryDeploys();
922
+ const s: RouterStore = { ...sourceStore(sourceChannel([], []), []), deploys };
923
+ await deploys.putBuild("acme/api", "dev", { state: "queued", ref: "new", at: "now" });
924
+ const old = { repo: "acme/api", ref: "old", container: "dev", state: "failure" as const, expires: Date.now() + 60_000 };
925
+ assert.equal((await buildReport(s, { report: old, signature: await signBuildReport(ROOT_KEY, old) })).status, 200);
926
+ assert.deepEqual(await deploys.build("acme/api", "dev"), { state: "queued", ref: "new", at: "now" });
927
+
928
+ const current = { ...old, ref: "new", state: "success" as const };
929
+ await buildReport(s, { report: current, signature: await signBuildReport(ROOT_KEY, current) });
930
+ assert.equal((await deploys.build("acme/api", "dev"))?.state, "success");
931
+ await buildReport(s, { report: old, signature: await signBuildReport(ROOT_KEY, old) });
932
+ assert.equal((await deploys.build("acme/api", "dev"))?.state, "success");
933
+ });
934
+
935
+ test("a deploy drops the logged builds of containers that the outpost no longer has", async () => {
936
+ const deploys = memoryDeploys();
937
+ await deploys.putBuild("acme/api", "ci", { state: "success", ref: "old", at: "then" });
938
+ await deploys.putBuild("acme/api", "gone", { state: "success", ref: "old", at: "then" });
939
+ const s: RouterStore = { ...sourceStore(sourceChannel([{ repo: "acme/api", ref: "abc" }], []), []), deploys };
940
+ s.outpost = async () => ({ ...runOutpost, containers: { ci: runOutpost.containers.dev! } });
941
+ await call(s);
942
+ assert.deepEqual(Object.keys((await deploys.list())[0]!.builds), ["ci"]);
943
+ });
944
+
945
+ test("repos lists each repo's last deploy with its builds", async () => {
946
+ const deploys = memoryDeploys();
947
+ await deploys.put("acme/web", { state: "failed", error: "bad", at: "then" });
948
+ await deploys.put("acme/api", { state: "deployed", ref: "abc", at: "now" });
949
+ await deploys.putBuild("acme/api", "dev", { state: "success", ref: "abc", at: "now" });
950
+ const s: RouterStore = { ...adminStore(adminChannel()), deploys };
951
+ const session = await signSession(ROOT_KEY, { login: "alice", id: "1", expires: Date.now() + 60_000 });
952
+ const { status, body } = await adminCall(s, "GET", "/admin/repos", { session });
953
+ assert.equal(status, 200);
954
+ assert.deepEqual(body.repos.map((r: RepoDeploy) => [r.repo, Object.keys(r.builds)]), [
955
+ ["acme/api", ["dev"]],
956
+ ["acme/web", []],
957
+ ]);
958
+ });
959
+
960
+ test("sync deploys every repo that the code host can read and allows, one at a time, and removes the outposts of the others", async () => {
961
+ const calls: string[] = [];
962
+ const deploys = memoryDeploys();
963
+ await deploys.put("acme/gone", { state: "deployed", at: "then" });
964
+ const channel = sourceChannel([], calls);
965
+ channel.repos = async () => ["acme/api", "other/api"];
966
+ const s: RouterStore = { ...sourceStore(channel, calls), deploys, syncKey: async () => SYNC_KEY };
967
+ const { status } = await syncCall(s, await signSync(SYNC_KEY, ORIGIN));
968
+ assert.equal(status, 200);
969
+ assert.deepEqual(calls.sort(), ["deploy acme/api head", "read acme/api .factory undefined", "remove acme/gone", "status acme/api deployed"]);
970
+ assert.deepEqual([...deploys.saved.keys()], ["acme/api"]);
971
+ });
972
+
973
+ test("sync hands the repos' deploys to the store's queue, where it has one", async () => {
974
+ const calls: string[] = [];
975
+ const queued: unknown[] = [];
976
+ const channel = sourceChannel([], calls);
977
+ channel.repos = async () => ["acme/api"];
978
+ const s: RouterStore = { ...sourceStore(channel, calls), syncKey: async () => SYNC_KEY, queueDeploys: async (changes) => void queued.push(changes) };
979
+ assert.equal((await syncCall(s, await signSync(SYNC_KEY, ORIGIN))).status, 200);
980
+ assert.deepEqual(queued, [[{ repo: "acme/api" }]]);
981
+ assert.deepEqual(calls, []);
982
+ });
983
+
984
+ test("sync answers before the repos' deploys finish, where the platform allows it", async () => {
985
+ const calls: string[] = [];
986
+ const tasks: Promise<unknown>[] = [];
987
+ const channel = sourceChannel([], calls);
988
+ channel.repos = async () => ["acme/api"];
989
+ const s: RouterStore = { ...sourceStore(channel, calls), syncKey: async () => SYNC_KEY, background: (task) => void tasks.push(task) };
990
+ assert.equal((await syncCall(s, await signSync(SYNC_KEY, ORIGIN))).status, 200);
991
+ assert.equal(tasks.length, 1);
992
+ await tasks[0];
993
+ assert.ok(calls.includes("deploy acme/api head"));
994
+ });
995
+
996
+ test("replay replays one failed delivery, or all of them, against the router's origin", async () => {
997
+ const replays: string[] = [];
998
+ const inbox: Inbox = {
999
+ receive: async () => true,
1000
+ failed: async () => [
1001
+ { connection: "fake/main", id: "d1", repo: "acme/api", event: "post", received: 1, failed: 2, triggers: [] },
1002
+ { connection: "fake/main", id: "d2", repo: "acme/api", event: "post", received: 1, failed: 2, triggers: [] },
1003
+ ],
1004
+ replay: async (connection, id, origin) => (replays.push(`${connection}/${id} ${origin}`), id === "d1"),
1005
+ };
1006
+ const s: RouterStore = { ...adminStore(adminChannel()), inbox };
1007
+ const session = await signSession(ROOT_KEY, { login: "alice", id: "1", expires: Date.now() + 60_000 });
1008
+ const one = await adminCall(s, "POST", "/admin/replay", { session, body: { connection: "fake/main", id: "d1" } });
1009
+ assert.deepEqual(one.body, { replayed: [{ connection: "fake/main", id: "d1" }], skipped: [] });
1010
+ const all = await adminCall(s, "POST", "/admin/replay", { session, body: {} });
1011
+ assert.deepEqual(all.body, { replayed: [{ connection: "fake/main", id: "d1" }], skipped: [{ connection: "fake/main", id: "d2" }] });
1012
+ assert.deepEqual(replays, ["fake/main/d1 https://router.test", "fake/main/d1 https://router.test", "fake/main/d2 https://router.test"]);
1013
+ assert.equal((await adminCall(s, "POST", "/admin/replay", { session, body: { id: "d1" } })).status, 400);
1014
+ });