@yunuseon/kayra 0.17.0 → 0.17.1

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.
Files changed (101) hide show
  1. package/ansible/roles/platform/tasks/main.yml +31 -0
  2. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  3. package/cli/dist/browser/index.html +1 -1
  4. package/cli/dist/clients/api/api.js +138 -218
  5. package/cli/dist/clients/api/auth.js +8 -7
  6. package/cli/dist/clients/api/commands.js +50 -14
  7. package/cli/dist/clients/api/contract.js +8 -6
  8. package/cli/dist/clients/api/discovery.js +7 -2
  9. package/cli/dist/clients/api/live.js +40 -0
  10. package/cli/dist/clients/api/protocol.js +17 -10
  11. package/cli/dist/clients/api/queries.js +3 -3
  12. package/cli/dist/clients/api/runs.js +10 -9
  13. package/cli/dist/clients/api/start.js +97 -0
  14. package/cli/dist/clients/api/status.js +29 -0
  15. package/cli/dist/clients/api/validate.js +13 -0
  16. package/cli/dist/clients/cli/explain.js +12 -10
  17. package/cli/dist/clients/cli/framed.js +12 -9
  18. package/cli/dist/clients/cli/invocation.js +4 -3
  19. package/cli/dist/clients/cli/paint.js +1 -1
  20. package/cli/dist/clients/cli/parser.js +8 -8
  21. package/cli/dist/clients/cli/questions.js +11 -10
  22. package/cli/dist/clients/cli/status.js +75 -0
  23. package/cli/dist/clients/cli/terminal.js +4 -2
  24. package/cli/dist/{core/present → clients/cli}/text.js +15 -24
  25. package/cli/dist/clients/cli/validate.js +32 -0
  26. package/cli/dist/clients/cli/values.js +19 -0
  27. package/cli/dist/{core/present → clients/cli}/views.js +28 -60
  28. package/cli/dist/core/adapters/fs.js +18 -0
  29. package/cli/dist/core/{net.js → adapters/network.js} +20 -5
  30. package/cli/dist/core/adapters/opentofu.js +24 -0
  31. package/cli/dist/core/ctl/answers.js +32 -0
  32. package/cli/dist/core/fleet/brand.js +45 -0
  33. package/cli/dist/core/{schemas.js → fleet/docs.js} +4 -3
  34. package/cli/dist/core/fleet/load.js +44 -0
  35. package/cli/dist/core/fleet/model.js +1 -0
  36. package/cli/dist/core/{fleet.js → fleet/parse.js} +61 -41
  37. package/cli/dist/core/{settings.js → fleet/settings.js} +10 -3
  38. package/cli/dist/core/{validate.js → fleet/shape.js} +6 -5
  39. package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
  40. package/cli/dist/core/interpreter/io.js +18 -0
  41. package/cli/dist/core/interpreter/loop.js +101 -0
  42. package/cli/dist/core/interpreter/needs.js +47 -0
  43. package/cli/dist/core/interpreter/process.js +107 -0
  44. package/cli/dist/core/interpreter/progress.js +15 -0
  45. package/cli/dist/core/interpreter/pty.js +8 -0
  46. package/cli/dist/core/operations/catalog.js +35 -18
  47. package/cli/dist/core/operations/{run.js → dispatch.js} +49 -46
  48. package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
  49. package/cli/dist/core/plan/model.js +14 -0
  50. package/cli/dist/core/{commands → recipes}/app-check.js +11 -16
  51. package/cli/dist/core/recipes/apps.js +63 -0
  52. package/cli/dist/core/recipes/backup.js +34 -0
  53. package/cli/dist/core/recipes/certs.js +4 -0
  54. package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
  55. package/cli/dist/core/recipes/host.js +104 -0
  56. package/cli/dist/core/recipes/ssh.js +20 -0
  57. package/cli/dist/core/recipes/steps.js +82 -0
  58. package/cli/dist/core/status/look.js +55 -0
  59. package/cli/dist/core/status/model.js +6 -0
  60. package/cli/dist/core/status/ports.js +1 -0
  61. package/cli/dist/core/text/plural.js +2 -0
  62. package/cli/dist/core/text/spans.js +22 -0
  63. package/cli/dist/core/text/time.js +12 -0
  64. package/cli/dist/core/validation/facts.js +49 -0
  65. package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
  66. package/cli/dist/deployer/app.js +2 -1
  67. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  68. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  69. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  70. package/cli/dist/deployer/cron.js +2 -2
  71. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  72. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  73. package/cli/dist/deployer/deployer.js +23 -22
  74. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  75. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  76. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  77. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  78. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  79. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  80. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  81. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  82. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  83. package/cli/dist/deployer/main.js +2 -2
  84. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  85. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  86. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  87. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  88. package/cli/dist/main.js +89 -89
  89. package/cli/dist/result.js +11 -1
  90. package/cli/dist/serve.js +2 -2
  91. package/cli/dist/typed.js +2 -0
  92. package/package.json +3 -2
  93. package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
  94. package/cli/dist/core/brand.js +0 -39
  95. package/cli/dist/core/commands/server.js +0 -298
  96. package/cli/dist/core/commands/status.js +0 -194
  97. package/cli/dist/core/gather.js +0 -61
  98. package/cli/dist/core/interpret.js +0 -276
  99. package/cli/dist/core/load.js +0 -64
  100. package/cli/dist/core/present/line.js +0 -17
  101. /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
@@ -0,0 +1,107 @@
1
+ import { spawn } from "node:child_process";
2
+ import { text } from "node:stream/consumers";
3
+ import { all, err, flatMap, ok } from "../../result.js";
4
+ import { isStopped } from "./io.js";
5
+ import { exitCode } from "../fleet/brand.js";
6
+ import { typed } from "../../typed.js";
7
+ const terminal = {};
8
+ /** A program that ignores SIGINT this long gets SIGTERM. */
9
+ const patience = 10_000;
10
+ export const spawned = async (argv, streams, env = {}, plumbing = terminal) => {
11
+ const [program, ...args] = argv;
12
+ const { output, signal } = plumbing;
13
+ if (isStopped(signal))
14
+ return typed({ code: exitCode(130), stdout: "", stderr: "", started: false });
15
+ const shown = (stream) => stream === "show" ? (typed(output === undefined ? "inherit" : "pipe")) : typed(stream === "capture" ? "pipe" : "ignore");
16
+ const stdin = streams.stdin ?? (output === undefined ? { kind: "inherit" } : { kind: "none" });
17
+ const child = spawn(program, args, {
18
+ env: { ...process.env, ...env },
19
+ detached: output !== undefined,
20
+ stdio: [stdin.kind === "inherit" ? "inherit" : stdin.kind === "none" ? "ignore" : "pipe", shown(streams.stdout), shown(streams.stderr)],
21
+ });
22
+ const forward = (from, sink) => {
23
+ child[from]?.setEncoding("utf8").on("data", (chunk) => {
24
+ sink(chunk, from);
25
+ });
26
+ };
27
+ if (output !== undefined && streams.stdout === "show")
28
+ forward("stdout", output);
29
+ if (output !== undefined && streams.stderr === "show")
30
+ forward("stderr", output);
31
+ // A program that exits before reading all it was given must not take kayra down with EPIPE.
32
+ child.stdin?.on("error", () => undefined);
33
+ if (stdin.kind === "given")
34
+ child.stdin?.end(stdin.text);
35
+ const unsubscribe = stdin.kind === "typed"
36
+ ? stdin.input((chunk) => {
37
+ child.stdin?.write(chunk);
38
+ })
39
+ : () => undefined;
40
+ const read = (from, stream) => {
41
+ const piped = child[from];
42
+ return piped === null || stream !== "capture" ? Promise.resolve("") : text(piped);
43
+ };
44
+ const stdout = read("stdout", streams.stdout);
45
+ const stderr = read("stderr", streams.stderr);
46
+ const kill = (withSignal) => {
47
+ if (child.pid === undefined)
48
+ return;
49
+ try {
50
+ if (output === undefined)
51
+ child.kill(withSignal);
52
+ else
53
+ process.kill(-child.pid, withSignal);
54
+ }
55
+ catch (error) {
56
+ if (!(error instanceof Error && "code" in error && error.code === "ESRCH"))
57
+ throw error;
58
+ }
59
+ };
60
+ // eslint-disable-next-line functional/prefer-immutable-types -- the escalation belongs to this child, cleared when it exits
61
+ const stopping = {};
62
+ const stop = () => {
63
+ if (stopping.timer !== undefined)
64
+ return;
65
+ if (stdin.kind === "typed")
66
+ child.stdin?.write("\u0003");
67
+ kill("SIGINT");
68
+ // eslint-disable-next-line functional/immutable-data -- see above
69
+ stopping.timer = setTimeout(() => { kill("SIGTERM"); }, patience);
70
+ stopping.timer.unref();
71
+ };
72
+ // The process group exists only once Node confirms the child has spawned.
73
+ child.once("spawn", () => {
74
+ signal?.addEventListener("abort", stop, { once: true });
75
+ if (isStopped(signal))
76
+ stop();
77
+ });
78
+ const exit = await new Promise((resolve) => {
79
+ child.on("error", resolve);
80
+ child.on("close", (code) => {
81
+ resolve(code ?? 1);
82
+ });
83
+ });
84
+ signal?.removeEventListener("abort", stop);
85
+ clearTimeout(stopping.timer);
86
+ unsubscribe();
87
+ return typed(exit instanceof Error ? { code: exitCode(127), stdout: "", stderr: exit.message, started: false } : { code: exitCode(exit), stdout: await stdout, stderr: await stderr, started: true });
88
+ };
89
+ /** A command's stdout, for kayra to read; its stderr reaches the operator unless captured too. */
90
+ export const capture = (argv, stderr = "show", env = {}, plumbing = terminal) => spawned(argv, { stdout: "capture", stderr }, env, plumbing);
91
+ export const answer = (probe, plumbing) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture", stdin: { kind: "none" } }, probe.kind === "exits-zero" ? probe.env : {}, plumbing);
92
+ /** Each query's answer in place of it, as `$(…)` would: one word, or split into many. */
93
+ export const resolve = async (argv, plumbing) => {
94
+ const words = await Promise.all(argv.map(async (value) => {
95
+ if (typeof value === "string")
96
+ return ok([value]);
97
+ const exit = await capture(value.argv, "show", value.env, plumbing);
98
+ if (exit.code !== 0)
99
+ return err(`$(${value.argv.join(" ")}) failed: exit ${String(exit.code)}`);
100
+ const output = exit.stdout.replace(/\n+$/, "");
101
+ return ok(value.words === "one" ? [output] : output.split(/\s+/).filter((word) => word !== ""));
102
+ }));
103
+ return flatMap(all(words), (lists) => {
104
+ const [program, ...rest] = lists.flat();
105
+ return program === undefined ? err("the command is empty") : ok([program, ...rest]);
106
+ });
107
+ };
@@ -0,0 +1,15 @@
1
+ import { typed } from "../../typed.js";
2
+ /** Why a plan stopped before its end. */
3
+ export const stopReasons = ["failed", "declined", "interrupted"];
4
+ /** Nothing around the steps: for commands whose output is the point (ssh, logs), and for tests. */
5
+ export const silent = {
6
+ plan: (_plan, work) => work(),
7
+ step: (_step, _at, work) => work(),
8
+ };
9
+ export const parts = (plan) => typed([...new Set(plan.flatMap((step) => (step.part === undefined ? Object.freeze([]) : Object.freeze([step.part]))))]);
10
+ /** Where the step at `index` is, for a plan that may consist of several parts. */
11
+ export const position = (plan, index) => {
12
+ const part = plan[index]?.part;
13
+ const opens = part !== undefined && parts(plan).length > 1 && plan[index - 1]?.part !== part;
14
+ return typed({ index, total: plan.length, ...(opens ? { opens: part } : {}) });
15
+ };
@@ -0,0 +1,8 @@
1
+ import { quote } from "../plan/describe.js";
2
+ import { typed } from "../../typed.js";
3
+ /** A step that talks with a person, given a pty: macOS's script, util-linux's elsewhere. */
4
+ export const inPty = (argv, size) => {
5
+ const { columns, rows } = size ?? { columns: 120, rows: 32 };
6
+ const sized = ["sh", "-c", `stty rows ${String(rows)} cols ${String(columns)} 2>/dev/null; exec "$@"`, "sh", ...argv];
7
+ return typed(process.platform === "darwin" ? ["bash", "-c", '"$@" < <(cat); code=$?; kill "$!" 2>/dev/null || :; exit "$code"', "bash", "script", "-q", "/dev/null", ...sized] : ["script", "-q", "-e", "-c", sized.map(quote).join(" "), "/dev/null"]);
8
+ };
@@ -1,66 +1,82 @@
1
1
  import { z } from "zod";
2
+ /**
3
+ * Every kayra operation, once: what each client (the command line, the API,
4
+ * the web interface) offers, and what it may ask for. A client names an
5
+ * operation and gives its input as plain JSON; the core checks it here, binds
6
+ * it to the fleet and runs it. A new operation is added here, and each client's
7
+ * coverage table refuses to compile until it offers it too.
8
+ */
9
+ /** What an operation acts on: the fleet as a whole, one server, one app on a server, or an app's own repository. */
10
+ export const scopes = ["fleet", "server", "app", "repo"];
11
+ /** What it does to the world: a client asks before a change to a real server, and twice before destroying. */
12
+ export const effects = ["reads", "changes", "destroys"];
13
+ /**
14
+ * How it runs: a plan of steps (shown before, followed while), a query
15
+ * answering at once, a stream of answers as they land (status), or an interactive session.
16
+ */
17
+ export const kinds = ["plan", "query", "stream", "session"];
2
18
  const server = z.string().min(1).describe("A server of the fleet (servers/<name>/)");
3
19
  const app = z.string().min(1).describe("An app name, including a removed app whose records or data remain");
4
- const onServer = z.strictObject({ server });
5
- const onApp = z.strictObject({ server, app });
20
+ const serverInput = z.strictObject({ server });
21
+ const appInput = z.strictObject({ server, app });
6
22
  export const operations = {
7
23
  up: {
8
24
  summary: "Provision, set up everything, point /etc/hosts at it.",
9
25
  scope: "server",
10
26
  effect: "changes",
11
27
  kind: "plan",
12
- input: onServer,
28
+ input: serverInput,
13
29
  },
14
30
  provision: {
15
31
  summary: "Create or update the machine (target home: build the image to import).",
16
32
  scope: "server",
17
33
  effect: "changes",
18
34
  kind: "plan",
19
- input: onServer,
35
+ input: serverInput,
20
36
  },
21
- deploy: { summary: "Host setup and every app, no provisioning.", scope: "server", effect: "changes", kind: "plan", input: onServer },
22
- setup: { summary: "The host layer only: the playbook for the server's kind.", scope: "server", effect: "changes", kind: "plan", input: onServer },
37
+ deploy: { summary: "Host setup and every app, no provisioning.", scope: "server", effect: "changes", kind: "plan", input: serverInput },
38
+ setup: { summary: "The host layer only: the playbook for the server's kind.", scope: "server", effect: "changes", kind: "plan", input: serverInput },
23
39
  plan: {
24
40
  summary: "What provision and setup would change, changing nothing (OpenTofu plan, Ansible check mode).",
25
41
  scope: "server",
26
42
  effect: "reads",
27
43
  kind: "plan",
28
- input: onServer,
44
+ input: serverInput,
29
45
  },
30
46
  verify: {
31
47
  summary: "Whether a platform server works as its users see it: logins, certificates, webhooks, apps, runs, alerts.",
32
48
  scope: "server",
33
49
  effect: "reads",
34
50
  kind: "plan",
35
- input: onServer,
51
+ input: serverInput,
36
52
  },
37
53
  apps: {
38
54
  summary: "Make the server's apps match server.yml: register each, remove the rest (data kept).",
39
55
  scope: "server",
40
56
  effect: "changes",
41
57
  kind: "plan",
42
- input: onServer,
58
+ input: serverInput,
43
59
  },
44
- hosts: { summary: "Point the domain at a multipass VM in /etc/hosts (sudo).", scope: "server", effect: "changes", kind: "plan", input: onServer },
45
- ssh: { summary: "Open an interactive SSH session.", scope: "server", effect: "changes", kind: "session", bare: true, input: onServer },
60
+ hosts: { summary: "Point the domain at a multipass VM in /etc/hosts (sudo).", scope: "server", effect: "changes", kind: "plan", input: serverInput },
61
+ ssh: { summary: "Open an interactive SSH session.", scope: "server", effect: "changes", kind: "session", bare: true, input: serverInput },
46
62
  "ssh.exec": {
47
63
  summary: "Run a command over SSH.", scope: "server", effect: "changes", kind: "plan", bare: true,
48
64
  input: z.strictObject({ server, command: z.array(z.string()).min(1).describe("The remote command and arguments") }),
49
65
  },
50
- down: { summary: "Destroy the machine.", scope: "server", effect: "destroys", kind: "plan", input: onServer },
66
+ down: { summary: "Destroy the machine.", scope: "server", effect: "destroys", kind: "plan", input: serverInput },
51
67
  adopt: {
52
68
  summary: "Once, for a server we did not create: add the deploy user as root.",
53
69
  scope: "server",
54
70
  effect: "changes",
55
71
  kind: "plan",
56
- input: onServer,
72
+ input: serverInput,
57
73
  },
58
74
  "backup.test": {
59
75
  summary: "Restore the latest backup to a scratch dir, check it, delete it.",
60
76
  scope: "server",
61
77
  effect: "changes",
62
78
  kind: "plan",
63
- input: onServer,
79
+ input: serverInput,
64
80
  },
65
81
  "app.check": {
66
82
  summary: "What the platform checks at deploy (app.yml, images, compose policy), in an app's repository. No fleet needed.",
@@ -69,14 +85,14 @@ export const operations = {
69
85
  kind: "plan",
70
86
  input: z.strictObject({ dir: z.string().min(1).default(".").describe("The app's repository") }),
71
87
  },
72
- "app.purge": { summary: "Delete a removed app's volumes: its data, irreversibly.", scope: "app", effect: "destroys", kind: "plan", input: onApp },
88
+ "app.purge": { summary: "Delete a removed app's volumes: its data, irreversibly.", scope: "app", effect: "destroys", kind: "plan", input: appInput },
73
89
  "app.runs": {
74
90
  summary: "What runs now, and the app's latest runs: state, commit, why, when, how long.",
75
91
  scope: "app",
76
92
  effect: "reads",
77
93
  kind: "query",
78
94
  bare: true,
79
- input: onApp,
95
+ input: appInput,
80
96
  },
81
97
  "app.log": {
82
98
  summary: "A run's log, the newest unless named; its errors and warnings marked.",
@@ -100,7 +116,7 @@ export const operations = {
100
116
  effect: "reads",
101
117
  kind: "query",
102
118
  bare: true,
103
- input: onApp,
119
+ input: appInput,
104
120
  },
105
121
  "app.rollback": {
106
122
  summary: "Deploy an earlier release again.",
@@ -149,4 +165,5 @@ export const operations = {
149
165
  export const operationNames = Object.keys(operations).filter((name) => Object.hasOwn(operations, name));
150
166
  export const isOperation = (name) => Object.hasOwn(operations, name);
151
167
  /** An operation as every client reads it, whatever its own entry spells out. */
152
- export const operation = (name) => operations[name];
168
+ const described = operations;
169
+ export const operation = (name) => Object.freeze(described[name]);
@@ -1,16 +1,26 @@
1
1
  import { resolve } from "node:path";
2
2
  import { z } from "zod";
3
- import { absolutePath, appName, domain, subdomain, within } from "../brand.js";
4
- import { appCheck } from "../commands/app-check.js";
5
- import { doctor } from "../commands/doctor.js";
6
- import * as server from "../commands/server.js";
7
- import { look } from "../commands/status.js";
8
- import { findings } from "../commands/validate.js";
9
- import { gather } from "../gather.js";
10
- import { interpret } from "../interpret.js";
11
- import { flat } from "../present/line.js";
3
+ import { absolutePath, appName, domain, subdomain, within } from "../fleet/brand.js";
4
+ import { appCheck } from "../recipes/app-check.js";
5
+ import { doctor } from "../recipes/doctor.js";
6
+ import { appPurge, apps, deployer } from "../recipes/apps.js";
7
+ import { adopt, deploy, down, hosts, preview, provision, setup, up, verify } from "../recipes/host.js";
8
+ import { backupTest } from "../recipes/backup.js";
9
+ import { certsFor } from "../recipes/certs.js";
10
+ import { ssh } from "../recipes/ssh.js";
11
+ import { look } from "../status/look.js";
12
+ import { findings } from "../validation/findings.js";
13
+ import { gather } from "../validation/facts.js";
12
14
  import { all, err, flatMap, map, ok } from "../../result.js";
13
15
  import { operations } from "./catalog.js";
16
+ import { textAt } from "../adapters/fs.js";
17
+ import { typed } from "../../typed.js";
18
+ import { resolve as substitute, spawned } from "../interpreter/process.js";
19
+ /** The context for a fleet, with the files read from disk: what every client runs the core with. */
20
+ export const contextFor = (parts) => {
21
+ const { kayra, ...rest } = parts;
22
+ return typed({ ...rest, engine: { kayra, fleet: parts.fleet.root }, read: textAt });
23
+ };
14
24
  /** Every operation with its input: what a client sends, parsed in one go. */
15
25
  const invocations = z.discriminatedUnion("name", [
16
26
  z.strictObject({ name: z.literal("up"), input: operations.up.input }),
@@ -47,7 +57,7 @@ export const invocation = (name, input) => {
47
57
  return ok(parsed.data);
48
58
  const issue = parsed.error.issues[0];
49
59
  const where = issue?.path.slice(1).join(".") ?? "";
50
- return err(name in operations ? `${name}: ${where === "" ? "input" : where}: ${issue?.message ?? "invalid"}` : `no operation '${name}'`);
60
+ return err(Object.hasOwn(operations, name) ? `${name}: ${where === "" ? "input" : where}: ${issue?.message ?? "invalid"}` : `no operation '${name}'`);
51
61
  };
52
62
  const onServer = (ctx, name) => {
53
63
  const found = ctx.fleet.servers.find((each) => each.name === name);
@@ -59,65 +69,58 @@ const onServer = (ctx, name) => {
59
69
  */
60
70
  const onApp = (ctx, input) => flatMap(onServer(ctx, input.server), (target) => map(appName(input.app), (app) => [target, app]));
61
71
  const withServer = (make) => (ctx, input) => flatMap(onServer(ctx, input.server), (target) => make(ctx.engine, target));
62
- const onDeployer = (command) => (ctx, input) => flatMap(onApp(ctx, input), ([target, app]) => server.deployer(target, command(app, input)));
72
+ const onDeployer = (command) => (ctx, input) => flatMap(onApp(ctx, input), ([target, app]) => deployer(target, command(app, input)));
63
73
  const optional = (value) => (typeof value === "string" ? value : undefined);
64
74
  /** Each plan operation, as the plan that does it: the compiler refuses one that has none. */
65
75
  const plans = {
66
- up: withServer(server.up),
67
- provision: withServer(server.provision),
68
- deploy: withServer(server.deploy),
69
- setup: withServer(server.setup),
70
- plan: withServer(server.preview),
71
- verify: withServer(server.verify),
72
- apps: withServer(server.apps),
73
- hosts: withServer(server.hosts),
74
- down: withServer(server.down),
75
- adopt: withServer(server.adopt),
76
- "backup.test": withServer(server.backupTest),
77
- ssh: (ctx, input) => flatMap(onServer(ctx, input.server), (target) => server.ssh(target, [])),
78
- "ssh.exec": (ctx, input) => flatMap(onServer(ctx, input.server), (target) => server.ssh(target, input.command)),
76
+ up: withServer(up),
77
+ provision: withServer(provision),
78
+ deploy: withServer(deploy),
79
+ setup: withServer(setup),
80
+ plan: withServer(preview),
81
+ verify: withServer(verify),
82
+ apps: withServer(apps),
83
+ hosts: withServer(hosts),
84
+ down: withServer(down),
85
+ adopt: withServer(adopt),
86
+ "backup.test": withServer(backupTest),
87
+ ssh: (ctx, input) => flatMap(onServer(ctx, input.server), (target) => ssh(target, [])),
88
+ "ssh.exec": (ctx, input) => flatMap(onServer(ctx, input.server), (target) => ssh(target, input.command)),
79
89
  "app.check": (ctx, input) => flatMap(absolutePath(resolve(ctx.here, input.dir)), (dir) => appCheck(ctx.engine.kayra, dir, ctx.read(within(dir, "app.yml")))),
80
- "app.purge": (ctx, input) => flatMap(onApp(ctx, input), ([target, app]) => server.appPurge(ctx.engine, target, app)),
90
+ "app.purge": (ctx, input) => flatMap(onApp(ctx, input), ([target, app]) => appPurge(ctx.engine, target, app)),
81
91
  "app.runs": onDeployer((app) => ({ kind: "runs", app, more: undefined })),
82
92
  "app.log": onDeployer((app, input) => ({ kind: "logs", app, more: optional(input["run"]) })),
83
93
  "app.deploy": onDeployer((app, input) => ({ kind: "deploy", app, more: optional(input["ref"]) })),
84
94
  "app.releases": onDeployer((app) => ({ kind: "rollback", app, more: undefined })),
85
95
  "app.rollback": onDeployer((app, input) => ({ kind: "rollback", app, more: optional(input["sha"]) })),
86
- job: (ctx, input) => flatMap(onServer(ctx, input.server), (target) => server.deployer(target, { kind: "job", job: input.job, noPrs: input.noPrs })),
96
+ job: (ctx, input) => flatMap(onServer(ctx, input.server), (target) => deployer(target, { kind: "job", job: input.job, noPrs: input.noPrs })),
87
97
  doctor: (ctx) => ok(doctor(ctx.fleet, ctx.engine.kayra)),
88
- certs: (ctx, input) => flatMap(domain(input.domain), (named) => flatMap(all(input.subdomains.map(subdomain)), (subdomains) => server.certsFor(ctx.engine, named, subdomains))),
98
+ certs: (ctx, input) => flatMap(domain(input.domain), (named) => flatMap(all(input.subdomains.map(subdomain)), (subdomains) => certsFor(ctx.engine, named, subdomains))),
89
99
  };
90
100
  export const planOf = (ctx, call) => plans[call.name](ctx, call.input);
91
101
  export const hasPlan = (call) => Object.hasOwn(plans, call.name);
102
+ /** What a deployer's ctl answers, read whole: its stdout, or why it failed. */
92
103
  const deployerAnswer = async (ctx, name, input) => {
93
104
  const plan = planOf(ctx, { name, input });
94
105
  if (!plan.ok)
95
106
  return plan;
96
- // eslint-disable-next-line functional/prefer-immutable-types -- the interpreter's captured streams
97
- const said = { stdout: "", stderr: "" };
98
- const passed = await interpret(plan.value.map((step) => step.kind === "run" ? { ...step, stdout: "show" } : step), {
99
- out: () => undefined,
100
- // eslint-disable-next-line functional/immutable-data -- capturing interpreter diagnostics
101
- err: (text) => { said.stderr += flat(text); },
102
- ask: () => Promise.resolve(""),
103
- ...(ctx.signal === undefined ? {} : { signal: ctx.signal }),
104
- output: (chunk, stream) => {
105
- // eslint-disable-next-line functional/immutable-data -- capturing program output
106
- if (stream === "stdout")
107
- said.stdout += chunk;
108
- // eslint-disable-next-line functional/immutable-data -- capturing program errors
109
- else
110
- said.stderr += chunk;
111
- },
112
- });
113
- return passed ? ok(said.stdout) : err(said.stderr.trim() || "the deployer query failed");
107
+ const [step] = plan.value;
108
+ if (step?.kind !== "run")
109
+ return err("the deployer's plan runs nothing");
110
+ // Like a step without a terminal: no stdin, and stopping reaches the whole process group.
111
+ const plumbing = { output: () => undefined, ...(ctx.signal === undefined ? {} : { signal: ctx.signal }) };
112
+ const argv = await substitute(step.argv, plumbing);
113
+ if (!argv.ok)
114
+ return argv;
115
+ const exit = await spawned(argv.value, { stdout: "capture", stderr: "capture" }, step.env, plumbing);
116
+ return exit.code === 0 ? ok(exit.stdout) : err(exit.stderr.trim() || "the deployer query failed");
114
117
  };
115
118
  const queries = {
116
119
  "app.runs": (ctx, input) => deployerAnswer(ctx, "app.runs", input),
117
120
  "app.releases": (ctx, input) => deployerAnswer(ctx, "app.releases", input),
118
121
  "app.log": (ctx, input) => deployerAnswer(ctx, "app.log", input),
119
122
  validate: async (ctx, input) => {
120
- const chosen = input.server === undefined ? ok(ctx.fleet.servers) : map(onServer(ctx, input.server), (one) => [one]);
123
+ const chosen = input.server === undefined ? ok(ctx.fleet.servers) : map(onServer(ctx, input.server), (one) => Object.freeze([one]));
121
124
  if (!chosen.ok)
122
125
  return chosen;
123
126
  return ok(await Promise.all(chosen.value.map(async (each) => ({ server: each, findings: findings(await gather(ctx.fleet.root, each)) }))));
@@ -1,12 +1,6 @@
1
- export const run = (title, argv, env = {}) => ({
2
- kind: "run",
3
- title,
4
- argv,
5
- env,
6
- stdout: "show",
7
- });
8
- const quote = (word) => (/^[\w@%+=:,./~-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`);
9
- export const shell = (argv) => argv.map(quote).join(" ");
1
+ /** A word as a shell reads it back: bare where it is safe, else single-quoted. */
2
+ export const quote = (word) => (/^[\w@%+=:,./~-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`);
3
+ const shell = (argv) => argv.map(quote).join(" ");
10
4
  const assignments = (env = {}) => Object.entries(env)
11
5
  .map(([key, value]) => `${key}=${quote(value)} `)
12
6
  .join("");
@@ -17,8 +11,6 @@ const arg = (value) => {
17
11
  return value.words === "one" ? `"${command}"` : command;
18
12
  };
19
13
  const describeProbe = (probe) => probe.kind === "on-path" ? `command -v ${quote(probe.program)}` : assignments(probe.env) + shell(probe.argv);
20
- /** Every step of a plan as part of one kayra command. */
21
- export const partOf = (part, plan) => plan.map((step) => ({ ...step, part }));
22
14
  /** guard, check, run, confirm or note: what kind of step it is, as --dry-run says. */
23
15
  export const kindOf = (step) => (step.kind === "check" ? (step.onFailure === "stop" ? "guard" : "check") : step.kind);
24
16
  /** What it is called while it runs; a confirmation and a note say what they say. */
@@ -66,6 +58,4 @@ const describe = (step) => {
66
58
  }
67
59
  };
68
60
  /** The plan as plain lines: --dry-run's output where it is read by a program. */
69
- export const render = (plan) => plan.map(describe);
70
- /** A plan with a step that talks with a person: a client without a terminal gives it a pty and the person's keys. */
71
- export const needsTerminal = (plan) => plan.some((step) => step.kind === "session");
61
+ export const render = (plan) => Object.freeze(plan.map(describe));
@@ -0,0 +1,14 @@
1
+ import { typed } from "../../typed.js";
2
+ /** The kayra commands a longer one is made of, each of which runs its part alone. */
3
+ export const parts = ["provision", "setup", "apps", "verify", "hosts"];
4
+ export const run = (title, argv, env = {}) => typed({
5
+ kind: "run",
6
+ title,
7
+ argv,
8
+ env,
9
+ stdout: "show",
10
+ });
11
+ /** Every step of a plan as part of one kayra command. */
12
+ export const partOf = (part, plan) => Object.freeze(plan.map((step) => ({ ...step, part })));
13
+ /** A plan with a step that talks with a person: a client without a terminal gives it a pty and the person's keys. */
14
+ export const needsTerminal = (plan) => plan.some((step) => step.kind === "session");
@@ -1,17 +1,12 @@
1
- import { appName, within } from "../brand.js";
2
- import { yamlOf } from "../fleet.js";
3
- import { run } from "../plan.js";
4
- import { err, flatMap, map } from "../../result.js";
5
- import { appManifestSchema } from "../settings.js";
6
- import { checkShape } from "../validate.js";
7
- const mapError = (result, f) => result.ok ? result : err(f(result.error));
8
- const tool = (program, hint) => ({
9
- kind: "check",
10
- label: `${program} is installed`,
11
- probe: { kind: "on-path", program },
12
- hint,
13
- onFailure: "stop",
14
- });
1
+ import { appName, within } from "../fleet/brand.js";
2
+ import { yamlOf } from "../fleet/parse.js";
3
+ import { run } from "../plan/model.js";
4
+ import { err, flatMap, map, mapError } from "../../result.js";
5
+ import { appManifestSchema } from "../fleet/settings.js";
6
+ import { checkShape } from "../fleet/shape.js";
7
+ import { onPath } from "./steps.js";
8
+ import { typed } from "../../typed.js";
9
+ const tool = (program, hint) => onPath(`${program} is installed`, program, hint, "stop");
15
10
  /**
16
11
  * In an app's own repository, before a push: what the platform checks when it
17
12
  * deploys the app — app.yml against its schema here, then app-check.sh (the
@@ -25,11 +20,11 @@ export const appCheck = (kayra, root, manifest) => {
25
20
  const parsed = appManifestSchema.safeParse(values);
26
21
  return parsed.success ? appName(parsed.data.name) : err("app.yml: invalid");
27
22
  });
28
- return map(shaped, () => [
23
+ return map(shaped, () => typed([
29
24
  tool("git", "brew install git"),
30
25
  tool("jq", "brew install jq"),
31
26
  tool("yq", "brew install yq"),
32
27
  tool("docker", "the docker CLI with Compose; no daemon is needed"),
33
28
  run("Image plan and compose policy", ["bash", within(kayra, "scripts", "local", "app-check.sh"), root]),
34
- ]);
29
+ ]));
35
30
  };
@@ -0,0 +1,63 @@
1
+ import { partOf, run } from "../plan/model.js";
2
+ import { err, map, ok } from "../../result.js";
3
+ import { ansibleEnv, ansiblePath, collections, fromMain, inventory, vault, vaulted } from "./steps.js";
4
+ import { sshTo } from "./ssh.js";
5
+ import { typed } from "../../typed.js";
6
+ /** Register every app in server.yml, then remove the rest (their data kept). */
7
+ export const apps = (engine, server) => {
8
+ const { env } = vault(server);
9
+ const playbook = (title, name, ...extra) => vaulted(run(title, ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", name), ...extra], ansibleEnv(engine, {})), server);
10
+ return ok(partOf("apps", [
11
+ fromMain(engine, server),
12
+ ...(server.kind === "platform"
13
+ ? [
14
+ ...server.apps.flatMap((app) => Object.freeze([
15
+ collections(engine, env),
16
+ playbook(`App ${app.name}`, "app.yml", "-e", `server=${server.name}`, "-e", `server_dir=${server.dir}`, "-e", `domain=${server.domain}`, "-e", `{"app": ${JSON.stringify(app.entry)}}`),
17
+ ])),
18
+ collections(engine, env),
19
+ playbook("Remove apps not in server.yml", "apps-prune.yml", "-e", `{"keep": ${JSON.stringify(server.apps.map((app) => app.name))}}`),
20
+ ]
21
+ : []),
22
+ ]));
23
+ };
24
+ /** A removed app's volumes: its data, irreversibly. */
25
+ export const appPurge = (engine, server, app) => ok([
26
+ fromMain(engine, server),
27
+ run(`Delete ${app}'s volumes`, [
28
+ "ansible",
29
+ "servers",
30
+ "-i",
31
+ inventory(server),
32
+ "--become",
33
+ "-m",
34
+ "ansible.builtin.command",
35
+ "-a",
36
+ `/opt/platform/bin/app-purge ${app}`,
37
+ ], ansibleEnv(engine, {})),
38
+ ]);
39
+ const ctlCall = (server, command) => {
40
+ switch (command.kind) {
41
+ case "job":
42
+ return typed({ title: `Job ${command.job}`, args: ["job", command.job, ...(command.noPrs ? ["--dry-run"] : [])], stdout: "show" });
43
+ case "logs":
44
+ return typed({
45
+ title: `Log of ${command.app}'s ${command.more === undefined ? "newest run" : `run ${command.more}`}`,
46
+ args: ["log", command.app, ...(command.more === undefined ? [] : [command.more])],
47
+ stdout: { view: "log", app: command.app, server: server.name },
48
+ });
49
+ case "runs":
50
+ return typed({ title: `Runs of ${command.app}`, args: ["runs", command.app, "--json"], stdout: { view: "runs", app: command.app, server: server.name } });
51
+ case "deploy":
52
+ return typed({ title: `Deploy ${command.app} at ${command.more ?? "its ref"}`, args: ["deploy", command.app, ...(command.more === undefined ? [] : [command.more])], stdout: "show" });
53
+ case "rollback":
54
+ return typed(command.more === undefined ? { title: `Releases of ${command.app}`, args: ["rollback", command.app, "--json"], stdout: { view: "releases", app: command.app, server: server.name } } : { title: `Roll ${command.app} back to ${command.more}`, args: ["rollback", command.app, command.more], stdout: "show" });
55
+ }
56
+ };
57
+ /** Inside the deployer container, as the deploy user (in the docker group): nothing here needs root. */
58
+ export const deployer = (server, command) => {
59
+ if (server.kind !== "platform")
60
+ return err(`'${server.name}' is a ${server.kind} server: only platform servers run apps.`);
61
+ const call = ctlCall(server, command);
62
+ return map(sshTo(server, ["cd", "/opt/platform", "&&", "docker", "compose", "exec", "-T", "deployer", "kayra-deployer", "ctl", ...call.args]), (argv) => typed([{ ...run(call.title, argv), stdout: call.stdout }]));
63
+ };
@@ -0,0 +1,34 @@
1
+ import { within } from "../fleet/brand.js";
2
+ import { run } from "../plan/model.js";
3
+ import { err, ok } from "../../result.js";
4
+ import { ansibleEnv, inventory, reachable, vaulted } from "./steps.js";
5
+ import { sshArgv } from "./ssh.js";
6
+ /**
7
+ * The restic-backup role's restore test: the latest backup, restored to a scratch dir and checked.
8
+ * It runs on the server, detached; kayra follows its log over SSH. Stopping kayra stops only the
9
+ * following, and running it again while a test runs follows that one instead of starting another.
10
+ */
11
+ export const backupTest = (engine, server) => {
12
+ if (server.backupDir === undefined)
13
+ return err(`${server.name} has no restic_backup.dir in its vars.yml`);
14
+ if (server.inventory === undefined)
15
+ return err(`no inventory for '${server.name}' — provision it first.`);
16
+ return ok([
17
+ ...reachable(engine, server),
18
+ vaulted(run("Start the restore test", [
19
+ "ansible",
20
+ "servers",
21
+ "-i",
22
+ inventory(server),
23
+ "--become",
24
+ "-e",
25
+ `@${within(server.dir, "secrets.yml")}`,
26
+ "-m",
27
+ "ansible.builtin.command",
28
+ "-a",
29
+ `docker compose -f ${server.backupDir}/docker-compose.yml exec -d -T backup /etc/backup/restore-test.sh`,
30
+ ], ansibleEnv(engine, {})), server),
31
+ { kind: "note", text: "Following the restore test. Ctrl-C stops following, not the test." },
32
+ run("Follow the restore test", sshArgv(server.inventory, ["-o", "StrictHostKeyChecking=accept-new"], ["sh", `${server.backupDir}/follow-restore-test.sh`])),
33
+ ]);
34
+ };
@@ -0,0 +1,4 @@
1
+ import { ok } from "../../result.js";
2
+ import { certs } from "./steps.js";
3
+ /** mkcert certs for a domain and its subdomains, for local dev and multipass. */
4
+ export const certsFor = (engine, domain, subdomains) => ok([certs(engine, domain, subdomains)]);