@yunuseon/kayra 0.17.0 → 0.17.2

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 (113) hide show
  1. package/agent/skills/kayra-release/SKILL.md +6 -1
  2. package/ansible/roles/platform/tasks/main.yml +40 -1
  3. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  4. package/cli/dist/browser/index.html +1 -1
  5. package/cli/dist/clients/api/api.js +138 -218
  6. package/cli/dist/clients/api/auth.js +8 -7
  7. package/cli/dist/clients/api/commands.js +50 -14
  8. package/cli/dist/clients/api/contract.js +8 -6
  9. package/cli/dist/clients/api/directories.js +1 -1
  10. package/cli/dist/clients/api/discovery.js +8 -3
  11. package/cli/dist/clients/api/live.js +40 -0
  12. package/cli/dist/clients/api/protocol.js +17 -10
  13. package/cli/dist/clients/api/queries.js +4 -4
  14. package/cli/dist/clients/api/runs.js +10 -9
  15. package/cli/dist/clients/api/start.js +97 -0
  16. package/cli/dist/clients/api/status.js +29 -0
  17. package/cli/dist/clients/api/validate.js +13 -0
  18. package/cli/dist/clients/cli/explain.js +12 -10
  19. package/cli/dist/clients/cli/framed.js +12 -9
  20. package/cli/dist/clients/cli/invocation.js +4 -3
  21. package/cli/dist/clients/cli/paint.js +1 -1
  22. package/cli/dist/clients/cli/parser.js +8 -8
  23. package/cli/dist/clients/cli/questions.js +11 -10
  24. package/cli/dist/clients/cli/status.js +75 -0
  25. package/cli/dist/clients/cli/terminal.js +4 -2
  26. package/cli/dist/{core/present → clients/cli}/text.js +15 -24
  27. package/cli/dist/clients/cli/validate.js +32 -0
  28. package/cli/dist/clients/cli/values.js +19 -0
  29. package/cli/dist/{core/present → clients/cli}/views.js +28 -60
  30. package/cli/dist/core/adapters/fs.js +18 -0
  31. package/cli/dist/core/{net.js → adapters/network.js} +20 -5
  32. package/cli/dist/core/adapters/opentofu.js +24 -0
  33. package/cli/dist/core/ctl/answers.js +32 -0
  34. package/cli/dist/core/fleet/brand.js +54 -0
  35. package/cli/dist/core/{schemas.js → fleet/docs.js} +5 -4
  36. package/cli/dist/core/fleet/load.js +45 -0
  37. package/cli/dist/core/fleet/model.js +1 -0
  38. package/cli/dist/core/fleet/parse.js +144 -0
  39. package/cli/dist/core/{settings.js → fleet/settings.js} +47 -15
  40. package/cli/dist/core/{validate.js → fleet/shape.js} +6 -20
  41. package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
  42. package/cli/dist/core/interpreter/io.js +18 -0
  43. package/cli/dist/core/interpreter/loop.js +101 -0
  44. package/cli/dist/core/interpreter/needs.js +47 -0
  45. package/cli/dist/core/interpreter/process.js +107 -0
  46. package/cli/dist/core/interpreter/progress.js +15 -0
  47. package/cli/dist/core/interpreter/pty.js +8 -0
  48. package/cli/dist/core/operations/catalog.js +35 -18
  49. package/cli/dist/core/operations/{run.js → dispatch.js} +50 -47
  50. package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
  51. package/cli/dist/core/plan/model.js +14 -0
  52. package/cli/dist/core/recipes/app-check.js +27 -0
  53. package/cli/dist/core/recipes/apps.js +63 -0
  54. package/cli/dist/core/recipes/backup.js +34 -0
  55. package/cli/dist/core/recipes/certs.js +4 -0
  56. package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
  57. package/cli/dist/core/recipes/host.js +104 -0
  58. package/cli/dist/core/recipes/ssh.js +20 -0
  59. package/cli/dist/core/recipes/steps.js +82 -0
  60. package/cli/dist/core/status/look.js +55 -0
  61. package/cli/dist/core/status/model.js +6 -0
  62. package/cli/dist/core/status/ports.js +1 -0
  63. package/cli/dist/core/text/plural.js +2 -0
  64. package/cli/dist/core/text/spans.js +22 -0
  65. package/cli/dist/core/text/time.js +12 -0
  66. package/cli/dist/core/validation/facts.js +50 -0
  67. package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
  68. package/cli/dist/deployer/app.js +3 -2
  69. package/cli/dist/deployer/brand.js +1 -1
  70. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  71. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  72. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  73. package/cli/dist/deployer/cron.js +3 -3
  74. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  75. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  76. package/cli/dist/deployer/deployer.js +24 -23
  77. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  78. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  79. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  80. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  81. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  82. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  83. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  84. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  85. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  86. package/cli/dist/deployer/main.js +2 -2
  87. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  88. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  89. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  90. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  91. package/cli/dist/lib/brand.js +2 -0
  92. package/cli/dist/lib/closest.js +17 -0
  93. package/cli/dist/lib/result.js +15 -0
  94. package/cli/dist/lib/schema.js +7 -0
  95. package/cli/dist/lib/typed.js +2 -0
  96. package/cli/dist/lib/yaml.js +21 -0
  97. package/cli/dist/main.js +89 -89
  98. package/cli/dist/serve.js +2 -2
  99. package/package.json +3 -2
  100. package/schema/app.json +4 -2
  101. package/schema/server.json +10 -5
  102. package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
  103. package/cli/dist/core/brand.js +0 -39
  104. package/cli/dist/core/commands/app-check.js +0 -35
  105. package/cli/dist/core/commands/server.js +0 -298
  106. package/cli/dist/core/commands/status.js +0 -194
  107. package/cli/dist/core/fleet.js +0 -156
  108. package/cli/dist/core/gather.js +0 -61
  109. package/cli/dist/core/interpret.js +0 -276
  110. package/cli/dist/core/load.js +0 -64
  111. package/cli/dist/core/present/line.js +0 -17
  112. package/cli/dist/result.js +0 -5
  113. /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
@@ -1,35 +0,0 @@
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
- });
15
- /**
16
- * In an app's own repository, before a push: what the platform checks when it
17
- * deploys the app — app.yml against its schema here, then app-check.sh (the
18
- * image plan and the compose policy, the same scripts the builder and the
19
- * deployer run). Needs no fleet and no server.
20
- */
21
- export const appCheck = (kayra, root, manifest) => {
22
- if (manifest === undefined)
23
- return err(`no app.yml in ${root}`);
24
- const shaped = flatMap(flatMap(mapError(yamlOf(manifest), (problem) => `app.yml ${problem}`), (values) => checkShape("app.yml", values, appManifestSchema)), (values) => {
25
- const parsed = appManifestSchema.safeParse(values);
26
- return parsed.success ? appName(parsed.data.name) : err("app.yml: invalid");
27
- });
28
- return map(shaped, () => [
29
- tool("git", "brew install git"),
30
- tool("jq", "brew install jq"),
31
- tool("yq", "brew install yq"),
32
- tool("docker", "the docker CLI with Compose; no daemon is needed"),
33
- run("Image plan and compose policy", ["bash", within(kayra, "scripts", "local", "app-check.sh"), root]),
34
- ]);
35
- };
@@ -1,298 +0,0 @@
1
- import { within, } from "../brand.js";
2
- import { partOf, run } from "../plan.js";
3
- import { all, err, map, ok } from "../../result.js";
4
- /** The local scripts that read the fleet's files find them here, not beside themselves. */
5
- const fleetEnv = ({ fleet }) => ({ FLEET_ROOT: fleet });
6
- const script = ({ kayra }, name) => within(kayra, "scripts", "local", name);
7
- const ansiblePath = ({ kayra }, ...segments) => within(kayra, "ansible", ...segments);
8
- const inventory = (server) => within(server.dir, "inventory.ini");
9
- const terraform = (server) => `-chdir=${within(server.dir, "terraform")}`;
10
- /**
11
- * How Ansible gets the vault password: from the server's password file, or
12
- * from kayra, which asks the operator once per run (Need "vault").
13
- */
14
- const vault = (server) => {
15
- switch (server.vault.kind) {
16
- case "file":
17
- return { env: { ANSIBLE_VAULT_PASSWORD_FILE: server.vault.file }, needs: [] };
18
- case "ask":
19
- return { env: {}, needs: [{ kind: "vault", server: server.name }] };
20
- case "none":
21
- return { env: {}, needs: [] };
22
- }
23
- };
24
- const needing = (step, needs) => ({ ...step, needs });
25
- /** The vault's environment, and its need where kayra must ask for the password. */
26
- const vaulted = (step, server) => {
27
- const { env, needs } = vault(server);
28
- return { ...step, env: { ...env, ...step.env }, ...(needs.length === 0 ? {} : { needs }) };
29
- };
30
- const ansibleEnv = (engine, env) => ({ ...env, ANSIBLE_CONFIG: ansiblePath(engine, "ansible.cfg") });
31
- /** --verbose: every playbook prints Ansible's own output, with -v, instead of kayra's summary of it (ansible.cfg's stdout_callback). */
32
- export const verbose = (plan) => plan.map((step) => step.kind === "run" && step.argv[0] === "ansible-playbook"
33
- ? { ...step, argv: ["ansible-playbook", "-v", ...step.argv.slice(1)], env: { ...step.env, ANSIBLE_STDOUT_CALLBACK: "default" } }
34
- : step);
35
- /** Real servers change only from main as merged; a multipass one from anything. */
36
- const fromMain = (engine, server) => ({
37
- kind: "check",
38
- label: `${server.name} may be changed from this checkout`,
39
- probe: { kind: "exits-zero", argv: ["bash", script(engine, "require-main.sh"), server.name], env: fleetEnv(engine) },
40
- onFailure: "stop",
41
- });
42
- /** OpenTofu only on the newest committed state: none waiting on an unmerged branch. */
43
- const latestState = (engine, server) => ({
44
- kind: "check",
45
- label: `${server.name}'s OpenTofu state is the newest`,
46
- probe: { kind: "exits-zero", argv: ["bash", script(engine, "require-latest-state.sh"), within(server.dir, "terraform")] },
47
- onFailure: "stop",
48
- });
49
- /** Before Ansible's UNREACHABLE: why a home machine cannot be reached. */
50
- const reachable = (engine, server) => server.target === "home"
51
- ? [
52
- {
53
- kind: "check",
54
- label: `${server.name} answers over SSH`,
55
- probe: {
56
- kind: "exits-zero",
57
- argv: ["bash", script(engine, "home-reach.sh"), server.name, server.kind],
58
- env: fleetEnv(engine),
59
- },
60
- onFailure: "stop",
61
- },
62
- ]
63
- : [];
64
- /** The pinned Ansible collections; a no-op once installed. */
65
- const collections = (engine, env) => ({
66
- kind: "run",
67
- title: "Ansible collections",
68
- argv: ["ansible-galaxy", "collection", "install", "-r", ansiblePath(engine, "requirements.yml")],
69
- env,
70
- stdout: "discard",
71
- });
72
- const appSubdomains = (engine, server) => ({
73
- kind: "query",
74
- argv: ["bash", script(engine, "app-manifests.sh"), "--subdomains", server.name],
75
- words: "many",
76
- env: fleetEnv(engine),
77
- });
78
- const certs = (engine, domain, subdomains) => run("mkcert certificates", ["bash", script(engine, "certs.sh"), domain, within(engine.fleet, ".cache", "certs"), ...subdomains]);
79
- export const provision = (engine, server) => ok(partOf("provision", [
80
- fromMain(engine, server),
81
- ...(server.vm ? [run("VM image and seed ISO", ["bash", script(engine, "home-image.sh"), server.name], fleetEnv(engine))] : []),
82
- ...(server.terraform
83
- ? [
84
- latestState(engine, server),
85
- run("OpenTofu init", ["tofu", terraform(server), "init", "-input=false"]),
86
- run("OpenTofu apply", ["tofu", terraform(server), "apply", "-auto-approve"]),
87
- ]
88
- : []),
89
- ]));
90
- /** The playbook for the server's kind, as setup runs it; plan adds check mode. */
91
- const hostPlaybook = (engine, server, extra = []) => vaulted(run(`Host layer · ${server.kind}.yml${extra.includes("--check") ? ", check mode" : ""}`, [
92
- "ansible-playbook",
93
- "-i",
94
- inventory(server),
95
- ansiblePath(engine, "playbooks", `${server.kind}.yml`),
96
- "-e",
97
- `server=${server.name}`,
98
- "-e",
99
- `server_dir=${server.dir}`,
100
- "-e",
101
- `domain=${server.domain}`,
102
- "-e",
103
- `target=${server.target}`,
104
- ...extra,
105
- ], ansibleEnv(engine, {})), server);
106
- /** The host layer: the playbook for the server's kind. */
107
- export const setup = (engine, server) => ok(partOf("setup", [
108
- fromMain(engine, server),
109
- // mkcert where Let's Encrypt cannot reach: test VMs, and home servers without DNS-01.
110
- ...(server.kind === "platform" && server.target !== "hetzner" && !server.acmeDns
111
- ? [certs(engine, server.domain, [appSubdomains(engine, server), ...server.stackHosts])]
112
- : []),
113
- ...reachable(engine, server),
114
- collections(engine, vault(server).env),
115
- hostPlaybook(engine, server),
116
- ]));
117
- /**
118
- * What provision and setup would change, changing nothing: OpenTofu's plan and
119
- * the playbook in check mode, with diffs (files holding secrets say only that
120
- * they would change). From any checkout: it previews a branch against a server.
121
- */
122
- export const preview = (engine, server) => ok([
123
- ...reachable(engine, server),
124
- ...(server.terraform
125
- ? [
126
- latestState(engine, server),
127
- run("OpenTofu init", ["tofu", terraform(server), "init", "-input=false"]),
128
- run("OpenTofu plan", ["tofu", terraform(server), "plan", "-input=false", "-lock=false"]),
129
- ]
130
- : []),
131
- collections(engine, vault(server).env),
132
- hostPlaybook(engine, server, ["--check", "--diff"]),
133
- { kind: "note", text: `kayra plan changed nothing on ${server.name}: the changed tasks above are what kayra setup would do.` },
134
- ]);
135
- /** Register every app in server.yml, then remove the rest (their data kept). */
136
- export const apps = (engine, server) => {
137
- const { env } = vault(server);
138
- const playbook = (title, name, ...extra) => vaulted(run(title, ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", name), ...extra], ansibleEnv(engine, {})), server);
139
- return ok(partOf("apps", [
140
- fromMain(engine, server),
141
- ...(server.kind === "platform"
142
- ? [
143
- ...server.apps.flatMap((app) => [
144
- collections(engine, env),
145
- playbook(`App ${app.name}`, "app.yml", "-e", `server=${server.name}`, "-e", `server_dir=${server.dir}`, "-e", `domain=${server.domain}`, "-e", `{"app": ${app.entry}}`),
146
- ]),
147
- collections(engine, env),
148
- playbook("Remove apps not in server.yml", "apps-prune.yml", "-e", `{"keep": ${JSON.stringify(server.apps.map((app) => app.name))}}`),
149
- ]
150
- : []),
151
- ]));
152
- };
153
- export const hosts = (engine, server) => ok(partOf("hosts", server.target === "multipass"
154
- ? [
155
- needing(run("/etc/hosts", [
156
- "bash",
157
- script(engine, "setup-hosts.sh"),
158
- server.domain,
159
- { kind: "query", argv: ["tofu", terraform(server), "output", "-raw", "server_ip"], words: "one" },
160
- appSubdomains(engine, server),
161
- ]), [{ kind: "sudo" }])
162
- ]
163
- : [{ kind: "note", text: `hosts: ${server.target} uses real DNS, nothing to do.` }]));
164
- const sequence = (plans) => map(all(plans), (each) => each.flat());
165
- /** Whether a platform server works as its users see it (scripts/local/verify.sh); other kinds have nothing to check yet. */
166
- const verifyStep = (engine, server) => ({
167
- ...run("Verify", ["bash", script(engine, "verify.sh"), server.name], fleetEnv(engine)),
168
- part: "verify",
169
- });
170
- export const verify = (engine, server) => server.kind === "platform"
171
- ? ok([verifyStep(engine, server)])
172
- : err(`'${server.name}' is of kind ${server.kind}: kayra verify checks platform servers only.`);
173
- /** Host setup, then the apps; a platform server is verified at the end, so a deploy that leaves it broken fails. */
174
- export const deploy = (engine, server) => map(sequence([setup(engine, server), apps(engine, server)]), (plan) => server.kind === "platform" ? [...plan, verifyStep(engine, server)] : plan);
175
- export const up = (engine, server) => sequence([provision(engine, server), deploy(engine, server), hosts(engine, server)]);
176
- export const down = (engine, server) => server.terraform
177
- ? ok([
178
- latestState(engine, server),
179
- ...(server.target === "hetzner"
180
- ? [
181
- {
182
- kind: "confirm",
183
- warning: `This destroys the Hetzner server '${server.name}' (${server.domain}) and everything on it.`,
184
- expect: server.name,
185
- },
186
- ]
187
- : []),
188
- run("OpenTofu destroy", ["tofu", terraform(server), "destroy", "-auto-approve"]),
189
- ])
190
- : err(`${server.name} has no terraform/: nothing here creates it, so nothing destroys it`);
191
- /** Once, for a server we did not create: the deploy user, added as root. */
192
- export const adopt = (engine, server) => ok([
193
- fromMain(engine, server),
194
- collections(engine, {}),
195
- run("Deploy user, added as root", ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", "adopt.yml")], ansibleEnv(engine, {})),
196
- ]);
197
- /** A removed app's volumes: its data, irreversibly. */
198
- export const appPurge = (engine, server, app) => ok([
199
- fromMain(engine, server),
200
- run(`Delete ${app}'s volumes`, [
201
- "ansible",
202
- "servers",
203
- "-i",
204
- inventory(server),
205
- "--become",
206
- "-m",
207
- "ansible.builtin.command",
208
- "-a",
209
- `/opt/platform/bin/app-purge ${app}`,
210
- ], ansibleEnv(engine, {})),
211
- ]);
212
- /**
213
- * The restic-backup role's restore test: the latest backup, restored to a scratch dir and checked.
214
- * It runs on the server, detached; kayra follows its log over SSH. Stopping kayra stops only the
215
- * following, and running it again while a test runs follows that one instead of starting another.
216
- */
217
- export const backupTest = (engine, server) => {
218
- if (server.backupDir === undefined)
219
- return err(`${server.name} has no restic_backup.dir in its vars.yml`);
220
- if (server.inventory === undefined)
221
- return err(`no inventory for '${server.name}' — provision it first.`);
222
- return ok([
223
- ...reachable(engine, server),
224
- vaulted(run("Start the restore test", [
225
- "ansible",
226
- "servers",
227
- "-i",
228
- inventory(server),
229
- "--become",
230
- "-e",
231
- `@${within(server.dir, "secrets.yml")}`,
232
- "-m",
233
- "ansible.builtin.command",
234
- "-a",
235
- `docker compose -f ${server.backupDir}/docker-compose.yml exec -d -T backup /etc/backup/restore-test.sh`,
236
- ], ansibleEnv(engine, {})), server),
237
- { kind: "note", text: "Following the restore test. Ctrl-C stops following, not the test." },
238
- run("Follow the restore test", [
239
- "ssh",
240
- "-p",
241
- server.inventory.port,
242
- "-i",
243
- server.inventory.key,
244
- "-o",
245
- "StrictHostKeyChecking=accept-new",
246
- `${server.inventory.user}@${server.inventory.host}`,
247
- "sh",
248
- `${server.backupDir}/follow-restore-test.sh`,
249
- ]),
250
- ]);
251
- };
252
- const sshTo = (server, remote) => server.inventory === undefined
253
- ? err(`no inventory for '${server.name}' — provision it first.`)
254
- : ok([
255
- "ssh",
256
- "-p",
257
- server.inventory.port,
258
- "-i",
259
- server.inventory.key,
260
- "-o",
261
- "StrictHostKeyChecking=no",
262
- "-o",
263
- "UserKnownHostsFile=/dev/null",
264
- `${server.inventory.user}@${server.inventory.host}`,
265
- ...remote,
266
- ]);
267
- /** An interactive shell, or the remote command as ssh runs it (the remote shell reads it). */
268
- export const ssh = (server, remote) => map(sshTo(server, remote), (argv) => [remote.length === 0 ? { ...run("SSH", argv), kind: "session" } : run("SSH", argv)]);
269
- /** What the deployer's ctl is asked, its title, and how its answer is shown: the lists as data kayra draws. */
270
- const ctlCall = (server, command) => {
271
- switch (command.kind) {
272
- case "job":
273
- return { title: `Job ${command.job}`, args: ["job", command.job, ...(command.noPrs ? ["--dry-run"] : [])], stdout: "show" };
274
- case "logs":
275
- return {
276
- title: `Log of ${command.app}'s ${command.more === undefined ? "newest run" : `run ${command.more}`}`,
277
- args: ["log", command.app, ...(command.more === undefined ? [] : [command.more])],
278
- stdout: { view: "log", app: command.app, server: server.name },
279
- };
280
- case "runs":
281
- return { title: `Runs of ${command.app}`, args: ["runs", command.app, "--json"], stdout: { view: "runs", app: command.app, server: server.name } };
282
- case "deploy":
283
- return { title: `Deploy ${command.app} at ${command.more ?? "its ref"}`, args: ["deploy", command.app, ...(command.more === undefined ? [] : [command.more])], stdout: "show" };
284
- case "rollback":
285
- return command.more === undefined
286
- ? { title: `Releases of ${command.app}`, args: ["rollback", command.app, "--json"], stdout: { view: "releases", app: command.app, server: server.name } }
287
- : { title: `Roll ${command.app} back to ${command.more}`, args: ["rollback", command.app, command.more], stdout: "show" };
288
- }
289
- };
290
- /** Inside the deployer container, as the deploy user (in the docker group): nothing here needs root. */
291
- export const deployer = (server, command) => {
292
- if (server.kind !== "platform")
293
- return err(`'${server.name}' is a ${server.kind} server: only platform servers run apps.`);
294
- const call = ctlCall(server, command);
295
- return map(sshTo(server, ["cd", "/opt/platform", "&&", "docker", "compose", "exec", "-T", "deployer", "kayra-deployer", "ctl", ...call.args]), (argv) => [{ ...run(call.title, argv), stdout: call.stdout }]);
296
- };
297
- /** mkcert certs for a domain and its subdomains, for local dev and multipass. */
298
- export const certsFor = (engine, domain, subdomains) => ok([certs(engine, domain, subdomains)]);
@@ -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 "../present/line.js";
5
- import { fit, table } from "../present/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
- });