@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.
@@ -0,0 +1,35 @@
1
+ import { type CredentialRef, ResourceGroup } from "@notation/resource";
2
+ import type { RepoPattern } from "../contracts/router.ts";
3
+
4
+ export type OutpostSecretOptions = {
5
+ /** The env var name that containers read the secret as, such as `DATABASE_URL`. */
6
+ name: string;
7
+ /** A credential, such as `source.credentials.value`. The deployer writes it to the hub's vault. */
8
+ value: CredentialRef<string>;
9
+ /** The repos whose containers get the secret, in the form of the code host's `allow`. */
10
+ allowedRepos: RepoPattern[];
11
+ };
12
+
13
+ /**
14
+ * `new OutpostSecret(id, ...)`: a secret that the containers of
15
+ * `allowedRepos` get as the env var `name`. Pass it to the deployer's
16
+ * `secrets`, which writes it to the hub's vault and binds it.
17
+ */
18
+ export class OutpostSecret extends ResourceGroup {
19
+ readonly name: string;
20
+ readonly value: CredentialRef<string>;
21
+ readonly allowedRepos: RepoPattern[];
22
+
23
+ constructor(id: string, { name, value, allowedRepos }: OutpostSecretOptions) {
24
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
25
+ throw new Error(`The outpost secret ${id} has the name ${JSON.stringify(name)}, which isn't an env var name.`);
26
+ }
27
+ if (allowedRepos.length === 0) {
28
+ throw new Error(`The outpost secret ${id} has no allowedRepos, so no container would get it.`);
29
+ }
30
+ super("factory/OutpostSecret", id, { name, allowedRepos });
31
+ this.name = name;
32
+ this.value = value;
33
+ this.allowedRepos = allowedRepos;
34
+ }
35
+ }
package/index.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export * from "./outpost.ts";
2
- export { RandomKey, type RandomKeyInstance } from "./resources/random-key.ts";
2
+ export { RandomKey, type RandomKeyInstance, RecordedKey } from "./resources/random-key.ts";
3
3
  export { RouterSync } from "./resources/router-sync.ts";
4
+ export { OutpostSecret, type OutpostSecretOptions } from "./implementations/outpost-secret.ts";
5
+ export { reposOverlap } from "./lib/repos.ts";
@@ -0,0 +1,17 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { allowsRepo, reposOverlap } from "./repos.ts";
4
+
5
+ test("a pattern without a repo allows every repo of its owner, whatever the case", () => {
6
+ assert.equal(allowsRepo([{ owner: "acme" }], "Acme/Web"), true);
7
+ assert.equal(allowsRepo([{ owner: "acme", repo: "web" }], "acme/WEB"), true);
8
+ assert.equal(allowsRepo([{ owner: "acme", repo: "web" }], "acme/api"), false);
9
+ assert.equal(allowsRepo([{ owner: "acme" }], "other/web"), false);
10
+ });
11
+
12
+ test("patterns overlap when one repo matches both", () => {
13
+ assert.equal(reposOverlap([{ owner: "acme" }], [{ owner: "ACME", repo: "web" }]), true);
14
+ assert.equal(reposOverlap([{ owner: "acme", repo: "web" }], [{ owner: "acme", repo: "Web" }]), true);
15
+ assert.equal(reposOverlap([{ owner: "acme", repo: "web" }], [{ owner: "acme", repo: "api" }]), false);
16
+ assert.equal(reposOverlap([{ owner: "acme" }], [{ owner: "other" }]), false);
17
+ });
package/lib/repos.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { RepoPattern } from "../contracts/router.ts";
2
+
3
+ /** Whether `repo`, as `owner/name`, matches one of `allow`. A pattern without `repo` matches every repo of its owner. Case doesn't matter. */
4
+ export const allowsRepo = (allow: RepoPattern[], repo: string) => {
5
+ const [owner, name] = repo.toLowerCase().split("/");
6
+ return allow.some(
7
+ (p) => p.owner.toLowerCase() === owner && (!p.repo || p.repo.toLowerCase() === name),
8
+ );
9
+ };
10
+
11
+ /** Whether some repo matches a pattern in `a` and a pattern in `b`. */
12
+ export const reposOverlap = (a: RepoPattern[], b: RepoPattern[]) =>
13
+ a.some((p) =>
14
+ b.some(
15
+ (q) =>
16
+ p.owner.toLowerCase() === q.owner.toLowerCase() &&
17
+ (!p.repo || !q.repo || p.repo.toLowerCase() === q.repo.toLowerCase()),
18
+ ),
19
+ );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory",
3
- "version": "0.2.0",
3
+ "version": "0.5.0",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,3 +52,46 @@ export const RandomKey = randomKeySchema.defineOperations({
52
52
  });
53
53
 
54
54
  export type RandomKeyInstance = InstanceType<typeof RandomKey>;
55
+
56
+ type RecordedKeyApi = {
57
+ Key: { KeyId: string };
58
+ CreateParams: { Bytes: number };
59
+ UpdateParams: undefined;
60
+ ReadResult: {};
61
+ };
62
+
63
+ const recordedKey = resource<RecordedKeyApi>({
64
+ type: "factory/keys/RecordedKey",
65
+ provider: "@notation/factory",
66
+ });
67
+
68
+ const recordedKeySchema = recordedKey.defineSchema({
69
+ Bytes: {
70
+ propertyType: "param",
71
+ presence: "required",
72
+ immutable: true,
73
+ value: v.pipe(v.number(), v.integer(), v.minValue(16)),
74
+ },
75
+ KeyId: {
76
+ propertyType: "computed",
77
+ presence: "required",
78
+ primaryKey: true,
79
+ value: v.string(),
80
+ },
81
+ /** `Bytes` random bytes, in hex. */
82
+ Value: { propertyType: "computed", presence: "required", value: v.string() },
83
+ } as const);
84
+
85
+ /**
86
+ * A random key whose value is a computed output, which state records, such
87
+ * as the router's sync key. Unlike a `RandomKey`, any deploy can take its
88
+ * value without rotating it.
89
+ */
90
+ export const RecordedKey = recordedKeySchema.defineOperations({
91
+ create: async (params) => ({
92
+ KeyId: randomUUID(),
93
+ Value: generate(params.Bytes),
94
+ }),
95
+ read: async (key) => key,
96
+ delete: async () => {},
97
+ });
@@ -1,11 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { resource } from "@notation/resource";
3
3
  import * as v from "valibot";
4
+ import { SYNC_HEADER, signSync } from "../router/sync.ts";
4
5
 
5
6
  type RouterSyncApi = {
6
7
  Key: { SyncId: string };
7
- CreateParams: { Url: string; Config: string };
8
- UpdateParams: { Url: string; Config: string };
8
+ CreateParams: { Url: string; Config: string; SyncKey: string; DeployId: string };
9
+ UpdateParams: { Url: string; Config: string; SyncKey: string; DeployId: string };
9
10
  ReadResult: {};
10
11
  };
11
12
 
@@ -16,8 +17,12 @@ const routerSync = resource<RouterSyncApi>({
16
17
 
17
18
  const routerSyncSchema = routerSync.defineSchema({
18
19
  Url: { propertyType: "param", presence: "required", value: v.string() },
19
- /** The router's config, as JSON. A change to it syncs again. */
20
+ /** The router's config, as JSON. */
20
21
  Config: { propertyType: "param", presence: "required", value: v.string() },
22
+ /** The key that the router checks the sync request's signature with. */
23
+ SyncKey: { propertyType: "param", presence: "required", sensitive: true, value: v.string() },
24
+ /** A new value on every deploy, so that every deploy syncs. */
25
+ DeployId: { propertyType: "param", presence: "required", value: v.string() },
21
26
  SyncId: {
22
27
  propertyType: "computed",
23
28
  presence: "required",
@@ -26,27 +31,38 @@ const routerSyncSchema = routerSync.defineSchema({
26
31
  },
27
32
  } as const);
28
33
 
29
- const sync = async (url: string) => {
30
- const response = await fetch(new URL("/sync", url), { method: "POST" });
34
+ const sync = async (url: string, syncKey: string) => {
35
+ const target = new URL("/sync", url);
36
+ const response = await fetch(target, {
37
+ method: "POST",
38
+ headers: { [SYNC_HEADER]: await signSync(syncKey, target.origin) },
39
+ });
31
40
  if (!response.ok) {
32
41
  throw new Error(
33
42
  `The router's sync at ${url} failed with ${response.status}: ${await response.text()}`,
34
43
  );
35
44
  }
45
+ console.error("The router is deploying the hub's repos again. Run `factory infra status` to see how the deploys went.");
36
46
  };
37
47
 
48
+ const announce = (url: string) =>
49
+ console.error(`The router is at ${url}. Set router in factory.config.ts to this URL, so that factory can reach the hub.`);
50
+
38
51
  /**
39
- * Calls the router's `/sync` when the router's URL or config changes, so
40
- * each connection's platform (for GitHub, the App's webhook URL and secret)
41
- * matches the router.
52
+ * Calls the router's `/sync` on every deploy. The router points each
53
+ * connection's platform at itself (for GitHub, the App's webhook URL and
54
+ * secret), and then deploys every repo again without making deploy wait.
55
+ * Prints the router's URL when it's new.
42
56
  */
43
57
  export const RouterSync = routerSyncSchema.defineOperations({
44
58
  create: async (params) => {
45
- await sync(params.Url);
59
+ await sync(params.Url, params.SyncKey);
60
+ announce(params.Url);
46
61
  return { SyncId: randomUUID() };
47
62
  },
48
- update: async (_key, _patch, params) => {
49
- await sync(params.Url);
63
+ update: async (_key, patch, params) => {
64
+ await sync(params.Url, params.SyncKey);
65
+ if (patch.Url !== undefined) announce(params.Url);
50
66
  },
51
67
  read: async (key) => key,
52
68
  delete: async () => {},
@@ -0,0 +1,100 @@
1
+ import type { OperatorsEntry } from "../contracts/router.ts";
2
+ import type { BuildCheck, FactoryStatus, Operator } from "./channel.ts";
3
+ import type { FailedDelivery } from "./deliveries.ts";
4
+ import { deriveKey, hmacHex, timingSafeEqual } from "./keys.ts";
5
+
6
+ /** How long an operator's admin session lasts. */
7
+ export const SESSION_TTL_MS = 4 * 60 * 60 * 1000;
8
+
9
+ /** The latest build of a container's image, as the deployer last reported it. */
10
+ export type ContainerBuild = { state: BuildCheck["state"]; ref: string; url?: string; summary?: string; at: string };
11
+
12
+ /** A repo's last deploy, and the latest build of each of its containers. */
13
+ export type RepoDeploy = {
14
+ repo: string;
15
+ status: FactoryStatus;
16
+ builds: Record<string, ContainerBuild>;
17
+ };
18
+
19
+ /**
20
+ * Where the router keeps each repo's last deploy, and each container's latest
21
+ * build, so that an operator can list them without a call to the code host.
22
+ * Each build is kept on its own, so that reports of different builds don't
23
+ * overwrite each other.
24
+ */
25
+ export type DeployLog = {
26
+ put(repo: string, status: FactoryStatus): Promise<void>;
27
+ /** Removes the repo's deploy and its builds. */
28
+ remove(repo: string): Promise<void>;
29
+ build(repo: string, container: string): Promise<ContainerBuild | undefined>;
30
+ putBuild(repo: string, container: string, build: ContainerBuild): Promise<void>;
31
+ /** Removes the repo's builds of containers other than `containers`. */
32
+ pruneBuilds(repo: string, containers: string[]): Promise<void>;
33
+ list(): Promise<RepoDeploy[]>;
34
+ /** The repos that have a deploy, in lowercase, without reading their deploys. */
35
+ repos(): Promise<string[]>;
36
+ };
37
+
38
+ /** `POST /admin/sign-in`: `state` comes back to the operator's browser with the code. */
39
+ export type SignInRequest = { state: string };
40
+ export type SignInResult = { url: string };
41
+
42
+ /** `POST /admin/session`: the code that the sign-in page sent to the operator's browser. */
43
+ export type SessionRequest = { code: string };
44
+ /** `operator` is who signed in, such as a GitHub login. `expires` is a time in milliseconds. */
45
+ export type SessionResult = { session: string; operator: string; expires: number };
46
+
47
+ /** `GET /admin/repos`. */
48
+ export type ReposResult = { repos: RepoDeploy[] };
49
+
50
+ /** `GET /admin/deliveries`. */
51
+ export type DeliveriesResult = { failed: FailedDelivery[] };
52
+
53
+ /** `POST /admin/replay`: one failed delivery, or all of them without `connection` and `id`. */
54
+ export type ReplayRequest = { connection?: string; id?: string };
55
+ export type ReplayResult = {
56
+ replayed: { connection: string; id: string }[];
57
+ /** The deliveries that the inbox no longer has as failed, such as one that another operator replayed. */
58
+ skipped: { connection: string; id: string }[];
59
+ };
60
+
61
+ const sessionKey = (rootKey: string) => deriveKey(rootKey, "operator:session");
62
+
63
+ type Session = Operator & { expires: number };
64
+
65
+ // encodeURIComponent leaves dots as they are.
66
+ const encodePart = (part: string) => encodeURIComponent(part).replaceAll(".", "%2E");
67
+
68
+ /**
69
+ * A session token for an operator: `<login>.<id>.<expires>.<signature>`,
70
+ * with the login and id URI-encoded so that neither can hold a dot. The
71
+ * token carries both, so that each request can check them against the
72
+ * operator auth again.
73
+ */
74
+ export const signSession = async (rootKey: string, { login, id, expires }: Session) => {
75
+ const body = `${encodePart(login)}.${encodePart(id)}.${expires}`;
76
+ return `${body}.${await hmacHex(await sessionKey(rootKey), body)}`;
77
+ };
78
+
79
+ /** The session in `token`, if the router signed it and it hasn't expired. */
80
+ export const verifySession = async (rootKey: string, token: string, now = Date.now()): Promise<Session | undefined> => {
81
+ const [login, id, expires, signature, ...rest] = token.split(".");
82
+ if (!login || !id || !expires || !signature || rest.length) return undefined;
83
+ if (!timingSafeEqual(signature, await hmacHex(await sessionKey(rootKey), `${login}.${id}.${expires}`))) return undefined;
84
+ const session = { login: decodeURIComponent(login), id: decodeURIComponent(id), expires: Number(expires) };
85
+ return session.expires > now ? session : undefined;
86
+ };
87
+
88
+ /**
89
+ * Whether the hub's operator auth lets `operator` in. Each of `users` is a
90
+ * GitHub login, compared without case, or a numeric account id.
91
+ */
92
+ export const isOperator = (operators: OperatorsEntry | undefined, { login, id }: Operator) => {
93
+ const users = operators?.users;
94
+ return (
95
+ Array.isArray(users) &&
96
+ users.some((entry) =>
97
+ typeof entry === "number" ? String(entry) === id : String(entry).toLowerCase() === login.toLowerCase(),
98
+ )
99
+ );
100
+ };
package/router/channel.ts CHANGED
@@ -26,18 +26,43 @@ export type Delivery<E> = {
26
26
  /**
27
27
  * Where a delivery's run reads and replies. `id` names the conversation,
28
28
  * such as an issue. `thread` is the channel's own reference to it, which
29
- * only its `reply` reads.
29
+ * only its `messages` and `reply` read. It holds what `messages` needs,
30
+ * such as the trigger's `from`.
30
31
  */
31
32
  export type Conversation = {
32
33
  id: string;
33
- prompt: string;
34
34
  thread: unknown;
35
+ /** The id of the thread's message that started the run, as `messages` names it. */
36
+ message?: string;
37
+ /**
38
+ * What happened, for a run that an event without a message started, such
39
+ * as `The issue was labelled \`ready\`.` The runner never skips such a run.
40
+ */
41
+ event?: string;
35
42
  /** What the conversation is, such as `GitHub issue`, for the runner's system prompt. */
36
43
  channel?: string;
37
44
  /** Text that the runner adds to its system prompt, such as which repo the conversation is in. */
38
45
  context?: string;
39
46
  };
40
47
 
48
+ /**
49
+ * One message in a conversation's thread, as the runner shows it to the
50
+ * agent. `author` is how the platform names the author, such as `@alice`.
51
+ * A reply from one of the hub's agents has `agent`, and another bot has
52
+ * `bot`. Only a person has `role`, their role where the thread is, and
53
+ * `canTrigger`, whether they match the trigger's `from`.
54
+ */
55
+ export type ThreadMessage = {
56
+ /** Unique in the thread. */
57
+ id: string;
58
+ author: string;
59
+ body: string;
60
+ agent?: string;
61
+ bot?: boolean;
62
+ role?: string;
63
+ canTrigger?: boolean;
64
+ };
65
+
41
66
  /** The trigger that a run is for: its selector, and the agent it runs. */
42
67
  export type ConversationTrigger = { selector: unknown; agent: string };
43
68
 
@@ -56,7 +81,12 @@ export type Received<E> =
56
81
  | { status: "rejected"; reason: string };
57
82
 
58
83
  /** The files under a directory of a repo at one commit, by their path in the directory. */
59
- export type SourceFiles = { ref: string; files: Record<string, string> };
84
+ export type SourceFiles = {
85
+ ref: string;
86
+ files: Record<string, string>;
87
+ /** The paths of the files that the repo marks executable. */
88
+ executables?: string[];
89
+ };
60
90
 
61
91
  /**
62
92
  * Whether a selector's `from` lets the delivery start a run. `check` holds
@@ -68,11 +98,10 @@ export type AuthorCheck =
68
98
  | { result: "denied" }
69
99
  | { result: "check"; sets: unknown[] };
70
100
 
71
- /**
72
- * One connection's deliveries, as the router handles them. A provider's
73
- * package implements it, and each platform decides where it runs.
74
- */
75
- export interface Channel<E = unknown> {
101
+ /** Who signed in: for GitHub, the user's login and numeric account id. */
102
+ export type Operator = { login: string; id: string };
103
+
104
+ interface ChannelBase<E> {
76
105
  /** Checks the delivery's signature and parses it. */
77
106
  receive(request: Request): Promise<Received<E>>;
78
107
  /** Whether `selector` selects the delivery, and if so, whether its author may start a run. */
@@ -85,14 +114,44 @@ export interface Channel<E = unknown> {
85
114
  writeStatus?(repo: string, status: FactoryStatus): Promise<void>;
86
115
  /** For a code host's channel: creates or updates the check named `check.name` on commit `ref`. */
87
116
  writeCheck?(repo: string, ref: string, check: BuildCheck): Promise<void>;
88
- /** The conversation that a run for the delivery belongs to. A channel without it can't start runs. */
89
- conversation?(delivery: Delivery<E>, trigger: ConversationTrigger): Conversation | Promise<Conversation>;
90
- /** Posts `text` to a conversation's thread. */
91
- reply?(thread: unknown, text: string): Promise<void>;
117
+ /** Shows on the delivery's post that a run is starting for it, such as with GitHub's 👀 reaction. */
118
+ acknowledge?(delivery: Delivery<E>): Promise<void>;
119
+ /**
120
+ * Posts `text` to a conversation's thread, or replaces the text of
121
+ * `message`, a message that an earlier reply to the thread posted.
122
+ * Resolves to the id of the message it posted or replaced.
123
+ */
124
+ reply?(thread: unknown, text: string, message?: string): Promise<string | undefined>;
92
125
  /** For a code host's channel: a short-lived token for `repo`, with only `permissions`. */
93
126
  token?(repo: string, permissions: Record<string, "read" | "write">): Promise<string>;
127
+ /** For a code host's channel: every repo that the hub can read, as `owner/name`. */
128
+ repos?(): Promise<string[]>;
129
+ /**
130
+ * For operator sign-in through the channel's platform: the page that
131
+ * signs the operator in, and then sends the browser to the CLI's callback
132
+ * with a code and `state`.
133
+ */
134
+ signInUrl?(state: string): Promise<string>;
135
+ /** For operator sign-in: exchanges the code that the callback got for the operator's identity. */
136
+ signIn?(code: string): Promise<Operator>;
94
137
  }
95
138
 
139
+ /** A channel that starts runs has both `conversation` and `messages`. A channel without them can't start runs. */
140
+ type Conversations<E> =
141
+ | {
142
+ /** The conversation that a run for the delivery belongs to. */
143
+ conversation(delivery: Delivery<E>, trigger: ConversationTrigger): Conversation | Promise<Conversation>;
144
+ /** The messages in a conversation's thread, oldest first. */
145
+ messages(thread: unknown): Promise<ThreadMessage[]>;
146
+ }
147
+ | { conversation?: never; messages?: never };
148
+
149
+ /**
150
+ * One connection's deliveries, as the router handles them. A provider's
151
+ * package implements it, and each platform decides where it runs.
152
+ */
153
+ export type Channel<E = unknown> = ChannelBase<E> & Conversations<E>;
154
+
96
155
  /** The outcome of a repo's last deploy, as the repo shows it. */
97
156
  export type FactoryStatus = {
98
157
  state: "deployed" | "failed";
@@ -101,8 +160,8 @@ export type FactoryStatus = {
101
160
  error?: string;
102
161
  /** When the deploy finished, as an ISO date. */
103
162
  at: string;
104
- /** The containers whose images started building. */
105
- building?: string[];
163
+ /** The containers whose images this deploy started building. Each build's progress is in its `factory/build <container>` check, not here. */
164
+ builds?: string[];
106
165
  };
107
166
 
108
167
  /** A container image's build, as a check on the commit it was built from. */
@@ -0,0 +1,126 @@
1
+ import type { Delivery } from "./channel.ts";
2
+
3
+ /** How often the router tries again a dispatch whose container's first image build hasn't finished. */
4
+ export const BUILD_POLL_MS = 30_000;
5
+
6
+ /**
7
+ * How long a dispatch waits for its container's first image build. The
8
+ * deployer reports a build that hasn't finished within 2 hours as failed,
9
+ * so this only applies when that report never arrives.
10
+ */
11
+ export const BUILD_WAIT_MS = 3 * 60 * 60 * 1000;
12
+
13
+ /** How long the router keeps a delivery's id, and a failed delivery, after it settles. */
14
+ export const KEEP_DELIVERY_MS = 7 * 24 * 60 * 60 * 1000;
15
+
16
+ /**
17
+ * One matched trigger's run, as the router hands it to the deployer.
18
+ * `pending` dispatches are tried at `next`, or at once without it.
19
+ */
20
+ export type TriggerDispatch = {
21
+ trigger: string;
22
+ run: string;
23
+ state: "pending" | "dispatched" | "failed";
24
+ /** When the dispatch started to wait for its container's first image build. */
25
+ since?: number;
26
+ next?: number;
27
+ error?: string;
28
+ /** The channel's thread of the run's conversation, once an attempt has named it. */
29
+ thread?: unknown;
30
+ /**
31
+ * The id of the message that shows on the thread while the dispatch waits
32
+ * for the build. The run's first reply, or the failure notice, replaces it.
33
+ */
34
+ waiting?: string;
35
+ };
36
+
37
+ /**
38
+ * A verified delivery that matched triggers whose authors may start runs,
39
+ * as the router saves it. `id` is the delivery's id, or a random id if the
40
+ * platform gave none. The router never saves a `Run`, whose tokens expire:
41
+ * each attempt mints new ones.
42
+ */
43
+ export type DeliveryRecord = {
44
+ id: string;
45
+ /** The delivery's connection, such as `github/gh`. */
46
+ connection: string;
47
+ delivery: Delivery<unknown>;
48
+ /** The router's origin, which runs reply to. */
49
+ origin: string;
50
+ received: number;
51
+ acknowledged?: boolean;
52
+ dispatches: TriggerDispatch[];
53
+ };
54
+
55
+ /** A delivery whose dispatch failed after its retries, as an operator lists it. */
56
+ export type FailedDelivery = {
57
+ connection: string;
58
+ id: string;
59
+ repo: string;
60
+ event: string;
61
+ received: number;
62
+ failed: number;
63
+ triggers: { trigger: string; error?: string }[];
64
+ };
65
+
66
+ /**
67
+ * Where the router keeps deliveries. Each platform adapts its own storage
68
+ * to it, and runs `advance` on each saved delivery until it settles,
69
+ * including after the router restarts.
70
+ */
71
+ export type Inbox = {
72
+ /** Saves `record`, and starts dispatching it. Resolves to false, and does nothing, if the inbox has a delivery with its connection and id. */
73
+ receive(record: DeliveryRecord): Promise<boolean>;
74
+ /** The deliveries whose dispatch failed after its retries, kept for `KEEP_DELIVERY_MS`. */
75
+ failed(): Promise<FailedDelivery[]>;
76
+ /**
77
+ * Dispatches the failed triggers of a failed delivery again, against the
78
+ * outpost config that its repo has now. Runs reply to `origin`. Resolves
79
+ * to false if the inbox has no such failed delivery.
80
+ */
81
+ replay(connection: string, id: string, origin: string): Promise<boolean>;
82
+ };
83
+
84
+ /** Whether a record has no dispatch left to try. */
85
+ export const settled = (record: DeliveryRecord) => record.dispatches.every((d) => d.state !== "pending");
86
+
87
+ /** The record as an operator lists it, if one of its dispatches failed. */
88
+ export const failedDelivery = (record: DeliveryRecord, now: number): FailedDelivery | undefined => {
89
+ const failed = record.dispatches.filter((d) => d.state === "failed");
90
+ if (!failed.length) return undefined;
91
+ return {
92
+ connection: record.connection,
93
+ id: record.id,
94
+ repo: record.delivery.repo,
95
+ event: record.delivery.event,
96
+ received: record.received,
97
+ failed: now,
98
+ triggers: failed.map((d) => ({ trigger: d.trigger, ...(d.error && { error: d.error }) })),
99
+ };
100
+ };
101
+
102
+ /** Sets a record's failed dispatches to be tried again, each as a new run. Resolves to false if none failed. */
103
+ export const replayRecord = (record: DeliveryRecord, origin: string) => {
104
+ const failed = record.dispatches.filter((d) => d.state === "failed");
105
+ if (!failed.length) return false;
106
+ for (const dispatch of failed) {
107
+ Object.assign(dispatch, { state: "pending", run: crypto.randomUUID() });
108
+ delete dispatch.since;
109
+ delete dispatch.next;
110
+ delete dispatch.error;
111
+ delete dispatch.waiting;
112
+ }
113
+ record.origin = origin;
114
+ return true;
115
+ };
116
+
117
+ /** The command that replays failed deliveries. */
118
+ export const REPLAY_COMMAND = "factory infra replay";
119
+
120
+ /** The message that tells the thread that a dispatch failed. */
121
+ export const failureNotice = (failed: TriggerDispatch) =>
122
+ `Couldn't start the run of trigger \`${failed.trigger}\`: ${failed.error ?? "no reason given"}\n\n` +
123
+ `Factory kept the event. An operator can run \`${REPLAY_COMMAND}\` to start the run again.`;
124
+
125
+ /** The message that shows on the thread while a dispatch waits for its container's first image build. */
126
+ export const waitingNotice = (container: string) => `> Booting container \`${container}\`...`;