@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.
- package/ansible/ansible.cfg +6 -3
- package/ansible/callback_plugins/kayra.py +299 -0
- package/cli/dist/cli.js +156 -30
- package/cli/dist/commands/app-check.js +1 -1
- package/cli/dist/commands/server.js +68 -49
- package/cli/dist/commands/status.js +181 -30
- package/cli/dist/commands/validate.js +92 -31
- package/cli/dist/deployer/answers.js +21 -0
- package/cli/dist/deployer/ctl.js +20 -6
- package/cli/dist/gather.js +9 -5
- package/cli/dist/interpret.js +71 -50
- package/cli/dist/main.js +85 -25
- package/cli/dist/net.js +52 -0
- package/cli/dist/plan.js +35 -4
- package/cli/dist/ui/explain.js +37 -0
- package/cli/dist/ui/line.js +39 -0
- package/cli/dist/ui/progress.js +100 -0
- package/cli/dist/ui/terminal.js +93 -0
- package/cli/dist/ui/text.js +71 -0
- package/cli/dist/ui/views.js +127 -0
- package/cli/dist/validate.js +8 -3
- package/package.json +1 -1
- package/scripts/local/verify.sh +2 -2
package/cli/dist/net.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Agent, request } from "node:https";
|
|
2
|
+
import { connect } from "node:net";
|
|
3
|
+
import { getCACertificates } from "node:tls";
|
|
4
|
+
import { failure } from "./commands/status.js";
|
|
5
|
+
const codeOf = (error) => typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "ERROR";
|
|
6
|
+
const since = (started) => Math.round(performance.now() - started);
|
|
7
|
+
/** The network, as status asks it: a TCP connect, an HTTPS GET, each given up after `ms`; every answer a Reach, never an exception. */
|
|
8
|
+
export const network = (ms) => {
|
|
9
|
+
// A multipass server's certificates are mkcert's, whose root is in the system's store, not Node's.
|
|
10
|
+
// Reading it takes a while: after the first frame, not before.
|
|
11
|
+
const agent = new Promise((resolve) => {
|
|
12
|
+
setImmediate(() => {
|
|
13
|
+
resolve(new Agent({ ca: [...new Set([...getCACertificates("default"), ...getCACertificates("system")])] }));
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
return {
|
|
17
|
+
connect: (host, port) => new Promise((resolve) => {
|
|
18
|
+
const started = performance.now();
|
|
19
|
+
const socket = connect({ host, port, timeout: ms });
|
|
20
|
+
socket.once("connect", () => {
|
|
21
|
+
socket.destroy();
|
|
22
|
+
resolve({ kind: "open", ms: since(started) });
|
|
23
|
+
});
|
|
24
|
+
socket.once("timeout", () => {
|
|
25
|
+
socket.destroy();
|
|
26
|
+
resolve({ kind: "no-answer" });
|
|
27
|
+
});
|
|
28
|
+
socket.once("error", (error) => {
|
|
29
|
+
resolve(failure(codeOf(error)));
|
|
30
|
+
});
|
|
31
|
+
}),
|
|
32
|
+
get: async (url) => {
|
|
33
|
+
const via = await agent;
|
|
34
|
+
return new Promise((resolve) => {
|
|
35
|
+
const started = performance.now();
|
|
36
|
+
const asked = request(url, { agent: via, timeout: ms }, (response) => {
|
|
37
|
+
response.resume();
|
|
38
|
+
resolve({ kind: "answered", status: response.statusCode ?? 0, ms: since(started) });
|
|
39
|
+
asked.destroy();
|
|
40
|
+
});
|
|
41
|
+
asked.once("timeout", () => {
|
|
42
|
+
asked.destroy();
|
|
43
|
+
resolve({ kind: "no-answer" });
|
|
44
|
+
});
|
|
45
|
+
asked.once("error", (error) => {
|
|
46
|
+
resolve(failure(codeOf(error)));
|
|
47
|
+
});
|
|
48
|
+
asked.end();
|
|
49
|
+
});
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
};
|
package/cli/dist/plan.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
export const run = (argv, env = {}) => ({
|
|
1
|
+
export const run = (title, argv, env = {}) => ({
|
|
2
2
|
kind: "run",
|
|
3
|
+
title,
|
|
3
4
|
argv,
|
|
4
5
|
env,
|
|
5
6
|
stdout: "show",
|
|
@@ -16,16 +17,46 @@ const arg = (value) => {
|
|
|
16
17
|
return value.words === "one" ? `"${command}"` : command;
|
|
17
18
|
};
|
|
18
19
|
const describeProbe = (probe) => probe.kind === "on-path" ? `command -v ${quote(probe.program)}` : assignments(probe.env) + shell(probe.argv);
|
|
20
|
+
/** Every step of a plan as part of one kayra command. */
|
|
21
|
+
export const partOf = (part, plan) => plan.map((step) => ({ ...step, part }));
|
|
22
|
+
/** guard, check, run, confirm or note: what kind of step it is, as --dry-run says. */
|
|
23
|
+
export const kindOf = (step) => (step.kind === "check" ? (step.onFailure === "stop" ? "guard" : "check") : step.kind);
|
|
24
|
+
/** What it is called while it runs; a confirmation and a note say what they say. */
|
|
25
|
+
export const titleOf = (step) => {
|
|
26
|
+
switch (step.kind) {
|
|
27
|
+
case "run":
|
|
28
|
+
return step.title;
|
|
29
|
+
case "check":
|
|
30
|
+
return step.label;
|
|
31
|
+
case "confirm":
|
|
32
|
+
return step.warning;
|
|
33
|
+
case "note":
|
|
34
|
+
return step.text;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** The shell command a step runs, or undefined if it runs none. */
|
|
38
|
+
export const commandOf = (step) => {
|
|
39
|
+
switch (step.kind) {
|
|
40
|
+
case "run":
|
|
41
|
+
return `${assignments(step.env)}${step.argv.map(arg).join(" ")}${step.stdout === "discard" ? " >/dev/null" : ""}`;
|
|
42
|
+
case "check":
|
|
43
|
+
return describeProbe(step.probe);
|
|
44
|
+
case "confirm":
|
|
45
|
+
case "note":
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
19
49
|
const describe = (step) => {
|
|
20
50
|
switch (step.kind) {
|
|
21
51
|
case "run":
|
|
22
|
-
return `run ${
|
|
52
|
+
return `run ${commandOf(step) ?? ""}`;
|
|
23
53
|
case "check":
|
|
24
|
-
return `${step.
|
|
54
|
+
return `${kindOf(step).padEnd(8)} ${step.label}: ${commandOf(step) ?? ""}`;
|
|
25
55
|
case "confirm":
|
|
26
|
-
return `confirm ${step.
|
|
56
|
+
return `confirm ${step.warning} (${step.expect})`;
|
|
27
57
|
case "note":
|
|
28
58
|
return `note ${step.text}`;
|
|
29
59
|
}
|
|
30
60
|
};
|
|
61
|
+
/** The plan as plain lines: --dry-run's output where it is read by a program. */
|
|
31
62
|
export const render = (plan) => plan.map(describe);
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { commandOf, kindOf, titleOf } from "../plan.js";
|
|
2
|
+
import { accent, active, bad, muted, strong, warn } from "./line.js";
|
|
3
|
+
import { position, steps as count } from "./progress.js";
|
|
4
|
+
import { wrap } from "./text.js";
|
|
5
|
+
import { drawnAs } from "./views.js";
|
|
6
|
+
const kinds = { guard: warn, check: active, run: active, confirm: bad, note: muted };
|
|
7
|
+
const tag = (step) => {
|
|
8
|
+
const kind = kindOf(step);
|
|
9
|
+
return (kinds[kind] ?? muted)(kind.padEnd(7));
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* --dry-run on a terminal: each step numbered, with its title and, below it, the
|
|
13
|
+
* command it runs. `short` names paths by their root (<kayra>, <fleet>, ~), so a
|
|
14
|
+
* command fits on a line or two; render() is the plain, copyable form.
|
|
15
|
+
*/
|
|
16
|
+
export const explain = (invocation, plan, short, columns) => {
|
|
17
|
+
const digits = String(plan.length).length;
|
|
18
|
+
const indent = " ".repeat(digits + 13);
|
|
19
|
+
const steps = plan.flatMap((step, index) => {
|
|
20
|
+
const { opens } = position(plan, index);
|
|
21
|
+
const command = commandOf(step);
|
|
22
|
+
return [
|
|
23
|
+
...(opens === undefined ? [] : index === 0 ? [[accent(opens)]] : [[], [accent(opens)]]),
|
|
24
|
+
[" ", muted(String(index + 1).padStart(digits)), " ", tag(step), " ", strong(titleOf(step))],
|
|
25
|
+
...(step.kind === "confirm" ? [[indent, muted(`asks for '${step.expect}' to be typed, or stops`)]] : []),
|
|
26
|
+
...(command === undefined
|
|
27
|
+
? []
|
|
28
|
+
: wrap(short(command).split(" "), Math.max(40, Math.min(columns, 120) - indent.length - 2)).map((line, at) => [indent, muted(at === 0 ? line : ` ${line}`)])),
|
|
29
|
+
...(step.kind === "run" && typeof step.stdout === "object" ? [[indent, muted(`→ ${drawnAs(step.stdout)}`)]] : []),
|
|
30
|
+
];
|
|
31
|
+
});
|
|
32
|
+
return [
|
|
33
|
+
[strong(invocation.command), muted([...invocation.about, count(plan), "dry run: nothing runs"].map((each) => ` · ${each}`).join(""))],
|
|
34
|
+
[],
|
|
35
|
+
...steps,
|
|
36
|
+
];
|
|
37
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
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("");
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { 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
|
+
};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** Optique's rule too, so help and kayra agree: a nonempty FORCE_COLOR, else no NO_COLOR, then a terminal. */
|
|
2
|
+
export const colors = (tty, env) => {
|
|
3
|
+
if ((env["FORCE_COLOR"] ?? "") !== "")
|
|
4
|
+
return true;
|
|
5
|
+
if ((env["NO_COLOR"] ?? "") !== "" || env["NODE_DISABLE_COLORS"] !== undefined)
|
|
6
|
+
return false;
|
|
7
|
+
return tty && env["TERM"] !== "dumb";
|
|
8
|
+
};
|
|
9
|
+
// OSC 9 is a notification in these, and OSC 9;4 a progress bar in some; elsewhere either may print as text.
|
|
10
|
+
const notifying = ["iTerm.app", "WezTerm", "ghostty"];
|
|
11
|
+
const showingProgress = ["WezTerm", "ghostty"];
|
|
12
|
+
const linking = ["iTerm.app", "WezTerm", "ghostty", "vscode"];
|
|
13
|
+
export const screen = (stream, env) => {
|
|
14
|
+
const tty = stream.isTTY === true;
|
|
15
|
+
const live = tty && env["TERM"] !== "dumb" && (env["CI"] ?? "") === "";
|
|
16
|
+
const program = env["TERM_PROGRAM"] ?? "";
|
|
17
|
+
// tmux and screen swallow what they do not know, or pass it to the wrong pane.
|
|
18
|
+
const direct = live && env["TMUX"] === undefined && env["STY"] === undefined;
|
|
19
|
+
return {
|
|
20
|
+
colors: colors(tty, env),
|
|
21
|
+
live,
|
|
22
|
+
// A pseudo-terminal may report 0.
|
|
23
|
+
columns: stream.columns !== undefined && stream.columns > 0 ? stream.columns : Number(env["COLUMNS"]) || 80,
|
|
24
|
+
title: live,
|
|
25
|
+
notifications: direct && notifying.includes(program),
|
|
26
|
+
progressBar: direct && (showingProgress.includes(program) || env["WT_SESSION"] !== undefined),
|
|
27
|
+
links: direct && linking.includes(program),
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
const printable = (text) => text.replace(/\p{Cc}/gu, " ");
|
|
31
|
+
const osc = (body) => `\u001b]${body}\u0007`;
|
|
32
|
+
export const escapes = {
|
|
33
|
+
clearLine: "\r\u001b[2K",
|
|
34
|
+
/** xterm's title stack: the shell's title comes back when kayra is done. */
|
|
35
|
+
pushTitle: "\u001b[22;0t",
|
|
36
|
+
popTitle: "\u001b[23;0t",
|
|
37
|
+
title: (text) => osc(`0;${printable(text)}`),
|
|
38
|
+
notify: (text) => osc(`9;${printable(text)}`),
|
|
39
|
+
progress: (percent) => osc(`9;4;1;${String(Math.round(percent))}`),
|
|
40
|
+
progressDone: osc("9;4;0;0"),
|
|
41
|
+
link: (text, href) => `${osc(`8;;${printable(href)}`)}${text}${osc("8;;")}`,
|
|
42
|
+
/** To the start of the line `count` lines up; nothing for none, since CSI 0 F still moves one. */
|
|
43
|
+
up: (count) => (count > 0 ? `\u001b[${String(count)}F` : ""),
|
|
44
|
+
clearDown: "\u001b[J",
|
|
45
|
+
};
|
|
46
|
+
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
47
|
+
const frameOf = (ms) => frames[Math.floor(ms / 80) % frames.length] ?? "";
|
|
48
|
+
/** Draws a line in place, again every frame, until stopped; stopping clears it. */
|
|
49
|
+
export const spinner = (write, draw) => {
|
|
50
|
+
const started = performance.now();
|
|
51
|
+
const frame = () => {
|
|
52
|
+
const ms = performance.now() - started;
|
|
53
|
+
write(`${escapes.clearLine}${draw(frameOf(ms), ms)}`);
|
|
54
|
+
};
|
|
55
|
+
frame();
|
|
56
|
+
const timer = setInterval(frame, 80);
|
|
57
|
+
return () => {
|
|
58
|
+
clearInterval(timer);
|
|
59
|
+
write(escapes.clearLine);
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
const tick = (ms) => new Promise((resolve) => {
|
|
63
|
+
setTimeout(() => {
|
|
64
|
+
resolve(undefined);
|
|
65
|
+
}, ms);
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* Draws a block of lines in place, again every frame and as each update lands,
|
|
69
|
+
* until all have; then clears it and returns the state they made. Each line
|
|
70
|
+
* must fit the terminal: one that wraps throws the redraw off.
|
|
71
|
+
*/
|
|
72
|
+
export const watch = async (write, initial, updates, draw) => {
|
|
73
|
+
const started = performance.now();
|
|
74
|
+
const redraw = (state, drawn) => {
|
|
75
|
+
const lines = draw(state, frameOf(performance.now() - started));
|
|
76
|
+
write(`${escapes.up(drawn)}${lines.map((line) => `${escapes.clearLine}${line}\n`).join("")}${escapes.clearDown}`);
|
|
77
|
+
return lines.length;
|
|
78
|
+
};
|
|
79
|
+
const go = async (state, waiting, drawn) => {
|
|
80
|
+
const shown = redraw(state, drawn);
|
|
81
|
+
if (waiting.length === 0) {
|
|
82
|
+
write(`${escapes.up(shown)}${escapes.clearDown}`);
|
|
83
|
+
return state;
|
|
84
|
+
}
|
|
85
|
+
const next = await Promise.race([...waiting.map((each) => each.landed), tick(80)]);
|
|
86
|
+
return next === undefined
|
|
87
|
+
? go(state, waiting, shown)
|
|
88
|
+
: go(next.update(state), waiting.filter((each) => each.id !== next.id), shown);
|
|
89
|
+
};
|
|
90
|
+
return go(initial, updates.map((update, id) => ({ id, landed: update.then((done) => ({ id, update: done })) })), 0);
|
|
91
|
+
};
|
|
92
|
+
/** What watch() returns, drawn nowhere: for a stream that is no terminal. */
|
|
93
|
+
export const settle = async (initial, updates) => (await Promise.all(updates)).reduce((state, update) => update(state), initial);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { characters, width } from "./line.js";
|
|
2
|
+
/** 0.4s, 12s, 2m03s, 1h04m: never more precise than it is worth reading. */
|
|
3
|
+
export const duration = (ms) => {
|
|
4
|
+
const seconds = Math.max(0, ms) / 1000;
|
|
5
|
+
if (seconds < 10)
|
|
6
|
+
return `${(Math.floor(seconds * 10) / 10).toFixed(1)}s`;
|
|
7
|
+
if (seconds < 60)
|
|
8
|
+
return `${String(Math.floor(seconds))}s`;
|
|
9
|
+
const minutes = Math.floor(seconds / 60);
|
|
10
|
+
if (minutes < 60)
|
|
11
|
+
return `${String(minutes)}m${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;
|
|
12
|
+
return `${String(Math.floor(minutes / 60))}h${String(minutes % 60).padStart(2, "0")}m`;
|
|
13
|
+
};
|
|
14
|
+
/** `left`, then `right` flush with the last column, at least two spaces apart. */
|
|
15
|
+
export const spread = (left, right, columns) => [
|
|
16
|
+
...left,
|
|
17
|
+
" ".repeat(Math.max(2, columns - width(left) - width(right))),
|
|
18
|
+
...right,
|
|
19
|
+
];
|
|
20
|
+
/** At most `columns` wide, cut with an ellipsis: a line redrawn in place must not wrap. */
|
|
21
|
+
export const truncate = (line, columns) => {
|
|
22
|
+
if (width(line) <= columns)
|
|
23
|
+
return line;
|
|
24
|
+
const cut = line.reduce((so, span) => {
|
|
25
|
+
const text = typeof span === "string" ? span : span.text;
|
|
26
|
+
const chars = characters(text);
|
|
27
|
+
const kept = chars.slice(0, Math.max(0, so.room)).join("");
|
|
28
|
+
const piece = typeof span === "string" ? kept : { ...span, text: kept };
|
|
29
|
+
return { kept: kept === "" ? so.kept : [...so.kept, piece], room: so.room - chars.length };
|
|
30
|
+
}, { kept: [], room: columns - 1 });
|
|
31
|
+
return [...cut.kept, "…"];
|
|
32
|
+
};
|
|
33
|
+
/** Words in lines of at most `columns`; a word longer than that gets a line of its own. */
|
|
34
|
+
export const wrap = (words, columns) => words.reduce((lines, word) => {
|
|
35
|
+
const last = lines.at(-1);
|
|
36
|
+
if (last === undefined)
|
|
37
|
+
return [word];
|
|
38
|
+
return characters(last).length + 1 + characters(word).length <= columns ? [...lines.slice(0, -1), `${last} ${word}`] : [...lines, word];
|
|
39
|
+
}, []);
|
|
40
|
+
/** How long ago, as a reader rounds it: 45s ago, 12m ago, 30h ago, 3d ago. */
|
|
41
|
+
export const ago = (ms) => {
|
|
42
|
+
const seconds = Math.floor(Math.max(0, ms) / 1000);
|
|
43
|
+
if (seconds < 60)
|
|
44
|
+
return `${String(seconds)}s ago`;
|
|
45
|
+
const minutes = Math.floor(seconds / 60);
|
|
46
|
+
if (minutes < 60)
|
|
47
|
+
return `${String(minutes)}m ago`;
|
|
48
|
+
const hours = Math.floor(minutes / 60);
|
|
49
|
+
return hours < 48 ? `${String(hours)}h ago` : `${String(Math.floor(hours / 24))}d ago`;
|
|
50
|
+
};
|
|
51
|
+
/** Rows of cells in columns as wide as their widest cell, two spaces apart; nothing trails a row's last cell. */
|
|
52
|
+
export const table = (rows) => {
|
|
53
|
+
const filled = rows.map((row) => row.slice(0, row.findLastIndex((cell) => width(cell) > 0) + 1));
|
|
54
|
+
const widths = filled.reduce((most, row) => Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? []))), []);
|
|
55
|
+
return filled.map((row) => row.flatMap((cell, at) => (at === row.length - 1 ? cell : [...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)])));
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Rows for table() that fit `room` columns: the cells of the columns in
|
|
59
|
+
* `shrink` cut, in that order, each to no less than its first row's (the
|
|
60
|
+
* heading's) width.
|
|
61
|
+
*/
|
|
62
|
+
export const fit = (rows, room, shrink) => {
|
|
63
|
+
const widths = rows.reduce((most, row) => Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? []))), []);
|
|
64
|
+
const over = widths.reduce((sum, each) => sum + each, 0) + 2 * Math.max(0, widths.length - 1) - room;
|
|
65
|
+
const cut = shrink.reduce((so, at) => {
|
|
66
|
+
const now = so.widths[at] ?? 0;
|
|
67
|
+
const less = Math.min(Math.max(0, so.over), Math.max(0, now - width(rows[0]?.[at] ?? [])));
|
|
68
|
+
return { widths: so.widths.with(at, now - less), over: so.over - less };
|
|
69
|
+
}, { widths, over }).widths;
|
|
70
|
+
return rows.map((row) => row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))));
|
|
71
|
+
};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { accent, active, bad, muted, ok, strong, warn } from "./line.js";
|
|
3
|
+
import { ago, duration, table } from "./text.js";
|
|
4
|
+
const deployed = z.object({ sha: z.string(), time: z.iso.datetime() });
|
|
5
|
+
const runsAnswer = z.object({
|
|
6
|
+
app: z.string(),
|
|
7
|
+
live: deployed.exactOptional(),
|
|
8
|
+
runs: z.array(z.object({
|
|
9
|
+
id: z.string(),
|
|
10
|
+
state: z.enum(["running", "success", "failure"]),
|
|
11
|
+
why: z.string(),
|
|
12
|
+
what: z.string(),
|
|
13
|
+
sha: z.string().exactOptional(),
|
|
14
|
+
started: z.iso.datetime(),
|
|
15
|
+
finished: z.iso.datetime().exactOptional(),
|
|
16
|
+
})),
|
|
17
|
+
});
|
|
18
|
+
const releasesAnswer = z.object({
|
|
19
|
+
app: z.string(),
|
|
20
|
+
releases: z.array(deployed.extend({ live: z.boolean() })),
|
|
21
|
+
});
|
|
22
|
+
/** The answer as the schema has it, or nothing: then it is not the answer this kayra expects. */
|
|
23
|
+
const parsed = (schema, answer) => {
|
|
24
|
+
try {
|
|
25
|
+
const json = JSON.parse(answer);
|
|
26
|
+
const result = schema.safeParse(json);
|
|
27
|
+
return result.success ? result.data : undefined;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
/** Lines as printing them one by one gives the text back: newline-ended, as a ctl writes. */
|
|
34
|
+
const linesOf = (text) => (text === "" ? [] : text.replace(/\n$/, "").split("\n"));
|
|
35
|
+
const short = (sha) => sha.slice(0, 7);
|
|
36
|
+
const since = (time, now) => ago(now - Date.parse(time));
|
|
37
|
+
const heading = (view, ...more) => [strong(view.app), muted(` on ${view.server}`), ...more];
|
|
38
|
+
const live = (release, now) => release === undefined
|
|
39
|
+
? [muted(" · not deployed yet")]
|
|
40
|
+
: [muted(" · live "), accent(short(release.sha)), muted(` since ${since(release.time, now)}`)];
|
|
41
|
+
const hint = (command, what) => [" ", active("→"), " ", strong(command), muted(` ${what}`)];
|
|
42
|
+
const states = {
|
|
43
|
+
success: [ok("✓ success")],
|
|
44
|
+
failure: [bad("✗ failure")],
|
|
45
|
+
running: [active("◆ running")],
|
|
46
|
+
};
|
|
47
|
+
const took = (run, now) => run.finished === undefined
|
|
48
|
+
? [active(`${duration(now - Date.parse(run.started))}…`)]
|
|
49
|
+
: [duration(Date.parse(run.finished) - Date.parse(run.started))];
|
|
50
|
+
const commit = (run, release) => {
|
|
51
|
+
if (run.sha === undefined)
|
|
52
|
+
return [muted("—")];
|
|
53
|
+
return run.sha === release?.sha ? [accent(short(run.sha))] : [short(run.sha)];
|
|
54
|
+
};
|
|
55
|
+
/** `kayra app runs`: what runs now, then a table of the newest runs. */
|
|
56
|
+
export const runsView = (view, answer, now) => {
|
|
57
|
+
const rows = table([
|
|
58
|
+
["STATE", "COMMIT", "WHY", "WHEN", "TOOK", "RUN"].map((title) => [muted(title)]),
|
|
59
|
+
...answer.runs.map((run) => [states[run.state], commit(run, answer.live), [run.why], [since(run.started, now)], took(run, now), [muted(run.id)]]),
|
|
60
|
+
]);
|
|
61
|
+
return [
|
|
62
|
+
heading(view, ...live(answer.live, now)),
|
|
63
|
+
[],
|
|
64
|
+
...(answer.runs.length === 0
|
|
65
|
+
? [[" ", muted("no runs yet")]]
|
|
66
|
+
: [...rows.map((row) => [" ", ...row]), [], hint(`kayra app logs ${view.server} ${view.app} [RUN]`, "shows a run's log, the newest by default")]),
|
|
67
|
+
];
|
|
68
|
+
};
|
|
69
|
+
/** `kayra app rollback` without a commit: every release, the live one marked, and how to go back to one. */
|
|
70
|
+
export const releasesView = (view, answer, now) => {
|
|
71
|
+
const earlier = answer.releases.find((release) => !release.live);
|
|
72
|
+
const rows = table([
|
|
73
|
+
[[muted(" COMMIT")], [muted("DEPLOYED")]],
|
|
74
|
+
...answer.releases.map((release) => [
|
|
75
|
+
release.live ? [ok("●"), " ", accent(short(release.sha))] : [" ", short(release.sha)],
|
|
76
|
+
[since(release.time, now)],
|
|
77
|
+
release.live ? [ok("live")] : [],
|
|
78
|
+
]),
|
|
79
|
+
]);
|
|
80
|
+
const count = answer.releases.length;
|
|
81
|
+
return [
|
|
82
|
+
heading(view, muted(` · ${String(count)} release${count === 1 ? "" : "s"}`)),
|
|
83
|
+
[],
|
|
84
|
+
...rows.map((row) => [" ", ...row]),
|
|
85
|
+
[],
|
|
86
|
+
earlier === undefined
|
|
87
|
+
? [" ", muted("nothing earlier to roll back to")]
|
|
88
|
+
: hint(`kayra app rollback ${view.server} ${view.app} ${short(earlier.sha)}`, "deploys that one again"),
|
|
89
|
+
];
|
|
90
|
+
};
|
|
91
|
+
const errors = /\b(error|fatal|failed|failure|panic|refused|denied|unhealthy)\b/i;
|
|
92
|
+
const warnings = /\b(warn|warning|deprecated)\b/i;
|
|
93
|
+
/** The deployer's time, before each line it logs. */
|
|
94
|
+
const stamped = /^(\d{2}:\d{2}:\d{2} )(.*)$/s;
|
|
95
|
+
const logLine = (line) => {
|
|
96
|
+
const [, time = "", text = line] = stamped.exec(line) ?? [];
|
|
97
|
+
const tone = errors.test(text) ? bad : warnings.test(text) ? warn : text.startsWith("── ") ? strong : text.startsWith("Deployed ") ? ok : undefined;
|
|
98
|
+
return [...(time === "" ? [] : [muted(time)]), tone === undefined ? text : tone(text)];
|
|
99
|
+
};
|
|
100
|
+
/** `kayra app logs`: the log as it is, its errors and warnings marked; uncoloured, the same bytes. */
|
|
101
|
+
export const logView = (log) => linesOf(log).map(logLine);
|
|
102
|
+
/** A deployer's answer as its view draws it, or as it came if it is not what the view reads (an older ctl). */
|
|
103
|
+
export const draw = (view, answer, now) => {
|
|
104
|
+
switch (view.view) {
|
|
105
|
+
case "runs": {
|
|
106
|
+
const runs = parsed(runsAnswer, answer);
|
|
107
|
+
return runs === undefined ? linesOf(answer) : runsView(view, runs, now);
|
|
108
|
+
}
|
|
109
|
+
case "releases": {
|
|
110
|
+
const releases = parsed(releasesAnswer, answer);
|
|
111
|
+
return releases === undefined ? linesOf(answer) : releasesView(view, releases, now);
|
|
112
|
+
}
|
|
113
|
+
case "log":
|
|
114
|
+
return logView(answer);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
/** What --dry-run says about a drawn answer. */
|
|
118
|
+
export const drawnAs = (view) => {
|
|
119
|
+
switch (view.view) {
|
|
120
|
+
case "runs":
|
|
121
|
+
return "its answer drawn as a table of runs";
|
|
122
|
+
case "releases":
|
|
123
|
+
return "its answer drawn as the releases, the live one marked";
|
|
124
|
+
case "log":
|
|
125
|
+
return "the log as it is, errors and warnings marked on a terminal";
|
|
126
|
+
}
|
|
127
|
+
};
|
package/cli/dist/validate.js
CHANGED
|
@@ -8,12 +8,17 @@ const distance = (a, b) => indices(b.length)
|
|
|
8
8
|
Math.min((row[i + 1] ?? 0) + 1, (next[i] ?? 0) + 1, (row[i] ?? 0) + (a.charAt(i) === b.charAt(j) ? 0 : 1)),
|
|
9
9
|
], [j + 1]), indices(a.length + 1))
|
|
10
10
|
.at(-1) ?? 0;
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/** The known name a key is most likely a typo of, if one is close enough. */
|
|
12
|
+
export const closest = (key, known) => {
|
|
13
|
+
const nearest = known
|
|
13
14
|
.map((name) => ({ name, cost: distance(key, name) }))
|
|
14
15
|
.toSorted((x, y) => x.cost - y.cost)
|
|
15
16
|
.at(0);
|
|
16
|
-
return
|
|
17
|
+
return nearest !== undefined && nearest.cost <= Math.max(2, Math.floor(key.length / 4)) ? nearest.name : undefined;
|
|
18
|
+
};
|
|
19
|
+
const suggestion = (key, known) => {
|
|
20
|
+
const name = closest(key, known);
|
|
21
|
+
return name === undefined ? "" : ` — did you mean '${name}'?`;
|
|
17
22
|
};
|
|
18
23
|
/** The first problem Zod found, said for the file it is in. */
|
|
19
24
|
const firstIssue = (file, error, known, unknownKey) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yunuseon/kayra",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "A self-hosted app platform and the CLI that runs it: Traefik, Authelia, a registry, rootless BuildKit and a small deployer per server, set up with OpenTofu and Ansible.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Yunus Öztürk",
|
package/scripts/local/verify.sh
CHANGED
|
@@ -28,8 +28,8 @@ dir="${FLEET_ROOT}/servers/${name}"
|
|
|
28
28
|
wait="${VERIFY_WAIT:-150}"
|
|
29
29
|
failed=0
|
|
30
30
|
|
|
31
|
-
fail() { echo "✗ $*"; failed=1; }
|
|
32
|
-
pass() { echo "✓ $*"; }
|
|
31
|
+
fail() { echo " ✗ $*"; failed=1; }
|
|
32
|
+
pass() { echo " ✓ $*"; }
|
|
33
33
|
|
|
34
34
|
domain="$(yq -r '.domain' "${dir}/server.yml")"
|
|
35
35
|
inventory="${dir}/inventory.ini"
|