@notation/factory 0.2.2 → 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,29 +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
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";
4
20
  import type {
5
21
  AuthorCheck,
6
22
  BuildCheck,
7
23
  Delivery,
8
24
  FactoryStatus,
25
+ Operator,
9
26
  RemoteChannel,
10
27
  SourceChange,
11
28
  SourceFiles,
12
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";
13
39
  import {
14
40
  type BuildReportRequest,
15
41
  isBranchName,
42
+ type MessagesRequest,
43
+ type MessagesResult,
16
44
  type Relay,
45
+ type RelayResult,
17
46
  REPLY_TTL_MS,
18
47
  type Run,
48
+ type RunResult,
49
+ signMessage,
19
50
  signTicket,
20
51
  signTokenTicket,
21
52
  type TokenRequest,
22
53
  type Tokens,
23
54
  verifyBuildReport,
55
+ verifyMessage,
24
56
  verifyTicket,
25
57
  verifyTokenTicket,
26
58
  } from "./run.ts";
59
+ import { SYNC_HEADER, verifySync } from "./sync.ts";
27
60
 
28
61
  /** The KV key that the deployer stores a repo's outpost config under. `repo` is `owner/name`. */
29
62
  export const outpostKey = (repo: string) => `outposts/${repo.toLowerCase()}`;
@@ -37,8 +70,21 @@ export type RouterStore = {
37
70
  deployer?: RemoteDeployer;
38
71
  /** The root key, which the router derives its own keys from. */
39
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>;
40
75
  /** Keeps `task` running after the response, where the platform allows it. Without it, the router waits for the task. */
41
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>;
42
88
  };
43
89
 
44
90
  /** The deployer, as the router calls it. */
@@ -49,8 +95,8 @@ export type RemoteDeployer = {
49
95
  remove(repo: string): Promise<void>;
50
96
  /** Calls the worktree function of the repo's trigger with `payload`, in the isolate that evaluates configs. */
51
97
  worktree(repo: string, trigger: string, payload: unknown): Promise<string | undefined>;
52
- /** Hands `run` to its container, which queues it. */
53
- 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>;
54
100
  };
55
101
 
56
102
  /** The name of the check that shows the build of a container's image, such as `factory/build dev`. */
@@ -84,7 +130,10 @@ const channels = (store: RouterStore) =>
84
130
  * 2. Has the channel verify and parse the delivery.
85
131
  * 3. Reads the outpost of the delivery's repo, and matches the triggers on
86
132
  * channels of the delivery's connection and scope.
87
- * 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.
88
137
  */
89
138
  const webhook = async (request: Request, key: string, store: RouterStore) => {
90
139
  const found = channels(store).find((c) => c.key === key);
@@ -105,18 +154,9 @@ const webhook = async (request: Request, key: string, store: RouterStore) => {
105
154
  if (!outpost) return json(202, { ...summary, ignored: "no outpost" });
106
155
 
107
156
  const matches: TriggerMatch[] = [];
108
- const runs: Promise<void>[] = [];
109
- const origin = new URL(request.url).origin;
157
+ const dispatches: TriggerDispatch[] = [];
110
158
  for (const [id, trigger] of Object.entries(outpost.triggers ?? {})) {
111
- const target = outpost.channels?.[trigger.channel];
112
- if (
113
- trigger.event !== delivery.event ||
114
- target?.provider !== entry.provider ||
115
- target.connection !== name ||
116
- target.scope !== delivery.scope
117
- ) {
118
- continue;
119
- }
159
+ if (!listens(outpost, trigger, entry.provider, name, delivery)) continue;
120
160
  const author = await channel.match(trigger.match, delivery);
121
161
  if (!author) continue;
122
162
  // Team checks need a call to the platform, which the router doesn't make yet.
@@ -126,30 +166,147 @@ const webhook = async (request: Request, key: string, store: RouterStore) => {
126
166
  }
127
167
  const run = crypto.randomUUID();
128
168
  matches.push({ trigger: id, author, run });
129
- runs.push(
130
- dispatch({ run, trigger: id, key, channel, delivery, outpost, origin }, store).catch((error) =>
131
- console.error(JSON.stringify({ run, trigger: id, error: message(error) })),
132
- ),
133
- );
169
+ dispatches.push({ trigger: id, run, state: "pending" });
134
170
  }
135
- if (runs.length) {
136
- const task = Promise.all(runs);
137
- if (store.background) store.background(task);
138
- 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
+ }
139
185
  }
140
186
  const result = { ...summary, matches };
141
187
  console.log(JSON.stringify(result));
142
188
  return json(202, result);
143
189
  };
144
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
+
145
300
  type Dispatch = {
146
- run: string;
147
- trigger: string;
148
- /** The delivery's connection. */
301
+ dispatch: TriggerDispatch;
302
+ /** The delivery's connection, and its provider and name. */
149
303
  key: string;
304
+ provider: string;
305
+ name: string;
150
306
  channel: RemoteChannel;
151
307
  delivery: Delivery<unknown>;
152
- outpost: OutpostConfig;
308
+ /** The repo's outpost config as it is now. */
309
+ outpost: OutpostConfig | undefined;
153
310
  /** The router's origin, which the runner replies to. */
154
311
  origin: string;
155
312
  };
@@ -182,95 +339,143 @@ const mintTokens = async (store: RouterStore, outpost: OutpostConfig, repo: stri
182
339
  };
183
340
 
184
341
  /**
185
- * Starts one run of a matched trigger:
186
- * 1. Has the delivery's channel name the conversation, and signs a ticket
187
- * 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.
188
349
  * 2. Has the deployer call the trigger's worktree function, if it has one.
189
350
  * 3. Has the code host's channel mint a read-only token for the clone, and a
190
351
  * token for each of the container's code host policies. Signs a ticket
191
352
  * for new tokens.
192
- * 4. Hands the run to the deployer. If a step fails, the channel replies
193
- * with the error.
353
+ * 4. Hands the run to the deployer.
194
354
  */
195
- const dispatch = async (d: Dispatch, store: RouterStore) => {
355
+ const dispatch = async (d: Dispatch, store: RouterStore): Promise<string | undefined> => {
196
356
  const { delivery, outpost } = d;
357
+ const { trigger: triggerId, run: runId, waiting } = d.dispatch;
197
358
  const repo = delivery.repo;
198
- 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
+ }
199
367
  const conversation = await d.channel.conversation(delivery, { selector: trigger.match, agent: trigger.agent });
368
+ d.dispatch.thread = conversation.thread;
200
369
  const ticket = { connection: d.key, thread: conversation.thread, expires: Date.now() + REPLY_TTL_MS };
201
370
  const rootKey = await store.rootKey();
202
- const reply = { url: `${d.origin}/relay`, ticket, signature: await signTicket(rootKey, ticket) };
203
- try {
204
- const { deployer } = store;
205
- if (!deployer) throw new Error("The hub has no deployer.");
206
- const container = outpost.containers[trigger.container];
207
- const agent = outpost.agents[trigger.agent];
208
- if (!container) throw new Error(`The outpost has no container ${trigger.container}.`);
209
- if (!agent) throw new Error(`The outpost has no agent ${trigger.agent}.`);
210
- const codeHost = codeHostChannel(store);
211
- if (!codeHost?.channel) throw new Error("The hub has no code host whose channel mints tokens.");
212
-
213
- let worktree: Run["worktree"];
214
- if (trigger.worktree) {
215
- const branch = await deployer.worktree(repo, d.trigger, delivery.payload);
216
- if (branch !== undefined) {
217
- if (typeof branch !== "string" || !isBranchName(branch)) {
218
- throw new Error(`The worktree function of ${d.trigger} returned ${JSON.stringify(branch)}, which isn't a branch name the runner can check out.`);
219
- }
220
- 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.`);
221
389
  }
390
+ worktree = { branch, ...(trigger.worktree.base && { base: trigger.worktree.base }) };
222
391
  }
223
-
224
- const tokens = await mintTokens(store, outpost, repo, trigger.container);
225
- const tokenTicket = { repo, container: trigger.container, expires: Date.now() + REPLY_TTL_MS };
226
- const refresh = { url: `${d.origin}/tokens`, ticket: tokenTicket, signature: await signTokenTicket(rootKey, tokenTicket) };
227
-
228
- await deployer.run({
229
- id: d.run,
230
- repo,
231
- trigger: d.trigger,
232
- container: trigger.container,
233
- runtimes: container.runtimes,
234
- files: container.files ?? {},
235
- agent: { id: trigger.agent, ...agent },
236
- conversation: {
237
- id: conversation.id,
238
- prompt: conversation.prompt,
239
- ...(conversation.channel && { channel: conversation.channel }),
240
- ...(conversation.context && { context: conversation.context }),
241
- },
242
- ...(worktree && { worktree }),
243
- cloneToken: await codeHost.channel.token(repo, { contents: "read" }),
244
- tokens,
245
- refresh,
246
- reply,
247
- });
248
- console.log(JSON.stringify({ run: d.run, repo, trigger: d.trigger, container: trigger.container, worktree }));
249
- } catch (error) {
250
- await d.channel.reply(conversation.thread, `Couldn't start the run of trigger \`${d.trigger}\`: ${message(error)}`);
251
- throw error;
252
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;
253
422
  };
254
423
 
255
- /** Posts a container's reply, if the router signed its ticket, through the channel of the ticket's connection. */
256
- const relay = async (request: Request, store: RouterStore) => {
257
- 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;
258
431
  try {
259
- body = (await request.json()) as Relay;
432
+ body = (await request.json()) as T;
260
433
  } catch {
261
434
  return json(400, { error: "the body isn't JSON" });
262
435
  }
263
- const { ticket, signature, text } = body ?? {};
264
- if (!ticket || typeof signature !== "string" || typeof text !== "string") {
265
- return json(400, { error: "the body needs ticket, signature and text" });
266
- }
267
- 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))) {
268
440
  return json(401, { error: "bad or expired ticket" });
269
441
  }
270
442
  const found = channels(store).find((c) => c.key === ticket.connection);
271
443
  if (!found) return json(404, { error: `no channel for connection ${ticket.connection}` });
272
- await found.channel.reply(ticket.thread, text);
273
- 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
+ }
274
479
  };
275
480
 
276
481
  /**
@@ -299,7 +504,11 @@ const tokens = async (request: Request, store: RouterStore) => {
299
504
  }
300
505
  };
301
506
 
302
- /** 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
+ */
303
512
  const builds = async (request: Request, store: RouterStore) => {
304
513
  let body: BuildReportRequest;
305
514
  try {
@@ -315,6 +524,10 @@ const builds = async (request: Request, store: RouterStore) => {
315
524
  const channel = codeHostChannel(store)?.channel;
316
525
  if (!channel) return json(404, { error: "the hub has no code host" });
317
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
+ );
318
531
  try {
319
532
  await channel.writeCheck(repo, ref, { name: buildCheckName(container), state, ...(url && { url }), ...(summary && { summary }) });
320
533
  } catch (error) {
@@ -323,6 +536,14 @@ const builds = async (request: Request, store: RouterStore) => {
323
536
  return json(200, { ok: true });
324
537
  };
325
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
+
326
547
  /** Writes a check, and logs a failure instead of throwing it. The App may not have the checks permission yet. */
327
548
  const writeCheck = async (channel: RemoteChannel, repo: string, ref: string, check: BuildCheck) => {
328
549
  try {
@@ -343,15 +564,23 @@ const message = (error: unknown) => (error instanceof Error ? error.message : St
343
564
  * 3. The channel shows the outcome on the repo, and a queued check on the
344
565
  * commit for each container whose image started building. The deployer
345
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.
346
569
  */
347
570
  const redeploy = async (
348
571
  change: SourceChange,
349
572
  allow: RepoPattern[],
350
573
  channel: RemoteChannel,
351
574
  deployer: RemoteDeployer,
575
+ store: RouterStore,
352
576
  ) => {
353
577
  const { repo, ref } = change;
354
- 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
+ }
355
584
  const at = () => new Date().toISOString();
356
585
  let status: FactoryStatus;
357
586
  if (!allowsRepo(allow, repo)) {
@@ -364,9 +593,16 @@ const redeploy = async (
364
593
  status = { state: "failed", ref, error: message(error), at: at() };
365
594
  }
366
595
  }
596
+ await log?.put(repo, status);
367
597
  await channel.writeStatus(repo, status);
368
598
  for (const container of status.builds ?? []) {
369
- if (status.ref) await writeCheck(channel, repo, status.ref, { name: buildCheckName(container), state: "queued" });
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));
370
606
  }
371
607
  console.log(JSON.stringify({ repo, ...status }));
372
608
  };
@@ -384,23 +620,80 @@ const source = async (
384
620
  }
385
621
  const { deployer } = store;
386
622
  if (!deployer) return json(200, { ignored: "no deployer" });
387
- const task = (async () => {
388
- for (const change of changes) {
389
- try {
390
- await redeploy(change, codeHost.allow ?? [], channel, deployer);
391
- } catch (error) {
392
- console.error(JSON.stringify({ repo: change.repo, error: message(error) }));
393
- }
394
- }
395
- })();
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>) => {
396
629
  if (store.background) store.background(task);
397
630
  else await task;
398
- return json(202, { connection: key, deploying: changes.map((c) => c.repo) });
399
631
  };
400
632
 
401
- /** 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
+ */
402
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" });
403
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
+ }
404
697
  const results: Record<string, string> = {};
405
698
  for (const { key, channel } of channels(store)) {
406
699
  try {
@@ -410,15 +703,142 @@ const sync = async (request: Request, store: RouterStore) => {
410
703
  results[key] = error instanceof Error ? error.message : String(error);
411
704
  }
412
705
  }
706
+ await later(
707
+ store,
708
+ syncRepos(store).catch((error) => console.error(JSON.stringify({ sync: "failed", error: message(error) }))),
709
+ );
413
710
  const failed = Object.values(results).some((r) => r !== "ok");
414
711
  return json(failed ? 502 : 200, { connections: results });
415
712
  };
416
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
+
417
836
  /**
418
- * The router's routes. `POST /sync` needs no auth, because a channel's sync
419
- * only sets the values the router derives. `POST /relay` and `POST /tokens`
420
- * take tickets that the router signed when it started a run. `POST /builds`
421
- * 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.
422
842
  */
423
843
  export const handle = (request: Request, store: RouterStore) => {
424
844
  const { pathname } = new URL(request.url);
@@ -428,6 +848,9 @@ export const handle = (request: Request, store: RouterStore) => {
428
848
  if (request.method === "POST" && pathname === "/relay") {
429
849
  return relay(request, store);
430
850
  }
851
+ if (request.method === "POST" && pathname === "/messages") {
852
+ return messages(request, store);
853
+ }
431
854
  if (request.method === "POST" && pathname === "/tokens") {
432
855
  return tokens(request, store);
433
856
  }
@@ -437,5 +860,8 @@ export const handle = (request: Request, store: RouterStore) => {
437
860
  if (request.method === "POST" && pathname === "/sync") {
438
861
  return sync(request, store);
439
862
  }
863
+ if (pathname.startsWith("/admin/")) {
864
+ return admin(request, pathname.slice("/admin/".length), store);
865
+ }
440
866
  return Promise.resolve(json(404, { error: "not found" }));
441
867
  };