@notation/factory 0.5.4 → 0.6.0

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.
@@ -10,10 +10,17 @@ const containerConfig = v.object({
10
10
  */
11
11
  image: v.optional(v.string()),
12
12
  /**
13
- * The size of the machine, in the provider's names, such as Cloudflare's
14
- * `standard-2`. Without it, the provider picks its default.
13
+ * The size of the machine: one of the provider's names, such as
14
+ * Cloudflare's `standard-2`, or its resources, such as
15
+ * `{ vcpu: 2, memoryMib: 10240, diskMb: 16000 }`. Without it, the
16
+ * provider picks its default.
15
17
  */
16
- instanceType: v.optional(v.string()),
18
+ instanceType: v.optional(
19
+ v.union([
20
+ v.string(),
21
+ v.strictObject({ vcpu: v.number(), memoryMib: v.number(), diskMb: v.number() }),
22
+ ]),
23
+ ),
17
24
  runtimes: v.optional(
18
25
  v.array(
19
26
  v.custom<Runtime>(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
package/router/channel.ts CHANGED
@@ -114,8 +114,12 @@ interface ChannelBase<E> {
114
114
  writeStatus?(repo: string, status: FactoryStatus): Promise<void>;
115
115
  /** For a code host's channel: creates or updates the check named `check.name` on commit `ref`. */
116
116
  writeCheck?(repo: string, ref: string, check: BuildCheck): Promise<void>;
117
- /** Shows on the delivery's post that a run is starting for it, such as with GitHub's 👀 reaction. */
118
- acknowledge?(delivery: Delivery<E>): Promise<void>;
117
+ /**
118
+ * Shows on the delivery's post that a run is starting for it, such as with
119
+ * GitHub's 👀 reaction. `selectors` are those of the triggers that start
120
+ * runs for it.
121
+ */
122
+ acknowledge?(delivery: Delivery<E>, selectors: unknown[]): Promise<void>;
119
123
  /**
120
124
  * Posts `text` to a conversation's thread, or replaces the text of
121
125
  * `message`, a message that an earlier reply to the thread posted.
@@ -127,13 +131,19 @@ interface ChannelBase<E> {
127
131
  /** For a code host's channel: every repo that the hub can read, as `owner/name`. */
128
132
  repos?(): Promise<string[]>;
129
133
  /**
130
- * For operator sign-in through the channel's platform: the page that
131
- * signs the operator in, and then sends the browser to the CLI's callback
132
- * with a code and `state`.
134
+ * For sign-in through the channel's platform: the page that signs a person
135
+ * in, and then sends the browser to `redirect` with a code and `state`.
136
+ * Without `redirect`, the browser goes to the CLI's callback, for operator
137
+ * sign-in.
138
+ */
139
+ signInUrl?(state: string, redirect?: string): Promise<string>;
140
+ /** For sign-in: exchanges the code that the callback at `redirect` got for the person's identity. */
141
+ signIn?(code: string, redirect?: string): Promise<Operator>;
142
+ /**
143
+ * Whether `selector`'s `from` lets `person`, who signed in with `signIn`,
144
+ * start a run for the delivery. The restart link of a lost run checks it.
133
145
  */
134
- signInUrl?(state: string): Promise<string>;
135
- /** For operator sign-in: exchanges the code that the callback got for the operator's identity. */
136
- signIn?(code: string): Promise<Operator>;
146
+ canTrigger?(selector: unknown, delivery: Delivery<E>, person: Operator): Promise<boolean>;
137
147
  }
138
148
 
139
149
  /** A channel that starts runs has both `conversation` and `messages`. A channel without them can't start runs. */
@@ -1,4 +1,5 @@
1
1
  import type { Delivery } from "./channel.ts";
2
+ import { LOST_AFTER_MS } from "./run.ts";
2
3
 
3
4
  /** How often the router tries again a dispatch whose container's first image build hasn't finished. */
4
5
  export const BUILD_POLL_MS = 30_000;
@@ -15,12 +16,14 @@ export const KEEP_DELIVERY_MS = 7 * 24 * 60 * 60 * 1000;
15
16
 
16
17
  /**
17
18
  * One matched trigger's run, as the router hands it to the deployer.
18
- * `pending` dispatches are tried at `next`, or at once without it.
19
+ * `pending` dispatches are tried at `next`, or at once without it. A
20
+ * `dispatched` run that stops sending heartbeats becomes `lost`. A restart
21
+ * gives a lost dispatch a new run id, so the old run counts as lost too.
19
22
  */
20
23
  export type TriggerDispatch = {
21
24
  trigger: string;
22
25
  run: string;
23
- state: "pending" | "dispatched" | "failed";
26
+ state: "pending" | "dispatched" | "failed" | "lost";
24
27
  /** When the dispatch started to wait for its container's first image build. */
25
28
  since?: number;
26
29
  next?: number;
@@ -29,11 +32,54 @@ export type TriggerDispatch = {
29
32
  thread?: unknown;
30
33
  /**
31
34
  * The id of the message that shows on the thread while the dispatch waits
32
- * for the build. The run's first reply, or the failure notice, replaces it.
35
+ * for the build, or the lost notice of a lost run. The run's first reply,
36
+ * or the failure notice, replaces it.
33
37
  */
34
38
  waiting?: string;
35
39
  };
36
40
 
41
+ /**
42
+ * A run's last heartbeat, which the inbox keeps apart from its record.
43
+ * `at` is in ms since the epoch. `message` is the id of the message that
44
+ * the run's replies replace, which the lost notice replaces too. A run that
45
+ * finished keeps `{ done: true }`, so that a heartbeat that arrives after
46
+ * its last one doesn't have the router watch it again.
47
+ */
48
+ export type Watch = { at: number; message?: string } | { done: true };
49
+
50
+ /**
51
+ * Whether the run `run` of `record` is lost: the router marked it lost, or
52
+ * a restart replaced it with a new run, so the record no longer has it.
53
+ * Without a record, the router knows nothing of the run.
54
+ */
55
+ export const isLost = (record: DeliveryRecord | undefined, run: string) => {
56
+ if (!record) return false;
57
+ const dispatch = record.dispatches.find((d) => d.run === run);
58
+ return dispatch === undefined || dispatch.state === "lost";
59
+ };
60
+
61
+ /**
62
+ * What a heartbeat of `run` does to the run's watch `current`. Resolves to
63
+ * `unknown` if there's no record, and to `lost` if the run is lost. `watch`
64
+ * is the run's new watch, if it changes: the first heartbeat starts it, a
65
+ * heartbeat with `done`, or of a run that failed, marks the run done, and a
66
+ * heartbeat of a done run changes nothing.
67
+ */
68
+ export const heartbeatWatch = (
69
+ record: DeliveryRecord | undefined,
70
+ run: string,
71
+ current: Watch | undefined,
72
+ beat: { message?: string; done?: boolean },
73
+ now: number,
74
+ ): { result: "ok" | "lost" | "unknown"; watch?: Watch } => {
75
+ if (!record) return { result: "unknown" };
76
+ if (isLost(record, run)) return { result: "lost" };
77
+ const dispatch = record.dispatches.find((d) => d.run === run)!;
78
+ if (current && "done" in current) return { result: "ok" };
79
+ if (beat.done || dispatch.state === "failed") return { result: "ok", watch: { done: true } };
80
+ return { result: "ok", watch: { at: now, ...(beat.message && { message: beat.message }) } };
81
+ };
82
+
37
83
  /**
38
84
  * A verified delivery that matched triggers whose authors may start runs,
39
85
  * as the router saves it. `id` is the delivery's id, or a random id if the
@@ -79,14 +125,53 @@ export type Inbox = {
79
125
  * to false if the inbox has no such failed delivery.
80
126
  */
81
127
  replay(connection: string, id: string, origin: string): Promise<boolean>;
128
+ /**
129
+ * Notes a heartbeat of the run `run` of a delivery, or with `done`, stops
130
+ * watching the run. See `heartbeatWatch`. Resolves to `unknown` if the
131
+ * inbox has no such delivery, and to `lost` if the run is lost.
132
+ */
133
+ heartbeat(connection: string, id: string, run: string, beat: { message?: string; done?: boolean }): Promise<"ok" | "lost" | "unknown">;
134
+ /** The delivery with this connection and id, if the inbox has it. */
135
+ record(connection: string, id: string): Promise<DeliveryRecord | undefined>;
136
+ /**
137
+ * Dispatches the lost run `run` of a delivery again, as a new run that
138
+ * replies to `origin`. Resolves to false if the delivery has no such lost
139
+ * run, such as when someone restarted it already.
140
+ */
141
+ restart(connection: string, id: string, run: string, origin: string): Promise<boolean>;
82
142
  };
83
143
 
84
144
  /** Whether a record has no dispatch left to try. */
85
145
  export const settled = (record: DeliveryRecord) => record.dispatches.every((d) => d.state !== "pending");
86
146
 
87
- /** The record as an operator lists it, if one of its dispatches failed. */
147
+ /** When to try the record's pending dispatches next, if it has any. A dispatch without `next` is due at `now`. */
148
+ export const nextTry = (record: DeliveryRecord, now: number) => {
149
+ const pending = record.dispatches.filter((d) => d.state === "pending");
150
+ return pending.length ? Math.min(...pending.map((d) => d.next ?? now)) : undefined;
151
+ };
152
+
153
+ /**
154
+ * The record to save once the inbox's alarm has changed `changed`, whose
155
+ * dispatches it read as the JSON in `read`, when a restart or replay may
156
+ * have saved `stored` in the meantime. Each dispatch that the alarm changed
157
+ * comes from `changed`, and the others from `stored`. The alarm changes only
158
+ * pending and dispatched dispatches, and a restart or replay only failed and
159
+ * lost ones, so they never change the same dispatch.
160
+ */
161
+ export const mergeRecord = (read: string[], changed: DeliveryRecord, stored: DeliveryRecord): DeliveryRecord => ({
162
+ ...stored,
163
+ ...(changed.acknowledged && { acknowledged: true }),
164
+ dispatches: stored.dispatches.map((d, i) => {
165
+ const mine = changed.dispatches[i]!;
166
+ return JSON.stringify(mine) === read[i] ? d : mine;
167
+ }),
168
+ });
169
+
170
+ const isFailed = (d: TriggerDispatch) => d.state === "failed" || d.state === "lost";
171
+
172
+ /** The record as an operator lists it, if one of its dispatches failed or was lost. */
88
173
  export const failedDelivery = (record: DeliveryRecord, now: number): FailedDelivery | undefined => {
89
- const failed = record.dispatches.filter((d) => d.state === "failed");
174
+ const failed = record.dispatches.filter(isFailed);
90
175
  if (!failed.length) return undefined;
91
176
  return {
92
177
  connection: record.connection,
@@ -99,16 +184,20 @@ export const failedDelivery = (record: DeliveryRecord, now: number): FailedDeliv
99
184
  };
100
185
  };
101
186
 
102
- /** Sets a record's failed dispatches to be tried again, each as a new run. Resolves to false if none failed. */
103
- export const replayRecord = (record: DeliveryRecord, origin: string) => {
104
- const failed = record.dispatches.filter((d) => d.state === "failed");
187
+ /**
188
+ * Sets a record's failed and lost dispatches to be tried again, each as a
189
+ * new run, or with `run`, only that lost run. Resolves to false if there was
190
+ * none. A lost run's new run replaces the lost notice.
191
+ */
192
+ export const replayRecord = (record: DeliveryRecord, origin: string, run?: string) => {
193
+ const failed = record.dispatches.filter((d) => (run === undefined ? isFailed(d) : d.run === run && d.state === "lost"));
105
194
  if (!failed.length) return false;
106
195
  for (const dispatch of failed) {
196
+ if (dispatch.state !== "lost") delete dispatch.waiting;
107
197
  Object.assign(dispatch, { state: "pending", run: crypto.randomUUID() });
108
198
  delete dispatch.since;
109
199
  delete dispatch.next;
110
200
  delete dispatch.error;
111
- delete dispatch.waiting;
112
201
  }
113
202
  record.origin = origin;
114
203
  return true;
@@ -122,5 +211,17 @@ export const failureNotice = (failed: TriggerDispatch) =>
122
211
  `Couldn't start the run of trigger \`${failed.trigger}\`: ${failed.error ?? "no reason given"}\n\n` +
123
212
  `Factory kept the event. An operator can run \`${REPLAY_COMMAND}\` to start the run again.`;
124
213
 
214
+ /** Why a lost dispatch failed, as operators list it. */
215
+ export const LOST_ERROR = `The run sent no heartbeat for ${LOST_AFTER_MS / 60_000} minutes.`;
216
+
217
+ /**
218
+ * The message that replaces a lost run's message on the thread. `restart`
219
+ * is the link that restarts the run.
220
+ */
221
+ export const lostNotice = (restart: string) =>
222
+ `This run sent no heartbeat for ${LOST_AFTER_MS / 60_000} minutes, so Factory marked it as lost. Its container may have stopped or run out of memory.\n\n` +
223
+ `[Restart the run](${restart}), or mention the agent again. The link works for ${KEEP_DELIVERY_MS / 86_400_000} days, for anyone who may trigger the agent. ` +
224
+ "A new run starts from the worktree and session as this run last saved them, up to a minute before it was lost.";
225
+
125
226
  /** The message that shows on the thread while a dispatch waits for its container's first image build. */
126
227
  export const waitingNotice = (container: string) => `> Booting container \`${container}\`...`;
@@ -2,10 +2,23 @@ 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 { BUILD_POLL_MS, BUILD_WAIT_MS, type DeliveryRecord, failedDelivery, type Inbox, replayRecord } from "./deliveries.ts";
5
+ import {
6
+ BUILD_POLL_MS,
7
+ BUILD_WAIT_MS,
8
+ type DeliveryRecord,
9
+ failedDelivery,
10
+ heartbeatWatch,
11
+ type Inbox,
12
+ LOST_ERROR,
13
+ lostNotice,
14
+ mergeRecord,
15
+ nextTry,
16
+ replayRecord,
17
+ type Watch,
18
+ } from "./deliveries.ts";
6
19
  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";
20
+ import { advance, handle, type RemoteDeployer, type RouterStore, watch } from "./handle.ts";
21
+ import { LOST_AFTER_MS, type Run, signBuildReport, signMessage, signRestart, signTicket, signTokenTicket } from "./run.ts";
9
22
  import { SYNC_HEADER, signSync } from "./sync.ts";
10
23
 
11
24
  const ROOT_KEY = "root";
@@ -33,12 +46,14 @@ const fake = (
33
46
  reply: async () => undefined,
34
47
  token: async (repo, permissions) => `token:${repo}:${JSON.stringify(permissions)}`,
35
48
  repos: async () => [],
36
- signInUrl: async (state) => `https://sign-in.test/?state=${state}`,
49
+ signInUrl: async (state, redirect) => `https://sign-in.test/?state=${encodeURIComponent(state)}${redirect ? `&redirect=${redirect}` : ""}`,
37
50
  // A code of `code-<login>-<id>` signs in as that user.
38
51
  signIn: async (code) => {
39
52
  const [login = "", id = "0"] = code.replace(/^code-/, "").split("-");
40
53
  return { login, id };
41
54
  },
55
+ // Only alice may trigger the agent.
56
+ canTrigger: async (_selector, _delivery, person) => person.login === "alice",
42
57
  });
43
58
 
44
59
  const accepted = (over: Partial<Delivery<FakeEvent>> = {}) =>
@@ -83,6 +98,9 @@ const atOnce: Inbox = {
83
98
  receive: async (record) => (await advance(record, calling), true),
84
99
  failed: async () => [],
85
100
  replay: async () => false,
101
+ heartbeat: async () => "unknown",
102
+ record: async () => undefined,
103
+ restart: async () => false,
86
104
  };
87
105
 
88
106
  const entry = (channel: string) => ({ provider: "fake", source: "1", credentials: {}, channel });
@@ -428,6 +446,13 @@ test("a delivery that starts a run is acknowledged once, before the run is hande
428
446
  assert.deepEqual(events, ["acknowledge d1", "run"]);
429
447
  });
430
448
 
449
+ test("acknowledge gets the selectors of the triggers that start runs", async () => {
450
+ const selectors: unknown[] = [];
451
+ const channel = { ...accepted(), acknowledge: async (_: Delivery<FakeEvent>, s: unknown[]) => void selectors.push(s) };
452
+ await call(runStore(channel, {}));
453
+ assert.deepEqual(selectors, [[{ pick: true }]]);
454
+ });
455
+
431
456
  test("a run starts even if the channel can't acknowledge its delivery", async () => {
432
457
  const runs: Run[] = [];
433
458
  const channel = {
@@ -561,6 +586,7 @@ test("tokens refuses a container that the repo's outpost no longer has", async (
561
586
  /** An inbox that keeps records in memory, by connection and id. It dispatches only when a test calls `advance`. */
562
587
  const memoryInbox = () => {
563
588
  const records = new Map<string, DeliveryRecord>();
589
+ const watches = new Map<string, Watch>();
564
590
  const inbox: Inbox = {
565
591
  receive: async (record) => {
566
592
  const key = `${record.connection}/${record.id}`;
@@ -570,8 +596,18 @@ const memoryInbox = () => {
570
596
  },
571
597
  failed: async () => [],
572
598
  replay: async () => false,
599
+ heartbeat: async (connection, id, run, beat) => {
600
+ const { result, watch } = heartbeatWatch(records.get(`${connection}/${id}`), run, watches.get(run), beat, Date.now());
601
+ if (watch) watches.set(run, watch);
602
+ return result;
603
+ },
604
+ record: async (connection, id) => records.get(`${connection}/${id}`),
605
+ restart: async (connection, id, run, origin) => {
606
+ const record = records.get(`${connection}/${id}`);
607
+ return record ? replayRecord(record, origin, run) : false;
608
+ },
573
609
  };
574
- return { inbox, records };
610
+ return { inbox, records, watches };
575
611
  };
576
612
 
577
613
  test("with an inbox, a delivery is saved before the router answers, and a second delivery with its id is a duplicate", async () => {
@@ -624,9 +660,9 @@ const memoryDeploys = (): NonNullable<RouterStore["deploys"]> & { saved: Map<str
624
660
  };
625
661
 
626
662
  const savedRecord = async (s: RouterStore) => {
627
- const { inbox, records } = memoryInbox();
663
+ const { inbox, records, watches } = memoryInbox();
628
664
  await call({ ...s, inbox });
629
- return { record: [...records.values()][0]!, store: { ...s, inbox } };
665
+ return { record: [...records.values()][0]!, store: { ...s, inbox }, watches };
630
666
  };
631
667
 
632
668
  test("a dispatch whose container's first image build hasn't finished waits for it, and its run replaces the waiting message", async () => {
@@ -813,6 +849,265 @@ test("a replay dispatches the failed triggers again as new runs, against the out
813
849
  assert.equal(runs.length, 2);
814
850
  });
815
851
 
852
+ const beat = (s: RouterStore, body: unknown) =>
853
+ handle(new Request("https://router.test/heartbeat", { method: "POST", body: JSON.stringify(body) }), s);
854
+
855
+ test("a run's ticket names its dispatch, and its heartbeats note the message that its replies replace", async () => {
856
+ const runs: Run[] = [];
857
+ const { record, store, watches } = await savedRecord(runStore(accepted(), { run: async (run) => (runs.push(run), "queued" as const) }));
858
+ await advance(record, store);
859
+ const { reply, id } = runs[0]!;
860
+ assert.equal(reply.heartbeat, "https://router.test/heartbeat");
861
+ assert.equal(reply.ticket.delivery, "d1");
862
+ assert.equal(reply.ticket.run, id);
863
+
864
+ const message = { id: "m1", signature: await signMessage(ROOT_KEY, reply.signature, "m1") };
865
+ const response = await beat(store, { ticket: reply.ticket, signature: reply.signature, message });
866
+ assert.equal(response.status, 200);
867
+ assert.deepEqual(await response.json(), { ok: true });
868
+ assert.deepEqual(watches.get(id), { at: (watches.get(id) as { at: number }).at, message: "m1" });
869
+
870
+ // A run can't have the lost notice replace a message that it didn't post.
871
+ const other = { id: "m2", signature: message.signature };
872
+ assert.equal((await beat(store, { ticket: reply.ticket, signature: reply.signature, message: other })).status, 401);
873
+ const forged = { ...reply.ticket, run: "other" };
874
+ assert.equal((await beat(store, { ticket: forged, signature: reply.signature })).status, 401);
875
+ const unnamed = { connection: "fake/main", thread: { repo: "acme/api" }, expires: Date.now() + 60_000 };
876
+ assert.equal((await beat(store, { ticket: unnamed, signature: await signTicket(ROOT_KEY, unnamed) })).status, 400);
877
+ const unknown = { ...reply.ticket, delivery: "other" };
878
+ assert.equal((await beat(store, { ticket: unknown, signature: await signTicket(ROOT_KEY, unknown) })).status, 404);
879
+
880
+ assert.equal((await beat(store, { ticket: reply.ticket, signature: reply.signature, done: true })).status, 200);
881
+ assert.deepEqual(watches.get(id), { done: true });
882
+ });
883
+
884
+ test("a heartbeat that arrives after a run's last one doesn't have the router watch the run again", async () => {
885
+ const replies: unknown[][] = [];
886
+ const runs: Run[] = [];
887
+ const channel = { ...accepted(), reply: async (_thread: unknown, text: string) => (replies.push([text]), "n1") };
888
+ const { record, store, watches } = await savedRecord(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
889
+ await advance(record, store, 0);
890
+ const { reply, id } = runs[0]!;
891
+ assert.equal((await beat(store, { ticket: reply.ticket, signature: reply.signature, done: true })).status, 200);
892
+ assert.equal((await beat(store, { ticket: reply.ticket, signature: reply.signature })).status, 200);
893
+ assert.deepEqual(watches.get(id), { done: true });
894
+ assert.deepEqual(await watch(record, watches, store, Date.now() + LOST_AFTER_MS), { forget: [], next: undefined, lost: false });
895
+ assert.equal(record.dispatches[0]!.state, "dispatched");
896
+ assert.equal(replies.length, 0);
897
+ });
898
+
899
+ test("a run is watched from its first heartbeat, so the router marks lost no run of an outpost that sends none", async () => {
900
+ const replies: unknown[][] = [];
901
+ const channel = { ...accepted(), reply: async (_thread: unknown, text: string, message?: string) => (replies.push([text, message]), "n1") };
902
+ const { record, store, watches } = await savedRecord(runStore(channel, { run: async () => "queued" as const }));
903
+ await advance(record, store, 1_000);
904
+ assert.deepEqual(await watch(record, watches, store, 1_000 + 10 * LOST_AFTER_MS), { forget: [], next: undefined, lost: false });
905
+ assert.equal(record.dispatches[0]!.state, "dispatched");
906
+ assert.equal(replies.length, 0);
907
+ });
908
+
909
+ test("a heartbeat or reply of a run that a restart replaced answers that the run is lost, and posts nothing", async () => {
910
+ const replies: unknown[][] = [];
911
+ const runs: Run[] = [];
912
+ const channel = { ...accepted(), reply: async (_thread: unknown, text: string) => (replies.push([text]), "n1") };
913
+ const { record, store, watches } = await savedRecord(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
914
+ await advance(record, store, 0);
915
+ const old = runs[0]!;
916
+ watches.set(old.id, { at: 0 });
917
+ await watch(record, watches, store, LOST_AFTER_MS);
918
+ assert.equal(replayRecord(record, ORIGIN, old.id), true);
919
+ await advance(record, store, LOST_AFTER_MS);
920
+ replies.length = 0;
921
+
922
+ const response = await beat(store, { ticket: old.reply.ticket, signature: old.reply.signature });
923
+ assert.equal(response.status, 200);
924
+ assert.deepEqual(await response.json(), { ok: true, lost: true });
925
+ const refused = await relay(store, { ticket: old.reply.ticket, signature: old.reply.signature, text: "late" });
926
+ assert.equal(refused.status, 409);
927
+ assert.equal((await refused.json()).lost, true);
928
+ assert.equal(replies.length, 0);
929
+
930
+ const current = runs[1]!;
931
+ assert.equal((await relay(store, { ticket: current.reply.ticket, signature: current.reply.signature, text: "working" })).status, 200);
932
+ assert.deepEqual(replies, [["working"]]);
933
+ });
934
+
935
+ test("a reply of a lost run posts nothing, so it doesn't replace the lost notice", async () => {
936
+ const replies: unknown[][] = [];
937
+ const runs: Run[] = [];
938
+ const channel = { ...accepted(), reply: async (_thread: unknown, text: string) => (replies.push([text]), "n1") };
939
+ const { record, store, watches } = await savedRecord(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
940
+ await advance(record, store, 0);
941
+ const { reply, id } = runs[0]!;
942
+ watches.set(id, { at: 0 });
943
+ await watch(record, watches, store, LOST_AFTER_MS);
944
+ assert.equal(replies.length, 1);
945
+ const refused = await relay(store, { ticket: reply.ticket, signature: reply.signature, text: "done", done: true });
946
+ assert.equal(refused.status, 409);
947
+ assert.equal(replies.length, 1);
948
+ assert.equal(record.dispatches[0]!.state, "lost");
949
+ });
950
+
951
+ test("a run's last reply stops the router watching it, once the reply is posted", async () => {
952
+ const replies: unknown[][] = [];
953
+ const runs: Run[] = [];
954
+ let failing = true;
955
+ const channel = {
956
+ ...accepted(),
957
+ reply: async (_thread: unknown, text: string) => {
958
+ if (failing) throw new Error("GitHub is down");
959
+ replies.push([text]);
960
+ return "n1";
961
+ },
962
+ };
963
+ const { record, store, watches } = await savedRecord(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
964
+ await advance(record, store, 0);
965
+ const { reply, id } = runs[0]!;
966
+ assert.equal((await beat(store, { ticket: reply.ticket, signature: reply.signature })).status, 200);
967
+
968
+ // A last reply that fails leaves the run watched, so the lost notice replaces the run's message.
969
+ await assert.rejects(relay(store, { ticket: reply.ticket, signature: reply.signature, text: "done", done: true }), /GitHub is down/);
970
+ assert.equal("done" in watches.get(id)!, false);
971
+
972
+ failing = false;
973
+ assert.equal((await relay(store, { ticket: reply.ticket, signature: reply.signature, text: "done", done: true })).status, 200);
974
+ assert.deepEqual(watches.get(id), { done: true });
975
+ assert.deepEqual(await watch(record, watches, store, Date.now() + LOST_AFTER_MS), { forget: [], next: undefined, lost: false });
976
+ assert.equal(record.dispatches[0]!.state, "dispatched");
977
+ assert.deepEqual(replies, [["done"]]);
978
+ });
979
+
980
+ test("a run without a heartbeat for 5 minutes is marked lost, and the lost notice replaces its message", async () => {
981
+ const replies: unknown[][] = [];
982
+ const runs: Run[] = [];
983
+ const channel = {
984
+ ...accepted(),
985
+ reply: async (_thread: unknown, text: string, message?: string) => (replies.push([text, message]), message ?? "n1"),
986
+ };
987
+ const { record, store, watches } = await savedRecord(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
988
+ await advance(record, store, 0);
989
+ const run = runs[0]!.id;
990
+ watches.set(run, { at: 1_000, message: "m1" });
991
+
992
+ assert.deepEqual(await watch(record, watches, store, 1_000 + LOST_AFTER_MS - 1), { forget: [], next: 1_000 + LOST_AFTER_MS, lost: false });
993
+ assert.equal(record.dispatches[0]!.state, "dispatched");
994
+
995
+ assert.deepEqual(await watch(record, watches, store, 1_000 + LOST_AFTER_MS), { forget: [run], next: undefined, lost: true });
996
+ assert.equal(record.dispatches[0]!.state, "lost");
997
+ assert.equal(replies.length, 1);
998
+ assert.equal(replies[0]![1], "m1");
999
+ assert.match(replies[0]![0] as string, /^This run sent no heartbeat for 5 minutes, so Factory marked it as lost\./);
1000
+ const link = new URL((replies[0]![0] as string).match(/\[Restart the run\]\((.+?)\)/)![1]!);
1001
+ assert.equal(`${link.origin}${link.pathname}`, "https://router.test/restart");
1002
+ assert.equal(replies[0]![0], lostNotice(link.toString()));
1003
+ assert.equal(record.dispatches[0]!.waiting, "m1");
1004
+ assert.deepEqual(failedDelivery(record, 2)?.triggers, [{ trigger: "mention", error: LOST_ERROR }]);
1005
+ assert.equal(await store.inbox.heartbeat("fake/main", "d1", run, {}), "lost");
1006
+
1007
+ // The run that replaces a lost one replaces the lost notice.
1008
+ assert.equal(replayRecord(record, ORIGIN), true);
1009
+ await advance(record, store, 3);
1010
+ assert.equal(record.dispatches[0]!.state, "dispatched");
1011
+ assert.equal(runs[1]!.reply.message?.id, "m1");
1012
+ });
1013
+
1014
+ const open = async (s: RouterStore, url: string) => {
1015
+ const response = await handle(new Request(url), s);
1016
+ return { status: response.status, location: response.headers.get("location"), text: await response.text() };
1017
+ };
1018
+
1019
+ test("a lost run's restart link signs the person in, checks them against the trigger's from, and restarts only that run", async () => {
1020
+ const replies: string[] = [];
1021
+ const runs: Run[] = [];
1022
+ const channel = {
1023
+ ...accepted(),
1024
+ reply: async (_thread: unknown, text: string, message?: string) => (replies.push(text), message ?? "n1"),
1025
+ };
1026
+ const { record, store, watches } = await savedRecord(runStore(channel, { run: async (run) => (runs.push(run), "queued" as const) }));
1027
+ await advance(record, store, 0);
1028
+ const lost = runs[0]!.id;
1029
+ watches.set(lost, { at: Date.now() - LOST_AFTER_MS });
1030
+ await watch(record, watches, store);
1031
+ const link = replies[0]!.match(/\[Restart the run\]\((.+?)\)/)![1]!;
1032
+ const token = new URL(link).searchParams.get("run")!;
1033
+
1034
+ const signIn = await open(store, link);
1035
+ assert.equal(signIn.status, 302);
1036
+ const location = new URL(signIn.location!);
1037
+ assert.equal(location.searchParams.get("state"), token);
1038
+ assert.equal(location.searchParams.get("redirect"), "https://router.test/restart/callback");
1039
+
1040
+ const callback = (code: string, state = token) =>
1041
+ open(store, `https://router.test/restart/callback?code=${code}&state=${encodeURIComponent(state)}`);
1042
+ const denied = await callback("code-bob-2");
1043
+ assert.equal(denied.status, 403);
1044
+ assert.match(denied.text, /bob may not trigger this agent/);
1045
+ assert.equal(record.dispatches[0]!.state, "lost");
1046
+
1047
+ // A link can't be changed to restart another run, or used after it expires.
1048
+ const signature = token.slice(token.lastIndexOf(".") + 1);
1049
+ const other = await signRestart(ROOT_KEY, { connection: "fake/main", delivery: "d1", run: crypto.randomUUID(), expires: Date.now() + 1000 });
1050
+ assert.equal((await callback("code-alice-1", `${other.slice(0, other.lastIndexOf("."))}.${signature}`)).status, 401);
1051
+ assert.equal((await open(store, `https://router.test/restart?run=${encodeURIComponent(`${token}0`)}`)).status, 401);
1052
+ const expired = await signRestart(ROOT_KEY, { connection: "fake/main", delivery: "d1", run: lost, expires: Date.now() - 1 });
1053
+ assert.equal((await callback("code-alice-1", expired)).status, 401);
1054
+
1055
+ // The callback redirects, so reloading the page that says the run restarted doesn't send the code again.
1056
+ const restarted = await callback("code-alice-1");
1057
+ assert.equal(restarted.status, 303);
1058
+ assert.equal(restarted.location, "https://router.test/restart/started");
1059
+ const started = await open(store, restarted.location!);
1060
+ assert.equal(started.status, 200);
1061
+ assert.match(started.text, /The run is starting again/);
1062
+ assert.equal(record.dispatches[0]!.state, "pending");
1063
+ await advance(record, store, 1);
1064
+ assert.notEqual(runs[1]!.id, lost);
1065
+ assert.equal(runs[1]!.reply.message?.id, "n1");
1066
+
1067
+ assert.equal((await callback("code-alice-1")).status, 409);
1068
+ // A link to a run that isn't lost any more says so before it sends the person to sign in.
1069
+ const again = await open(store, link);
1070
+ assert.equal(again.status, 409);
1071
+ assert.match(again.text, /isn't lost any more/);
1072
+ });
1073
+
1074
+ test("the record that an alarm saves keeps a restart that was saved while the alarm waited on a channel", async () => {
1075
+ const record: DeliveryRecord = {
1076
+ id: "d1",
1077
+ connection: "fake/main",
1078
+ delivery: { id: "d1", scope: "acme/api", repo: "acme/api", event: "post", data: {}, payload: {} },
1079
+ origin: ORIGIN,
1080
+ received: 0,
1081
+ acknowledged: true,
1082
+ dispatches: [
1083
+ { trigger: "a", run: "r1", state: "dispatched" },
1084
+ { trigger: "b", run: "r2", state: "lost", error: LOST_ERROR },
1085
+ ],
1086
+ };
1087
+ const read = record.dispatches.map((d) => JSON.stringify(d));
1088
+ const stored = structuredClone(record);
1089
+ // The alarm marks the first run lost, while the person restarts the second.
1090
+ Object.assign(record.dispatches[0]!, { state: "lost", error: LOST_ERROR });
1091
+ assert.equal(replayRecord(stored, "https://router.new", "r2"), true);
1092
+ const saved = mergeRecord(read, record, stored);
1093
+ assert.deepEqual(saved.dispatches.map((d) => d.state), ["lost", "pending"]);
1094
+ assert.notEqual(saved.dispatches[1]!.run, "r2");
1095
+ assert.equal(saved.origin, "https://router.new");
1096
+ assert.equal(nextTry(saved, 5), 5);
1097
+ });
1098
+
1099
+ test("watching forgets runs that the record no longer has or that failed, and leaves runs that aren't dispatched yet", async () => {
1100
+ const { record, store } = await savedRecord(runStore(accepted(), {}));
1101
+ const watches = new Map<string, Watch>([
1102
+ [record.dispatches[0]!.run, { at: 0 }],
1103
+ ["gone", { at: 0 }],
1104
+ ]);
1105
+ assert.deepEqual(await watch(record, watches, store, LOST_AFTER_MS), { forget: ["gone"], next: LOST_AFTER_MS, lost: false });
1106
+ assert.equal(record.dispatches[0]!.state, "pending");
1107
+ record.dispatches[0]!.state = "failed";
1108
+ assert.deepEqual(await watch(record, watches, store, LOST_AFTER_MS), { forget: [record.dispatches[0]!.run, "gone"], next: undefined, lost: false });
1109
+ });
1110
+
816
1111
  const adminStore = (channel: RemoteChannel<FakeEvent>, calls: string[] = []): RouterStore => ({
817
1112
  ...sourceStore(channel, calls),
818
1113
  config: {
@@ -1002,6 +1297,9 @@ test("replay replays one failed delivery, or all of them, against the router's o
1002
1297
  { connection: "fake/main", id: "d2", repo: "acme/api", event: "post", received: 1, failed: 2, triggers: [] },
1003
1298
  ],
1004
1299
  replay: async (connection, id, origin) => (replays.push(`${connection}/${id} ${origin}`), id === "d1"),
1300
+ heartbeat: async () => "unknown",
1301
+ record: async () => undefined,
1302
+ restart: async () => false,
1005
1303
  };
1006
1304
  const s: RouterStore = { ...adminStore(adminChannel()), inbox };
1007
1305
  const session = await signSession(ROOT_KEY, { login: "alice", id: "1", expires: Date.now() + 60_000 });