@notation/factory 0.2.0 → 0.5.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.
package/router/handle.ts CHANGED
@@ -1,28 +1,62 @@
1
- import type { OutpostConfig } from "../contracts/outpost.ts";
1
+ import type { OutpostConfig, TriggerEntry } from "../contracts/outpost.ts";
2
2
  import type { RepoPattern, RouterConfig } from "../contracts/router.ts";
3
+ import { allowsRepo } from "../lib/repos.ts";
4
+ import {
5
+ type ContainerBuild,
6
+ type DeliveriesResult,
7
+ type DeployLog,
8
+ isOperator,
9
+ type ReplayRequest,
10
+ type ReplayResult,
11
+ type ReposResult,
12
+ SESSION_TTL_MS,
13
+ type SessionRequest,
14
+ type SessionResult,
15
+ type SignInRequest,
16
+ type SignInResult,
17
+ signSession,
18
+ verifySession,
19
+ } from "./admin.ts";
3
20
  import type {
4
21
  AuthorCheck,
5
22
  BuildCheck,
6
23
  Delivery,
7
24
  FactoryStatus,
25
+ Operator,
8
26
  RemoteChannel,
9
27
  SourceChange,
10
28
  SourceFiles,
11
29
  } from "./channel.ts";
30
+ import {
31
+ BUILD_POLL_MS,
32
+ BUILD_WAIT_MS,
33
+ type DeliveryRecord,
34
+ failureNotice,
35
+ type Inbox,
36
+ type TriggerDispatch,
37
+ waitingNotice,
38
+ } from "./deliveries.ts";
12
39
  import {
13
40
  type BuildReportRequest,
14
41
  isBranchName,
42
+ type MessagesRequest,
43
+ type MessagesResult,
15
44
  type Relay,
45
+ type RelayResult,
16
46
  REPLY_TTL_MS,
17
47
  type Run,
48
+ type RunResult,
49
+ signMessage,
18
50
  signTicket,
19
51
  signTokenTicket,
20
52
  type TokenRequest,
21
53
  type Tokens,
22
54
  verifyBuildReport,
55
+ verifyMessage,
23
56
  verifyTicket,
24
57
  verifyTokenTicket,
25
58
  } from "./run.ts";
59
+ import { SYNC_HEADER, verifySync } from "./sync.ts";
26
60
 
27
61
  /** The KV key that the deployer stores a repo's outpost config under. `repo` is `owner/name`. */
28
62
  export const outpostKey = (repo: string) => `outposts/${repo.toLowerCase()}`;
@@ -36,8 +70,21 @@ export type RouterStore = {
36
70
  deployer?: RemoteDeployer;
37
71
  /** The root key, which the router derives its own keys from. */
38
72
  rootKey(): Promise<string>;
73
+ /** The key that deploy signs `POST /sync` with. Without it, the router refuses every sync. */
74
+ syncKey?(): Promise<string | undefined>;
39
75
  /** Keeps `task` running after the response, where the platform allows it. Without it, the router waits for the task. */
40
76
  background?(task: Promise<unknown>): void;
77
+ /** Where the router saves deliveries, which dispatches them and keeps the failed ones. */
78
+ inbox: Inbox;
79
+ /** Where the router keeps each repo's last deploy. Without it, operators can't list deploys. */
80
+ deploys?: DeployLog;
81
+ /**
82
+ * Deploys each change with `redeployRepo`, one at a time, until all are
83
+ * done, without the time limit of a request. A new call replaces the
84
+ * changes that are left. Without it, a sync deploys the repos in the
85
+ * background.
86
+ */
87
+ queueDeploys?(changes: SourceChange[]): Promise<void>;
41
88
  };
42
89
 
43
90
  /** The deployer, as the router calls it. */
@@ -48,8 +95,8 @@ export type RemoteDeployer = {
48
95
  remove(repo: string): Promise<void>;
49
96
  /** Calls the worktree function of the repo's trigger with `payload`, in the isolate that evaluates configs. */
50
97
  worktree(repo: string, trigger: string, payload: unknown): Promise<string | undefined>;
51
- /** Hands `run` to its container, which queues it. */
52
- run(run: Run): Promise<void>;
98
+ /** Hands `run` to its container, which queues it. Throws if the container refuses it or doesn't answer. */
99
+ run(run: Run): Promise<RunResult>;
53
100
  };
54
101
 
55
102
  /** The name of the check that shows the build of a container's image, such as `factory/build dev`. */
@@ -83,7 +130,10 @@ const channels = (store: RouterStore) =>
83
130
  * 2. Has the channel verify and parse the delivery.
84
131
  * 3. Reads the outpost of the delivery's repo, and matches the triggers on
85
132
  * channels of the delivery's connection and scope.
86
- * 4. Starts a run for each match whose author may start one.
133
+ * 4. If any match's author may start a run, saves the delivery to the
134
+ * inbox before it answers, and the inbox dispatches it with `advance`.
135
+ * A delivery whose connection and id the inbox has seen is a duplicate,
136
+ * and starts nothing.
87
137
  */
88
138
  const webhook = async (request: Request, key: string, store: RouterStore) => {
89
139
  const found = channels(store).find((c) => c.key === key);
@@ -104,18 +154,9 @@ const webhook = async (request: Request, key: string, store: RouterStore) => {
104
154
  if (!outpost) return json(202, { ...summary, ignored: "no outpost" });
105
155
 
106
156
  const matches: TriggerMatch[] = [];
107
- const runs: Promise<void>[] = [];
108
- const origin = new URL(request.url).origin;
157
+ const dispatches: TriggerDispatch[] = [];
109
158
  for (const [id, trigger] of Object.entries(outpost.triggers ?? {})) {
110
- const target = outpost.channels?.[trigger.channel];
111
- if (
112
- trigger.event !== delivery.event ||
113
- target?.provider !== entry.provider ||
114
- target.connection !== name ||
115
- target.scope !== delivery.scope
116
- ) {
117
- continue;
118
- }
159
+ if (!listens(outpost, trigger, entry.provider, name, delivery)) continue;
119
160
  const author = await channel.match(trigger.match, delivery);
120
161
  if (!author) continue;
121
162
  // Team checks need a call to the platform, which the router doesn't make yet.
@@ -125,30 +166,147 @@ const webhook = async (request: Request, key: string, store: RouterStore) => {
125
166
  }
126
167
  const run = crypto.randomUUID();
127
168
  matches.push({ trigger: id, author, run });
128
- runs.push(
129
- dispatch({ run, trigger: id, key, channel, delivery, outpost, origin }, store).catch((error) =>
130
- console.error(JSON.stringify({ run, trigger: id, error: message(error) })),
131
- ),
132
- );
169
+ dispatches.push({ trigger: id, run, state: "pending" });
133
170
  }
134
- if (runs.length) {
135
- const task = Promise.all(runs);
136
- if (store.background) store.background(task);
137
- else await task;
171
+ if (dispatches.length) {
172
+ const record: DeliveryRecord = {
173
+ id: delivery.id || crypto.randomUUID(),
174
+ connection: key,
175
+ delivery,
176
+ origin: new URL(request.url).origin,
177
+ received: Date.now(),
178
+ dispatches,
179
+ };
180
+ if (!(await store.inbox.receive(record))) {
181
+ const result = { ...summary, duplicate: true };
182
+ console.log(JSON.stringify(result));
183
+ return json(200, result);
184
+ }
138
185
  }
139
186
  const result = { ...summary, matches };
140
187
  console.log(JSON.stringify(result));
141
188
  return json(202, result);
142
189
  };
143
190
 
191
+ /** Whether `trigger` listens on a channel of the delivery's connection and scope, for the delivery's event. `name` is the connection's name. */
192
+ const listens = (outpost: OutpostConfig, trigger: TriggerEntry, provider: string, name: string, delivery: Delivery<unknown>) => {
193
+ const target = outpost.channels?.[trigger.channel];
194
+ return (
195
+ trigger.event === delivery.event &&
196
+ target?.provider === provider &&
197
+ target.connection === name &&
198
+ target.scope === delivery.scope
199
+ );
200
+ };
201
+
202
+ /**
203
+ * Tries a saved delivery's dispatches that are due, and resolves to when
204
+ * to call it again, if any dispatch is left to try. It changes `record`,
205
+ * which the caller saves:
206
+ * 1. Has the channel show on the delivery's post that a run is starting,
207
+ * once.
208
+ * 2. Reads the repo's outpost config as it is now, and dispatches each due
209
+ * trigger with new tokens.
210
+ * 3. A dispatch whose container's first image build hasn't finished waits
211
+ * for it. See `waitForBuild`. It isn't tried again while the deploy log
212
+ * says the build is queued or in progress, so it doesn't mint tokens
213
+ * for nothing.
214
+ * 4. Posts a notice to the thread of each dispatch that fails, if the
215
+ * dispatch got as far as naming the conversation.
216
+ */
217
+ export const advance = async (record: DeliveryRecord, store: RouterStore, now = Date.now()): Promise<number | undefined> => {
218
+ const due = record.dispatches.filter((d) => d.state === "pending" && (d.next ?? 0) <= now);
219
+ const found = channels(store).find((c) => c.key === record.connection);
220
+ if (due.length && !found) {
221
+ for (const d of due) Object.assign(d, { state: "failed", error: `The hub has no channel for connection ${record.connection}.` });
222
+ } else if (due.length && found) {
223
+ const { entry, channel } = found;
224
+ if (!record.acknowledged) {
225
+ await channel.acknowledge(record.delivery).catch((error) =>
226
+ console.error(JSON.stringify({ delivery: record.id, state: "acknowledge failed", error: message(error) })),
227
+ );
228
+ record.acknowledged = true;
229
+ }
230
+ const outpost = await store.outpost(record.delivery.repo);
231
+ const name = record.connection.slice(entry.provider.length + 1);
232
+ const repo = record.delivery.repo;
233
+ await Promise.all(
234
+ due.map(async (d) => {
235
+ try {
236
+ const waitingFor = d.since !== undefined ? outpost?.triggers?.[d.trigger]?.container : undefined;
237
+ if (waitingFor && (await isBuilding(store, repo, waitingFor))) {
238
+ await waitForBuild(d, waitingFor, repo, channel, store, now);
239
+ return;
240
+ }
241
+ const building = await dispatch(
242
+ { dispatch: d, key: record.connection, provider: entry.provider, name, channel, delivery: record.delivery, outpost, origin: record.origin },
243
+ store,
244
+ );
245
+ if (building) await waitForBuild(d, building, repo, channel, store, now);
246
+ else d.state = "dispatched";
247
+ } catch (error) {
248
+ Object.assign(d, { state: "failed", error: message(error) });
249
+ console.error(JSON.stringify({ run: d.run, trigger: d.trigger, error: d.error }));
250
+ if (d.thread === undefined) return;
251
+ await channel
252
+ .reply(d.thread, failureNotice(d), d.waiting)
253
+ .catch((error) => console.error(JSON.stringify({ run: d.run, state: "notice failed", error: message(error) })));
254
+ }
255
+ }),
256
+ );
257
+ }
258
+ const pending = record.dispatches.filter((d) => d.state === "pending");
259
+ return pending.length ? Math.min(...pending.map((d) => d.next ?? now)) : undefined;
260
+ };
261
+
262
+ const isBuilding = async (store: RouterStore, repo: string, container: string) => {
263
+ const state = (await store.deploys?.build(repo, container))?.state;
264
+ return state === "queued" || state === "in_progress";
265
+ };
266
+
267
+ /**
268
+ * Has a dispatch wait for its container's first image build, and try again
269
+ * in `BUILD_POLL_MS`. The first time, it posts the waiting message to the
270
+ * thread. Throws if the repo's last deploy says the build failed, or the
271
+ * dispatch has waited `BUILD_WAIT_MS`.
272
+ */
273
+ const waitForBuild = async (
274
+ d: TriggerDispatch,
275
+ container: string,
276
+ repo: string,
277
+ channel: RemoteChannel,
278
+ store: RouterStore,
279
+ now: number,
280
+ ) => {
281
+ const build = await store.deploys?.build(repo, container);
282
+ if (build?.state === "failure" || build?.state === "cancelled") {
283
+ const outcome = build.state === "failure" ? "failed" : "was cancelled";
284
+ const details = [build.summary, build.url && `The build's log: ${build.url}`].filter(Boolean).join(" ");
285
+ throw new Error(`The first image build of container \`${container}\` ${outcome}.${details ? ` ${details}` : ""}`);
286
+ }
287
+ if (d.since !== undefined && now - d.since >= BUILD_WAIT_MS) {
288
+ throw new Error(`The first image build of container \`${container}\` didn't finish within ${BUILD_WAIT_MS / 3_600_000} hours.`);
289
+ }
290
+ d.next = now + BUILD_POLL_MS;
291
+ if (d.since !== undefined) return;
292
+ d.since = now;
293
+ try {
294
+ d.waiting = await channel.reply(d.thread, waitingNotice(container));
295
+ } catch (error) {
296
+ console.error(JSON.stringify({ run: d.run, state: "waiting notice failed", error: message(error) }));
297
+ }
298
+ };
299
+
144
300
  type Dispatch = {
145
- run: string;
146
- trigger: string;
147
- /** The delivery's connection. */
301
+ dispatch: TriggerDispatch;
302
+ /** The delivery's connection, and its provider and name. */
148
303
  key: string;
304
+ provider: string;
305
+ name: string;
149
306
  channel: RemoteChannel;
150
307
  delivery: Delivery<unknown>;
151
- outpost: OutpostConfig;
308
+ /** The repo's outpost config as it is now. */
309
+ outpost: OutpostConfig | undefined;
152
310
  /** The router's origin, which the runner replies to. */
153
311
  origin: string;
154
312
  };
@@ -181,95 +339,143 @@ const mintTokens = async (store: RouterStore, outpost: OutpostConfig, repo: stri
181
339
  };
182
340
 
183
341
  /**
184
- * Starts one run of a matched trigger:
185
- * 1. Has the delivery's channel name the conversation, and signs a ticket
186
- * for replies to its thread.
342
+ * Starts one run of a matched trigger, and resolves to the run's container
343
+ * if its first image build hasn't finished. Throws if the run can't start.
344
+ * 1. Checks that the outpost still has the trigger, and that it still
345
+ * matches the delivery and its author. Has the delivery's channel name
346
+ * the conversation, and signs a ticket for reading and replying to its
347
+ * thread. The run's first reply replaces the thread's waiting message,
348
+ * if there is one.
187
349
  * 2. Has the deployer call the trigger's worktree function, if it has one.
188
350
  * 3. Has the code host's channel mint a read-only token for the clone, and a
189
351
  * token for each of the container's code host policies. Signs a ticket
190
352
  * for new tokens.
191
- * 4. Hands the run to the deployer. If a step fails, the channel replies
192
- * with the error.
353
+ * 4. Hands the run to the deployer.
193
354
  */
194
- const dispatch = async (d: Dispatch, store: RouterStore) => {
355
+ const dispatch = async (d: Dispatch, store: RouterStore): Promise<string | undefined> => {
195
356
  const { delivery, outpost } = d;
357
+ const { trigger: triggerId, run: runId, waiting } = d.dispatch;
196
358
  const repo = delivery.repo;
197
- const trigger = outpost.triggers[d.trigger]!;
359
+ const trigger = outpost?.triggers?.[triggerId];
360
+ if (!outpost || !trigger) throw new Error(`The outpost of ${repo} no longer has the trigger \`${triggerId}\`.`);
361
+ if (
362
+ !listens(outpost, trigger, d.provider, d.name, delivery) ||
363
+ (await d.channel.match(trigger.match, delivery))?.result !== "allowed"
364
+ ) {
365
+ throw new Error(`The trigger \`${triggerId}\` no longer matches the event.`);
366
+ }
198
367
  const conversation = await d.channel.conversation(delivery, { selector: trigger.match, agent: trigger.agent });
368
+ d.dispatch.thread = conversation.thread;
199
369
  const ticket = { connection: d.key, thread: conversation.thread, expires: Date.now() + REPLY_TTL_MS };
200
370
  const rootKey = await store.rootKey();
201
- const reply = { url: `${d.origin}/relay`, ticket, signature: await signTicket(rootKey, ticket) };
202
- try {
203
- const { deployer } = store;
204
- if (!deployer) throw new Error("The hub has no deployer.");
205
- const container = outpost.containers[trigger.container];
206
- const agent = outpost.agents[trigger.agent];
207
- if (!container) throw new Error(`The outpost has no container ${trigger.container}.`);
208
- if (!agent) throw new Error(`The outpost has no agent ${trigger.agent}.`);
209
- const codeHost = codeHostChannel(store);
210
- if (!codeHost?.channel) throw new Error("The hub has no code host whose channel mints tokens.");
211
-
212
- let worktree: Run["worktree"];
213
- if (trigger.worktree) {
214
- const branch = await deployer.worktree(repo, d.trigger, delivery.payload);
215
- if (branch !== undefined) {
216
- if (typeof branch !== "string" || !isBranchName(branch)) {
217
- throw new Error(`The worktree function of ${d.trigger} returned ${JSON.stringify(branch)}, which isn't a branch name the runner can check out.`);
218
- }
219
- worktree = { branch, ...(trigger.worktree.base && { base: trigger.worktree.base }) };
371
+ const signature = await signTicket(rootKey, ticket);
372
+ const reply: Run["reply"] = { url: `${d.origin}/relay`, ticket, signature };
373
+ if (waiting) reply.message = { id: waiting, signature: await signMessage(rootKey, signature, waiting) };
374
+ const { deployer } = store;
375
+ if (!deployer) throw new Error("The hub has no deployer.");
376
+ const container = outpost.containers[trigger.container];
377
+ const agent = outpost.agents[trigger.agent];
378
+ if (!container) throw new Error(`The outpost has no container ${trigger.container}.`);
379
+ if (!agent) throw new Error(`The outpost has no agent ${trigger.agent}.`);
380
+ const codeHost = codeHostChannel(store);
381
+ if (!codeHost?.channel) throw new Error("The hub has no code host whose channel mints tokens.");
382
+
383
+ let worktree: Run["worktree"];
384
+ if (trigger.worktree) {
385
+ const branch = await deployer.worktree(repo, triggerId, delivery.payload);
386
+ if (branch !== undefined) {
387
+ if (typeof branch !== "string" || !isBranchName(branch)) {
388
+ throw new Error(`The worktree function of ${triggerId} returned ${JSON.stringify(branch)}, which isn't a branch name the runner can check out.`);
220
389
  }
390
+ worktree = { branch, ...(trigger.worktree.base && { base: trigger.worktree.base }) };
221
391
  }
222
-
223
- const tokens = await mintTokens(store, outpost, repo, trigger.container);
224
- const tokenTicket = { repo, container: trigger.container, expires: Date.now() + REPLY_TTL_MS };
225
- const refresh = { url: `${d.origin}/tokens`, ticket: tokenTicket, signature: await signTokenTicket(rootKey, tokenTicket) };
226
-
227
- await deployer.run({
228
- id: d.run,
229
- repo,
230
- trigger: d.trigger,
231
- container: trigger.container,
232
- runtimes: container.runtimes,
233
- files: container.files ?? {},
234
- agent: { id: trigger.agent, ...agent },
235
- conversation: {
236
- id: conversation.id,
237
- prompt: conversation.prompt,
238
- ...(conversation.channel && { channel: conversation.channel }),
239
- ...(conversation.context && { context: conversation.context }),
240
- },
241
- ...(worktree && { worktree }),
242
- cloneToken: await codeHost.channel.token(repo, { contents: "read" }),
243
- tokens,
244
- refresh,
245
- reply,
246
- });
247
- console.log(JSON.stringify({ run: d.run, repo, trigger: d.trigger, container: trigger.container, worktree }));
248
- } catch (error) {
249
- await d.channel.reply(conversation.thread, `Couldn't start the run of trigger \`${d.trigger}\`: ${message(error)}`);
250
- throw error;
251
392
  }
393
+
394
+ const tokens = await mintTokens(store, outpost, repo, trigger.container);
395
+ const tokenTicket = { repo, container: trigger.container, expires: Date.now() + REPLY_TTL_MS };
396
+ const refresh = { url: `${d.origin}/tokens`, ticket: tokenTicket, signature: await signTokenTicket(rootKey, tokenTicket) };
397
+
398
+ const result = await deployer.run({
399
+ id: runId,
400
+ repo,
401
+ trigger: triggerId,
402
+ container: trigger.container,
403
+ runtimes: container.runtimes,
404
+ files: container.files ?? {},
405
+ agent: { id: trigger.agent, ...agent },
406
+ conversation: {
407
+ id: conversation.id,
408
+ ...(conversation.message && { message: conversation.message }),
409
+ ...(conversation.event && { event: conversation.event }),
410
+ ...(conversation.channel && { channel: conversation.channel }),
411
+ ...(conversation.context && { context: conversation.context }),
412
+ },
413
+ ...(worktree && { worktree }),
414
+ cloneToken: await codeHost.channel.token(repo, { contents: "read" }),
415
+ tokens,
416
+ refresh,
417
+ reply,
418
+ });
419
+ if (result === "building") return trigger.container;
420
+ console.log(JSON.stringify({ run: runId, repo, trigger: triggerId, container: trigger.container, worktree }));
421
+ return undefined;
252
422
  };
253
423
 
254
- /** Posts a container's reply, if the router signed its ticket, through the channel of the ticket's connection. */
255
- const relay = async (request: Request, store: RouterStore) => {
256
- let body: Relay;
424
+ /**
425
+ * Reads a body that carries a reply ticket, checks the ticket's signature,
426
+ * and finds the channel of the ticket's connection. Returns a response
427
+ * instead if any step fails.
428
+ */
429
+ const ticketed = async <T extends MessagesRequest>(request: Request, store: RouterStore) => {
430
+ let body: T;
257
431
  try {
258
- body = (await request.json()) as Relay;
432
+ body = (await request.json()) as T;
259
433
  } catch {
260
434
  return json(400, { error: "the body isn't JSON" });
261
435
  }
262
- const { ticket, signature, text } = body ?? {};
263
- if (!ticket || typeof signature !== "string" || typeof text !== "string") {
264
- return json(400, { error: "the body needs ticket, signature and text" });
265
- }
266
- if (!(await verifyTicket(await store.rootKey(), ticket, signature))) {
436
+ const { ticket, signature } = body ?? {};
437
+ if (!ticket || typeof signature !== "string") return json(400, { error: "the body needs ticket and signature" });
438
+ const rootKey = await store.rootKey();
439
+ if (!(await verifyTicket(rootKey, ticket, signature))) {
267
440
  return json(401, { error: "bad or expired ticket" });
268
441
  }
269
442
  const found = channels(store).find((c) => c.key === ticket.connection);
270
443
  if (!found) return json(404, { error: `no channel for connection ${ticket.connection}` });
271
- await found.channel.reply(ticket.thread, text);
272
- return json(200, { ok: true });
444
+ return { body, rootKey, channel: found.channel };
445
+ };
446
+
447
+ /** Posts a container's reply, if the router signed its ticket, through the channel of the ticket's connection. */
448
+ const relay = async (request: Request, store: RouterStore) => {
449
+ const found = await ticketed<Relay>(request, store);
450
+ if (found instanceof Response) return found;
451
+ const { body, rootKey, channel } = found;
452
+ const { ticket, signature, text, message } = body;
453
+ if (typeof text !== "string") return json(400, { error: "the body needs text" });
454
+ if (message !== undefined && (typeof message?.id !== "string" || typeof message.signature !== "string")) {
455
+ return json(400, { error: "the message needs id and signature" });
456
+ }
457
+ if (message && !(await verifyMessage(rootKey, signature, message))) {
458
+ return json(401, { error: "bad message signature" });
459
+ }
460
+ const id = await channel.reply(ticket.thread, text, message?.id);
461
+ const result: RelayResult = { ok: true };
462
+ if (typeof id === "string") result.message = { id, signature: await signMessage(rootKey, signature, id) };
463
+ return json(200, result);
464
+ };
465
+
466
+ /**
467
+ * Answers a run's thread's messages, if the router signed its reply ticket.
468
+ * The runner builds the agent's prompt from them when the run starts.
469
+ */
470
+ const messages = async (request: Request, store: RouterStore) => {
471
+ const found = await ticketed<MessagesRequest>(request, store);
472
+ if (found instanceof Response) return found;
473
+ try {
474
+ const result: MessagesResult = { messages: await found.channel.messages(found.body.ticket.thread) };
475
+ return json(200, result);
476
+ } catch (error) {
477
+ return json(502, { error: message(error) });
478
+ }
273
479
  };
274
480
 
275
481
  /**
@@ -298,7 +504,11 @@ const tokens = async (request: Request, store: RouterStore) => {
298
504
  }
299
505
  };
300
506
 
301
- /** Shows a container image's build on the commit it was built from, through the code host's channel. */
507
+ /**
508
+ * Shows a container image's build on the commit it was built from, through
509
+ * the code host's channel, and logs it as the container's latest build
510
+ * unless the log has a build of another commit.
511
+ */
302
512
  const builds = async (request: Request, store: RouterStore) => {
303
513
  let body: BuildReportRequest;
304
514
  try {
@@ -314,6 +524,10 @@ const builds = async (request: Request, store: RouterStore) => {
314
524
  const channel = codeHostChannel(store)?.channel;
315
525
  if (!channel) return json(404, { error: "the hub has no code host" });
316
526
  const { repo, ref, container, state, url, summary } = report;
527
+ const build: ContainerBuild = { state, ref, ...(url && { url }), ...(summary && { summary }), at: new Date().toISOString() };
528
+ await logBuild(store, repo, container, build).catch((error) =>
529
+ console.error(JSON.stringify({ repo, container, state: "build log failed", error: message(error) })),
530
+ );
317
531
  try {
318
532
  await channel.writeCheck(repo, ref, { name: buildCheckName(container), state, ...(url && { url }), ...(summary && { summary }) });
319
533
  } catch (error) {
@@ -322,6 +536,14 @@ const builds = async (request: Request, store: RouterStore) => {
322
536
  return json(200, { ok: true });
323
537
  };
324
538
 
539
+ const logBuild = async (store: RouterStore, repo: string, container: string, build: ContainerBuild) => {
540
+ const latest = await store.deploys?.build(repo, container);
541
+ // A deploy logs each build it starts as queued, after the builds before it.
542
+ // So a report for another commit is a late report of an older build.
543
+ if (latest && latest.ref !== build.ref) return;
544
+ await store.deploys?.putBuild(repo, container, build);
545
+ };
546
+
325
547
  /** Writes a check, and logs a failure instead of throwing it. The App may not have the checks permission yet. */
326
548
  const writeCheck = async (channel: RemoteChannel, repo: string, ref: string, check: BuildCheck) => {
327
549
  try {
@@ -331,13 +553,6 @@ const writeCheck = async (channel: RemoteChannel, repo: string, ref: string, che
331
553
  }
332
554
  };
333
555
 
334
- const allows = (allow: RepoPattern[], repo: string) => {
335
- const [owner, name] = repo.toLowerCase().split("/");
336
- return allow.some(
337
- (p) => p.owner.toLowerCase() === owner && (!p.repo || p.repo.toLowerCase() === name),
338
- );
339
- };
340
-
341
556
  const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
342
557
 
343
558
  /**
@@ -349,18 +564,26 @@ const message = (error: unknown) => (error instanceof Error ? error.message : St
349
564
  * 3. The channel shows the outcome on the repo, and a queued check on the
350
565
  * commit for each container whose image started building. The deployer
351
566
  * reports each build's progress to `/builds`.
567
+ * 4. After a deploy that succeeds, the log drops the builds of containers
568
+ * that the outpost no longer has.
352
569
  */
353
570
  const redeploy = async (
354
571
  change: SourceChange,
355
572
  allow: RepoPattern[],
356
573
  channel: RemoteChannel,
357
574
  deployer: RemoteDeployer,
575
+ store: RouterStore,
358
576
  ) => {
359
577
  const { repo, ref } = change;
360
- if (change.removed) return deployer.remove(repo);
578
+ const log = store.deploys;
579
+ if (change.removed) {
580
+ await deployer.remove(repo);
581
+ await log?.remove(repo);
582
+ return;
583
+ }
361
584
  const at = () => new Date().toISOString();
362
585
  let status: FactoryStatus;
363
- if (!allows(allow, repo)) {
586
+ if (!allowsRepo(allow, repo)) {
364
587
  await deployer.remove(repo);
365
588
  status = { state: "failed", error: `The hub doesn't serve ${repo}: the code host's allow list doesn't include it.`, at: at() };
366
589
  } else {
@@ -370,9 +593,16 @@ const redeploy = async (
370
593
  status = { state: "failed", ref, error: message(error), at: at() };
371
594
  }
372
595
  }
596
+ await log?.put(repo, status);
373
597
  await channel.writeStatus(repo, status);
374
- for (const container of status.building ?? []) {
375
- if (status.ref) await writeCheck(channel, repo, status.ref, { name: buildCheckName(container), state: "queued" });
598
+ for (const container of status.builds ?? []) {
599
+ if (!status.ref) continue;
600
+ await log?.putBuild(repo, container, { state: "queued", ref: status.ref, at: status.at });
601
+ await writeCheck(channel, repo, status.ref, { name: buildCheckName(container), state: "queued" });
602
+ }
603
+ if (log && status.state === "deployed") {
604
+ const outpost = await store.outpost(repo);
605
+ if (outpost) await log.pruneBuilds(repo, Object.keys(outpost.containers));
376
606
  }
377
607
  console.log(JSON.stringify({ repo, ...status }));
378
608
  };
@@ -390,23 +620,80 @@ const source = async (
390
620
  }
391
621
  const { deployer } = store;
392
622
  if (!deployer) return json(200, { ignored: "no deployer" });
393
- const task = (async () => {
394
- for (const change of changes) {
395
- try {
396
- await redeploy(change, codeHost.allow ?? [], channel, deployer);
397
- } catch (error) {
398
- console.error(JSON.stringify({ repo: change.repo, error: message(error) }));
399
- }
400
- }
401
- })();
623
+ await later(store, redeployEach(changes, codeHost.allow ?? [], channel, deployer, store));
624
+ return json(202, { connection: key, deploying: changes.map((c) => c.repo) });
625
+ };
626
+
627
+ /** Runs `task` after the response where the platform allows it, or else waits for it. */
628
+ const later = async (store: RouterStore, task: Promise<void>) => {
402
629
  if (store.background) store.background(task);
403
630
  else await task;
404
- return json(202, { connection: key, deploying: changes.map((c) => c.repo) });
405
631
  };
406
632
 
407
- /** Has each connection's channel set up its platform side, pointing it at this router. */
633
+ /** Deploys each change one at a time. */
634
+ const redeployEach = async (
635
+ changes: SourceChange[],
636
+ allow: RepoPattern[],
637
+ channel: RemoteChannel,
638
+ deployer: RemoteDeployer,
639
+ store: RouterStore,
640
+ ) => {
641
+ for (const change of changes) {
642
+ try {
643
+ await redeploy(change, allow, channel, deployer, store);
644
+ } catch (error) {
645
+ console.error(JSON.stringify({ repo: change.repo, error: message(error) }));
646
+ }
647
+ }
648
+ };
649
+
650
+ /** Deploys one repo's outpost again, as a source change through the code host's channel would. Logs an error instead of throwing it. */
651
+ export const redeployRepo = async (change: SourceChange, store: RouterStore) => {
652
+ const codeHost = store.config.codeHost;
653
+ const channel = codeHostChannel(store)?.channel;
654
+ const { deployer } = store;
655
+ if (!codeHost || !channel || !deployer) return;
656
+ await redeployEach([change], codeHost.allow ?? [], channel, deployer, store);
657
+ };
658
+
659
+ /**
660
+ * Deploys every repo again:
661
+ * 1. Has the code host's channel list the repos that the hub can read, and
662
+ * keeps those that the code host's allow list includes.
663
+ * 2. Deploys each of them again from its default branch, one at a time,
664
+ * through `queueDeploys` if the store has it.
665
+ * 3. Removes the outposts of the other deployed repos.
666
+ */
667
+ const syncRepos = async (store: RouterStore) => {
668
+ const codeHost = store.config.codeHost;
669
+ const channel = codeHostChannel(store)?.channel;
670
+ const { deployer } = store;
671
+ if (!codeHost || !channel || !deployer) return;
672
+ const allow = codeHost.allow ?? [];
673
+ const deploying = (await channel.repos()).filter((repo) => allowsRepo(allow, repo));
674
+ const kept = new Set(deploying.map((repo) => repo.toLowerCase()));
675
+ const deployed = (await store.deploys?.repos()) ?? [];
676
+ const removing = deployed.filter((repo) => !kept.has(repo.toLowerCase()));
677
+ console.log(JSON.stringify({ sync: { deploying, removing } }));
678
+ const changes: SourceChange[] = [...deploying.map((repo) => ({ repo })), ...removing.map((repo) => ({ repo, removed: true }))];
679
+ if (store.queueDeploys) await store.queueDeploys(changes);
680
+ else await redeployEach(changes, allow, channel, deployer, store);
681
+ };
682
+
683
+ /**
684
+ * Handles the sync that deploy sends after it deploys the hub:
685
+ * 1. Checks that the request was signed with the sync key.
686
+ * 2. Has each connection's channel set up its platform side, pointing it
687
+ * at this router, and answers with each one's outcome.
688
+ * 3. Deploys every repo again with `syncRepos`, after the response.
689
+ */
408
690
  const sync = async (request: Request, store: RouterStore) => {
691
+ const syncKey = await store.syncKey?.();
692
+ if (!syncKey) return json(501, { error: "the router has no sync key" });
409
693
  const { origin } = new URL(request.url);
694
+ if (!(await verifySync(syncKey, request.headers.get(SYNC_HEADER) ?? "", origin))) {
695
+ return json(401, { error: "the sync request isn't signed with the sync key" });
696
+ }
410
697
  const results: Record<string, string> = {};
411
698
  for (const { key, channel } of channels(store)) {
412
699
  try {
@@ -416,15 +703,142 @@ const sync = async (request: Request, store: RouterStore) => {
416
703
  results[key] = error instanceof Error ? error.message : String(error);
417
704
  }
418
705
  }
706
+ await later(
707
+ store,
708
+ syncRepos(store).catch((error) => console.error(JSON.stringify({ sync: "failed", error: message(error) }))),
709
+ );
419
710
  const failed = Object.values(results).some((r) => r !== "ok");
420
711
  return json(failed ? 502 : 200, { connections: results });
421
712
  };
422
713
 
714
+ /** Reads a JSON object body, or answers 400. */
715
+ const readJson = async <T>(request: Request): Promise<T | Response> => {
716
+ try {
717
+ const body = (await request.json()) as T;
718
+ if (body && typeof body === "object") return body;
719
+ } catch {}
720
+ return json(400, { error: "the body isn't a JSON object" });
721
+ };
722
+
723
+ /** The channel that signs operators in, for an operator auth that signs in through a connection's platform. */
724
+ const signInChannel = (store: RouterStore) => {
725
+ const operators = store.config.operators;
726
+ if (!operators) return json(404, { error: "the hub has no operator auth" });
727
+ // Only GitHub sign-in is built. `isOperator` relies on this check.
728
+ if (operators.provider !== "github") {
729
+ return json(501, { error: `the router can't sign operators in with ${operators.provider} yet` });
730
+ }
731
+ const key = `${operators.provider}/${operators.connection}`;
732
+ const channel = channels(store).find((c) => c.key === key)?.channel;
733
+ if (!channel) return json(404, { error: `no channel for connection ${key}` });
734
+ return channel;
735
+ };
736
+
737
+ /** Answers the page that signs an operator in, which sends their browser back to the CLI's callback. */
738
+ const signIn = async (request: Request, store: RouterStore) => {
739
+ const body = await readJson<SignInRequest>(request);
740
+ if (body instanceof Response) return body;
741
+ if (typeof body.state !== "string") return json(400, { error: "the body needs state" });
742
+ const channel = signInChannel(store);
743
+ if (channel instanceof Response) return channel;
744
+ try {
745
+ const result: SignInResult = { url: await channel.signInUrl(body.state) };
746
+ return json(200, result);
747
+ } catch (error) {
748
+ return json(502, { error: message(error) });
749
+ }
750
+ };
751
+
752
+ /** Exchanges a sign-in code for an admin session, if the operator auth lets the operator in. */
753
+ const session = async (request: Request, store: RouterStore) => {
754
+ const body = await readJson<SessionRequest>(request);
755
+ if (body instanceof Response) return body;
756
+ if (typeof body.code !== "string") return json(400, { error: "the body needs code" });
757
+ const channel = signInChannel(store);
758
+ if (channel instanceof Response) return channel;
759
+ let operator: Operator;
760
+ try {
761
+ operator = await channel.signIn(body.code);
762
+ } catch (error) {
763
+ return json(401, { error: message(error) });
764
+ }
765
+ if (!isOperator(store.config.operators, operator)) {
766
+ return json(403, { error: `${operator.login} isn't one of the hub's operators` });
767
+ }
768
+ const expires = Date.now() + SESSION_TTL_MS;
769
+ const session = await signSession(await store.rootKey(), { ...operator, expires });
770
+ const result: SessionResult = { session, operator: operator.login, expires };
771
+ console.log(JSON.stringify({ operator: operator.login, id: operator.id, state: "signed in" }));
772
+ return json(200, result);
773
+ };
774
+
775
+ /** The operator of the request's admin session, or a 401. The operator must still be in the operator auth. */
776
+ const operatorOf = async (request: Request, store: RouterStore) => {
777
+ const header = request.headers.get("authorization") ?? "";
778
+ const token = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
779
+ const found = token ? await verifySession(await store.rootKey(), token) : undefined;
780
+ if (!found || !isOperator(store.config.operators, found)) {
781
+ return json(401, { error: "sign in as an operator" });
782
+ }
783
+ return found.login;
784
+ };
785
+
786
+ /** Lists each repo's last deploy, and its containers' latest builds. */
787
+ const listRepos = async (store: RouterStore) => {
788
+ if (!store.deploys) return json(501, { error: "the router keeps no deploys" });
789
+ const result: ReposResult = { repos: await store.deploys.list() };
790
+ result.repos.sort((a, b) => a.repo.localeCompare(b.repo));
791
+ return json(200, result);
792
+ };
793
+
794
+ const listDeliveries = async (store: RouterStore) => {
795
+ const failed = await store.inbox.failed();
796
+ failed.sort((a, b) => a.received - b.received);
797
+ const result: DeliveriesResult = { failed };
798
+ return json(200, result);
799
+ };
800
+
801
+ /** Replays one failed delivery, or every one. Runs reply to this router's origin. */
802
+ const replay = async (request: Request, store: RouterStore, operator: string) => {
803
+ const body = await readJson<ReplayRequest>(request);
804
+ if (body instanceof Response) return body;
805
+ const { inbox } = store;
806
+ if ((body.connection === undefined) !== (body.id === undefined)) {
807
+ return json(400, { error: "name both connection and id, or neither" });
808
+ }
809
+ const targets =
810
+ body.connection !== undefined && body.id !== undefined
811
+ ? [{ connection: body.connection, id: body.id }]
812
+ : (await inbox.failed()).map(({ connection, id }) => ({ connection, id }));
813
+ const { origin } = new URL(request.url);
814
+ const result: ReplayResult = { replayed: [], skipped: [] };
815
+ for (const target of targets) {
816
+ const replayed = await inbox.replay(target.connection, target.id, origin);
817
+ result[replayed ? "replayed" : "skipped"].push(target);
818
+ }
819
+ console.log(JSON.stringify({ operator, ...result }));
820
+ return json(200, result);
821
+ };
822
+
823
+ /** The routes under `/admin/`. Signing in needs no session. The others need an operator's admin session. */
824
+ const admin = async (request: Request, route: string, store: RouterStore) => {
825
+ const { method } = request;
826
+ if (method === "POST" && route === "sign-in") return signIn(request, store);
827
+ if (method === "POST" && route === "session") return session(request, store);
828
+ const operator = await operatorOf(request, store);
829
+ if (operator instanceof Response) return operator;
830
+ if (method === "GET" && route === "repos") return listRepos(store);
831
+ if (method === "GET" && route === "deliveries") return listDeliveries(store);
832
+ if (method === "POST" && route === "replay") return replay(request, store, operator);
833
+ return json(404, { error: "not found" });
834
+ };
835
+
423
836
  /**
424
- * The router's routes. `POST /sync` needs no auth, because a channel's sync
425
- * only sets the values the router derives. `POST /relay` and `POST /tokens`
426
- * take tickets that the router signed when it started a run. `POST /builds`
427
- * takes reports that the deployer signed.
837
+ * The router's routes. `POST /sync` takes requests that deploy signed with
838
+ * the sync key. `POST /relay`, `POST /messages`
839
+ * and `POST /tokens` take tickets that the router signed when it started a
840
+ * run. `POST /builds` takes reports that the deployer signed. The routes
841
+ * under `/admin/` are for operators.
428
842
  */
429
843
  export const handle = (request: Request, store: RouterStore) => {
430
844
  const { pathname } = new URL(request.url);
@@ -434,6 +848,9 @@ export const handle = (request: Request, store: RouterStore) => {
434
848
  if (request.method === "POST" && pathname === "/relay") {
435
849
  return relay(request, store);
436
850
  }
851
+ if (request.method === "POST" && pathname === "/messages") {
852
+ return messages(request, store);
853
+ }
437
854
  if (request.method === "POST" && pathname === "/tokens") {
438
855
  return tokens(request, store);
439
856
  }
@@ -443,5 +860,8 @@ export const handle = (request: Request, store: RouterStore) => {
443
860
  if (request.method === "POST" && pathname === "/sync") {
444
861
  return sync(request, store);
445
862
  }
863
+ if (pathname.startsWith("/admin/")) {
864
+ return admin(request, pathname.slice("/admin/".length), store);
865
+ }
446
866
  return Promise.resolve(json(404, { error: "not found" }));
447
867
  };