@yunuseon/kayra 0.16.1 → 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 (117) hide show
  1. package/README.md +4 -0
  2. package/ansible/roles/platform/tasks/main.yml +31 -0
  3. package/cli/dist/browser/assets/{index-3W_NFATj.css → index-Ct0Eudk4.css} +1 -1
  4. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  5. package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
  6. package/cli/dist/browser/index.html +2 -2
  7. package/cli/dist/clients/api/api.js +189 -0
  8. package/cli/dist/clients/api/auth.js +37 -0
  9. package/cli/dist/clients/api/commands.js +63 -0
  10. package/cli/dist/clients/api/contract.gen.js +1 -0
  11. package/cli/dist/clients/api/contract.js +91 -0
  12. package/cli/dist/clients/api/directories.js +20 -0
  13. package/cli/dist/clients/api/discovery.js +43 -0
  14. package/cli/dist/clients/api/live.js +40 -0
  15. package/cli/dist/clients/api/protocol.js +68 -0
  16. package/cli/dist/clients/api/queries.js +20 -0
  17. package/cli/dist/{web → clients/api}/runs.js +14 -11
  18. package/cli/dist/clients/api/start.js +97 -0
  19. package/cli/dist/clients/api/status.js +29 -0
  20. package/cli/dist/clients/api/validate.js +13 -0
  21. package/cli/dist/{ui → clients/cli}/explain.js +10 -8
  22. package/cli/dist/clients/cli/framed.js +67 -0
  23. package/cli/dist/clients/cli/invocation.js +84 -0
  24. package/cli/dist/clients/cli/paint.js +23 -0
  25. package/cli/dist/{cli.js → clients/cli/parser.js} +38 -32
  26. package/cli/dist/clients/cli/questions.js +89 -0
  27. package/cli/dist/clients/cli/status.js +75 -0
  28. package/cli/dist/{ui → clients/cli}/terminal.js +5 -15
  29. package/cli/dist/{ui → clients/cli}/text.js +15 -24
  30. package/cli/dist/clients/cli/validate.js +32 -0
  31. package/cli/dist/clients/cli/values.js +19 -0
  32. package/cli/dist/{ui → clients/cli}/views.js +28 -60
  33. package/cli/dist/clients/ui/assets.js +36 -0
  34. package/cli/dist/core/adapters/fs.js +18 -0
  35. package/cli/dist/{net.js → core/adapters/network.js} +20 -5
  36. package/cli/dist/core/adapters/opentofu.js +24 -0
  37. package/cli/dist/core/ctl/answers.js +32 -0
  38. package/cli/dist/core/fleet/brand.js +45 -0
  39. package/cli/dist/{schemas.js → core/fleet/docs.js} +4 -3
  40. package/cli/dist/core/fleet/load.js +44 -0
  41. package/cli/dist/core/fleet/model.js +1 -0
  42. package/cli/dist/{fleet.js → core/fleet/parse.js} +61 -41
  43. package/cli/dist/{settings.js → core/fleet/settings.js} +10 -3
  44. package/cli/dist/{validate.js → core/fleet/shape.js} +6 -5
  45. package/cli/dist/core/interpreter/events.js +81 -0
  46. package/cli/dist/core/interpreter/io.js +18 -0
  47. package/cli/dist/core/interpreter/loop.js +101 -0
  48. package/cli/dist/core/interpreter/needs.js +47 -0
  49. package/cli/dist/core/interpreter/process.js +107 -0
  50. package/cli/dist/core/interpreter/progress.js +15 -0
  51. package/cli/dist/core/interpreter/pty.js +8 -0
  52. package/cli/dist/core/operations/catalog.js +169 -0
  53. package/cli/dist/core/operations/dispatch.js +142 -0
  54. package/cli/dist/{plan.js → core/plan/describe.js} +13 -16
  55. package/cli/dist/core/plan/model.js +14 -0
  56. package/cli/dist/{commands → core/recipes}/app-check.js +11 -16
  57. package/cli/dist/core/recipes/apps.js +63 -0
  58. package/cli/dist/core/recipes/backup.js +34 -0
  59. package/cli/dist/core/recipes/certs.js +4 -0
  60. package/cli/dist/{commands → core/recipes}/doctor.js +20 -35
  61. package/cli/dist/core/recipes/host.js +104 -0
  62. package/cli/dist/core/recipes/ssh.js +20 -0
  63. package/cli/dist/core/recipes/steps.js +82 -0
  64. package/cli/dist/core/status/look.js +55 -0
  65. package/cli/dist/core/status/model.js +6 -0
  66. package/cli/dist/core/status/ports.js +1 -0
  67. package/cli/dist/core/status/updates.js +13 -0
  68. package/cli/dist/core/text/plural.js +2 -0
  69. package/cli/dist/core/text/spans.js +22 -0
  70. package/cli/dist/core/text/time.js +12 -0
  71. package/cli/dist/core/validation/facts.js +49 -0
  72. package/cli/dist/{commands/validate.js → core/validation/findings.js} +31 -66
  73. package/cli/dist/deployer/app.js +2 -1
  74. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  75. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  76. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  77. package/cli/dist/deployer/cron.js +2 -2
  78. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  79. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  80. package/cli/dist/deployer/deployer.js +23 -22
  81. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  82. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  83. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  84. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  85. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  86. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  87. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  88. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  89. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  90. package/cli/dist/deployer/main.js +2 -2
  91. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  92. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  93. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  94. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  95. package/cli/dist/main.js +98 -99
  96. package/cli/dist/result.js +11 -1
  97. package/cli/dist/serve.js +77 -0
  98. package/cli/dist/typed.js +2 -0
  99. package/package.json +4 -2
  100. package/scripts/agent/guard.sh +9 -2
  101. package/scripts/local/packed-runs.sh +20 -5
  102. package/scripts/local/setup-hosts.sh +9 -2
  103. package/cli/dist/brand.js +0 -39
  104. package/cli/dist/browser/assets/index-DRFX9Q77.js +0 -2
  105. package/cli/dist/commands/index.js +0 -52
  106. package/cli/dist/commands/server.js +0 -289
  107. package/cli/dist/commands/status.js +0 -194
  108. package/cli/dist/gather.js +0 -61
  109. package/cli/dist/interpret.js +0 -141
  110. package/cli/dist/load.js +0 -64
  111. package/cli/dist/ui/line.js +0 -39
  112. package/cli/dist/ui/progress.js +0 -144
  113. package/cli/dist/web/auth.js +0 -36
  114. package/cli/dist/web/commands.js +0 -102
  115. package/cli/dist/web/contract.js +0 -7
  116. package/cli/dist/web/server.js +0 -336
  117. /package/cli/dist/{web → clients/ui}/opener.js +0 -0
@@ -1,194 +0,0 @@
1
- import { within } from "../brand.js";
2
- import { capture } from "../interpret.js";
3
- import { err, ok } from "../result.js";
4
- import { active, bad, link, muted, ok as fine, strong, warn } from "../ui/line.js";
5
- import { fit, table } from "../ui/text.js";
6
- /** Why a connection failed, by Node's error code. */
7
- export const failure = (code) => {
8
- if (code === "ECONNREFUSED")
9
- return { kind: "refused" };
10
- if (code === "ETIMEDOUT")
11
- return { kind: "no-answer" };
12
- if (["EHOSTUNREACH", "ENETUNREACH", "EHOSTDOWN", "EADDRNOTAVAIL"].includes(code))
13
- return { kind: "unreachable" };
14
- if (["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME", "EAI_NODATA"].includes(code))
15
- return { kind: "unknown-host" };
16
- if (/CERT|SELF_SIGNED|UNABLE_TO_(GET|VERIFY)/.test(code))
17
- return { kind: "bad-certificate", code };
18
- return { kind: "failed", code };
19
- };
20
- /** Why tofu could not read the state, in a few words: the first line of its error. */
21
- export const unreadable = (stderr) => {
22
- if (stderr.includes("tofu init"))
23
- return "tofu init needed";
24
- const line = stderr
25
- .split("\n")
26
- .map((each) => each.replace(/^[│╷╵\s]+/, "").replace(/^Error:\s*/, "").trim())
27
- .find((each) => each !== "");
28
- return line ?? "tofu failed";
29
- };
30
- /** OpenTofu, read and never changed. */
31
- export const opentofu = {
32
- state: async (dir) => {
33
- const listed = await capture(["tofu", `-chdir=${dir}`, "state", "list", "-no-color"], "capture");
34
- return listed.code === 0 ? ok(listed.stdout.split("\n").filter((line) => line.trim() !== "")) : err(unreadable(listed.stderr));
35
- },
36
- output: async (dir, name) => {
37
- const value = await capture(["tofu", `-chdir=${dir}`, "output", "-raw", name], "capture");
38
- const text = value.stdout.trim();
39
- return value.code === 0 && text !== "" ? text : undefined;
40
- },
41
- };
42
- /** A machine kayra's modules create, by its resource type; a data source is none. */
43
- export const isMachine = (resource) => /(?:^|\.)(?<!data\.)(?:hcloud_server|multipass_instance)\.[^.]+$/.test(resource);
44
- /** The inventory names the address: hand-written at home, written by provision elsewhere. */
45
- const listed = (server) => server.inventory === undefined
46
- ? undefined
47
- : { kind: "found", address: server.inventory.host === "" ? undefined : server.inventory.host, from: "inventory" };
48
- const provisioned = async (server, tofu) => {
49
- const dir = within(server.dir, "terraform");
50
- const state = await tofu.state(dir);
51
- if (!state.ok)
52
- return { kind: "unreadable", reason: state.error };
53
- if (state.value.length === 0)
54
- return { kind: "not-provisioned" };
55
- if (!state.value.some(isMachine))
56
- return { kind: "no-machine" };
57
- return { kind: "found", address: await tofu.output(dir, "server_ip"), from: "opentofu" };
58
- };
59
- const sshPort = (server) => Number(server.inventory?.port ?? "22");
60
- const authUrl = (server) => `https://auth.${server.domain}/`;
61
- const pending = { kind: "pending" };
62
- const skipped = { kind: "skipped" };
63
- const at = (index, change) => (looks) => looks.map((look, each) => (each === index ? { ...look, ...change } : look));
64
- /**
65
- * Every server as far as the fleet's files tell, and the answers still to
66
- * come, each an update to it: OpenTofu's state where no inventory names the
67
- * address, then a TCP connect to SSH, and on platform servers HTTPS on
68
- * auth.<domain> (Authelia's health), all at once. Without a network
69
- * (--offline), only OpenTofu.
70
- */
71
- export const look = (fleet, tofu, network) => fleet.servers.reduce((so, server, index) => {
72
- const known = listed(server);
73
- const machine = known === undefined ? provisioned(server, tofu) : Promise.resolve(known);
74
- const platform = server.kind === "platform";
75
- const updates = [
76
- ...(known === undefined ? [machine.then((answer) => at(index, { machine: answer }))] : []),
77
- ...(network === undefined
78
- ? []
79
- : [
80
- machine
81
- .then((found) => found.kind === "found" && found.address !== undefined ? network.connect(found.address, sshPort(server)) : skipped)
82
- .then((answer) => at(index, { ssh: answer })),
83
- ...(platform ? [network.get(`${authUrl(server)}api/health`).then((answer) => at(index, { https: answer }))] : []),
84
- ]),
85
- ];
86
- const first = {
87
- server,
88
- machine: known ?? pending,
89
- ssh: network === undefined ? skipped : pending,
90
- https: platform ? (network === undefined ? skipped : pending) : undefined,
91
- };
92
- return { initial: [...so.initial, first], updates: [...so.updates, ...updates] };
93
- }, { initial: [], updates: [] });
94
- /** A spinner as wide as most answers, so the columns hardly move when they come. */
95
- const waiting = (frame, width) => [active(frame), " ".repeat(width - 1)];
96
- const machineCell = (machine, frame) => {
97
- switch (machine.kind) {
98
- case "pending":
99
- return waiting(frame, "255.255.255.255".length);
100
- case "found":
101
- return [machine.address ?? muted("unknown")];
102
- case "not-provisioned":
103
- return [muted("not provisioned")];
104
- case "no-machine":
105
- return [muted("no machine")];
106
- case "unreadable":
107
- return [bad("state unreadable")];
108
- }
109
- };
110
- const took = (ms) => muted(` ${String(ms)}ms`);
111
- /** An answer, said the same way for both probes. */
112
- const said = (reach, frame) => {
113
- switch (reach.kind) {
114
- case "pending":
115
- return waiting(frame, "open 99ms".length);
116
- case "skipped":
117
- return [muted("–")];
118
- case "no-answer":
119
- return [bad("no answer")];
120
- case "unreachable":
121
- return [bad("unreachable")];
122
- case "unknown-host":
123
- return [bad("unknown host")];
124
- case "bad-certificate":
125
- return [bad(reach.code === "CERT_HAS_EXPIRED" ? "cert expired" : reach.code === "ERR_TLS_CERT_ALTNAME_INVALID" ? "wrong cert" : "untrusted cert")];
126
- case "failed":
127
- return [bad(reach.code.toLowerCase())];
128
- case "refused":
129
- return [bad("refused")];
130
- case "open":
131
- return [fine("open"), took(reach.ms)];
132
- case "answered":
133
- return [(reach.status < 400 ? fine : reach.status < 500 ? warn : bad)(String(reach.status)), took(reach.ms)];
134
- }
135
- };
136
- const sshCell = (reach, frame) => (reach.kind === "refused" ? [warn("off")] : said(reach, frame));
137
- const httpsCell = (reach, frame, url) => said(reach, frame).map((span, index) => (index === 0 && typeof span !== "string" ? link(span.text, url, span.tone) : span));
138
- const headings = ["SERVER", "KIND", "TARGET", "DOMAIN", "ADDRESS", "SSH", "HTTPS", "APPS"];
139
- const probed = ["SSH", "HTTPS"];
140
- const row = (look, frame) => {
141
- const { server } = look;
142
- return [
143
- [strong(server.name)],
144
- [server.kind],
145
- [server.target],
146
- [link(server.domain, `https://${server.domain}/`)],
147
- machineCell(look.machine, frame),
148
- sshCell(look.ssh, frame),
149
- look.https === undefined ? [] : httpsCell(look.https, frame, authUrl(server)),
150
- [server.apps.map((app) => app.name).join(", ")],
151
- ];
152
- };
153
- /** Every server in a table, then what could not be read; --offline drops the probes' columns. */
154
- export const statusView = (looks, drawing) => {
155
- const shown = headings.flatMap((heading, index) => (drawing.offline && probed.includes(heading) ? [] : [index]));
156
- const rows = [headings.map((heading) => [muted(heading)]), ...looks.map((look) => row(look, drawing.frame))].map((cells) => shown.map((index) => cells[index] ?? []));
157
- const notes = looks.flatMap((look) => look.machine.kind === "unreadable"
158
- ? [
159
- [" ", bad("✗"), " ", strong(look.server.name), `: OpenTofu's state could not be read: ${look.machine.reason}`],
160
- ...(look.machine.reason === "tofu init needed"
161
- ? [[" ", active("→"), " ", `tofu -chdir=servers/${look.server.name}/terraform init`]]
162
- : []),
163
- ]
164
- : []);
165
- return [...table(fit(rows, drawing.room, [shown.length - 1, shown.indexOf(3)])), ...(notes.length === 0 ? [] : [[], ...notes])];
166
- };
167
- const ms = (reach) => ("ms" in reach ? reach.ms : null);
168
- const error = (reach) => ("code" in reach ? reach.code : null);
169
- /** `kayra status --json`: the shape cli.md documents. */
170
- export const statusJson = (looks) => ({
171
- servers: looks.map(({ server, machine, ssh, https }) => ({
172
- name: server.name,
173
- kind: server.kind,
174
- target: server.target,
175
- domain: server.domain,
176
- apps: server.apps.map((app) => app.name),
177
- machine: {
178
- state: machine.kind,
179
- address: machine.kind === "found" ? (machine.address ?? null) : null,
180
- from: machine.kind === "found" ? machine.from : null,
181
- reason: machine.kind === "unreadable" ? machine.reason : null,
182
- },
183
- ssh: { port: sshPort(server), state: ssh.kind, ms: ms(ssh), error: error(ssh) },
184
- https: https === undefined
185
- ? null
186
- : {
187
- url: `${authUrl(server)}api/health`,
188
- state: https.kind,
189
- status: https.kind === "answered" ? https.status : null,
190
- ms: ms(https),
191
- error: error(https),
192
- },
193
- })),
194
- });
@@ -1,61 +0,0 @@
1
- import { existsSync, readdirSync, readFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import { yamlOf } from "./fleet.js";
5
- import { capture } from "./interpret.js";
6
- const text = (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined);
7
- const mappingOf = (source) => {
8
- if (source === undefined)
9
- return {};
10
- const parsed = yamlOf(source);
11
- return parsed.ok && typeof parsed.value === "object" && parsed.value !== null && !Array.isArray(parsed.value)
12
- ? Object.fromEntries(Object.entries(parsed.value))
13
- : {};
14
- };
15
- const vaulted = (source) => source.startsWith("$ANSIBLE_VAULT");
16
- /** A secrets file's values: plaintext as is, a vault only with the server's password file; a missing file has none. */
17
- const secretsOf = async (server, path) => {
18
- const source = text(path);
19
- if (source === undefined)
20
- return { kind: "readable", values: {} };
21
- if (!vaulted(source))
22
- return { kind: "readable", values: mappingOf(source) };
23
- if (server.vault.kind !== "file")
24
- return { kind: "locked", reason: "vaulted, and server.yml names no vault_password_file", hint: "vault_password_file in server.yml lets kayra open it" };
25
- const file = server.vault.file.replace(homedir(), "~");
26
- if (!existsSync(server.vault.file))
27
- return { kind: "locked", reason: `vaulted, and there is no ${file} here`, hint: "put the vault's password there" };
28
- const opened = await capture(["ansible-vault", "view", "--vault-password-file", server.vault.file, path], "capture");
29
- return opened.code === 0
30
- ? { kind: "readable", values: mappingOf(opened.stdout) }
31
- : { kind: "locked", reason: `${file} does not open it`, hint: "is it this vault's password?" };
32
- };
33
- const appPath = (entry) => {
34
- const parsed = JSON.parse(entry);
35
- const path = typeof parsed === "object" && parsed !== null && "path" in parsed ? parsed.path : undefined;
36
- return typeof path === "string" ? path : ".";
37
- };
38
- /** What validate needs of a server, read from the fleet (and its clones under .cache/apps). */
39
- export const gather = async (root, server) => {
40
- const varsText = text(join(server.dir, "vars.yml")) ?? "";
41
- const stacks = join(server.dir, "stacks");
42
- const appSecrets = await Promise.all(server.apps.map(async (app) => [app.name, await secretsOf(server, join(server.dir, "apps", `${app.name}.secrets.yml`))]));
43
- return {
44
- server,
45
- vars: mappingOf(varsText),
46
- varsText,
47
- secrets: await secretsOf(server, join(server.dir, "secrets.yml")),
48
- stackDirs: existsSync(stacks)
49
- ? readdirSync(stacks, { withFileTypes: true })
50
- .filter((entry) => entry.isDirectory())
51
- .map((entry) => entry.name)
52
- .toSorted()
53
- : [],
54
- appConfig: Object.fromEntries(server.apps.map((app) => [app.name, mappingOf(text(join(server.dir, "apps", `${app.name}.yml`)))])),
55
- appSecrets: Object.fromEntries(appSecrets),
56
- manifests: Object.fromEntries(server.apps.flatMap((app) => {
57
- const manifest = text(join(root, ".cache", "apps", app.name, appPath(app.entry), "app.yml"));
58
- return manifest === undefined ? [] : [[app.name, mappingOf(manifest)]];
59
- })),
60
- };
61
- };
@@ -1,141 +0,0 @@
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 { active, bad, muted, ok as fine, strong } from "./ui/line.js";
5
- import { position, silent } from "./ui/progress.js";
6
- import { draw } from "./ui/views.js";
7
- const terminal = {};
8
- /** A program that ignores SIGINT this long gets SIGTERM. */
9
- const patience = 10_000;
10
- const spawned = async (argv, streams, env = {}, plumbing = terminal) => {
11
- const [program, ...args] = argv;
12
- const { output, signal } = plumbing;
13
- if (signal?.aborted === true)
14
- return { code: 130, stdout: "", stderr: "", started: false };
15
- const shown = (stream) => stream === "show" ? (output === undefined ? "inherit" : "pipe") : stream === "capture" ? "pipe" : "ignore";
16
- const child = spawn(program, args, {
17
- env: { ...process.env, ...env },
18
- stdio: [output === undefined ? "inherit" : "ignore", shown(streams.stdout), shown(streams.stderr)],
19
- });
20
- const forward = (from, sink) => {
21
- child[from]?.setEncoding("utf8").on("data", (chunk) => {
22
- sink(chunk, from);
23
- });
24
- };
25
- if (output !== undefined && streams.stdout === "show")
26
- forward("stdout", output);
27
- if (output !== undefined && streams.stderr === "show")
28
- forward("stderr", output);
29
- const read = (from, stream) => {
30
- const piped = child[from];
31
- return piped === null || stream !== "capture" ? Promise.resolve("") : text(piped);
32
- };
33
- const stdout = read("stdout", streams.stdout);
34
- const stderr = read("stderr", streams.stderr);
35
- const stop = () => {
36
- child.kill("SIGINT");
37
- setTimeout(() => child.kill("SIGTERM"), patience).unref();
38
- };
39
- signal?.addEventListener("abort", stop, { once: true });
40
- const exit = await new Promise((resolve) => {
41
- child.on("error", resolve);
42
- child.on("close", (code) => {
43
- resolve(code ?? 1);
44
- });
45
- });
46
- signal?.removeEventListener("abort", stop);
47
- return exit instanceof Error
48
- ? { code: 127, stdout: "", stderr: exit.message, started: false }
49
- : { code: exit, stdout: await stdout, stderr: await stderr, started: true };
50
- };
51
- /** A command's stdout, for kayra to read; its stderr reaches the operator unless captured too. */
52
- export const capture = (argv, stderr = "show", env = {}, plumbing = terminal) => spawned(argv, { stdout: "capture", stderr }, env, plumbing);
53
- const answer = (probe, plumbing) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture" }, probe.kind === "exits-zero" ? probe.env : {}, plumbing);
54
- /** Each query's answer in place of it, as `$(…)` would: one word, or split into many. */
55
- const resolve = async (argv, plumbing) => {
56
- const words = await Promise.all(argv.map(async (value) => {
57
- if (typeof value === "string")
58
- return ok([value]);
59
- const exit = await capture(value.argv, "show", value.env, plumbing);
60
- if (exit.code !== 0)
61
- return err(`$(${value.argv.join(" ")}) failed: exit ${String(exit.code)}`);
62
- const output = exit.stdout.replace(/\n+$/, "");
63
- return ok(value.words === "one" ? [output] : output.split(/\s+/).filter((word) => word !== ""));
64
- }));
65
- return flatMap(all(words), (lists) => {
66
- const [program, ...rest] = lists.flat();
67
- return program === undefined ? err("the command is empty") : ok([program, ...rest]);
68
- });
69
- };
70
- const lines = (text) => text
71
- .trimEnd()
72
- .split("\n")
73
- .filter((line) => line !== "");
74
- /** Under the step's own line. */
75
- const detail = (line) => [" ", line];
76
- const aside = (line) => [" ", muted(line)];
77
- const hint = (text) => (text === undefined ? [] : [[" ", active("→"), " ", text]]);
78
- const goOn = { failed: false, stopped: false, out: [], err: [] };
79
- const check = async (step, plumbing) => {
80
- const exit = await answer(step.probe, plumbing);
81
- const said = [...lines(exit.stderr).map(detail), ...hint(step.hint)];
82
- if (step.onFailure === "stop")
83
- return exit.code === 0 ? goOn : { failed: true, stopped: true, out: [], err: said };
84
- return exit.code === 0
85
- ? { ...goOn, out: [[fine("✓"), " ", step.label]] }
86
- : { failed: true, stopped: false, out: [[bad("✗"), " ", step.label], ...said], err: [] };
87
- };
88
- const runStep = async (step, plumbing) => {
89
- const argv = await resolve(step.argv, plumbing);
90
- if (!argv.ok)
91
- return { failed: true, stopped: true, why: "a query failed", out: [], err: [detail(argv.error)] };
92
- const { stdout } = step;
93
- // A quiet step's stderr waits until it is done, so it cannot tear through a spinner.
94
- const quiet = stdout === "discard";
95
- const exit = await spawned(argv.value, { stdout: typeof stdout === "string" ? stdout : "capture", stderr: quiet ? "capture" : "show" }, step.env, plumbing);
96
- if (!exit.started)
97
- return { failed: true, stopped: true, why: "not started", out: [], err: [detail(`${argv.value[0]}: ${exit.stderr}`)] };
98
- // Whatever it answered is shown, even when it failed: it may say why.
99
- const out = typeof stdout === "string" ? [] : draw(stdout, exit.stdout, Date.now());
100
- if (exit.code === 0)
101
- return { ...goOn, out, err: lines(exit.stderr).map(aside) };
102
- return { failed: true, stopped: true, why: `exit ${String(exit.code)}`, out, err: lines(exit.stderr).map(detail) };
103
- };
104
- const perform = async (step, io) => {
105
- switch (step.kind) {
106
- case "run":
107
- return runStep(step, io);
108
- case "check":
109
- return check(step, io);
110
- case "confirm": {
111
- io.err("");
112
- io.err([" ", bad("▲"), " ", strong(step.warning)]);
113
- const typed = await io.ask([" Type ", strong(step.expect), " to confirm: "]);
114
- return typed === step.expect ? goOn : { failed: false, stopped: true, out: ["Aborted."], err: [] };
115
- }
116
- case "note":
117
- return { ...goOn, out: [step.text] };
118
- }
119
- };
120
- /**
121
- * Runs a plan step by step, until it ends or a step stops it, shown by `progress`.
122
- * True if nothing failed and the operator did not interrupt it.
123
- */
124
- export const interpret = async (plan, io, progress = silent, interrupted = () => false) => {
125
- const ended = await progress.plan(plan, () => plan.reduce(async (previous, step, index) => {
126
- const so = await previous;
127
- if (so.stop !== undefined)
128
- return so;
129
- const done = await progress.step(step, position(plan, index), () => perform(step, io));
130
- // Ctrl-C reached the step's program too: how it ended says nothing about the server.
131
- if (interrupted())
132
- return { failures: so.failures, stop: { index, step, why: "interrupted" } };
133
- done.out.forEach(io.out);
134
- done.err.forEach(io.err);
135
- const failures = so.failures + (done.failed ? 1 : 0);
136
- if (done.stopped)
137
- return { failures, stop: { index, step, why: done.failed ? "failed" : "declined" } };
138
- return { failures };
139
- }, Promise.resolve({ failures: 0 })));
140
- return ended.failures === 0 && ended.stop?.why !== "interrupted";
141
- };
package/cli/dist/load.js DELETED
@@ -1,64 +0,0 @@
1
- import { existsSync, readdirSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { fleetRoot, serverDir, serverName, within } from "./brand.js";
4
- import { parseServer, yamlOf } from "./fleet.js";
5
- import { all, err, flatMap, map, ok } from "./result.js";
6
- import { defaultsSchema } from "./settings.js";
7
- import { checkSettings, knownSettings } from "./validate.js";
8
- /** The fleet is the nearest directory, from `from` upwards, with a servers/defaults.yml. */
9
- export const findFleetRoot = (from) => {
10
- if (existsSync(join(from, "servers", "defaults.yml")))
11
- return ok(fleetRoot(from));
12
- const parent = within(from, "..");
13
- return parent === from
14
- ? err("no fleet here: no servers/defaults.yml in this directory or above it")
15
- : findFleetRoot(parent);
16
- };
17
- const text = (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined);
18
- const stacks = (dir) => existsSync(join(dir, "stacks"))
19
- ? readdirSync(join(dir, "stacks"))
20
- .toSorted()
21
- .flatMap((stack) => text(join(dir, "stacks", stack, "compose.yaml")) ?? [])
22
- : [];
23
- const appValues = (dir) => existsSync(join(dir, "apps"))
24
- ? readdirSync(join(dir, "apps"))
25
- .filter((file) => file.endsWith(".yml"))
26
- .toSorted()
27
- .map((file) => ({ file, text: readFileSync(join(dir, "apps", file), "utf8") }))
28
- : [];
29
- const readServer = (root, entry) => {
30
- const name = serverName(entry);
31
- if (!name.ok)
32
- return err(`servers/${entry}: ${name.error}`);
33
- const dir = serverDir(root, name.value);
34
- const server = parseServer({
35
- name: name.value,
36
- dir,
37
- descriptor: readFileSync(join(dir, "server.yml"), "utf8"),
38
- vars: text(join(dir, "vars.yml")),
39
- secrets: text(join(dir, "secrets.yml")),
40
- inventory: text(join(dir, "inventory.ini")),
41
- terraform: existsSync(join(dir, "terraform")),
42
- stacks: stacks(dir),
43
- appValues: appValues(dir),
44
- });
45
- return server.ok ? server : err(`servers/${entry}/server.yml: ${server.error}`);
46
- };
47
- /** servers/defaults.yml: settings shared by every server, any kind's. */
48
- const checkDefaults = (root) => {
49
- const parsed = yamlOf(readFileSync(join(root, "servers", "defaults.yml"), "utf8"));
50
- if (!parsed.ok)
51
- return err(`servers/defaults.yml ${parsed.error}`);
52
- const values = parsed.value;
53
- if (values === null || values === undefined)
54
- return ok(true);
55
- if (typeof values !== "object" || Array.isArray(values))
56
- return err("servers/defaults.yml is not a YAML mapping");
57
- return map(checkSettings("servers/defaults.yml", Object.fromEntries(Object.entries(values)), defaultsSchema, knownSettings(undefined)), () => true);
58
- };
59
- export const loadFleet = (root) => flatMap(checkDefaults(root), () => fleetOf(root));
60
- const fleetOf = (root) => map(all(readdirSync(join(root, "servers"), { withFileTypes: true })
61
- .filter((entry) => entry.isDirectory() && existsSync(join(root, "servers", entry.name, "server.yml")))
62
- .map((entry) => entry.name)
63
- .toSorted()
64
- .map((entry) => readServer(root, entry))), (servers) => ({ root, servers }));
@@ -1,39 +0,0 @@
1
- import { styleText } from "node:util";
2
- import { escapes } from "./terminal.js";
3
- const toned = (tone) => (text) => ({ tone, text });
4
- export const ok = toned("ok");
5
- export const bad = toned("bad");
6
- export const warn = toned("warn");
7
- export const active = toned("active");
8
- export const muted = toned("muted");
9
- export const strong = toned("strong");
10
- export const accent = toned("accent");
11
- export const link = (text, href, tone) => ({ text, href, ...(tone === undefined ? {} : { tone }) });
12
- const looks = {
13
- ok: ["green"],
14
- bad: ["red"],
15
- warn: ["yellow"],
16
- active: ["cyan"],
17
- muted: ["dim"],
18
- strong: ["bold"],
19
- accent: ["magenta", "bold"],
20
- };
21
- const spans = (text) => (typeof text === "string" ? [text] : text);
22
- const textOf = (span) => (typeof span === "string" ? span : span.text);
23
- export const flat = (text) => spans(text).map(textOf).join("");
24
- const graphemes = new Intl.Segmenter();
25
- /** A string's characters as a reader counts them. */
26
- export const characters = (text) => Array.from(graphemes.segment(text), (each) => each.segment);
27
- /** Columns it takes: one per character, which holds for everything kayra writes itself. */
28
- export const width = (text) => characters(flat(text)).length;
29
- export const paint = (text, colors, links = false) => spans(text)
30
- .map((span) => {
31
- if (typeof span === "string")
32
- return span;
33
- const { tone, href } = span;
34
- const styled = colors && tone !== undefined
35
- ? looks[tone].reduce((so, format) => styleText(format, so, { validateStream: false }), span.text)
36
- : span.text;
37
- return links && href !== undefined ? escapes.link(styled, href) : styled;
38
- })
39
- .join("");
@@ -1,144 +0,0 @@
1
- import { commandOf, kindOf, titleOf } from "../plan.js";
2
- import { accent, active, bad, muted, ok, paint, strong, warn } from "./line.js";
3
- import { escapes, spinner } from "./terminal.js";
4
- import { duration, spread, truncate } from "./text.js";
5
- /** Nothing around the steps: for commands whose output is the point (ssh, logs), and for tests. */
6
- export const silent = {
7
- plan: (_plan, work) => work(),
8
- step: (_step, _at, work) => work(),
9
- };
10
- const parts = (plan) => [...new Set(plan.flatMap((step) => (step.part === undefined ? [] : [step.part])))];
11
- /** Where the step at `index` is, for a plan that may consist of several parts. */
12
- export const position = (plan, index) => {
13
- const part = plan[index]?.part;
14
- const opens = part !== undefined && parts(plan).length > 1 && plan[index - 1]?.part !== part;
15
- return { index, total: plan.length, ...(opens ? { opens: part } : {}) };
16
- };
17
- /** A run of this long earns a notification when it ends: the operator has looked away. */
18
- const worthNotifying = 30_000;
19
- /** "8 steps", or "15 checks" for a plan of nothing else (doctor). */
20
- export const steps = (plan) => {
21
- const noun = plan.every((step) => step.kind === "check") ? "check" : "step";
22
- return `${String(plan.length)} ${noun}${plan.length === 1 ? "" : "s"}`;
23
- };
24
- /** The footer: how it went, how long it took, and what reruns a failed part alone. */
25
- export const footer = (invocation, plan, ended, ms) => {
26
- const took = duration(ms);
27
- const { command } = invocation;
28
- const { stop } = ended;
29
- if (stop === undefined)
30
- return ended.failures === 0
31
- ? [[ok("✓"), " ", strong(command), muted(` · ${steps(plan)} · ${took}`)]]
32
- : [[bad("✗"), " ", strong(command), muted(` · ${String(ended.failures)} of ${steps(plan)} failed · ${took}`)]];
33
- const where = `step ${String(stop.index + 1)} of ${String(plan.length)}`;
34
- if (stop.why === "declined")
35
- return [[warn("■"), " ", strong(command), muted(` stopped at ${where}: not confirmed`)]];
36
- if (stop.why === "interrupted")
37
- return [[warn("■"), " ", strong(command), muted(` interrupted at ${where} · ${took}`)]];
38
- const { part } = stop.step;
39
- const alone = part !== undefined && parts(plan).length > 1 && invocation.server !== undefined;
40
- return [
41
- [bad("✗"), " ", strong(command), " failed at ", strong(titleOf(stop.step)), muted(` · ${where} · ${took}`)],
42
- ...(alone ? [[" ", active("→"), " ", strong(`kayra ${part} ${invocation.server ?? ""}`), muted(" runs just this part")]] : []),
43
- ];
44
- };
45
- /** Frames on stderr: a heading, each step as it runs and how it went, a footer; on a terminal also spinners, the window title, a notification. */
46
- export const framed = (screen, write, invocation) => {
47
- const columns = Math.min(screen.columns, 80);
48
- const say = (text) => {
49
- write(`${paint(text, screen.colors)}\n`);
50
- };
51
- const tell = (raw, when) => {
52
- if (when)
53
- write(raw);
54
- };
55
- return {
56
- plan: async (plan, work) => {
57
- const started = performance.now();
58
- tell(escapes.pushTitle + escapes.title(invocation.command), screen.title);
59
- say([strong(invocation.command), muted([...invocation.about, steps(plan)].map((each) => ` · ${each}`).join(""))]);
60
- say("");
61
- const ended = await work();
62
- const ms = performance.now() - started;
63
- say("");
64
- footer(invocation, plan, ended, ms).forEach(say);
65
- tell(escapes.popTitle, screen.title);
66
- tell(escapes.progressDone, screen.progressBar);
67
- const failed = ended.failures > 0 || ended.stop?.why === "failed";
68
- tell(escapes.notify(`${invocation.command} ${failed ? "failed" : "is done"} after ${duration(ms)}`), screen.notifications && ms >= worthNotifying);
69
- return ended;
70
- },
71
- step: async (step, at, work) => {
72
- if (step.kind === "confirm" || step.kind === "note")
73
- return work();
74
- if (at.opens !== undefined) {
75
- if (at.index > 0)
76
- say("");
77
- say([accent(at.opens)]);
78
- }
79
- const title = titleOf(step);
80
- const counter = `${String(at.index + 1)}/${String(at.total)}`;
81
- tell(escapes.title(`${invocation.command} · ${counter} ${title}`), screen.title);
82
- tell(escapes.progress((at.index / at.total) * 100), screen.progressBar);
83
- const shown = step.kind === "run" && step.stdout === "show";
84
- if (shown)
85
- say(spread([" ", active("◆"), " ", strong(title)], [muted(counter)], columns));
86
- const stop = !shown && screen.live
87
- ? spinner(write, (frame, ms) => paint(spread(truncate([" ", active(frame), " ", title], columns - 8), [muted(duration(ms))], columns), screen.colors))
88
- : () => undefined;
89
- const started = performance.now();
90
- const done = await work();
91
- stop();
92
- // A diagnosis reports itself on stdout: that line is doctor's output.
93
- if (step.kind === "check" && step.onFailure === "continue")
94
- return done;
95
- const took = duration(performance.now() - started);
96
- say(spread([" ", done.failed ? bad("✗") : ok("✓"), " ", title], [muted(done.why === undefined ? took : `${done.why} · ${took}`)], columns));
97
- return done;
98
- },
99
- };
100
- };
101
- /** Every step of a plan, its command's paths named by their root. */
102
- export const listed = (plan, short) => plan.map((step, index) => {
103
- const command = commandOf(step);
104
- const { opens } = position(plan, index);
105
- return {
106
- index,
107
- kind: kindOf(step),
108
- title: titleOf(step),
109
- ...(command === undefined ? {} : { command: short(command) }),
110
- ...(step.part === undefined ? {} : { part: step.part }),
111
- ...(opens === undefined ? {} : { opens }),
112
- };
113
- });
114
- /** The plan and each step as events: what framed draws on a terminal, as data. */
115
- export const reporting = (emit, invocation, short) => ({
116
- plan: async (plan, work) => {
117
- const started = performance.now();
118
- emit({ kind: "plan", invocation, steps: listed(plan, short) });
119
- const ended = await work();
120
- const ms = performance.now() - started;
121
- emit({
122
- kind: "ended",
123
- failures: ended.failures,
124
- ...(ended.stop === undefined ? {} : { stop: { index: ended.stop.index, why: ended.stop.why } }),
125
- ms,
126
- footer: footer(invocation, plan, ended, ms),
127
- });
128
- return ended;
129
- },
130
- step: async (_step, at, work) => {
131
- const started = performance.now();
132
- emit({ kind: "started", index: at.index });
133
- const done = await work();
134
- emit({
135
- kind: "done",
136
- index: at.index,
137
- failed: done.failed,
138
- stopped: done.stopped,
139
- ...(done.why === undefined ? {} : { why: done.why }),
140
- ms: performance.now() - started,
141
- });
142
- return done;
143
- },
144
- });