@yunuseon/kayra 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { within, } from "../brand.js";
2
- import { run } from "../plan.js";
2
+ import { partOf, run } from "../plan.js";
3
3
  import { all, err, map, ok } from "../result.js";
4
4
  /** The local scripts that read the fleet's files find them here, not beside themselves. */
5
5
  const fleetEnv = ({ fleet }) => ({ FLEET_ROOT: fleet });
@@ -19,6 +19,10 @@ const vaultEnv = (server) => {
19
19
  }
20
20
  };
21
21
  const ansibleEnv = (engine, env) => ({ ...env, ANSIBLE_CONFIG: ansiblePath(engine, "ansible.cfg") });
22
+ /** --verbose: every playbook prints Ansible's own output, with -v, instead of kayra's summary of it (ansible.cfg's stdout_callback). */
23
+ export const verbose = (plan) => plan.map((step) => step.kind === "run" && step.argv[0] === "ansible-playbook"
24
+ ? { ...step, argv: ["ansible-playbook", "-v", ...step.argv.slice(1)], env: { ...step.env, ANSIBLE_STDOUT_CALLBACK: "default" } }
25
+ : step);
22
26
  /** Real servers change only from main as merged; a multipass one from anything. */
23
27
  const fromMain = (engine, server) => ({
24
28
  kind: "check",
@@ -51,6 +55,7 @@ const reachable = (engine, server) => server.target === "home"
51
55
  /** The pinned Ansible collections; a no-op once installed. */
52
56
  const collections = (engine, env) => ({
53
57
  kind: "run",
58
+ title: "Ansible collections",
54
59
  argv: ["ansible-galaxy", "collection", "install", "-r", ansiblePath(engine, "requirements.yml")],
55
60
  env,
56
61
  stdout: "discard",
@@ -61,20 +66,20 @@ const appSubdomains = (engine, server) => ({
61
66
  words: "many",
62
67
  env: fleetEnv(engine),
63
68
  });
64
- const certs = (engine, domain, subdomains) => run(["bash", script(engine, "certs.sh"), domain, within(engine.fleet, ".cache", "certs"), ...subdomains]);
65
- export const provision = (engine, server) => ok([
69
+ const certs = (engine, domain, subdomains) => run("mkcert certificates", ["bash", script(engine, "certs.sh"), domain, within(engine.fleet, ".cache", "certs"), ...subdomains]);
70
+ export const provision = (engine, server) => ok(partOf("provision", [
66
71
  fromMain(engine, server),
67
- ...(server.vm ? [run(["bash", script(engine, "home-image.sh"), server.name], fleetEnv(engine))] : []),
72
+ ...(server.vm ? [run("VM image and seed ISO", ["bash", script(engine, "home-image.sh"), server.name], fleetEnv(engine))] : []),
68
73
  ...(server.terraform
69
74
  ? [
70
75
  latestState(engine, server),
71
- run(["tofu", terraform(server), "init", "-input=false"]),
72
- run(["tofu", terraform(server), "apply", "-auto-approve"]),
76
+ run("OpenTofu init", ["tofu", terraform(server), "init", "-input=false"]),
77
+ run("OpenTofu apply", ["tofu", terraform(server), "apply", "-auto-approve"]),
73
78
  ]
74
79
  : []),
75
- ]);
80
+ ]));
76
81
  /** The playbook for the server's kind, as setup runs it; plan adds check mode. */
77
- const hostPlaybook = (engine, server, extra = []) => run([
82
+ const hostPlaybook = (engine, server, extra = []) => run(`Host layer · ${server.kind}.yml${extra.includes("--check") ? ", check mode" : ""}`, [
78
83
  "ansible-playbook",
79
84
  "-i",
80
85
  inventory(server),
@@ -90,7 +95,7 @@ const hostPlaybook = (engine, server, extra = []) => run([
90
95
  ...extra,
91
96
  ], ansibleEnv(engine, vaultEnv(server)));
92
97
  /** The host layer: the playbook for the server's kind. */
93
- export const setup = (engine, server) => ok([
98
+ export const setup = (engine, server) => ok(partOf("setup", [
94
99
  fromMain(engine, server),
95
100
  // mkcert where Let's Encrypt cannot reach: test VMs, and home servers without DNS-01.
96
101
  ...(server.kind === "platform" && server.target !== "hetzner" && !server.acmeDns
@@ -99,7 +104,7 @@ export const setup = (engine, server) => ok([
99
104
  ...reachable(engine, server),
100
105
  collections(engine, vaultEnv(server)),
101
106
  hostPlaybook(engine, server),
102
- ]);
107
+ ]));
103
108
  /**
104
109
  * What provision and setup would change, changing nothing: OpenTofu's plan and
105
110
  * the playbook in check mode, with diffs (files holding secrets say only that
@@ -110,8 +115,8 @@ export const preview = (engine, server) => ok([
110
115
  ...(server.terraform
111
116
  ? [
112
117
  latestState(engine, server),
113
- run(["tofu", terraform(server), "init", "-input=false"]),
114
- run(["tofu", terraform(server), "plan", "-input=false", "-lock=false"]),
118
+ run("OpenTofu init", ["tofu", terraform(server), "init", "-input=false"]),
119
+ run("OpenTofu plan", ["tofu", terraform(server), "plan", "-input=false", "-lock=false"]),
115
120
  ]
116
121
  : []),
117
122
  collections(engine, vaultEnv(server)),
@@ -121,24 +126,24 @@ export const preview = (engine, server) => ok([
121
126
  /** Register every app in server.yml, then remove the rest (their data kept). */
122
127
  export const apps = (engine, server) => {
123
128
  const env = vaultEnv(server);
124
- const playbook = (name, ...extra) => run(["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", name), ...extra], ansibleEnv(engine, env));
125
- return ok([
129
+ const playbook = (title, name, ...extra) => run(title, ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", name), ...extra], ansibleEnv(engine, env));
130
+ return ok(partOf("apps", [
126
131
  fromMain(engine, server),
127
132
  ...(server.kind === "platform"
128
133
  ? [
129
134
  ...server.apps.flatMap((app) => [
130
135
  collections(engine, env),
131
- playbook("app.yml", "-e", `server=${server.name}`, "-e", `server_dir=${server.dir}`, "-e", `domain=${server.domain}`, "-e", `{"app": ${app.entry}}`),
136
+ playbook(`App ${app.name}`, "app.yml", "-e", `server=${server.name}`, "-e", `server_dir=${server.dir}`, "-e", `domain=${server.domain}`, "-e", `{"app": ${app.entry}}`),
132
137
  ]),
133
138
  collections(engine, env),
134
- playbook("apps-prune.yml", "-e", `{"keep": ${JSON.stringify(server.apps.map((app) => app.name))}}`),
139
+ playbook("Remove apps not in server.yml", "apps-prune.yml", "-e", `{"keep": ${JSON.stringify(server.apps.map((app) => app.name))}}`),
135
140
  ]
136
141
  : []),
137
- ]);
142
+ ]));
138
143
  };
139
- export const hosts = (engine, server) => ok(server.target === "multipass"
144
+ export const hosts = (engine, server) => ok(partOf("hosts", server.target === "multipass"
140
145
  ? [
141
- run([
146
+ run("/etc/hosts", [
142
147
  "bash",
143
148
  script(engine, "setup-hosts.sh"),
144
149
  server.domain,
@@ -146,10 +151,13 @@ export const hosts = (engine, server) => ok(server.target === "multipass"
146
151
  appSubdomains(engine, server),
147
152
  ]),
148
153
  ]
149
- : [{ kind: "note", text: `hosts: ${server.target} uses real DNS, nothing to do.` }]);
154
+ : [{ kind: "note", text: `hosts: ${server.target} uses real DNS, nothing to do.` }]));
150
155
  const sequence = (plans) => map(all(plans), (each) => each.flat());
151
156
  /** Whether a platform server works as its users see it (scripts/local/verify.sh); other kinds have nothing to check yet. */
152
- const verifyStep = (engine, server) => run(["bash", script(engine, "verify.sh"), server.name], fleetEnv(engine));
157
+ const verifyStep = (engine, server) => ({
158
+ ...run("Verify", ["bash", script(engine, "verify.sh"), server.name], fleetEnv(engine)),
159
+ part: "verify",
160
+ });
153
161
  export const verify = (engine, server) => server.kind === "platform"
154
162
  ? ok([verifyStep(engine, server)])
155
163
  : err(`'${server.name}' is of kind ${server.kind}: kayra verify checks platform servers only.`);
@@ -163,24 +171,24 @@ export const down = (engine, server) => server.terraform
163
171
  ? [
164
172
  {
165
173
  kind: "confirm",
166
- prompt: `This destroys the Hetzner server '${server.name}' (${server.domain}). Type the name to confirm: `,
174
+ warning: `This destroys the Hetzner server '${server.name}' (${server.domain}) and everything on it.`,
167
175
  expect: server.name,
168
176
  },
169
177
  ]
170
178
  : []),
171
- run(["tofu", terraform(server), "destroy", "-auto-approve"]),
179
+ run("OpenTofu destroy", ["tofu", terraform(server), "destroy", "-auto-approve"]),
172
180
  ])
173
181
  : err(`${server.name} has no terraform/: nothing here creates it, so nothing destroys it`);
174
182
  /** Once, for a server we did not create: the deploy user, added as root. */
175
183
  export const adopt = (engine, server) => ok([
176
184
  fromMain(engine, server),
177
185
  collections(engine, {}),
178
- run(["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", "adopt.yml")], ansibleEnv(engine, {})),
186
+ run("Deploy user, added as root", ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", "adopt.yml")], ansibleEnv(engine, {})),
179
187
  ]);
180
188
  /** A removed app's volumes: its data, irreversibly. */
181
189
  export const appPurge = (engine, server, app) => ok([
182
190
  fromMain(engine, server),
183
- run([
191
+ run(`Delete ${app}'s volumes`, [
184
192
  "ansible",
185
193
  "servers",
186
194
  "-i",
@@ -204,7 +212,7 @@ export const backupTest = (engine, server) => {
204
212
  return err(`no inventory for '${server.name}' — provision it first.`);
205
213
  return ok([
206
214
  ...reachable(engine, server),
207
- run([
215
+ run("Start the restore test", [
208
216
  "ansible",
209
217
  "servers",
210
218
  "-i",
@@ -218,7 +226,7 @@ export const backupTest = (engine, server) => {
218
226
  `docker compose -f ${server.backupDir}/docker-compose.yml exec -d -T backup /etc/backup/restore-test.sh`,
219
227
  ], ansibleEnv(engine, vaultEnv(server))),
220
228
  { kind: "note", text: "Following the restore test. Ctrl-C stops following, not the test." },
221
- run([
229
+ run("Follow the restore test", [
222
230
  "ssh",
223
231
  "-p",
224
232
  server.inventory.port,
@@ -232,39 +240,50 @@ export const backupTest = (engine, server) => {
232
240
  ]),
233
241
  ]);
234
242
  };
235
- /** An interactive shell, or the remote command as ssh runs it (the remote shell reads it). */
236
- export const ssh = (server, remote) => server.inventory === undefined
243
+ const sshTo = (server, remote) => server.inventory === undefined
237
244
  ? err(`no inventory for '${server.name}' — provision it first.`)
238
245
  : ok([
239
- run([
240
- "ssh",
241
- "-p",
242
- server.inventory.port,
243
- "-i",
244
- server.inventory.key,
245
- "-o",
246
- "StrictHostKeyChecking=no",
247
- "-o",
248
- "UserKnownHostsFile=/dev/null",
249
- `${server.inventory.user}@${server.inventory.host}`,
250
- ...remote,
251
- ]),
246
+ "ssh",
247
+ "-p",
248
+ server.inventory.port,
249
+ "-i",
250
+ server.inventory.key,
251
+ "-o",
252
+ "StrictHostKeyChecking=no",
253
+ "-o",
254
+ "UserKnownHostsFile=/dev/null",
255
+ `${server.inventory.user}@${server.inventory.host}`,
256
+ ...remote,
252
257
  ]);
253
- const ctlArgs = (command) => {
258
+ /** An interactive shell, or the remote command as ssh runs it (the remote shell reads it). */
259
+ export const ssh = (server, remote) => map(sshTo(server, remote), (argv) => [run("SSH", argv)]);
260
+ /** What the deployer's ctl is asked, its title, and how its answer is shown: the lists as data kayra draws. */
261
+ const ctlCall = (server, command) => {
254
262
  switch (command.kind) {
255
263
  case "job":
256
- return ["job", command.job, ...(command.noPrs ? ["--dry-run"] : [])];
264
+ return { title: `Job ${command.job}`, args: ["job", command.job, ...(command.noPrs ? ["--dry-run"] : [])], stdout: "show" };
257
265
  case "logs":
258
- return ["log", command.app, ...(command.more === undefined ? [] : [command.more])];
266
+ return {
267
+ title: `Log of ${command.app}'s ${command.more === undefined ? "newest run" : `run ${command.more}`}`,
268
+ args: ["log", command.app, ...(command.more === undefined ? [] : [command.more])],
269
+ stdout: { view: "log", app: command.app, server: server.name },
270
+ };
259
271
  case "runs":
272
+ return { title: `Runs of ${command.app}`, args: ["runs", command.app, "--json"], stdout: { view: "runs", app: command.app, server: server.name } };
260
273
  case "deploy":
274
+ return { title: `Deploy ${command.app} at ${command.more ?? "its ref"}`, args: ["deploy", command.app, ...(command.more === undefined ? [] : [command.more])], stdout: "show" };
261
275
  case "rollback":
262
- return [command.kind, command.app, ...(command.more === undefined ? [] : [command.more])];
276
+ return command.more === undefined
277
+ ? { title: `Releases of ${command.app}`, args: ["rollback", command.app, "--json"], stdout: { view: "releases", app: command.app, server: server.name } }
278
+ : { title: `Roll ${command.app} back to ${command.more}`, args: ["rollback", command.app, command.more], stdout: "show" };
263
279
  }
264
280
  };
265
281
  /** Inside the deployer container, as the deploy user (in the docker group): nothing here needs root. */
266
- export const deployer = (server, command) => server.kind === "platform"
267
- ? ssh(server, ["cd", "/opt/platform", "&&", "docker", "compose", "exec", "-T", "deployer", "kayra-deployer", "ctl", ...ctlArgs(command)])
268
- : err(`'${server.name}' is a ${server.kind} server: only platform servers run apps.`);
282
+ export const deployer = (server, command) => {
283
+ if (server.kind !== "platform")
284
+ return err(`'${server.name}' is a ${server.kind} server: only platform servers run apps.`);
285
+ const call = ctlCall(server, command);
286
+ 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 }]);
287
+ };
269
288
  /** mkcert certs for a domain and its subdomains, for local dev and multipass. */
270
289
  export const certsFor = (engine, domain, subdomains) => ok([certs(engine, domain, subdomains)]);
@@ -1,22 +1,22 @@
1
1
  import { within } from "../brand.js";
2
2
  import { capture } from "../interpret.js";
3
- const describe = (machine) => {
4
- switch (machine.kind) {
5
- case "none":
6
- return "not provisioned";
7
- case "provisioned":
8
- return `provisioned (${machine.ip ?? "?"})`;
9
- case "unreadable":
10
- return `state unreadable: ${machine.reason}`;
11
- }
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 };
12
19
  };
13
- export const statusLine = (server, machine) => [
14
- server.name.padEnd(10),
15
- `kind=${server.kind.padEnd(9)} target=${server.target.padEnd(10)}`,
16
- `domain=${server.domain.padEnd(24)}`,
17
- `apps=${server.apps.map((app) => app.name).join(",").padEnd(10)}`,
18
- describe(machine),
19
- ].join(" ");
20
20
  /** Why tofu could not read the state, in a few words: the first line of its error. */
21
21
  export const unreadable = (stderr) => {
22
22
  if (stderr.includes("tofu init"))
@@ -27,17 +27,168 @@ export const unreadable = (stderr) => {
27
27
  .find((each) => each !== "");
28
28
  return line ?? "tofu failed";
29
29
  };
30
- const machine = async (server) => {
31
- if (!server.terraform)
32
- return { kind: "none" };
33
- const chdir = `-chdir=${within(server.dir, "terraform")}`;
34
- const state = await capture(["tofu", chdir, "state", "list", "-no-color"], "capture");
35
- if (state.code !== 0)
36
- return { kind: "unreadable", reason: unreadable(state.stderr) };
37
- if (state.stdout.trim() === "")
38
- return { kind: "none" };
39
- const ip = await capture(["tofu", chdir, "output", "-raw", "server_ip"], "capture");
40
- return { kind: "provisioned", ip: ip.code === 0 ? ip.stdout.replace(/\n+$/, "") : undefined };
41
- };
42
- /** Every server and whether a machine exists for it. Reads state, changes nothing. */
43
- export const status = async (fleet) => Promise.all(fleet.servers.map(async (server) => statusLine(server, await machine(server))));
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
+ });