@notation/factory 0.5.5 → 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.
- package/contracts/index.ts +1 -1
- package/contracts/outpost.ts +5 -2
- package/contracts/runner.ts +16 -0
- package/deployer/sdk.gen.ts +1 -1
- package/implementations/container.ts +10 -3
- package/package.json +1 -1
- package/router/channel.ts +12 -6
- package/router/deliveries.ts +110 -9
- package/router/handle.test.ts +298 -7
- package/router/handle.ts +236 -11
- package/router/index.ts +27 -2
- package/router/run.ts +73 -7
- package/runner/index.ts +352 -52
- package/runner/runner.test.ts +304 -7
package/router/handle.ts
CHANGED
|
@@ -33,26 +33,38 @@ import {
|
|
|
33
33
|
type DeliveryRecord,
|
|
34
34
|
failureNotice,
|
|
35
35
|
type Inbox,
|
|
36
|
+
isLost,
|
|
37
|
+
KEEP_DELIVERY_MS,
|
|
38
|
+
LOST_ERROR,
|
|
39
|
+
lostNotice,
|
|
40
|
+
nextTry,
|
|
36
41
|
type TriggerDispatch,
|
|
37
42
|
waitingNotice,
|
|
43
|
+
type Watch,
|
|
38
44
|
} from "./deliveries.ts";
|
|
39
45
|
import {
|
|
40
46
|
type BuildReportRequest,
|
|
47
|
+
type Heartbeat,
|
|
48
|
+
type HeartbeatResult,
|
|
41
49
|
isBranchName,
|
|
50
|
+
LOST_AFTER_MS,
|
|
42
51
|
type MessagesRequest,
|
|
43
52
|
type MessagesResult,
|
|
44
53
|
type Relay,
|
|
45
54
|
type RelayResult,
|
|
46
55
|
REPLY_TTL_MS,
|
|
56
|
+
type RestartTicket,
|
|
47
57
|
type Run,
|
|
48
58
|
type RunResult,
|
|
49
59
|
signMessage,
|
|
60
|
+
signRestart,
|
|
50
61
|
signTicket,
|
|
51
62
|
signTokenTicket,
|
|
52
63
|
type TokenRequest,
|
|
53
64
|
type Tokens,
|
|
54
65
|
verifyBuildReport,
|
|
55
66
|
verifyMessage,
|
|
67
|
+
verifyRestart,
|
|
56
68
|
verifyTicket,
|
|
57
69
|
verifyTokenTicket,
|
|
58
70
|
} from "./run.ts";
|
|
@@ -108,6 +120,15 @@ export const FACTORY_DIR = ".factory";
|
|
|
108
120
|
/** A trigger that a delivery matched. `run` is the id of the run it started, if its author may start one. */
|
|
109
121
|
export type TriggerMatch = { trigger: string; author: AuthorCheck; run?: string };
|
|
110
122
|
|
|
123
|
+
/** The router's page that a lost run's restart link opens. */
|
|
124
|
+
export const RESTART_PATH = "/restart";
|
|
125
|
+
|
|
126
|
+
/** The router's page that the sign-in of a restart link sends the browser back to. A code host's App must allow it as a callback URL. */
|
|
127
|
+
export const RESTART_CALLBACK_PATH = "/restart/callback";
|
|
128
|
+
|
|
129
|
+
/** The router's page that says a run is starting again. The callback redirects to it, so reloading the page doesn't send GitHub's code again. */
|
|
130
|
+
const RESTARTED_PATH = "/restart/started";
|
|
131
|
+
|
|
111
132
|
/** The path that a connection's platform delivers to. `key` is the connection's key, such as `github/gh`. */
|
|
112
133
|
export const webhookPath = (key: string) => `/webhook/${key}`;
|
|
113
134
|
|
|
@@ -244,7 +265,17 @@ export const advance = async (record: DeliveryRecord, store: RouterStore, now =
|
|
|
244
265
|
return;
|
|
245
266
|
}
|
|
246
267
|
const building = await dispatch(
|
|
247
|
-
{
|
|
268
|
+
{
|
|
269
|
+
dispatch: d,
|
|
270
|
+
id: record.id,
|
|
271
|
+
key: record.connection,
|
|
272
|
+
provider: entry.provider,
|
|
273
|
+
name,
|
|
274
|
+
channel,
|
|
275
|
+
delivery: record.delivery,
|
|
276
|
+
outpost,
|
|
277
|
+
origin: record.origin,
|
|
278
|
+
},
|
|
248
279
|
store,
|
|
249
280
|
);
|
|
250
281
|
if (building) await waitForBuild(d, building, repo, channel, store, now);
|
|
@@ -260,8 +291,7 @@ export const advance = async (record: DeliveryRecord, store: RouterStore, now =
|
|
|
260
291
|
}),
|
|
261
292
|
);
|
|
262
293
|
}
|
|
263
|
-
|
|
264
|
-
return pending.length ? Math.min(...pending.map((d) => d.next ?? now)) : undefined;
|
|
294
|
+
return nextTry(record, now);
|
|
265
295
|
};
|
|
266
296
|
|
|
267
297
|
const isBuilding = async (store: RouterStore, repo: string, container: string) => {
|
|
@@ -302,8 +332,55 @@ const waitForBuild = async (
|
|
|
302
332
|
}
|
|
303
333
|
};
|
|
304
334
|
|
|
335
|
+
/**
|
|
336
|
+
* Marks lost each dispatched run of the record whose last heartbeat in
|
|
337
|
+
* `watches` is `LOST_AFTER_MS` old, and posts the lost notice in place of
|
|
338
|
+
* the run's message. A run is watched from its first heartbeat, which the
|
|
339
|
+
* outpost posts as soon as it takes the run, so the router doesn't mark
|
|
340
|
+
* lost the runs of an outpost that sends no heartbeats. The notice has a
|
|
341
|
+
* restart link, signed for the run, which works for `KEEP_DELIVERY_MS`, as
|
|
342
|
+
* long as the inbox keeps the delivery. It changes `record`, which the
|
|
343
|
+
* caller saves, and resolves to the runs to stop watching, to when to check
|
|
344
|
+
* the others again, and to whether it marked a run lost.
|
|
345
|
+
*/
|
|
346
|
+
export const watch = async (record: DeliveryRecord, watches: Map<string, Watch>, store: RouterStore, now = Date.now()) => {
|
|
347
|
+
const forget: string[] = [];
|
|
348
|
+
let next: number | undefined;
|
|
349
|
+
let lost = false;
|
|
350
|
+
const channel = channels(store).find((c) => c.key === record.connection)?.channel;
|
|
351
|
+
for (const [run, beat] of watches) {
|
|
352
|
+
const d = record.dispatches.find((d) => d.run === run);
|
|
353
|
+
if (!d || d.state === "failed" || d.state === "lost") {
|
|
354
|
+
forget.push(run);
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
if ("done" in beat) continue;
|
|
358
|
+
const due = beat.at + LOST_AFTER_MS;
|
|
359
|
+
if (d.state !== "dispatched" || due > now) {
|
|
360
|
+
next = Math.min(next ?? due, due);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
Object.assign(d, { state: "lost", error: LOST_ERROR });
|
|
364
|
+
forget.push(run);
|
|
365
|
+
lost = true;
|
|
366
|
+
console.error(JSON.stringify({ run, trigger: d.trigger, state: "lost", heartbeat: beat.at }));
|
|
367
|
+
if (!channel || d.thread === undefined) continue;
|
|
368
|
+
try {
|
|
369
|
+
const ticket = { connection: record.connection, delivery: record.id, run, expires: now + KEEP_DELIVERY_MS };
|
|
370
|
+
const link = `${record.origin}${RESTART_PATH}?run=${encodeURIComponent(await signRestart(await store.rootKey(), ticket))}`;
|
|
371
|
+
const posted = await channel.reply(d.thread, lostNotice(link), beat.message ?? d.waiting);
|
|
372
|
+
if (posted !== undefined) d.waiting = posted;
|
|
373
|
+
} catch (error) {
|
|
374
|
+
console.error(JSON.stringify({ run, state: "lost notice failed", error: message(error) }));
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return { forget, next, lost };
|
|
378
|
+
};
|
|
379
|
+
|
|
305
380
|
type Dispatch = {
|
|
306
381
|
dispatch: TriggerDispatch;
|
|
382
|
+
/** The delivery's id in the inbox. */
|
|
383
|
+
id: string;
|
|
307
384
|
/** The delivery's connection, and its provider and name. */
|
|
308
385
|
key: string;
|
|
309
386
|
provider: string;
|
|
@@ -349,8 +426,8 @@ const mintTokens = async (store: RouterStore, outpost: OutpostConfig, repo: stri
|
|
|
349
426
|
* 1. Checks that the outpost still has the trigger, and that it still
|
|
350
427
|
* matches the delivery and its author. Has the delivery's channel name
|
|
351
428
|
* the conversation, and signs a ticket for reading and replying to its
|
|
352
|
-
* thread. The run's first reply replaces
|
|
353
|
-
* if there is one.
|
|
429
|
+
* thread, and for the run's heartbeats. The run's first reply replaces
|
|
430
|
+
* the thread's waiting message, if there is one.
|
|
354
431
|
* 2. Has the deployer call the trigger's worktree function, if it has one.
|
|
355
432
|
* 3. Has the code host's channel mint a read-only token for the clone, and a
|
|
356
433
|
* token for each of the container's code host policies. Signs a ticket
|
|
@@ -371,10 +448,10 @@ const dispatch = async (d: Dispatch, store: RouterStore): Promise<string | undef
|
|
|
371
448
|
}
|
|
372
449
|
const conversation = await d.channel.conversation(delivery, { selector: trigger.match, agent: trigger.agent });
|
|
373
450
|
d.dispatch.thread = conversation.thread;
|
|
374
|
-
const ticket = { connection: d.key, thread: conversation.thread, expires: Date.now() + REPLY_TTL_MS };
|
|
451
|
+
const ticket = { connection: d.key, thread: conversation.thread, delivery: d.id, run: runId, expires: Date.now() + REPLY_TTL_MS };
|
|
375
452
|
const rootKey = await store.rootKey();
|
|
376
453
|
const signature = await signTicket(rootKey, ticket);
|
|
377
|
-
const reply: Run["reply"] = { url: `${d.origin}/relay`, ticket, signature };
|
|
454
|
+
const reply: Run["reply"] = { url: `${d.origin}/relay`, ticket, signature, heartbeat: `${d.origin}/heartbeat` };
|
|
378
455
|
if (waiting) reply.message = { id: waiting, signature: await signMessage(rootKey, signature, waiting) };
|
|
379
456
|
const { deployer } = store;
|
|
380
457
|
if (!deployer) throw new Error("The hub has no deployer.");
|
|
@@ -449,12 +526,21 @@ const ticketed = async <T extends MessagesRequest>(request: Request, store: Rout
|
|
|
449
526
|
return { body, rootKey, channel: found.channel };
|
|
450
527
|
};
|
|
451
528
|
|
|
452
|
-
/**
|
|
529
|
+
/**
|
|
530
|
+
* Posts a container's reply, if the router signed its ticket, through the
|
|
531
|
+
* channel of the ticket's connection. For a ticket that names a run:
|
|
532
|
+
* 1. Answers 409 with `lost`, and posts nothing, if the run is lost, so a
|
|
533
|
+
* run that comes back doesn't replace the lost notice.
|
|
534
|
+
* 2. With `done`, stops watching the run once the reply is posted. A reply
|
|
535
|
+
* that fails leaves the run watched, so the lost notice replaces the
|
|
536
|
+
* run's last message.
|
|
537
|
+
*/
|
|
453
538
|
const relay = async (request: Request, store: RouterStore) => {
|
|
454
539
|
const found = await ticketed<Relay>(request, store);
|
|
455
540
|
if (found instanceof Response) return found;
|
|
456
541
|
const { body, rootKey, channel } = found;
|
|
457
|
-
const { ticket, signature, text, message } = body;
|
|
542
|
+
const { ticket, signature, text, message, done } = body;
|
|
543
|
+
const { delivery, run } = ticket;
|
|
458
544
|
if (typeof text !== "string") return json(400, { error: "the body needs text" });
|
|
459
545
|
if (message !== undefined && (typeof message?.id !== "string" || typeof message.signature !== "string")) {
|
|
460
546
|
return json(400, { error: "the message needs id and signature" });
|
|
@@ -462,7 +548,17 @@ const relay = async (request: Request, store: RouterStore) => {
|
|
|
462
548
|
if (message && !(await verifyMessage(rootKey, signature, message))) {
|
|
463
549
|
return json(401, { error: "bad message signature" });
|
|
464
550
|
}
|
|
551
|
+
const named = typeof delivery === "string" && typeof run === "string";
|
|
552
|
+
if (named && isLost(await store.inbox.record(ticket.connection, delivery), run)) {
|
|
553
|
+
return json(409, { error: "the router marked the run lost", lost: true });
|
|
554
|
+
}
|
|
465
555
|
const id = await channel.reply(ticket.thread, text, message?.id);
|
|
556
|
+
if (named && done === true) {
|
|
557
|
+
// The reply is posted, so answer 200 even if the done mark fails.
|
|
558
|
+
await store.inbox.heartbeat(ticket.connection, delivery, run, { done: true }).catch((error) => {
|
|
559
|
+
console.error(JSON.stringify({ run, relay: "done mark failed", error: String(error) }));
|
|
560
|
+
});
|
|
561
|
+
}
|
|
466
562
|
const result: RelayResult = { ok: true };
|
|
467
563
|
if (typeof id === "string") result.message = { id, signature: await signMessage(rootKey, signature, id) };
|
|
468
564
|
return json(200, result);
|
|
@@ -483,6 +579,34 @@ const messages = async (request: Request, store: RouterStore) => {
|
|
|
483
579
|
}
|
|
484
580
|
};
|
|
485
581
|
|
|
582
|
+
/**
|
|
583
|
+
* Notes a run's heartbeat in the inbox, if the router signed its reply
|
|
584
|
+
* ticket for a run. Answers `lost` if the run is lost, such as when a
|
|
585
|
+
* restart replaced it with a new run.
|
|
586
|
+
*/
|
|
587
|
+
const heartbeat = async (request: Request, store: RouterStore) => {
|
|
588
|
+
const found = await ticketed<Heartbeat>(request, store);
|
|
589
|
+
if (found instanceof Response) return found;
|
|
590
|
+
const { body, rootKey } = found;
|
|
591
|
+
const { ticket, signature, message: posted, done } = body;
|
|
592
|
+
if (typeof ticket.delivery !== "string" || typeof ticket.run !== "string") {
|
|
593
|
+
return json(400, { error: "the ticket names no run" });
|
|
594
|
+
}
|
|
595
|
+
if (posted !== undefined && (typeof posted?.id !== "string" || typeof posted.signature !== "string")) {
|
|
596
|
+
return json(400, { error: "the message needs id and signature" });
|
|
597
|
+
}
|
|
598
|
+
if (posted && !(await verifyMessage(rootKey, signature, posted))) {
|
|
599
|
+
return json(401, { error: "bad message signature" });
|
|
600
|
+
}
|
|
601
|
+
const result = await store.inbox.heartbeat(ticket.connection, ticket.delivery, ticket.run, {
|
|
602
|
+
...(posted && { message: posted.id }),
|
|
603
|
+
...(done === true && { done: true }),
|
|
604
|
+
});
|
|
605
|
+
if (result === "unknown") return json(404, { error: "the inbox has no such run" });
|
|
606
|
+
const answer: HeartbeatResult = { ok: true, ...(result === "lost" && { lost: true }) };
|
|
607
|
+
return json(200, answer);
|
|
608
|
+
};
|
|
609
|
+
|
|
486
610
|
/**
|
|
487
611
|
* Mints a container's policy tokens again, if the router signed the
|
|
488
612
|
* ticket. The tokens follow the outpost config that the repo has now.
|
|
@@ -716,6 +840,93 @@ const sync = async (request: Request, store: RouterStore) => {
|
|
|
716
840
|
return json(failed ? 502 : 200, { connections: results });
|
|
717
841
|
};
|
|
718
842
|
|
|
843
|
+
const escapeHtml = (text: string) =>
|
|
844
|
+
text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
845
|
+
|
|
846
|
+
/** A page for a person's browser, with one paragraph of text. */
|
|
847
|
+
const page = (status: number, text: string) =>
|
|
848
|
+
new Response(`<!doctype html><meta charset="utf-8"><title>Notation Factory</title><p>${escapeHtml(text)}</p>`, {
|
|
849
|
+
status,
|
|
850
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
851
|
+
});
|
|
852
|
+
|
|
853
|
+
/** The ticket of a restart link's token, and the channel of its connection, or a page that says why there's none. */
|
|
854
|
+
const restartTicket = async (token: string, store: RouterStore) => {
|
|
855
|
+
const ticket = token ? await verifyRestart(await store.rootKey(), token) : undefined;
|
|
856
|
+
if (!ticket) return page(401, "This restart link isn't valid, or it has expired.");
|
|
857
|
+
const channel = channels(store).find((c) => c.key === ticket.connection)?.channel;
|
|
858
|
+
if (!channel) return page(404, `The hub has no channel for connection ${ticket.connection}.`);
|
|
859
|
+
return { ticket, channel };
|
|
860
|
+
};
|
|
861
|
+
|
|
862
|
+
/** The delivery of a restart link's ticket, and its dispatch, if that dispatch is still the lost run. */
|
|
863
|
+
const lostRun = async (ticket: RestartTicket, store: RouterStore) => {
|
|
864
|
+
const record = await store.inbox.record(ticket.connection, ticket.delivery);
|
|
865
|
+
const dispatch = record?.dispatches.find((d) => d.run === ticket.run);
|
|
866
|
+
return record && dispatch?.state === "lost" ? { record, dispatch } : undefined;
|
|
867
|
+
};
|
|
868
|
+
|
|
869
|
+
const NOT_LOST = "This run isn't lost any more. Someone may have restarted it already.";
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* Sends the browser to the sign-in page of the lost run's channel, which
|
|
873
|
+
* sends it to the callback with the link's token as the state, if the run
|
|
874
|
+
* is still lost.
|
|
875
|
+
*/
|
|
876
|
+
const restartLink = async (request: Request, store: RouterStore) => {
|
|
877
|
+
const url = new URL(request.url);
|
|
878
|
+
const token = url.searchParams.get("run") ?? "";
|
|
879
|
+
const found = await restartTicket(token, store);
|
|
880
|
+
if (found instanceof Response) return found;
|
|
881
|
+
if (!(await lostRun(found.ticket, store))) return page(409, NOT_LOST);
|
|
882
|
+
try {
|
|
883
|
+
const location = await found.channel.signInUrl(token, `${url.origin}${RESTART_CALLBACK_PATH}`);
|
|
884
|
+
return new Response(null, { status: 302, headers: { location } });
|
|
885
|
+
} catch (error) {
|
|
886
|
+
return page(502, `Factory couldn't start the sign-in: ${message(error)}`);
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* Restarts a lost run for the person who signed in:
|
|
892
|
+
* 1. Checks the restart link's token, which comes back as the sign-in's state.
|
|
893
|
+
* 2. Has the channel of the token's connection sign the person in with the code.
|
|
894
|
+
* 3. Finds the lost run in the inbox, and its trigger in the outpost config
|
|
895
|
+
* that the repo has now.
|
|
896
|
+
* 4. Has the channel check that the trigger's `from` lets the person start a run.
|
|
897
|
+
* 5. Has the inbox dispatch the run again, as a new run, and redirects the
|
|
898
|
+
* browser to the page that says so.
|
|
899
|
+
*/
|
|
900
|
+
const restartCallback = async (request: Request, store: RouterStore) => {
|
|
901
|
+
const url = new URL(request.url);
|
|
902
|
+
const found = await restartTicket(url.searchParams.get("state") ?? "", store);
|
|
903
|
+
if (found instanceof Response) return found;
|
|
904
|
+
const { ticket, channel } = found;
|
|
905
|
+
const code = url.searchParams.get("code");
|
|
906
|
+
if (!code) return page(400, "The sign-in returned no code.");
|
|
907
|
+
let person: Operator;
|
|
908
|
+
try {
|
|
909
|
+
person = await channel.signIn(code, `${url.origin}${RESTART_CALLBACK_PATH}`);
|
|
910
|
+
} catch (error) {
|
|
911
|
+
return page(401, `Signing in failed: ${message(error)}`);
|
|
912
|
+
}
|
|
913
|
+
const lost = await lostRun(ticket, store);
|
|
914
|
+
if (!lost) return page(409, NOT_LOST);
|
|
915
|
+
const { record, dispatch } = lost;
|
|
916
|
+
const trigger = (await store.outpost(record.delivery.repo))?.triggers?.[dispatch.trigger];
|
|
917
|
+
if (!trigger) return page(404, `The outpost of ${record.delivery.repo} no longer has the trigger ${dispatch.trigger}.`);
|
|
918
|
+
let allowed: boolean;
|
|
919
|
+
try {
|
|
920
|
+
allowed = await channel.canTrigger(trigger.match, record.delivery, person);
|
|
921
|
+
} catch (error) {
|
|
922
|
+
return page(502, `Factory couldn't check who may trigger the agent: ${message(error)}`);
|
|
923
|
+
}
|
|
924
|
+
if (!allowed) return page(403, `${person.login} may not trigger this agent, so the run wasn't restarted.`);
|
|
925
|
+
if (!(await store.inbox.restart(ticket.connection, ticket.delivery, ticket.run, url.origin))) return page(409, NOT_LOST);
|
|
926
|
+
console.log(JSON.stringify({ run: ticket.run, delivery: ticket.delivery, state: "restarted", by: person.login, id: person.id }));
|
|
927
|
+
return new Response(null, { status: 303, headers: { location: `${url.origin}${RESTARTED_PATH}` } });
|
|
928
|
+
};
|
|
929
|
+
|
|
719
930
|
/** Reads a JSON object body, or answers 400. */
|
|
720
931
|
const readJson = async <T>(request: Request): Promise<T | Response> => {
|
|
721
932
|
try {
|
|
@@ -840,10 +1051,12 @@ const admin = async (request: Request, route: string, store: RouterStore) => {
|
|
|
840
1051
|
|
|
841
1052
|
/**
|
|
842
1053
|
* The router's routes. `POST /sync` takes requests that deploy signed with
|
|
843
|
-
* the sync key. `POST /relay`, `POST /messages`
|
|
1054
|
+
* the sync key. `POST /relay`, `POST /messages`, `POST /heartbeat`
|
|
844
1055
|
* and `POST /tokens` take tickets that the router signed when it started a
|
|
845
1056
|
* run. `POST /builds` takes reports that the deployer signed. The routes
|
|
846
|
-
* under `/admin/` are for operators.
|
|
1057
|
+
* under `/admin/` are for operators. `GET /restart`, `GET
|
|
1058
|
+
* /restart/callback` and `GET /restart/started` are the pages of a lost
|
|
1059
|
+
* run's restart link, which the router signed.
|
|
847
1060
|
*/
|
|
848
1061
|
export const handle = (request: Request, store: RouterStore) => {
|
|
849
1062
|
const { pathname } = new URL(request.url);
|
|
@@ -856,6 +1069,9 @@ export const handle = (request: Request, store: RouterStore) => {
|
|
|
856
1069
|
if (request.method === "POST" && pathname === "/messages") {
|
|
857
1070
|
return messages(request, store);
|
|
858
1071
|
}
|
|
1072
|
+
if (request.method === "POST" && pathname === "/heartbeat") {
|
|
1073
|
+
return heartbeat(request, store);
|
|
1074
|
+
}
|
|
859
1075
|
if (request.method === "POST" && pathname === "/tokens") {
|
|
860
1076
|
return tokens(request, store);
|
|
861
1077
|
}
|
|
@@ -865,6 +1081,15 @@ export const handle = (request: Request, store: RouterStore) => {
|
|
|
865
1081
|
if (request.method === "POST" && pathname === "/sync") {
|
|
866
1082
|
return sync(request, store);
|
|
867
1083
|
}
|
|
1084
|
+
if (request.method === "GET" && pathname === RESTART_PATH) {
|
|
1085
|
+
return restartLink(request, store);
|
|
1086
|
+
}
|
|
1087
|
+
if (request.method === "GET" && pathname === RESTART_CALLBACK_PATH) {
|
|
1088
|
+
return restartCallback(request, store);
|
|
1089
|
+
}
|
|
1090
|
+
if (request.method === "GET" && pathname === RESTARTED_PATH) {
|
|
1091
|
+
return Promise.resolve(page(200, "The run is starting again. Its replies will show on the thread."));
|
|
1092
|
+
}
|
|
868
1093
|
if (pathname.startsWith("/admin/")) {
|
|
869
1094
|
return admin(request, pathname.slice("/admin/".length), store);
|
|
870
1095
|
}
|
package/router/index.ts
CHANGED
|
@@ -28,13 +28,38 @@ export {
|
|
|
28
28
|
type DeliveryRecord,
|
|
29
29
|
type FailedDelivery,
|
|
30
30
|
failedDelivery,
|
|
31
|
+
heartbeatWatch,
|
|
31
32
|
type Inbox,
|
|
32
33
|
KEEP_DELIVERY_MS,
|
|
34
|
+
mergeRecord,
|
|
35
|
+
nextTry,
|
|
33
36
|
replayRecord,
|
|
34
37
|
settled,
|
|
38
|
+
type Watch,
|
|
35
39
|
} from "./deliveries.ts";
|
|
36
|
-
export {
|
|
40
|
+
export {
|
|
41
|
+
advance,
|
|
42
|
+
handle,
|
|
43
|
+
outpostKey,
|
|
44
|
+
redeployRepo,
|
|
45
|
+
type RemoteDeployer,
|
|
46
|
+
RESTART_CALLBACK_PATH,
|
|
47
|
+
RESTART_PATH,
|
|
48
|
+
type RouterStore,
|
|
49
|
+
watch,
|
|
50
|
+
webhookPath,
|
|
51
|
+
} from "./handle.ts";
|
|
37
52
|
export { deriveKey, hmacHex, timingSafeEqual } from "./keys.ts";
|
|
38
53
|
export { allowsRepo } from "../lib/repos.ts";
|
|
39
|
-
export {
|
|
54
|
+
export {
|
|
55
|
+
type BuildReport,
|
|
56
|
+
type Heartbeat,
|
|
57
|
+
type HeartbeatResult,
|
|
58
|
+
LOST_AFTER_MS,
|
|
59
|
+
type Relay,
|
|
60
|
+
type RelayResult,
|
|
61
|
+
type Run,
|
|
62
|
+
type RunResult,
|
|
63
|
+
signBuildReport,
|
|
64
|
+
} from "./run.ts";
|
|
40
65
|
export { SYNC_HEADER, signSync } from "./sync.ts";
|
package/router/run.ts
CHANGED
|
@@ -2,8 +2,12 @@ import type { AgentEntry, ContainerEntry } from "../contracts/outpost.ts";
|
|
|
2
2
|
import type { ThreadMessage } from "./channel.ts";
|
|
3
3
|
import { deriveKey, hmacHex, timingSafeEqual } from "./keys.ts";
|
|
4
4
|
|
|
5
|
-
/**
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Where a run's reply goes: the connection whose channel posts it, and the
|
|
7
|
+
* channel's thread. `delivery` and `run` name the run's dispatch in the
|
|
8
|
+
* inbox, for its heartbeats. `expires` is in ms since the epoch.
|
|
9
|
+
*/
|
|
10
|
+
export type ReplyTicket = { connection: string; thread: unknown; delivery?: string; run?: string; expires: number };
|
|
7
11
|
|
|
8
12
|
/**
|
|
9
13
|
* A message that a run's reply posted, which a later reply of the run
|
|
@@ -12,12 +16,38 @@ export type ReplyTicket = { connection: string; thread: unknown; expires: number
|
|
|
12
16
|
*/
|
|
13
17
|
export type ReplyMessage = { id: string; signature: string };
|
|
14
18
|
|
|
15
|
-
/**
|
|
16
|
-
|
|
19
|
+
/**
|
|
20
|
+
* What the runner posts to a run's `reply.url`. With `message`, the reply
|
|
21
|
+
* replaces that message. `done` says that this is the run's last reply, so
|
|
22
|
+
* the router stops watching the run once it posts it.
|
|
23
|
+
*/
|
|
24
|
+
export type Relay = { ticket: ReplyTicket; signature: string; text: string; message?: ReplyMessage; done?: boolean };
|
|
17
25
|
|
|
18
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* What the router answers to a `Relay`: the message that the reply posted or
|
|
28
|
+
* replaced, if the channel names it. If the router marked the run lost, it
|
|
29
|
+
* posts nothing and answers 409 with `{ lost: true }`.
|
|
30
|
+
*/
|
|
19
31
|
export type RelayResult = { ok: true; message?: ReplyMessage };
|
|
20
32
|
|
|
33
|
+
/**
|
|
34
|
+
* What the runner posts to a run's `reply.heartbeat` once a minute while it
|
|
35
|
+
* holds the run, queued or running.
|
|
36
|
+
* `message` is the message that the run's replies replace now. `done` says
|
|
37
|
+
* that the run finished without a last reply, so the router stops watching it.
|
|
38
|
+
*/
|
|
39
|
+
export type Heartbeat = { ticket: ReplyTicket; signature: string; message?: ReplyMessage; done?: boolean };
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* What the router answers to a `Heartbeat`. `lost` means that the router has
|
|
43
|
+
* marked the run lost, and posted a notice in place of its message, or that
|
|
44
|
+
* a restart replaced the run with a new one.
|
|
45
|
+
*/
|
|
46
|
+
export type HeartbeatResult = { ok: true; lost?: boolean };
|
|
47
|
+
|
|
48
|
+
/** How long the router waits for a run's next heartbeat before it marks the run lost. */
|
|
49
|
+
export const LOST_AFTER_MS = 5 * 60 * 1000;
|
|
50
|
+
|
|
21
51
|
/** What the runner posts to the router's `/messages` route, next to `reply.url`. The router answers with `MessagesResult`. */
|
|
22
52
|
export type MessagesRequest = { ticket: ReplyTicket; signature: string };
|
|
23
53
|
|
|
@@ -74,9 +104,10 @@ export type Run = {
|
|
|
74
104
|
/**
|
|
75
105
|
* The runner posts a `Relay` with this ticket and signature to `url`.
|
|
76
106
|
* `message` is a message that the router posted while the run waited for
|
|
77
|
-
* its container, which the run's first reply replaces.
|
|
107
|
+
* its container, which the run's first reply replaces. The runner posts a
|
|
108
|
+
* `Heartbeat` with the same ticket to `heartbeat`, if it's set.
|
|
78
109
|
*/
|
|
79
|
-
reply: { url: string; ticket: ReplyTicket; signature: string; message?: ReplyMessage };
|
|
110
|
+
reply: { url: string; ticket: ReplyTicket; signature: string; message?: ReplyMessage; heartbeat?: string };
|
|
80
111
|
};
|
|
81
112
|
|
|
82
113
|
/**
|
|
@@ -121,6 +152,41 @@ export const signBuildReport = (rootKey: string, report: BuildReport) => sign(ro
|
|
|
121
152
|
export const verifyBuildReport = (rootKey: string, report: BuildReport, signature: string) =>
|
|
122
153
|
verify(rootKey, "router:builds", report, signature);
|
|
123
154
|
|
|
155
|
+
/** A lost run that a restart link starts again: the run `run` of the delivery `delivery` of `connection`. `expires` is in ms since the epoch. */
|
|
156
|
+
export type RestartTicket = { connection: string; delivery: string; run: string; expires: number };
|
|
157
|
+
|
|
158
|
+
const base64url = (text: string) =>
|
|
159
|
+
btoa(String.fromCharCode(...new TextEncoder().encode(text)))
|
|
160
|
+
.replaceAll("+", "-")
|
|
161
|
+
.replaceAll("/", "_")
|
|
162
|
+
.replace(/=+$/, "");
|
|
163
|
+
|
|
164
|
+
const fromBase64url = (text: string) =>
|
|
165
|
+
new TextDecoder().decode(Uint8Array.from(atob(text.replaceAll("-", "+").replaceAll("_", "/")), (c) => c.charCodeAt(0)));
|
|
166
|
+
|
|
167
|
+
/** A restart link's token: the ticket as base64url JSON, a dot, and its signature. */
|
|
168
|
+
export const signRestart = async (rootKey: string, ticket: RestartTicket) =>
|
|
169
|
+
`${base64url(JSON.stringify(ticket))}.${await sign(rootKey, "router:restart", ticket)}`;
|
|
170
|
+
|
|
171
|
+
/** The ticket in a restart link's token, if the router signed it and it hasn't expired. */
|
|
172
|
+
export const verifyRestart = async (rootKey: string, token: string): Promise<RestartTicket | undefined> => {
|
|
173
|
+
const dot = token.lastIndexOf(".");
|
|
174
|
+
if (dot < 0) return undefined;
|
|
175
|
+
let parsed: Partial<RestartTicket>;
|
|
176
|
+
try {
|
|
177
|
+
parsed = JSON.parse(fromBase64url(token.slice(0, dot)));
|
|
178
|
+
} catch {
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
const { connection, delivery, run, expires } = parsed ?? {};
|
|
182
|
+
if (typeof connection !== "string" || typeof delivery !== "string" || typeof run !== "string" || typeof expires !== "number") {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
// The signature covers the ticket's JSON with its keys in this order.
|
|
186
|
+
const ticket = { connection, delivery, run, expires };
|
|
187
|
+
return (await verify(rootKey, "router:restart", ticket, token.slice(dot + 1))) ? ticket : undefined;
|
|
188
|
+
};
|
|
189
|
+
|
|
124
190
|
/** A git branch name the runner can check out: no `..`, no leading `-` or `/`, and only letters, digits and `._/-`. */
|
|
125
191
|
export const isBranchName = (name: string) =>
|
|
126
192
|
/^[A-Za-z0-9._][A-Za-z0-9._/-]*$/.test(name) &&
|