@notation/factory-cli 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/bin/factory.ts CHANGED
@@ -1,9 +1,15 @@
1
1
  #!/usr/bin/env bun
2
- import { infraDown, infraUp } from "../commands/infra.ts";
2
+ import { infraDown, infraReplay, infraStatus, infraUp } from "../commands/infra.ts";
3
3
  import { repoInstall, repoStatus } from "../commands/repo.ts";
4
4
 
5
5
  const usage = `Usage:
6
- factory infra up [--dry-run] deploy the hub in this directory
6
+ factory infra up [--dry-run] [--credential <id>.<credential>@<hash>=<var>]
7
+ deploy the hub in this directory, and have
8
+ it deploy its repos again
9
+ factory infra status show each repo's last deploy, and the
10
+ failed deliveries
11
+ factory infra replay [<delivery>]
12
+ start the failed deliveries' runs again
7
13
  factory infra down destroy the hub in this directory
8
14
  factory repo install [--repo <owner/name>]
9
15
  install the hub's GitHub Apps on this repo,
@@ -16,12 +22,16 @@ const flag = (args: string[], name: string) => {
16
22
  return index === -1 ? undefined : args[index + 1];
17
23
  };
18
24
 
25
+ const flags = (args: string[], name: string) => args.flatMap((arg, i) => (arg === name && args[i + 1] ? [args[i + 1]!] : []));
26
+
19
27
  const [group, command, ...args] = process.argv.slice(2);
20
28
  const dryRun = args.includes("--dry-run");
21
29
  const repo = flag(args, "--repo");
22
30
 
23
31
  const run = async () => {
24
- if (group === "infra" && command === "up") return infraUp({ dryRun });
32
+ if (group === "infra" && command === "up") return infraUp({ dryRun, credentials: flags(args, "--credential") });
33
+ if (group === "infra" && command === "status") return infraStatus();
34
+ if (group === "infra" && command === "replay") return infraReplay({ delivery: args.find((a) => !a.startsWith("--")) });
25
35
  if (group === "infra" && command === "down") return infraDown();
26
36
  if (group === "repo" && command === "install") return repoInstall({ repo });
27
37
  if (group === "repo" && command === "status") return repoStatus({ repo });
package/commands/infra.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import type { DeliveriesResult, ReplayResult, ReposResult } from "@notation/factory/router";
4
+ import { admin } from "./operator.ts";
3
5
  import { type HubConfig, loadConfig, shell } from "./shell.ts";
4
6
 
5
7
  const hubDir = () => {
@@ -10,22 +12,83 @@ const hubDir = () => {
10
12
  return dir;
11
13
  };
12
14
 
15
+ const hubConfig = (dir: string) => loadConfig<HubConfig>(join(dir, "factory.config.ts"));
16
+
17
+ const NO_ROUTER = "Set router in factory.config.ts to the router's URL. `factory infra up` prints it when it creates the router.";
18
+
19
+ /** The URL of the hub's router, from `factory.config.ts`. */
20
+ const routerUrl = async () => {
21
+ const { router } = await hubConfig(hubDir());
22
+ if (!router) throw new Error(NO_ROUTER);
23
+ return router;
24
+ };
25
+
26
+ const quote = (arg: string) => `'${arg.replace(/'/g, `'\\''`)}'`;
27
+
13
28
  // The packages ship TypeScript, which Node won't strip from files under
14
29
  // node_modules, so Notation runs on bun.
15
30
  const notation = async (args: string) => {
16
31
  const dir = hubDir();
17
- const { loadEnv } = await loadConfig<HubConfig>(join(dir, "factory.config.ts"));
32
+ const { loadEnv } = await hubConfig(dir);
18
33
  await shell(`${loadEnv ? `${loadEnv} ` : ""}bun x --bun notation ${args} --pretty`, dir);
19
34
  };
20
35
 
21
- /** Deploys the hub. Deploy also syncs each connection with the router. */
22
- export const infraUp = async ({ dryRun }: { dryRun: boolean }) => {
23
- await notation(dryRun ? "plan" : "deploy");
24
- if (!dryRun) {
25
- console.log("\nThe hub is up. To serve a repo, run `factory repo install` in it.");
26
- }
36
+ /**
37
+ * Deploys the hub. The deploy syncs each connection with the router, and has
38
+ * the router deploy every repo again, without waiting for those deploys.
39
+ * Each of `credentials` is passed to Notation as `--credential`.
40
+ */
41
+ export const infraUp = async ({ dryRun, credentials = [] }: { dryRun: boolean; credentials?: string[] }) => {
42
+ const flags = credentials.map((c) => ` --credential ${quote(c)}`).join("");
43
+ await notation(`${dryRun ? "plan" : "deploy"}${flags}`);
44
+ if (dryRun) return;
45
+ console.log("\nThe hub is up. To serve a repo, run `factory repo install` in it.");
27
46
  };
28
47
 
29
48
  export const infraDown = async () => {
30
49
  await notation("destroy");
31
50
  };
51
+
52
+ const short = (ref?: string) => (ref ? ref.slice(0, 7) : undefined);
53
+
54
+ /** Prints each repo's last deploy and its containers' builds, then the failed deliveries. */
55
+ export const infraStatus = async () => {
56
+ const router = await routerUrl();
57
+ const repos = await admin<ReposResult>(router, "GET", "/admin/repos");
58
+ const deliveries = await admin<DeliveriesResult>(router, "GET", "/admin/deliveries");
59
+ if (!repos.repos.length) console.log("The hub has deployed no repos.");
60
+ for (const { repo, status, builds } of repos.repos) {
61
+ const from = status.ref ? ` from ${short(status.ref)}` : "";
62
+ console.log(`${repo}: ${status.state}${from} at ${status.at}`);
63
+ if (status.error) console.log(` ${status.error.split("\n").join("\n ")}`);
64
+ for (const [container, build] of Object.entries(builds)) {
65
+ console.log(` ${container}: build ${build.state} at ${short(build.ref)}${build.url ? ` ${build.url}` : ""}`);
66
+ }
67
+ }
68
+ if (!deliveries.failed.length) {
69
+ console.log("\nNo deliveries failed in the last 7 days.");
70
+ return;
71
+ }
72
+ console.log("\nFailed deliveries:");
73
+ for (const d of deliveries.failed) {
74
+ console.log(` ${d.connection}/${d.id}: ${d.event} on ${d.repo}, received ${new Date(d.received).toISOString()}`);
75
+ for (const t of d.triggers) console.log(` ${t.trigger}: ${t.error ?? "no reason given"}`);
76
+ }
77
+ console.log("\nRun `factory infra replay` to start them again, or `factory infra replay <delivery>` for one.");
78
+ };
79
+
80
+ /** Replays one failed delivery, named as `<connection>/<id>` like `factory infra status` lists it, or all of them. */
81
+ export const infraReplay = async ({ delivery }: { delivery?: string }) => {
82
+ const router = await routerUrl();
83
+ let body: { connection: string; id: string } | undefined;
84
+ if (delivery) {
85
+ const slash = delivery.lastIndexOf("/");
86
+ if (slash <= 0) throw new Error(`${delivery} isn't a delivery. Name it as \`factory infra status\` lists it, such as github/gh/<id>.`);
87
+ body = { connection: delivery.slice(0, slash), id: delivery.slice(slash + 1) };
88
+ }
89
+ const { replayed, skipped } = await admin<ReplayResult>(router, "POST", "/admin/replay", body ?? {});
90
+ for (const d of replayed) console.log(`Replaying ${d.connection}/${d.id}.`);
91
+ for (const d of skipped) console.log(`${d.connection}/${d.id} is no longer a failed delivery, so it wasn't replayed.`);
92
+ if (!replayed.length && !skipped.length) console.log("No deliveries failed in the last 7 days.");
93
+ if (skipped.length && delivery) process.exitCode = 1;
94
+ };
@@ -0,0 +1,135 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { createServer } from "node:http";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import type { SessionResult, SignInResult } from "@notation/factory/router";
7
+ import { OPERATOR_CALLBACK_URL } from "@notation/factory-github/app";
8
+ import { openBrowser } from "./shell.ts";
9
+
10
+ /** Where the CLI keeps each hub's admin session, by the router's origin. */
11
+ const SESSIONS_FILE = join(homedir(), ".config", "notation-factory", "sessions.json");
12
+
13
+ /** A cached session that expires within this time is not used, so that it doesn't expire mid-command. */
14
+ const EXPIRY_MARGIN_MS = 5 * 60 * 1000;
15
+
16
+ const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
17
+
18
+ type Sessions = Record<string, SessionResult>;
19
+
20
+ const readSessions = async (): Promise<Sessions> => {
21
+ try {
22
+ return JSON.parse(await readFile(SESSIONS_FILE, "utf8")) as Sessions;
23
+ } catch {
24
+ return {};
25
+ }
26
+ };
27
+
28
+ const saveSession = async (origin: string, session: SessionResult | undefined) => {
29
+ const sessions = await readSessions();
30
+ if (session) sessions[origin] = session;
31
+ else delete sessions[origin];
32
+ await mkdir(dirname(SESSIONS_FILE), { recursive: true });
33
+ await writeFile(SESSIONS_FILE, JSON.stringify(sessions, null, 2), { mode: 0o600 });
34
+ // `mode` only applies when writeFile creates the file.
35
+ await chmod(SESSIONS_FILE, 0o600);
36
+ };
37
+
38
+ const post = async <T>(router: string, path: string, body: unknown): Promise<T> => {
39
+ const response = await fetch(new URL(path, router), {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json" },
42
+ body: JSON.stringify(body),
43
+ });
44
+ const result = (await response.json().catch(() => ({}))) as T & { error?: string };
45
+ if (!response.ok) throw new Error(`The hub refused the sign-in: ${result.error ?? `status ${response.status}`}`);
46
+ return result;
47
+ };
48
+
49
+ /**
50
+ * Signs in to the hub at `router` in the browser:
51
+ * 1. Listens for the browser on the callback URL that the App allows.
52
+ * 2. Asks the router for its sign-in page, and opens it.
53
+ * 3. Takes the code that the page sends to the callback, and exchanges it
54
+ * with the router for an admin session.
55
+ */
56
+ const signIn = async (router: string): Promise<SessionResult> => {
57
+ const state = randomBytes(16).toString("hex");
58
+ const callback = new URL(OPERATOR_CALLBACK_URL);
59
+ let resolve!: (code: string) => void;
60
+ let reject!: (error: Error) => void;
61
+ const code = new Promise<string>((res, rej) => {
62
+ resolve = res;
63
+ reject = rej;
64
+ });
65
+ const server = createServer((req, res) => {
66
+ const url = new URL(req.url ?? "/", callback.origin);
67
+ const send = (status: number, body: string) => {
68
+ res.writeHead(status, { "content-type": "text/plain" });
69
+ res.end(body);
70
+ };
71
+ if (url.pathname !== callback.pathname || url.searchParams.get("state") !== state) return send(404, "not found");
72
+ const error = url.searchParams.get("error");
73
+ const found = url.searchParams.get("code");
74
+ if (error || !found) {
75
+ send(400, "The sign-in didn't finish. See the terminal.");
76
+ reject(new Error(`The sign-in didn't finish: ${url.searchParams.get("error_description") ?? error ?? "GitHub sent no code"}`));
77
+ return;
78
+ }
79
+ send(200, "Signed in. You can close this tab.");
80
+ resolve(found);
81
+ });
82
+ await new Promise<void>((listening, failed) => {
83
+ server.once("error", (error: NodeJS.ErrnoException) =>
84
+ failed(
85
+ error.code === "EADDRINUSE"
86
+ ? new Error(`Signing in needs port ${callback.port}, which another program is using.`)
87
+ : error,
88
+ ),
89
+ );
90
+ server.listen(Number(callback.port), callback.hostname, listening);
91
+ });
92
+ const timeout = setTimeout(() => reject(new Error("The sign-in didn't finish within 5 minutes.")), SIGN_IN_TIMEOUT_MS);
93
+ try {
94
+ const { url } = await post<SignInResult>(router, "/admin/sign-in", { state });
95
+ console.error(`Sign in to the hub in your browser: ${url}`);
96
+ openBrowser(url);
97
+ const session = await post<SessionResult>(router, "/admin/session", { code: await code });
98
+ console.error(`Signed in to the hub as ${session.operator}.`);
99
+ return session;
100
+ } finally {
101
+ clearTimeout(timeout);
102
+ server.close();
103
+ }
104
+ };
105
+
106
+ /** The admin session for the hub at `router`: the cached one if it's still good, or a new one. */
107
+ const session = async (router: string) => {
108
+ const { origin } = new URL(router);
109
+ const cached = (await readSessions())[origin];
110
+ if (cached && cached.expires - EXPIRY_MARGIN_MS > Date.now()) return cached.session;
111
+ const fresh = await signIn(router);
112
+ await saveSession(origin, fresh);
113
+ return fresh.session;
114
+ };
115
+
116
+ /** Calls an admin route of the hub at `router`. A refused session is dropped, and the operator signs in again once. */
117
+ export const admin = async <T>(router: string, method: string, path: string, body?: unknown): Promise<T> => {
118
+ const call = async () =>
119
+ fetch(new URL(path, router), {
120
+ method,
121
+ headers: {
122
+ authorization: `Bearer ${await session(router)}`,
123
+ ...(body !== undefined && { "content-type": "application/json" }),
124
+ },
125
+ ...(body !== undefined && { body: JSON.stringify(body) }),
126
+ });
127
+ let response = await call();
128
+ if (response.status === 401) {
129
+ await saveSession(new URL(router).origin, undefined);
130
+ response = await call();
131
+ }
132
+ const result = (await response.json().catch(() => ({}))) as T & { error?: string };
133
+ if (!response.ok) throw new Error(`The hub's ${method} ${path} failed: ${result.error ?? `status ${response.status}`}`);
134
+ return result;
135
+ };
package/commands/shell.ts CHANGED
@@ -38,6 +38,8 @@ export const openBrowser = (url: string) => {
38
38
  export type HubConfig = {
39
39
  /** A command prefix that sets credentials in the environment, such as `op run --env-file .env --`. */
40
40
  loadEnv?: string;
41
+ /** The URL of the hub's router, which the commands that talk to the running hub call. */
42
+ router?: string;
41
43
  };
42
44
 
43
45
  /** An outpost's `.factory/config.ts`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory-cli",
3
- "version": "0.2.2",
3
+ "version": "0.5.0",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,6 +21,6 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@notation/resource": "0.28.1",
24
- "@notation/factory-github": "0.2.2"
24
+ "@notation/factory-github": "0.5.0"
25
25
  }
26
26
  }