@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.
- package/agent/skills/kayra-release/SKILL.md +6 -1
- package/ansible/roles/platform/tasks/main.yml +40 -1
- package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
- package/cli/dist/browser/index.html +1 -1
- package/cli/dist/clients/api/api.js +138 -218
- package/cli/dist/clients/api/auth.js +8 -7
- package/cli/dist/clients/api/commands.js +50 -14
- package/cli/dist/clients/api/contract.js +8 -6
- package/cli/dist/clients/api/directories.js +1 -1
- package/cli/dist/clients/api/discovery.js +8 -3
- package/cli/dist/clients/api/live.js +40 -0
- package/cli/dist/clients/api/protocol.js +17 -10
- package/cli/dist/clients/api/queries.js +4 -4
- package/cli/dist/clients/api/runs.js +10 -9
- package/cli/dist/clients/api/start.js +97 -0
- package/cli/dist/clients/api/status.js +29 -0
- package/cli/dist/clients/api/validate.js +13 -0
- package/cli/dist/clients/cli/explain.js +12 -10
- package/cli/dist/clients/cli/framed.js +12 -9
- package/cli/dist/clients/cli/invocation.js +4 -3
- package/cli/dist/clients/cli/paint.js +1 -1
- package/cli/dist/clients/cli/parser.js +8 -8
- package/cli/dist/clients/cli/questions.js +11 -10
- package/cli/dist/clients/cli/status.js +75 -0
- package/cli/dist/clients/cli/terminal.js +4 -2
- package/cli/dist/{core/present → clients/cli}/text.js +15 -24
- package/cli/dist/clients/cli/validate.js +32 -0
- package/cli/dist/clients/cli/values.js +19 -0
- package/cli/dist/{core/present → clients/cli}/views.js +28 -60
- package/cli/dist/core/adapters/fs.js +18 -0
- package/cli/dist/core/{net.js → adapters/network.js} +20 -5
- package/cli/dist/core/adapters/opentofu.js +24 -0
- package/cli/dist/core/ctl/answers.js +32 -0
- package/cli/dist/core/fleet/brand.js +54 -0
- package/cli/dist/core/{schemas.js → fleet/docs.js} +5 -4
- package/cli/dist/core/fleet/load.js +45 -0
- package/cli/dist/core/fleet/model.js +1 -0
- package/cli/dist/core/fleet/parse.js +144 -0
- package/cli/dist/core/{settings.js → fleet/settings.js} +47 -15
- package/cli/dist/core/{validate.js → fleet/shape.js} +6 -20
- package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
- package/cli/dist/core/interpreter/io.js +18 -0
- package/cli/dist/core/interpreter/loop.js +101 -0
- package/cli/dist/core/interpreter/needs.js +47 -0
- package/cli/dist/core/interpreter/process.js +107 -0
- package/cli/dist/core/interpreter/progress.js +15 -0
- package/cli/dist/core/interpreter/pty.js +8 -0
- package/cli/dist/core/operations/catalog.js +35 -18
- package/cli/dist/core/operations/{run.js → dispatch.js} +50 -47
- package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
- package/cli/dist/core/plan/model.js +14 -0
- package/cli/dist/core/recipes/app-check.js +27 -0
- package/cli/dist/core/recipes/apps.js +63 -0
- package/cli/dist/core/recipes/backup.js +34 -0
- package/cli/dist/core/recipes/certs.js +4 -0
- package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
- package/cli/dist/core/recipes/host.js +104 -0
- package/cli/dist/core/recipes/ssh.js +20 -0
- package/cli/dist/core/recipes/steps.js +82 -0
- package/cli/dist/core/status/look.js +55 -0
- package/cli/dist/core/status/model.js +6 -0
- package/cli/dist/core/status/ports.js +1 -0
- package/cli/dist/core/text/plural.js +2 -0
- package/cli/dist/core/text/spans.js +22 -0
- package/cli/dist/core/text/time.js +12 -0
- package/cli/dist/core/validation/facts.js +50 -0
- package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
- package/cli/dist/deployer/app.js +3 -2
- package/cli/dist/deployer/brand.js +1 -1
- package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
- package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
- package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
- package/cli/dist/deployer/cron.js +3 -3
- package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
- package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
- package/cli/dist/deployer/deployer.js +24 -23
- package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
- package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
- package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
- package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
- package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
- package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
- package/cli/dist/deployer/{http.js → http/http.js} +1 -0
- package/cli/dist/deployer/{page.js → http/page.js} +1 -1
- package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
- package/cli/dist/deployer/main.js +2 -2
- package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
- package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
- package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
- package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
- package/cli/dist/lib/brand.js +2 -0
- package/cli/dist/lib/closest.js +17 -0
- package/cli/dist/lib/result.js +15 -0
- package/cli/dist/lib/schema.js +7 -0
- package/cli/dist/lib/typed.js +2 -0
- package/cli/dist/lib/yaml.js +21 -0
- package/cli/dist/main.js +89 -89
- package/cli/dist/serve.js +2 -2
- package/package.json +3 -2
- package/schema/app.json +4 -2
- package/schema/server.json +10 -5
- package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
- package/cli/dist/core/brand.js +0 -39
- package/cli/dist/core/commands/app-check.js +0 -35
- package/cli/dist/core/commands/server.js +0 -298
- package/cli/dist/core/commands/status.js +0 -194
- package/cli/dist/core/fleet.js +0 -156
- package/cli/dist/core/gather.js +0 -61
- package/cli/dist/core/interpret.js +0 -276
- package/cli/dist/core/load.js +0 -64
- package/cli/dist/core/present/line.js +0 -17
- package/cli/dist/result.js +0 -5
- /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { absolutePath, host, sshDefaultPort, keyFile, port, remotePath, sshUser, vaultPasswordFile } from "./brand.js";
|
|
2
|
+
import { err, map, ok } from "../../lib/result.js";
|
|
3
|
+
import { serverSchema, varsSchema } from "./settings.js";
|
|
4
|
+
import { checkSettings, knownSettings } from "./shape.js";
|
|
5
|
+
import { typed } from "../../lib/typed.js";
|
|
6
|
+
import { fields, mapping } from "../../lib/yaml.js";
|
|
7
|
+
export const isVaulted = (text) => text.startsWith("$ANSIBLE_VAULT");
|
|
8
|
+
const vault = (descriptor) => {
|
|
9
|
+
const file = descriptor.vault_password_file;
|
|
10
|
+
if (!descriptor.vault)
|
|
11
|
+
return ok({ kind: "none" });
|
|
12
|
+
if (file === undefined)
|
|
13
|
+
return ok({ kind: "ask" });
|
|
14
|
+
return map(absolutePath(file), (path) => typed({ kind: "file", file: vaultPasswordFile(path) }));
|
|
15
|
+
};
|
|
16
|
+
/** What Zod's expected types are called in a fleet's YAML. */
|
|
17
|
+
const expected = { string: "a string", boolean: "true or false", array: "a list", object: "a mapping" };
|
|
18
|
+
/** What the file says at a path Zod reports: Zod's issues leave the input out. */
|
|
19
|
+
const written = (value, path) => {
|
|
20
|
+
// Recursive: a path one key at a time.
|
|
21
|
+
const [key, ...rest] = path;
|
|
22
|
+
if (key === undefined)
|
|
23
|
+
return value;
|
|
24
|
+
const next = Array.isArray(value) && typeof key === "number" ? value[key] : mapping(value)?.[String(key)];
|
|
25
|
+
return written(next, rest);
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The first thing wrong with server.yml, said as the operator wrote it: an
|
|
29
|
+
* app by its name, a missing key as required. The schema's own messages are
|
|
30
|
+
* whole sentences already.
|
|
31
|
+
*/
|
|
32
|
+
const serverProblem = (error, descriptor) => {
|
|
33
|
+
const issue = error.issues.at(0);
|
|
34
|
+
if (issue === undefined)
|
|
35
|
+
return "server.yml is invalid";
|
|
36
|
+
const [first, index] = issue.path;
|
|
37
|
+
const name = index === undefined ? undefined : written(descriptor, ["apps", index, "name"]);
|
|
38
|
+
const app = first === "apps" && typeof index === "number" ? `app ${typeof name === "string" ? name : `#${String(index + 1)}`}: ` : "";
|
|
39
|
+
const key = String(issue.path.at(-1) ?? "");
|
|
40
|
+
if (issue.code === "unrecognized_keys") {
|
|
41
|
+
const where = issue.path.length === 0 ? "" : ` (in ${issue.path.join(".")})`;
|
|
42
|
+
return `server.yml: '${issue.keys.at(0) ?? ""}' is not a key it knows${where}`;
|
|
43
|
+
}
|
|
44
|
+
if (issue.code === "invalid_type")
|
|
45
|
+
return `${app}${key} ${written(descriptor, issue.path) === undefined ? "is required" : `must be ${expected[issue.expected] ?? issue.expected}`}`;
|
|
46
|
+
return `${app}${issue.message}`;
|
|
47
|
+
};
|
|
48
|
+
const inventoryField = (inventory, key) => new RegExp(`${key}=([^ \\n]*)`).exec(inventory)?.[1] ?? "";
|
|
49
|
+
/** A field the inventory may leave out: undefined where it does. */
|
|
50
|
+
const optional = (value, mint) => value === "" ? ok(undefined) : mint(value);
|
|
51
|
+
const inventoryOf = (text) => {
|
|
52
|
+
const fields = [
|
|
53
|
+
optional(inventoryField(text, "ansible_host"), host),
|
|
54
|
+
port(inventoryField(text, "ansible_port") || sshDefaultPort),
|
|
55
|
+
optional(inventoryField(text, "ansible_user"), sshUser),
|
|
56
|
+
optional(inventoryField(text, "ansible_ssh_private_key_file"), keyFile),
|
|
57
|
+
];
|
|
58
|
+
const [address, sshPort, user, key] = fields;
|
|
59
|
+
if (!address.ok)
|
|
60
|
+
return err(`inventory.ini: ansible_host ${address.error}`);
|
|
61
|
+
if (!sshPort.ok)
|
|
62
|
+
return err(`inventory.ini: ansible_port ${sshPort.error}`);
|
|
63
|
+
if (!user.ok)
|
|
64
|
+
return err(`inventory.ini: ansible_user ${user.error}`);
|
|
65
|
+
if (!key.ok)
|
|
66
|
+
return err(`inventory.ini: ansible_ssh_private_key_file ${key.error}`);
|
|
67
|
+
return ok({ host: address.value, port: sshPort.value, user: user.value, key: key.value });
|
|
68
|
+
};
|
|
69
|
+
const stackHosts = (stacks, serverDomain) => Object.freeze(stacks
|
|
70
|
+
.flatMap((compose) => Object.freeze([...compose.matchAll(/Host\(`([^`]*)`\)/g)].map((match) => match[1] ?? "")))
|
|
71
|
+
.map((host) => (host.endsWith(`.${serverDomain}`) ? host.slice(0, -serverDomain.length - 1) : host)));
|
|
72
|
+
/** An app's config is plaintext, to be read and diffed; its secrets are vaulted wherever secrets.yml is. */
|
|
73
|
+
const appValuesProblem = (appValues, secretsMustBeVaulted) => appValues
|
|
74
|
+
.map(({ file, text }) => file.endsWith(".secrets.yml")
|
|
75
|
+
? secretsMustBeVaulted && !isVaulted(text)
|
|
76
|
+
? `apps/${file} must be vault-encrypted`
|
|
77
|
+
: undefined
|
|
78
|
+
: isVaulted(text)
|
|
79
|
+
? `apps/${file} is vault-encrypted; it holds config only — secrets go in apps/${file.replace(/\.yml$/, ".secrets.yml")}`
|
|
80
|
+
: undefined)
|
|
81
|
+
.find((problem) => problem !== undefined);
|
|
82
|
+
/** What every command may rely on, checked for every server whenever the fleet loads. */
|
|
83
|
+
export const parseServer = (files) => {
|
|
84
|
+
const descriptor = fields(files.descriptor);
|
|
85
|
+
if (!descriptor.ok)
|
|
86
|
+
return descriptor;
|
|
87
|
+
const parsed = serverSchema.safeParse(descriptor.value);
|
|
88
|
+
if (!parsed.success)
|
|
89
|
+
return err(serverProblem(parsed.error, descriptor.value));
|
|
90
|
+
const { kind, target, domain, apps } = parsed.data;
|
|
91
|
+
const serverVault = vault(parsed.data);
|
|
92
|
+
if (!serverVault.ok)
|
|
93
|
+
return serverVault;
|
|
94
|
+
if (target === "home" && files.inventory === undefined)
|
|
95
|
+
return err("target home needs a hand-written inventory.ini next to it");
|
|
96
|
+
if (target !== "home" && !files.hasTerraform)
|
|
97
|
+
return err("no terraform/ next to it");
|
|
98
|
+
if (files.vars === undefined)
|
|
99
|
+
return err("no vars.yml next to it");
|
|
100
|
+
if (files.secrets === undefined)
|
|
101
|
+
return err("no secrets.yml next to it");
|
|
102
|
+
if (isVaulted(files.vars))
|
|
103
|
+
return err("vars.yml is vault-encrypted; it holds settings only — secrets go in secrets.yml");
|
|
104
|
+
if (target !== "multipass" && serverVault.value.kind === "none")
|
|
105
|
+
return err(`target ${target} requires vault: true`);
|
|
106
|
+
if (target !== "multipass" && !isVaulted(files.secrets))
|
|
107
|
+
return err(`target ${target} requires a vault-encrypted secrets.yml`);
|
|
108
|
+
const appValues = appValuesProblem(files.appValues, target !== "multipass");
|
|
109
|
+
if (appValues !== undefined)
|
|
110
|
+
return err(appValues);
|
|
111
|
+
const vars = fields(files.vars);
|
|
112
|
+
if (!vars.ok)
|
|
113
|
+
return err(`vars.yml ${vars.error}`);
|
|
114
|
+
const varsChecked = checkSettings("vars.yml", vars.value, varsSchema(kind), knownSettings(kind));
|
|
115
|
+
if (!varsChecked.ok)
|
|
116
|
+
return varsChecked;
|
|
117
|
+
const backup = mapping(vars.value["restic_backup"])?.["dir"];
|
|
118
|
+
const backupDir = typeof backup === "string" ? remotePath(backup) : ok(undefined);
|
|
119
|
+
if (!backupDir.ok)
|
|
120
|
+
return err(`vars.yml: restic_backup.dir ${backupDir.error}`);
|
|
121
|
+
const inventory = files.inventory === undefined ? ok(undefined) : inventoryOf(files.inventory);
|
|
122
|
+
if (!inventory.ok)
|
|
123
|
+
return inventory;
|
|
124
|
+
const declared = descriptor.value["apps"];
|
|
125
|
+
const entries = Array.isArray(declared) ? declared : [];
|
|
126
|
+
return ok({
|
|
127
|
+
name: files.name,
|
|
128
|
+
dir: files.dir,
|
|
129
|
+
kind,
|
|
130
|
+
target,
|
|
131
|
+
domain,
|
|
132
|
+
vault: serverVault.value,
|
|
133
|
+
hasVaultedSecrets: isVaulted(files.secrets),
|
|
134
|
+
apps: apps.map((app, index) => typed({ name: app.name, repo: app.repo, path: app.path, entry: mapping(entries[index]) ?? {} })),
|
|
135
|
+
hasTerraform: files.hasTerraform,
|
|
136
|
+
buildsVm: target === "home" && vars.value["vm"] !== undefined,
|
|
137
|
+
usesAcmeDns: typeof vars.value["acme_dns"] === "string" && vars.value["acme_dns"] !== "",
|
|
138
|
+
inventory: inventory.value,
|
|
139
|
+
backupDir: backupDir.value,
|
|
140
|
+
stackHosts: stackHosts(files.stacks.flatMap((stack) => Object.freeze(stack.compose ?? [])), domain),
|
|
141
|
+
vars: vars.value,
|
|
142
|
+
files: { vars: files.vars, secrets: files.secrets, stacks: files.stacks.map((stack) => stack.name), appValues: files.appValues },
|
|
143
|
+
});
|
|
144
|
+
};
|
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { typed } from "../../lib/typed.js";
|
|
3
|
+
import { appNameSchema, domainSchema, repoPathSchema, repoUrlSchema, subdomainSchema } from "./brand.js";
|
|
4
|
+
import { serverTargets } from "./model.js";
|
|
2
5
|
/** The server kinds, each with its playbook; settings say which kinds read them. */
|
|
3
6
|
export const serverKinds = ["platform", "edge", "nas"];
|
|
4
|
-
|
|
5
|
-
const
|
|
7
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
|
|
8
|
+
const setting = (name, kinds, schema, description) => typed({ name, kinds, secret: false, schema: schema.describe(description), description });
|
|
9
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
|
|
10
|
+
const secret = (name, kinds, schema, description) => typed({ name, kinds, secret: true, schema: schema.describe(description), description });
|
|
6
11
|
const text = z.string();
|
|
7
12
|
const texts = z.array(z.string());
|
|
8
13
|
const platform = ["platform"];
|
|
9
14
|
const edge = ["edge"];
|
|
10
15
|
const nas = ["nas"];
|
|
11
16
|
/** Nested settings check the fields they know and allow others: a typo is caught at the top. */
|
|
17
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
|
|
12
18
|
const record = (fields) => z.looseObject(fields);
|
|
13
19
|
export const settings = [
|
|
14
20
|
// Every kind that serves HTTPS
|
|
@@ -100,36 +106,62 @@ export const settings = [
|
|
|
100
106
|
];
|
|
101
107
|
/** Ansible's own variables (connection, privilege escalation) are always allowed. */
|
|
102
108
|
export const isAnsibleVariable = (key) => key.startsWith("ansible_");
|
|
103
|
-
export const settingsFor = (kind, secrets) => settings.filter((each) => each.secret === secrets && each.kinds.includes(kind));
|
|
109
|
+
export const settingsFor = (kind, secrets) => Object.freeze(settings.filter((each) => each.secret === secrets && each.kinds.includes(kind)));
|
|
110
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- Zod schemas: immutable once built, but classes the rule cannot see into
|
|
104
111
|
const shape = (chosen) => Object.fromEntries(chosen.map((each) => [each.name, each.schema.optional()]));
|
|
105
112
|
/** vars.yml for a kind: its settings and nothing else (Ansible's own variables apart). */
|
|
113
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
|
|
106
114
|
export const varsSchema = (kind) => z.strictObject(shape(settingsFor(kind, false)));
|
|
107
115
|
/** defaults.yml: settings shared by every server, so any kind's. */
|
|
108
116
|
export const defaultsSchema = z.strictObject(shape(settings.filter((each) => !each.secret)));
|
|
109
117
|
/** secrets.yml: the known secrets typed; other keys may be helpers that vars.yml references. */
|
|
118
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
|
|
110
119
|
export const secretsSchema = (kind) => z.looseObject(shape(settingsFor(kind, true)));
|
|
111
|
-
/**
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
120
|
+
/**
|
|
121
|
+
* A multipass server, a test machine by definition, may clone an app over
|
|
122
|
+
* plain HTTP too: the upgrade lab serves its fixture app that way.
|
|
123
|
+
*/
|
|
124
|
+
const schemes = (target) => typed(target === "multipass" ? ["https://", "http://"] : ["https://"]);
|
|
125
|
+
/** server.yml: topology only. What it says is checked here, once: the parser, the editors' schema and the docs read it. */
|
|
126
|
+
export const serverSchema = z
|
|
127
|
+
.strictObject({
|
|
128
|
+
kind: z
|
|
129
|
+
.enum(serverKinds, { error: (issue) => `kind must be ${serverKinds.join(", ")}, not '${String(issue.input)}'` })
|
|
130
|
+
.default("platform")
|
|
131
|
+
.describe("Which playbook: platform (default; Traefik, Authelia, the deployer, apps), edge or nas."),
|
|
132
|
+
target: z
|
|
133
|
+
.enum(serverTargets, { error: (issue) => `target must be ${serverTargets.join(", ")}, not '${String(issue.input)}'` })
|
|
134
|
+
.describe("Where it runs: hetzner, multipass (a local VM) or home (a machine nothing creates)."),
|
|
135
|
+
domain: domainSchema.describe("The server's domain; platform subdomains and the apps' hang off it."),
|
|
136
|
+
vault: z.boolean().default(false).describe("secrets.yml is vault-encrypted (required outside multipass)."),
|
|
117
137
|
vault_password_file: z.string().optional().describe("The vault password file; without it, Ansible asks."),
|
|
118
138
|
apps: z
|
|
119
139
|
.array(z.strictObject({
|
|
120
|
-
name:
|
|
121
|
-
repo:
|
|
140
|
+
name: appNameSchema,
|
|
141
|
+
repo: repoUrlSchema.describe("The app's repository, https://."),
|
|
122
142
|
ref: z.string().optional().describe("The branch to build and deploy (default main)."),
|
|
123
|
-
path:
|
|
143
|
+
path: repoPathSchema.prefault(".").describe("The app's root inside the repository (default .)."),
|
|
124
144
|
}))
|
|
125
|
-
.
|
|
145
|
+
.default([])
|
|
126
146
|
.describe("The apps this server runs (platform only)."),
|
|
147
|
+
})
|
|
148
|
+
.superRefine((server, context) => {
|
|
149
|
+
if (server.kind !== "platform" && server.apps.length > 0)
|
|
150
|
+
context.addIssue({ code: "custom", path: ["apps"], message: "apps run on platform servers only" });
|
|
151
|
+
server.apps.forEach((app, index) => {
|
|
152
|
+
if (!schemes(server.target).some((scheme) => app.repo.startsWith(scheme)))
|
|
153
|
+
context.addIssue({
|
|
154
|
+
code: "custom",
|
|
155
|
+
path: ["apps", index, "repo"],
|
|
156
|
+
message: `repo must be an https:// URL${server.target === "multipass" ? " (or http:// on multipass)" : ""}`,
|
|
157
|
+
});
|
|
158
|
+
});
|
|
127
159
|
});
|
|
128
160
|
/** app.yml, at the root of an app's repository: the app contract. */
|
|
129
161
|
export const appManifestSchema = z.strictObject({
|
|
130
|
-
name:
|
|
162
|
+
name: appNameSchema.describe("The app's name, as in the server.yml entry."),
|
|
131
163
|
compose: z.array(z.string()).describe("Compose files, relative to the app root, in order."),
|
|
132
|
-
subdomains: z.array(
|
|
164
|
+
subdomains: z.array(subdomainSchema).describe("Hostnames the app claims: <sub>.<domain>."),
|
|
133
165
|
secrets: z.array(z.string()).optional().describe("Secret keys; their values come from the fleet's apps/<app>.secrets.yml."),
|
|
134
166
|
config: z.array(z.string()).optional().describe("Config keys; their values come from the fleet's apps/<app>.yml."),
|
|
135
167
|
});
|
|
@@ -1,21 +1,6 @@
|
|
|
1
|
-
import { err, ok } from "
|
|
1
|
+
import { err, ok } from "../../lib/result.js";
|
|
2
2
|
import { isAnsibleVariable, settings } from "./settings.js";
|
|
3
|
-
|
|
4
|
-
const indices = (length) => [...Array(length).keys()];
|
|
5
|
-
const distance = (a, b) => indices(b.length)
|
|
6
|
-
.reduce((row, j) => indices(a.length).reduce((next, i) => [
|
|
7
|
-
...next,
|
|
8
|
-
Math.min((row[i + 1] ?? 0) + 1, (next[i] ?? 0) + 1, (row[i] ?? 0) + (a.charAt(i) === b.charAt(j) ? 0 : 1)),
|
|
9
|
-
], [j + 1]), indices(a.length + 1))
|
|
10
|
-
.at(-1) ?? 0;
|
|
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
|
|
14
|
-
.map((name) => ({ name, cost: distance(key, name) }))
|
|
15
|
-
.toSorted((x, y) => x.cost - y.cost)
|
|
16
|
-
.at(0);
|
|
17
|
-
return nearest !== undefined && nearest.cost <= Math.max(2, Math.floor(key.length / 4)) ? nearest.name : undefined;
|
|
18
|
-
};
|
|
3
|
+
import { closest } from "../../lib/closest.js";
|
|
19
4
|
const suggestion = (key, known) => {
|
|
20
5
|
const name = closest(key, known);
|
|
21
6
|
return name === undefined ? "" : ` — did you mean '${name}'?`;
|
|
@@ -47,9 +32,10 @@ export const checkSettings = (file, values, schema, known) => {
|
|
|
47
32
|
return parsed.success ? ok(values) : err(firstIssue(file, parsed.error, known, "is not a setting"));
|
|
48
33
|
};
|
|
49
34
|
/** The names a kind's vars.yml may set. */
|
|
50
|
-
export const knownSettings = (kind) => settings.filter((each) => !each.secret && (kind === undefined || each.kinds.includes(kind))).map((each) => each.name);
|
|
51
|
-
/** A YAML document against a schema, for files whose keys are not settings (
|
|
35
|
+
export const knownSettings = (kind) => Object.freeze(settings.filter((each) => !each.secret && (kind === undefined || each.kinds.includes(kind))).map((each) => each.name));
|
|
36
|
+
/** A YAML document against a schema, for files whose keys are not settings (app.yml): what the schema makes of it. */
|
|
37
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
|
|
52
38
|
export const checkShape = (file, values, schema) => {
|
|
53
39
|
const parsed = schema.safeParse(values);
|
|
54
|
-
return parsed.success ? ok(
|
|
40
|
+
return parsed.success ? ok(parsed.data) : err(firstIssue(file, parsed.error, [], "is not a key it knows"));
|
|
55
41
|
};
|
|
@@ -1,22 +1,20 @@
|
|
|
1
|
-
import { commandOf, kindOf, titleOf } from "../plan.js";
|
|
2
|
-
import {
|
|
3
|
-
import { duration } from "
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return { index, total: plan.length, ...(opens ? { opens: part } : {}) };
|
|
15
|
-
};
|
|
1
|
+
import { commandOf, kindOf, titleOf } from "../plan/describe.js";
|
|
2
|
+
import { bad, muted, ok, pointing, strong, warn } from "../text/spans.js";
|
|
3
|
+
import { duration } from "../text/time.js";
|
|
4
|
+
import { parts, position } from "./progress.js";
|
|
5
|
+
import { count } from "../text/plural.js";
|
|
6
|
+
import { milliseconds } from "../fleet/brand.js";
|
|
7
|
+
import { typed } from "../../lib/typed.js";
|
|
8
|
+
/** The heading for a command: as typed, what it runs on, which kayra. */
|
|
9
|
+
export const heading = (command, target, version) => typed({
|
|
10
|
+
command,
|
|
11
|
+
...(target === undefined ? {} : { server: target.name }),
|
|
12
|
+
about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${version}`],
|
|
13
|
+
});
|
|
16
14
|
/** "8 steps", or "15 checks" for a plan of nothing else (doctor). */
|
|
17
15
|
export const steps = (plan) => {
|
|
18
16
|
const noun = plan.every((step) => step.kind === "check") ? "check" : "step";
|
|
19
|
-
return
|
|
17
|
+
return count(plan.length, noun);
|
|
20
18
|
};
|
|
21
19
|
/** The footer: how it went, how long it took, and what reruns a failed part alone. */
|
|
22
20
|
export const footer = (invocation, plan, ended, ms) => {
|
|
@@ -24,41 +22,39 @@ export const footer = (invocation, plan, ended, ms) => {
|
|
|
24
22
|
const { command } = invocation;
|
|
25
23
|
const { stop } = ended;
|
|
26
24
|
if (stop === undefined)
|
|
27
|
-
return ended.failures === 0
|
|
28
|
-
? [[ok("✓"), " ", strong(command), muted(` · ${steps(plan)} · ${took}`)]]
|
|
29
|
-
: [[bad("✗"), " ", strong(command), muted(` · ${String(ended.failures)} of ${steps(plan)} failed · ${took}`)]];
|
|
25
|
+
return typed(ended.failures === 0 ? [[ok("✓"), " ", strong(command), muted(` · ${steps(plan)} · ${took}`)]] : [[bad("✗"), " ", strong(command), muted(` · ${String(ended.failures)} of ${steps(plan)} failed · ${took}`)]]);
|
|
30
26
|
const where = `step ${String(stop.index + 1)} of ${String(plan.length)}`;
|
|
31
27
|
if (stop.why === "declined")
|
|
32
|
-
return [[warn("■"), " ", strong(command), muted(` stopped at ${where}: not confirmed`)]];
|
|
28
|
+
return typed([[warn("■"), " ", strong(command), muted(` stopped at ${where}: not confirmed`)]]);
|
|
33
29
|
if (stop.why === "interrupted")
|
|
34
|
-
return [[warn("■"), " ", strong(command), muted(` interrupted at ${where} · ${took}`)]];
|
|
30
|
+
return typed([[warn("■"), " ", strong(command), muted(` interrupted at ${where} · ${took}`)]]);
|
|
35
31
|
const { part } = stop.step;
|
|
36
32
|
const alone = part !== undefined && parts(plan).length > 1 && invocation.server !== undefined;
|
|
37
|
-
return [
|
|
33
|
+
return typed([
|
|
38
34
|
[bad("✗"), " ", strong(command), " failed at ", strong(titleOf(stop.step)), muted(` · ${where} · ${took}`)],
|
|
39
|
-
...(alone ? [
|
|
40
|
-
];
|
|
35
|
+
...(alone ? [pointing(" ", strong(`kayra ${part} ${invocation.server ?? ""}`), muted(" runs just this part"))] : []),
|
|
36
|
+
]);
|
|
41
37
|
};
|
|
42
38
|
/** Every step of a plan, its command's paths named by their root. */
|
|
43
|
-
export const listed = (plan, short) => plan.map((step, index) => {
|
|
39
|
+
export const listed = (plan, short) => Object.freeze(plan.map((step, index) => {
|
|
44
40
|
const command = commandOf(step);
|
|
45
41
|
const { opens } = position(plan, index);
|
|
46
|
-
return {
|
|
42
|
+
return typed({
|
|
47
43
|
index,
|
|
48
44
|
kind: kindOf(step),
|
|
49
45
|
title: titleOf(step),
|
|
50
46
|
...(command === undefined ? {} : { command: short(command) }),
|
|
51
47
|
...(step.part === undefined ? {} : { part: step.part }),
|
|
52
48
|
...(opens === undefined ? {} : { opens }),
|
|
53
|
-
};
|
|
54
|
-
});
|
|
49
|
+
});
|
|
50
|
+
}));
|
|
55
51
|
/** The plan and each step as events: what framed draws on a terminal, as data. */
|
|
56
|
-
export const reporting = (emit, invocation, short) => ({
|
|
52
|
+
export const reporting = (emit, invocation, short) => typed({
|
|
57
53
|
plan: async (plan, work) => {
|
|
58
54
|
const started = performance.now();
|
|
59
55
|
emit({ kind: "plan", invocation, steps: listed(plan, short) });
|
|
60
56
|
const ended = await work();
|
|
61
|
-
const ms = performance.now() - started;
|
|
57
|
+
const ms = milliseconds(performance.now() - started);
|
|
62
58
|
emit({
|
|
63
59
|
kind: "ended",
|
|
64
60
|
failures: ended.failures,
|
|
@@ -78,7 +74,7 @@ export const reporting = (emit, invocation, short) => ({
|
|
|
78
74
|
failed: done.failed,
|
|
79
75
|
stopped: done.stopped,
|
|
80
76
|
...(done.why === undefined ? {} : { why: done.why }),
|
|
81
|
-
ms: performance.now() - started,
|
|
77
|
+
ms: milliseconds(performance.now() - started),
|
|
82
78
|
});
|
|
83
79
|
return done;
|
|
84
80
|
},
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const isStopped = (signal) => signal?.aborted === true;
|
|
2
|
+
/** Cancellation also ends a question; a late answer cannot restart the plan. */
|
|
3
|
+
export const ask = async (io, question) => {
|
|
4
|
+
if (isStopped(io.signal))
|
|
5
|
+
return undefined;
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
const done = (answer) => {
|
|
8
|
+
io.signal?.removeEventListener("abort", stopped);
|
|
9
|
+
resolve(answer);
|
|
10
|
+
};
|
|
11
|
+
const stopped = () => { done(undefined); };
|
|
12
|
+
io.signal?.addEventListener("abort", stopped, { once: true });
|
|
13
|
+
void io.ask(question).then(done, (error) => {
|
|
14
|
+
io.signal?.removeEventListener("abort", stopped);
|
|
15
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { bad, ok as fine, muted, pointing, strong } from "../text/spans.js";
|
|
2
|
+
import { position, silent } from "./progress.js";
|
|
3
|
+
import { ask, isStopped } from "./io.js";
|
|
4
|
+
import { answer, resolve, spawned } from "./process.js";
|
|
5
|
+
import { meet, scratch } from "./needs.js";
|
|
6
|
+
import { inPty } from "./pty.js";
|
|
7
|
+
import { typed } from "../../lib/typed.js";
|
|
8
|
+
/** Lines as printing them one by one gives the text back: newline-ended, as a ctl writes. */
|
|
9
|
+
const asItCame = (_answer, said) => (said === "" ? typed([]) : said.replace(/\n$/, "").split("\n"));
|
|
10
|
+
const lines = (text) => Object.freeze(text
|
|
11
|
+
.trimEnd()
|
|
12
|
+
.split("\n")
|
|
13
|
+
.filter((line) => line !== ""));
|
|
14
|
+
/** Under the step's own line. */
|
|
15
|
+
const detail = (line) => typed([" ", line]);
|
|
16
|
+
const aside = (line) => typed([" ", muted(line)]);
|
|
17
|
+
const hint = (text) => (typed(text === undefined ? [] : [pointing(" ", text)]));
|
|
18
|
+
const goOn = { failed: false, stopped: false, out: [], err: [] };
|
|
19
|
+
const check = async (step, plumbing) => {
|
|
20
|
+
const exit = await answer(step.probe, plumbing);
|
|
21
|
+
const said = [...lines(exit.stderr).map(detail), ...hint(step.hint)];
|
|
22
|
+
if (step.onFailure === "stop")
|
|
23
|
+
return exit.code === 0 ? goOn : typed({ failed: true, stopped: true, out: [], err: said });
|
|
24
|
+
return typed(exit.code === 0 ? { ...goOn, out: [[fine("✓"), " ", step.label]] } : { failed: true, stopped: false, out: [[bad("✗"), " ", step.label], ...said], err: [] });
|
|
25
|
+
};
|
|
26
|
+
const runStep = async (step, io, met) => {
|
|
27
|
+
const argv = await resolve(step.argv, io);
|
|
28
|
+
if (!argv.ok)
|
|
29
|
+
return typed({ failed: true, stopped: true, why: "a query failed", out: [], err: [detail(argv.error)] });
|
|
30
|
+
const { stdout } = step;
|
|
31
|
+
const talks = step.kind === "session" && io.output !== undefined;
|
|
32
|
+
if (talks && io.input === undefined)
|
|
33
|
+
return typed({ failed: true, stopped: true, why: "no terminal", out: [], err: [detail("it talks with a person, and this client gives it no keys")] });
|
|
34
|
+
// A quiet step's stderr waits until it is done, so it cannot tear through a spinner.
|
|
35
|
+
const quiet = stdout === "discard";
|
|
36
|
+
const exit = await spawned(talks ? inPty(argv.value, io.size) : argv.value, {
|
|
37
|
+
stdout: typeof stdout === "string" ? stdout : "capture",
|
|
38
|
+
stderr: quiet ? "capture" : "show",
|
|
39
|
+
...(talks && io.input !== undefined ? { stdin: { kind: "typed", input: io.input } } : met.stdin === undefined ? {} : { stdin: met.stdin }),
|
|
40
|
+
}, { ...step.env, ...met.env }, io);
|
|
41
|
+
if (!exit.started)
|
|
42
|
+
return typed({ failed: true, stopped: true, why: "not started", out: [], err: [detail(`${argv.value[0]}: ${exit.stderr}`)] });
|
|
43
|
+
// Whatever it answered is shown, even when it failed: it may say why.
|
|
44
|
+
const out = typeof stdout === "string" ? [] : (io.draw ?? asItCame)(stdout, exit.stdout);
|
|
45
|
+
if (exit.code === 0)
|
|
46
|
+
return typed({ ...goOn, out, err: lines(exit.stderr).map(aside) });
|
|
47
|
+
return typed({ failed: true, stopped: true, why: `exit ${String(exit.code)}`, out, err: lines(exit.stderr).map(detail) });
|
|
48
|
+
};
|
|
49
|
+
const perform = async (step, io, met) => {
|
|
50
|
+
switch (step.kind) {
|
|
51
|
+
case "session":
|
|
52
|
+
case "run":
|
|
53
|
+
return runStep(step, io, met);
|
|
54
|
+
case "check":
|
|
55
|
+
return check(step, io);
|
|
56
|
+
case "confirm": {
|
|
57
|
+
io.err("");
|
|
58
|
+
io.err([" ", bad("▲"), " ", strong(step.warning)]);
|
|
59
|
+
const answered = await ask(io, { kind: "confirm", text: [" Type ", strong(step.expect), " to confirm: "], expect: step.expect });
|
|
60
|
+
return answered === step.expect ? goOn : typed({ failed: false, stopped: true, out: ["Aborted."], err: [] });
|
|
61
|
+
}
|
|
62
|
+
case "note":
|
|
63
|
+
return typed({ ...goOn, out: [step.text] });
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Runs a plan step by step, until it ends or a step stops it, shown by `progress`.
|
|
68
|
+
* True if nothing failed and the operator did not interrupt it.
|
|
69
|
+
*/
|
|
70
|
+
export const interpret = async (plan, io, progress = silent, interrupted = () => false) => {
|
|
71
|
+
const made = scratch();
|
|
72
|
+
try {
|
|
73
|
+
const ended = await progress.plan(plan, () => plan.reduce(async (previous, step, index) => {
|
|
74
|
+
const so = await previous;
|
|
75
|
+
if (so.stop !== undefined)
|
|
76
|
+
return so;
|
|
77
|
+
if (interrupted() || isStopped(io.signal))
|
|
78
|
+
return { ...so, stop: { index, step, why: "interrupted" } };
|
|
79
|
+
// What a step needs is asked before its frame opens: a prompt, then the step.
|
|
80
|
+
const met = (step.kind === "run" || step.kind === "session") && step.needs !== undefined ? await meet(step.needs, so.asked, io, made) : { met: { env: {} }, asked: so.asked };
|
|
81
|
+
if (met === undefined) {
|
|
82
|
+
io.err([" ", muted("Nothing given: stopped before it ran.")]);
|
|
83
|
+
return { ...so, stop: { index, step, why: isStopped(io.signal) ? "interrupted" : "declined" } };
|
|
84
|
+
}
|
|
85
|
+
const done = await progress.step(step, position(plan, index), () => perform(step, io, met.met));
|
|
86
|
+
// Ctrl-C reached the step's program too: how it ended says nothing about the server.
|
|
87
|
+
if (interrupted() || isStopped(io.signal))
|
|
88
|
+
return { failures: so.failures, asked: met.asked, stop: { index, step, why: "interrupted" } };
|
|
89
|
+
done.out.forEach(io.out);
|
|
90
|
+
done.err.forEach(io.err);
|
|
91
|
+
const failures = so.failures + (done.failed ? 1 : 0);
|
|
92
|
+
if (done.stopped)
|
|
93
|
+
return { failures, asked: met.asked, stop: { index, step, why: done.failed ? "failed" : "declined" } };
|
|
94
|
+
return { failures, asked: met.asked };
|
|
95
|
+
}, Promise.resolve({ failures: 0, asked: {} })));
|
|
96
|
+
return ended.failures === 0 && ended.stop?.why !== "interrupted";
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
made.clean();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { active, muted, strong } from "../text/spans.js";
|
|
5
|
+
import { ask } from "./io.js";
|
|
6
|
+
import { spawned } from "./process.js";
|
|
7
|
+
import { typed } from "../../lib/typed.js";
|
|
8
|
+
const keyOf = (need) => (need.kind === "vault" ? `vault:${need.server}` : "sudo");
|
|
9
|
+
const questionOf = (need) => typed(need.kind === "vault" ? { kind: "secret", text: [" ", active("?"), " ", strong(`${need.server}'s vault password`), muted(" (asked once, kept for this run): ")] } : { kind: "secret", text: [" ", active("?"), " ", strong("sudo's password"), muted(" (for this step only): ")] });
|
|
10
|
+
/** Whether sudo would run without a password: a cached one, or none needed. */
|
|
11
|
+
const sudoReady = async (plumbing) => (await spawned(["sudo", "-n", "true"], { stdout: "discard", stderr: "capture", stdin: { kind: "none" } }, {}, plumbing)).code === 0;
|
|
12
|
+
export const scratch = () => {
|
|
13
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- made on first need, removed when the run ends
|
|
14
|
+
const made = {};
|
|
15
|
+
const dir = () => {
|
|
16
|
+
// eslint-disable-next-line functional/immutable-data -- see above
|
|
17
|
+
made.dir ??= mkdtempSync(join(tmpdir(), "kayra-"));
|
|
18
|
+
return made.dir;
|
|
19
|
+
};
|
|
20
|
+
return typed({
|
|
21
|
+
vaultScript: () => {
|
|
22
|
+
const script = join(dir(), "vault-password");
|
|
23
|
+
writeFileSync(script, '#!/bin/sh\nprintf \'%s\\n\' "$KAYRA_VAULT_PASSWORD"\n', { mode: 0o700 });
|
|
24
|
+
chmodSync(script, 0o700);
|
|
25
|
+
return script;
|
|
26
|
+
},
|
|
27
|
+
clean: () => {
|
|
28
|
+
if (made.dir !== undefined)
|
|
29
|
+
rmSync(made.dir, { recursive: true, force: true });
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
/** Asks what a step needs and has not been given yet in this run; undefined if the operator gave nothing. */
|
|
34
|
+
export const meet = async (needs, asked, io, made) => needs.reduce(async (previous, need) => {
|
|
35
|
+
const so = await previous;
|
|
36
|
+
if (so === undefined)
|
|
37
|
+
return undefined;
|
|
38
|
+
if (need.kind === "sudo" && (await sudoReady(io)))
|
|
39
|
+
return so;
|
|
40
|
+
const key = keyOf(need);
|
|
41
|
+
const given = so.asked[key] ?? (await ask(io, questionOf(need)));
|
|
42
|
+
// An empty password is none: Enter alone declines.
|
|
43
|
+
if (given === undefined || given === "")
|
|
44
|
+
return undefined;
|
|
45
|
+
const now = need.kind === "vault" ? { ...so.asked, [key]: given } : so.asked;
|
|
46
|
+
return typed(need.kind === "vault" ? { asked: now, met: { ...so.met, env: { ...so.met.env, ANSIBLE_VAULT_PASSWORD_FILE: made.vaultScript(), KAYRA_VAULT_PASSWORD: given } } } : { asked: now, met: { env: { ...so.met.env, KAYRA_SUDO_STDIN: "1" }, stdin: { kind: "given", text: `${given}\n` } } });
|
|
47
|
+
}, Promise.resolve({ met: { env: {} }, asked }));
|