@yunuseon/kayra 0.17.0 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/agent/skills/kayra-release/SKILL.md +6 -1
  2. package/ansible/roles/platform/tasks/main.yml +40 -1
  3. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  4. package/cli/dist/browser/index.html +1 -1
  5. package/cli/dist/clients/api/api.js +138 -218
  6. package/cli/dist/clients/api/auth.js +8 -7
  7. package/cli/dist/clients/api/commands.js +50 -14
  8. package/cli/dist/clients/api/contract.js +8 -6
  9. package/cli/dist/clients/api/directories.js +1 -1
  10. package/cli/dist/clients/api/discovery.js +8 -3
  11. package/cli/dist/clients/api/live.js +40 -0
  12. package/cli/dist/clients/api/protocol.js +17 -10
  13. package/cli/dist/clients/api/queries.js +4 -4
  14. package/cli/dist/clients/api/runs.js +10 -9
  15. package/cli/dist/clients/api/start.js +97 -0
  16. package/cli/dist/clients/api/status.js +29 -0
  17. package/cli/dist/clients/api/validate.js +13 -0
  18. package/cli/dist/clients/cli/explain.js +12 -10
  19. package/cli/dist/clients/cli/framed.js +12 -9
  20. package/cli/dist/clients/cli/invocation.js +4 -3
  21. package/cli/dist/clients/cli/paint.js +1 -1
  22. package/cli/dist/clients/cli/parser.js +8 -8
  23. package/cli/dist/clients/cli/questions.js +11 -10
  24. package/cli/dist/clients/cli/status.js +75 -0
  25. package/cli/dist/clients/cli/terminal.js +4 -2
  26. package/cli/dist/{core/present → clients/cli}/text.js +15 -24
  27. package/cli/dist/clients/cli/validate.js +32 -0
  28. package/cli/dist/clients/cli/values.js +19 -0
  29. package/cli/dist/{core/present → clients/cli}/views.js +28 -60
  30. package/cli/dist/core/adapters/fs.js +18 -0
  31. package/cli/dist/core/{net.js → adapters/network.js} +20 -5
  32. package/cli/dist/core/adapters/opentofu.js +24 -0
  33. package/cli/dist/core/ctl/answers.js +32 -0
  34. package/cli/dist/core/fleet/brand.js +54 -0
  35. package/cli/dist/core/{schemas.js → fleet/docs.js} +5 -4
  36. package/cli/dist/core/fleet/load.js +45 -0
  37. package/cli/dist/core/fleet/model.js +1 -0
  38. package/cli/dist/core/fleet/parse.js +144 -0
  39. package/cli/dist/core/{settings.js → fleet/settings.js} +47 -15
  40. package/cli/dist/core/{validate.js → fleet/shape.js} +6 -20
  41. package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
  42. package/cli/dist/core/interpreter/io.js +18 -0
  43. package/cli/dist/core/interpreter/loop.js +101 -0
  44. package/cli/dist/core/interpreter/needs.js +47 -0
  45. package/cli/dist/core/interpreter/process.js +107 -0
  46. package/cli/dist/core/interpreter/progress.js +15 -0
  47. package/cli/dist/core/interpreter/pty.js +8 -0
  48. package/cli/dist/core/operations/catalog.js +35 -18
  49. package/cli/dist/core/operations/{run.js → dispatch.js} +50 -47
  50. package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
  51. package/cli/dist/core/plan/model.js +14 -0
  52. package/cli/dist/core/recipes/app-check.js +27 -0
  53. package/cli/dist/core/recipes/apps.js +63 -0
  54. package/cli/dist/core/recipes/backup.js +34 -0
  55. package/cli/dist/core/recipes/certs.js +4 -0
  56. package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
  57. package/cli/dist/core/recipes/host.js +104 -0
  58. package/cli/dist/core/recipes/ssh.js +20 -0
  59. package/cli/dist/core/recipes/steps.js +82 -0
  60. package/cli/dist/core/status/look.js +55 -0
  61. package/cli/dist/core/status/model.js +6 -0
  62. package/cli/dist/core/status/ports.js +1 -0
  63. package/cli/dist/core/text/plural.js +2 -0
  64. package/cli/dist/core/text/spans.js +22 -0
  65. package/cli/dist/core/text/time.js +12 -0
  66. package/cli/dist/core/validation/facts.js +50 -0
  67. package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
  68. package/cli/dist/deployer/app.js +3 -2
  69. package/cli/dist/deployer/brand.js +1 -1
  70. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  71. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  72. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  73. package/cli/dist/deployer/cron.js +3 -3
  74. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  75. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  76. package/cli/dist/deployer/deployer.js +24 -23
  77. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  78. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  79. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  80. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  81. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  82. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  83. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  84. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  85. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  86. package/cli/dist/deployer/main.js +2 -2
  87. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  88. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  89. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  90. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  91. package/cli/dist/lib/brand.js +2 -0
  92. package/cli/dist/lib/closest.js +17 -0
  93. package/cli/dist/lib/result.js +15 -0
  94. package/cli/dist/lib/schema.js +7 -0
  95. package/cli/dist/lib/typed.js +2 -0
  96. package/cli/dist/lib/yaml.js +21 -0
  97. package/cli/dist/main.js +89 -89
  98. package/cli/dist/serve.js +2 -2
  99. package/package.json +3 -2
  100. package/schema/app.json +4 -2
  101. package/schema/server.json +10 -5
  102. package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
  103. package/cli/dist/core/brand.js +0 -39
  104. package/cli/dist/core/commands/app-check.js +0 -35
  105. package/cli/dist/core/commands/server.js +0 -298
  106. package/cli/dist/core/commands/status.js +0 -194
  107. package/cli/dist/core/fleet.js +0 -156
  108. package/cli/dist/core/gather.js +0 -61
  109. package/cli/dist/core/interpret.js +0 -276
  110. package/cli/dist/core/load.js +0 -64
  111. package/cli/dist/core/present/line.js +0 -17
  112. package/cli/dist/result.js +0 -5
  113. /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
@@ -1,28 +1,29 @@
1
1
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
2
  import { createServer } from "node:http";
3
3
  import { join } from "node:path";
4
- import { err, ok } from "../result.js";
5
- import { field, registered } from "./app.js";
6
- import { owner, runId, sha } from "./brand.js";
7
- import { body, json, send } from "./http.js";
8
- import { page, runPage } from "./page.js";
9
- import { spawnLines } from "./process.js";
10
- import { forgeRepo, signed } from "./forge.js";
11
- import { pushedRef } from "./webhook.js";
4
+ import { err, ok } from "../../lib/result.js";
5
+ import { field, registered } from "../app.js";
6
+ import { owner, runId, sha } from "../brand.js";
7
+ import { body, json, send } from "../http/http.js";
8
+ import { page, runPage } from "../http/page.js";
9
+ import { spawnLines } from "../process.js";
10
+ import { forgeRepo, signed } from "../forges/forge.js";
11
+ import { pushedRef } from "../http/webhook.js";
12
+ import { typed } from "../../lib/typed.js";
12
13
  const fromFile = (path) => () => (existsSync(path) ? readFileSync(path, "utf8").trim() : "");
13
14
  const settings = (env) => {
14
15
  const platformDir = env["PLATFORM_DIR"] ?? "/opt/platform";
15
- return {
16
+ return typed({
16
17
  platformDir,
17
18
  work: env["WORK_DIR"] ?? "/work",
18
19
  deployer: env["DEPLOYER_URL"] ?? "http://deployer:8090",
19
20
  resolveImages: env["RESOLVE_IMAGES"] ?? "/opt/kayra/scripts/platform/resolve-images.sh",
20
21
  webhookSecret: () => env["WEBHOOK_SECRET"] ?? "",
21
22
  gitToken: fromFile("/run/platform-secrets/GIT_TOKEN"),
22
- };
23
+ });
23
24
  };
24
25
  /** git with the platform's token as a header: neither in the clone's config nor in the process list. */
25
- const gitEnv = (token) => ({
26
+ const gitEnv = (token) => typed({
26
27
  GIT_TERMINAL_PROMPT: "0",
27
28
  GIT_CONFIG_COUNT: "1",
28
29
  GIT_CONFIG_KEY_0: "http.extraHeader",
@@ -38,7 +39,7 @@ export const resolveRef = async (app, ref, token) => {
38
39
  return err(`git ls-remote ${app.repo} failed (exit ${String(exit.code)})`);
39
40
  const refs = new Map(exit.stdout.split("\n").flatMap((line) => {
40
41
  const [commit, name] = line.split("\t");
41
- return commit === undefined || name === undefined ? [] : [[name, commit]];
42
+ return typed(commit === undefined || name === undefined ? [] : [[name, commit]]);
42
43
  }));
43
44
  const found = refs.get(`refs/tags/${ref}^{}`) ?? refs.get(`refs/heads/${ref}`) ?? refs.get(`refs/tags/${ref}`);
44
45
  return found === undefined ? err(`${ref} is no branch or tag of ${app.repo}`) : sha(found);
@@ -83,7 +84,7 @@ export const prepare = async (app, commit, s, line) => {
83
84
  const artifacts = planned.value
84
85
  .split("\n")
85
86
  .filter((row) => row !== "")
86
- .map((row) => row.split("\t"));
87
+ .map((row) => Object.freeze(row.split("\t")));
87
88
  const built = await sequence(artifacts.map(([name]) => () => {
88
89
  line(`── Image ${name ?? "?"}`);
89
90
  return run(["bash", s.resolveImages, app.name, root, "--ensure", name ?? ""], { env: buildEnv }, line);
@@ -1,6 +1,7 @@
1
- import { err, ok } from "../result.js";
2
- import { field } from "./app.js";
3
- import { sha } from "./brand.js";
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { field } from "../app.js";
3
+ import { sha } from "../brand.js";
4
+ import { typed } from "../../lib/typed.js";
4
5
  const relative = (path) => path !== "" && !path.startsWith("/") && !path.split("/").some((segment) => segment === ".." || segment === "");
5
6
  export const parseBundle = (app, expected, json) => {
6
7
  if (typeof json !== "object" || json === null)
@@ -16,25 +17,25 @@ export const parseBundle = (app, expected, json) => {
16
17
  const own = new RegExp(`^localhost:5000/${app}/[a-z0-9._/-]+:[0-9a-f]{12}$`);
17
18
  const parsedImages = images.map((image) => {
18
19
  if (typeof image !== "object" || image === null)
19
- return "an image is not an object";
20
+ return typed("an image is not an object");
20
21
  const variable = field(image, "variable");
21
22
  const ref = field(image, "ref");
22
23
  if (typeof variable !== "string" || !/^[A-Z][A-Z0-9_]*_IMAGE$/.test(variable))
23
24
  return `image variable ${String(variable)}`;
24
25
  if (typeof ref !== "string" || !own.test(ref))
25
26
  return `image ${String(ref)} is outside ${app}/`;
26
- return { variable, ref };
27
+ return typed({ variable, ref });
27
28
  });
28
29
  const parsedCompose = compose.map((file) => {
29
30
  if (typeof file !== "object" || file === null)
30
- return "a compose file is not an object";
31
+ return typed("a compose file is not an object");
31
32
  const path = field(file, "path");
32
33
  const content = field(file, "content");
33
34
  if (typeof path !== "string" || !relative(path))
34
35
  return `compose file ${String(path)}`;
35
36
  if (typeof content !== "string")
36
37
  return `compose file ${path} has no content`;
37
- return { path, content };
38
+ return typed({ path, content });
38
39
  });
39
40
  const problem = [...parsedImages, ...parsedCompose].find((item) => typeof item === "string");
40
41
  if (problem !== undefined)
@@ -1,3 +1,4 @@
1
+ import { typed } from "../../lib/typed.js";
1
2
  /**
2
3
  * The app's compose project, run in the run's directory: its .env from the
3
4
  * platform (operator config), the image refs from this run, the compose files
@@ -6,21 +7,21 @@
6
7
  */
7
8
  const project = (app, appsDir, bundle) => {
8
9
  const dir = `${appsDir}/${app.name}`;
9
- return [
10
+ return typed([
10
11
  "compose", "-p", app.name, "--project-directory", dir, "--env-file", `${dir}/.env`, "--env-file", "images.env",
11
12
  ...bundle.compose.flatMap((file) => ["-f", file.path]),
12
- ];
13
+ ]);
13
14
  };
14
15
  /**
15
16
  * What admission checks. --no-env-resolution: otherwise compose reads every
16
17
  * env_file here, from any path (another app's secrets included), and bakes it
17
18
  * into the config; unresolved, the allow-list sees env_file and refuses it.
18
19
  */
19
- export const config = (app, appsDir, bundle) => [
20
+ export const config = (app, appsDir, bundle) => typed([
20
21
  "docker", ...project(app, appsDir, bundle), "config", "--no-env-resolution", "--format", "json",
21
- ];
22
- export const policy = (app, script) => ["bash", script, app.name, ...app.hosts];
22
+ ]);
23
+ export const policy = (app, script) => typed(["bash", script, app.name, ...app.hosts]);
23
24
  /** --remove-orphans: a service the app dropped from its compose files must not keep running. */
24
- export const up = (app, appsDir, bundle) => [
25
+ export const up = (app, appsDir, bundle) => typed([
25
26
  "docker", ...project(app, appsDir, bundle), "up", "-d", "--wait", "--wait-timeout", "180", "--remove-orphans",
26
- ];
27
+ ]);
@@ -1,5 +1,5 @@
1
- import { all, err, map, ok } from "../result.js";
2
- const range = (from, to, step) => Array.from({ length: Math.floor((to - from) / step) + 1 }, (_, i) => from + i * step);
1
+ import { all, err, map, ok } from "../lib/result.js";
2
+ const range = (from, to, step) => Object.freeze(Array.from({ length: Math.floor((to - from) / step) + 1 }, (_, i) => from + i * step));
3
3
  const part = (text, min, max) => {
4
4
  const match = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(text);
5
5
  if (match === null)
@@ -10,7 +10,7 @@ const part = (text, min, max) => {
10
10
  const to = whole === "*" ? max : high === undefined ? (every === undefined ? from : max) : Number(high);
11
11
  return from < min || to > max || from > to || step < 1 ? err(`'${text}' (${String(min)}-${String(max)})`) : ok(range(from, to, step));
12
12
  };
13
- const values = (text, min, max) => map(all(text.split(",").map((piece) => part(piece, min, max))), (parts) => new Set(parts.flat()));
13
+ const values = (text, min, max) => map(all(text.split(",").map((piece) => part(piece, min, max))), (parts) => Object.freeze(new Set(parts.flat())));
14
14
  export const parseCron = (spec) => {
15
15
  const fields = spec.trim().split(/\s+/);
16
16
  const [minute, hour, day, month, weekday] = fields;
@@ -1,7 +1,8 @@
1
+ import { typed } from "../../lib/typed.js";
1
2
  /** A release record's compact UTC time, 20261018T101500Z, as ISO 8601. */
2
3
  const iso = (compact) => compact.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, "$1-$2-$3T$4:$5:$6Z");
3
- const deployed = (release) => ({ sha: release.sha, time: iso(release.time) });
4
- const answer = (run) => ({
4
+ const deployed = (release) => typed({ sha: release.sha, time: iso(release.time) });
5
+ const answer = (run) => typed({
5
6
  id: run.id,
6
7
  state: run.state,
7
8
  why: run.why,
@@ -10,12 +11,12 @@ const answer = (run) => ({
10
11
  started: run.started,
11
12
  ...(run.finished === undefined ? {} : { finished: run.finished }),
12
13
  });
13
- export const runsAnswer = (app, runs, live) => ({
14
+ export const runsAnswer = (app, runs, live) => typed({
14
15
  app,
15
16
  ...(live === undefined ? {} : { live: deployed(live) }),
16
17
  runs: runs.map(answer),
17
18
  });
18
- export const releasesAnswer = (app, releases) => ({
19
+ export const releasesAnswer = (app, releases) => typed({
19
20
  app,
20
21
  releases: releases.map((release, index) => ({ ...deployed(release), live: index === 0 })),
21
22
  });
@@ -1,9 +1,9 @@
1
1
  import { existsSync, readdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { releasesAnswer, runsAnswer } from "./answers.js";
4
- import { appOwner, appName, owner as mintOwner, runId } from "./brand.js";
5
- import { releases } from "./records.js";
6
- import { log, runsOf } from "./store.js";
4
+ import { appOwner, appName, owner as mintOwner, runId } from "../brand.js";
5
+ import { releases } from "../runs/records.js";
6
+ import { log, runsOf } from "../runs/store.js";
7
7
  /**
8
8
  * The operator's side, run inside the deployer container by `kayra app …` and
9
9
  * `kayra job …` over SSH. Reads runs/ and releases/ directly; anything that
@@ -5,19 +5,20 @@ import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline";
7
7
  import { Readable } from "node:stream";
8
- import { all, err, ok } from "../result.js";
8
+ import { all, err, ok } from "../lib/result.js";
9
9
  import { field, registered } from "./app.js";
10
10
  import { appName, appOwner, jobOwner, newRunId, sha } from "./brand.js";
11
11
  import { matches, parseCron } from "./cron.js";
12
- import { forge, forgeRepo } from "./forge.js";
13
- import { json, send } from "./http.js";
12
+ import { forge, forgeRepo } from "./forges/forge.js";
13
+ import { json, send } from "./http/http.js";
14
14
  import { spawnLines } from "./process.js";
15
- import { empty, enqueue, finish } from "./queue.js";
16
- import { expired, moved, releaseName, releases } from "./records.js";
17
- import { githubIssues } from "./github-issues.js";
18
- import { decide, parseNotify, silent } from "./notify.js";
19
- import { deploy, renovate } from "./run.js";
20
- import { runsOf } from "./store.js";
15
+ import { empty, enqueue, finish } from "./runs/queue.js";
16
+ import { expired, moved, releaseName, releases } from "./runs/records.js";
17
+ import { githubIssues } from "./forges/issues.js";
18
+ import { decide, parseNotify, silent } from "./forges/notify.js";
19
+ import { deploy, renovate } from "./runs/run.js";
20
+ import { runsOf } from "./runs/store.js";
21
+ import { typed } from "../lib/typed.js";
21
22
  const token = (name) => {
22
23
  const path = `/run/platform-secrets/${name}`;
23
24
  return existsSync(path) ? readFileSync(path, "utf8").trim() : "";
@@ -29,8 +30,8 @@ const must = (result) => {
29
30
  };
30
31
  const settings = (env) => {
31
32
  const scripts = env["PLATFORM_SCRIPTS"] ?? "/opt/kayra/scripts/platform";
32
- const strings = Object.fromEntries(Object.entries(env).flatMap(([key, value]) => (value === undefined ? [] : [[key, value]])));
33
- return {
33
+ const strings = Object.fromEntries(Object.entries(env).flatMap(([key, value]) => typed(value === undefined ? [] : [[key, value]])));
34
+ return typed({
34
35
  platformDir: env["PLATFORM_DIR"] ?? "/opt/platform",
35
36
  appsDir: env["APPS_DIR"] ?? "/opt/apps",
36
37
  builder: env["BUILDER_URL"] ?? "http://builder:8081",
@@ -44,7 +45,7 @@ const settings = (env) => {
44
45
  env: strings,
45
46
  server: env["SERVER"] ?? env["DOMAIN"] ?? "this server",
46
47
  notifier: notifierFor(must(parseNotify(env["NOTIFIER"])), env["PLATFORM_DIR"] ?? "/opt/platform"),
47
- };
48
+ });
48
49
  };
49
50
  /** The configured notifier; its open alerts are kept in <platformDir>/alerts/<key>. */
50
51
  const notifierFor = (config, platformDir) => {
@@ -88,11 +89,11 @@ const runsDir = (s) => join(s.platformDir, "runs");
88
89
  const keepRuns = 50;
89
90
  const registeredApps = (s) => {
90
91
  const dir = join(s.platformDir, "apps");
91
- return (existsSync(dir) ? readdirSync(dir) : []).flatMap((file) => {
92
+ return Object.freeze((existsSync(dir) ? readdirSync(dir) : []).flatMap((file) => {
92
93
  const name = /^(.+)\.json$/.exec(file)?.[1];
93
94
  const app = name === undefined ? undefined : registered(s.platformDir, name);
94
- return app?.ok === true ? [app.value] : [];
95
- });
95
+ return app?.ok === true ? Object.freeze([app.value]) : Object.freeze([]);
96
+ }));
96
97
  };
97
98
  const builderResolve = async (s, app, ref) => {
98
99
  const response = await fetch(`${s.builder}/resolve`, { method: "POST", body: JSON.stringify({ app: app.name, ref }) }).catch(() => undefined);
@@ -139,7 +140,7 @@ const appSecrets = (app) => {
139
140
  return read.ok ? ok(Object.fromEntries(read.value)) : read;
140
141
  };
141
142
  const target = (s, who, id) => `https://deploy.${s.domain}/runs/${who}/${id}`;
142
- const effects = (s, who, id, log) => ({
143
+ const effects = (s, who, id, log) => typed({
143
144
  log,
144
145
  resolve: (app, ref) => builderResolve(s, app, ref),
145
146
  prepare: (app, commit) => builderPrepare(s, app, commit, log),
@@ -172,21 +173,21 @@ const effects = (s, who, id, log) => ({
172
173
  },
173
174
  });
174
175
  const describe = (request) => request.work.kind === "deploy"
175
- ? { what: `deploy ${request.work.ref}`, why: request.work.why }
176
- : { what: `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`, why: "schedule" };
176
+ ? typed({ what: `deploy ${request.work.ref}`, why: request.work.why })
177
+ : typed({ what: `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`, why: "schedule" });
177
178
  const work = async (s, request, fx) => {
178
179
  if (request.work.kind === "deploy") {
179
180
  const app = registered(s.platformDir, request.work.app);
180
181
  if (!app.ok) {
181
182
  fx.log(app.error);
182
- return { ok: false };
183
+ return typed({ ok: false });
183
184
  }
184
185
  return deploy(app.value, request.work.ref, { appsDir: s.appsDir, policyScript: s.policyScript }, fx);
185
186
  }
186
187
  const argv = request.work.job === "gc" ? ["bash", s.gcScript] : renovate(s.env, request.work.dryRun, s.renovateImage);
187
188
  const env = request.work.job === "renovate" ? { RENOVATE_TOKEN: token("RENOVATE_TOKEN") } : {};
188
189
  const exit = await fx.exec(argv, { cwd: s.platformDir, env });
189
- return { ok: exit.code === 0 };
190
+ return typed({ ok: exit.code === 0 });
190
191
  };
191
192
  /** The daemon's one mutable cell: the queue, swapped whole on every change. */
192
193
  // eslint-disable-next-line functional/prefer-immutable-types -- the daemon's state lives here, nowhere else
@@ -213,7 +214,7 @@ const start = async (s, request) => {
213
214
  };
214
215
  const outcome = await work(s, request, effects(s, request.owner, id, log)).catch((error) => {
215
216
  log(`deployer: ${String(error)}`);
216
- return { ok: false };
217
+ return typed({ ok: false });
217
218
  });
218
219
  const ended = {
219
220
  ...begun,
@@ -233,11 +234,11 @@ const start = async (s, request) => {
233
234
  });
234
235
  swap(s, (queue) => finish(queue, request.owner));
235
236
  };
236
- const deployRequest = (app, ref, why) => ({
237
+ const deployRequest = (app, ref, why) => typed({
237
238
  owner: appOwner(app.name),
238
239
  work: { kind: "deploy", app: app.name, ref, why },
239
240
  });
240
- const jobRequest = (job, dryRun) => ({ owner: jobOwner(job), work: { kind: "job", job, dryRun } });
241
+ const jobRequest = (job, dryRun) => typed({ owner: jobOwner(job), work: { kind: "job", job, dryRun } });
241
242
  /** The webhook's fallback: an app whose ref moved to a commit no run has tried yet and no release runs (one migrated from Jenkins has releases but no runs). */
242
243
  const poll = async (s) => {
243
244
  await Promise.all(registeredApps(s).map(async (app) => {
@@ -1,6 +1,7 @@
1
1
  import { forgejo } from "./forgejo.js";
2
2
  import { github } from "./github.js";
3
3
  import { gitlab } from "./gitlab.js";
4
+ import { typed } from "../../lib/typed.js";
4
5
  const adapters = { github, forgejo, gitlab };
5
6
  const kinds = { "https://github.com": "github", "https://gitlab.com": "gitlab" };
6
7
  /** GitHub for https://github.com, GitLab for https://gitlab.com, a Forgejo for any other host; undefined for a URL none understands. */
@@ -11,7 +12,7 @@ export const forgeRepo = (repo) => {
11
12
  const [, origin, owner, name] = match;
12
13
  if (origin === undefined || owner === undefined || name === undefined)
13
14
  return undefined;
14
- return { kind: kinds[origin] ?? "forgejo", origin, owner, name };
15
+ return typed({ kind: kinds[origin] ?? "forgejo", origin, owner, name });
15
16
  };
16
17
  export const forge = (repo, token, fetch) => adapters[repo.kind].api(repo, token, fetch);
17
18
  export const signed = (repo, secret, body, headers) => adapters[repo.kind].signed(secret, body, headers);
@@ -1,5 +1,5 @@
1
- import { err, ok } from "../result.js";
2
- import { header, hmacMatches } from "./webhook.js";
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { header, hmacMatches } from "../http/webhook.js";
3
3
  /** A Forgejo's API (Gitea's statuses endpoint); webhooks signed `X-Forgejo-Signature: <hex>` (or Gitea's, or GitHub's, which it sends too). */
4
4
  export const forgejo = {
5
5
  api: (repo, token, fetch) => ({
@@ -1,5 +1,5 @@
1
- import { err, ok } from "../result.js";
2
- import { header, hmacMatches } from "./webhook.js";
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { header, hmacMatches } from "../http/webhook.js";
3
3
  /** GitHub's REST API; webhooks signed `X-Hub-Signature-256: sha256=<hex>`. */
4
4
  export const github = {
5
5
  api: (repo, token, fetch) => ({
@@ -1,5 +1,5 @@
1
- import { err, ok } from "../result.js";
2
- import { header, secretMatches } from "./webhook.js";
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { header, secretMatches } from "../http/webhook.js";
3
3
  /** GitLab knows no "failure" or "error", only "failed". */
4
4
  const states = { pending: "pending", success: "success", failure: "failed", error: "failed" };
5
5
  /**
@@ -1,6 +1,7 @@
1
1
  import { createSign } from "node:crypto";
2
- import { err, ok } from "../result.js";
3
- import { field } from "./app.js";
2
+ import { err, ok } from "../../lib/result.js";
3
+ import { field } from "../app.js";
4
+ import { typed } from "../../lib/typed.js";
4
5
  const base64url = (data) => Buffer.from(data).toString("base64url");
5
6
  /** The app's own token: a JWT signed with its private key, valid nine minutes. */
6
7
  export const appJwt = (appId, privateKey, nowSeconds) => {
@@ -10,7 +11,7 @@ export const appJwt = (appId, privateKey, nowSeconds) => {
10
11
  return `${header}.${payload}.${base64url(signature)}`;
11
12
  };
12
13
  const api = "https://api.github.com";
13
- const headers = (token) => ({
14
+ const headers = (token) => typed({
14
15
  Authorization: `Bearer ${token}`,
15
16
  Accept: "application/vnd.github+json",
16
17
  "Content-Type": "application/json",
@@ -67,5 +68,5 @@ export const githubIssues = (repository, appId, world) => {
67
68
  world.remember(key, undefined);
68
69
  return ok(undefined);
69
70
  };
70
- return { raise, resolve };
71
+ return typed({ raise, resolve });
71
72
  };
@@ -1,5 +1,6 @@
1
- import { err, ok } from "../result.js";
2
- import { field } from "./app.js";
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { field } from "../app.js";
3
+ import { typed } from "../../lib/typed.js";
3
4
  export const silent = {
4
5
  raise: () => Promise.resolve(ok(undefined)),
5
6
  resolve: () => Promise.resolve(ok(undefined)),
@@ -37,25 +38,25 @@ export const decide = (end) => {
37
38
  const key = request.owner;
38
39
  const commit = end.sha === undefined ? "" : ` at ${end.sha.slice(0, 12)}`;
39
40
  if (end.ok)
40
- return { kind: "resolve", key, note: `Recovered: ${end.page}` };
41
+ return typed({ kind: "resolve", key, note: `Recovered: ${end.page}` });
41
42
  if (request.work.kind === "deploy") {
42
43
  if (request.work.why !== "push" && request.work.why !== "poll")
43
- return { kind: "none" };
44
- return {
44
+ return typed({ kind: "none" });
45
+ return typed({
45
46
  kind: "raise",
46
47
  alert: {
47
48
  key,
48
49
  title: `${server}: ${request.work.app} did not deploy${commit}`,
49
50
  body: `${request.work.app}'s ${request.work.ref} failed to build or deploy on ${server}${commit}, after a ${request.work.why}.\n\nThe run: ${end.page}\n\nIt stays open until a deploy of ${request.work.app} on ${server} succeeds.`,
50
51
  },
51
- };
52
+ });
52
53
  }
53
- return {
54
+ return typed({
54
55
  kind: "raise",
55
56
  alert: {
56
57
  key,
57
58
  title: `${server}: the ${request.work.job} job failed`,
58
59
  body: `The platform's ${request.work.job} job failed on ${server}.\n\nThe run: ${end.page}\n\nIt stays open until the job succeeds on ${server}.`,
59
60
  },
60
- };
61
+ });
61
62
  };
@@ -1,5 +1,6 @@
1
1
  /** The request body, refused past `limit` bytes. */
2
2
  export const body = async (request, limit = 1 << 20) => {
3
+ // eslint-disable-next-line functional/prefer-immutable-types -- Node's Buffer: bytes, never changed here
3
4
  const chunks = await Array.fromAsync(request, (chunk) => chunk);
4
5
  const all = Buffer.concat(chunks);
5
6
  return all.length > limit ? undefined : all;
@@ -1,4 +1,4 @@
1
- import { log, meta, owners, runsOf } from "./store.js";
1
+ import { log, meta, owners, runsOf } from "../runs/store.js";
2
2
  /** The read-only runs pages at deploy.<domain>, behind Authelia: what Jenkins' job pages were for. */
3
3
  const escape = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
4
4
  const shell = (title, content) => `<!doctype html>
@@ -1,5 +1,5 @@
1
1
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
- import { field } from "./app.js";
2
+ import { field } from "../app.js";
3
3
  /** A header's single value; undefined when it is missing or repeated. */
4
4
  export const header = (headers, name) => {
5
5
  const value = headers[name];
@@ -16,6 +16,7 @@ export const hmacMatches = (secret, body, given) => {
16
16
  export const secretMatches = (secret, given) => {
17
17
  if (secret === "" || given === undefined)
18
18
  return false;
19
+ // eslint-disable-next-line functional/prefer-immutable-types -- Node's Buffer: bytes, never changed here
19
20
  const digest = (text) => createHash("sha256").update(text).digest();
20
21
  return timingSafeEqual(digest(secret), digest(given));
21
22
  };
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { serveBuilder } from "./builder.js";
3
- import { ctl } from "./ctl.js";
2
+ import { serveBuilder } from "./build/builder.js";
3
+ import { ctl } from "./ctl/ctl.js";
4
4
  import { serveDeployer } from "./deployer.js";
5
5
  /** One program, three roles: `builder`, `deployer` (the two daemons) and `ctl` (the operator, inside the deployer). */
6
6
  const [role, ...args] = process.argv.slice(2);
@@ -1,4 +1,5 @@
1
- export const empty = (limit) => ({ running: [], waiting: [], limit });
1
+ import { typed } from "../../lib/typed.js";
2
+ export const empty = (limit) => typed({ running: [], waiting: [], limit });
2
3
  const exclusive = (request) => request.work.kind === "job" && request.work.job === "gc";
3
4
  /** Starts what may start, in order; a waiting exclusive request holds back everything behind it. */
4
5
  const fill = (queue) => {
@@ -13,10 +14,10 @@ const fill = (queue) => {
13
14
  const free = so.running.length < queue.limit && !so.running.some((running) => running.owner === request.owner);
14
15
  return free ? { ...so, running: [...so.running, request], start: [...so.start, request] } : so;
15
16
  }, { running: queue.running, blocked: false, start: [] });
16
- return {
17
+ return typed({
17
18
  queue: { ...queue, running: pick.running, waiting: queue.waiting.filter((request) => !pick.start.includes(request)) },
18
19
  start: pick.start,
19
- };
20
+ });
20
21
  };
21
22
  export const enqueue = (queue, request) => {
22
23
  const waits = queue.waiting.some((waiting) => waiting.owner === request.owner);
@@ -1,17 +1,18 @@
1
- import { runId, sha } from "./brand.js";
2
- import { field } from "./app.js";
1
+ import { runId, sha } from "../brand.js";
2
+ import { field } from "../app.js";
3
+ import { typed } from "../../lib/typed.js";
3
4
  /** A release record's name: releases/<app>/<UTC time>-<sha>.env. registry-gc.sh reads the same files. */
4
5
  export const releaseName = (at, commit) => `${at.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${commit}.env`;
5
6
  /** Newest first, one per commit: the first is what runs now, the rest are what rollback offers. */
6
- export const releases = (names) => names
7
+ export const releases = (names) => Object.freeze(names
7
8
  .toSorted()
8
9
  .toReversed()
9
10
  .flatMap((name) => {
10
11
  const match = /^(\d{8}T\d{6}Z)-([0-9a-f]{40})\.env$/.exec(name);
11
12
  const commit = sha(match?.[2] ?? "");
12
- return match?.[1] === undefined || !commit.ok ? [] : [{ sha: commit.value, time: match[1] }];
13
+ return match?.[1] === undefined || !commit.ok ? Object.freeze([]) : Object.freeze([{ sha: commit.value, time: match[1] }]);
13
14
  })
14
- .filter((release, i, all) => all.findIndex((other) => other.sha === release.sha) === i);
15
+ .filter((release, i, all) => all.findIndex((other) => other.sha === release.sha) === i));
15
16
  /** The poll's question: has the ref moved to a commit neither the newest run tried nor the newest release runs? */
16
17
  export const moved = (resolved, lastRun, lastRelease) => resolved !== lastRun && resolved !== lastRelease;
17
18
  const whys = ["push", "poll", "deploy", "rollback", "schedule", "manual"];
@@ -33,7 +34,7 @@ export const parseMeta = (json) => {
33
34
  return undefined;
34
35
  if (!isWhy(why) || !isState(state))
35
36
  return undefined;
36
- return {
37
+ return typed({
37
38
  id: id.value,
38
39
  owner,
39
40
  what,
@@ -42,7 +43,7 @@ export const parseMeta = (json) => {
42
43
  started,
43
44
  ...(commit.ok ? { sha: commit.value } : {}),
44
45
  ...(typeof finished === "string" ? { finished } : {}),
45
- };
46
+ });
46
47
  };
47
48
  /** Run directories past the newest `keep`, oldest first: what retention deletes. */
48
- export const expired = (ids, keep) => ids.toSorted().slice(0, Math.max(0, ids.length - keep));
49
+ export const expired = (ids, keep) => Object.freeze(ids.toSorted().slice(0, Math.max(0, ids.length - keep)));
@@ -1,6 +1,7 @@
1
- import { err, ok } from "../result.js";
2
- import { imagesEnv, parseBundle } from "./bundle.js";
3
- import { config, policy, up } from "./compose.js";
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { imagesEnv, parseBundle } from "../build/bundle.js";
3
+ import { config, policy, up } from "../build/compose.js";
4
+ import { typed } from "../../lib/typed.js";
4
5
  const step = async (fx, label, argv, options) => {
5
6
  fx.log(`── ${label}`);
6
7
  const exit = await fx.exec(argv, options);
@@ -38,7 +39,7 @@ export const deploy = async (app, ref, paths, fx) => {
38
39
  const commit = await fx.resolve(app, ref);
39
40
  if (!commit.ok) {
40
41
  fx.log(commit.error);
41
- return { ok: false };
42
+ return typed({ ok: false });
42
43
  }
43
44
  const sha = commit.value;
44
45
  fx.log(`── ${ref} is ${sha}`);
@@ -48,7 +49,7 @@ export const deploy = async (app, ref, paths, fx) => {
48
49
  if (!bundle.ok) {
49
50
  fx.log(bundle.error);
50
51
  await fx.status(app, sha, "kayra/build", "failure", "Build failed");
51
- return { ok: false, sha };
52
+ return typed({ ok: false, sha });
52
53
  }
53
54
  await fx.status(app, sha, "kayra/build", "success", "Images built");
54
55
  await fx.status(app, sha, "kayra/deploy", "pending", "Deploying");
@@ -56,21 +57,21 @@ export const deploy = async (app, ref, paths, fx) => {
56
57
  if (!deployed.ok) {
57
58
  fx.log(deployed.error);
58
59
  await fx.status(app, sha, "kayra/deploy", "failure", deployed.error);
59
- return { ok: false, sha };
60
+ return typed({ ok: false, sha });
60
61
  }
61
62
  fx.log(`Deployed ${sha}`);
62
63
  await fx.status(app, sha, "kayra/deploy", "success", "Deployed");
63
- return { ok: true, sha };
64
+ return typed({ ok: true, sha });
64
65
  };
65
66
  /** Renovate's settings, as the platform's .env holds them; the optional ones only when set. */
66
67
  export const renovate = (env, dryRun, image) => {
67
68
  const optional = ["RENOVATE_ENDPOINT", "RENOVATE_GIT_URL", "RENOVATE_HOST_RULES", "RENOVATE_GITHUB_COM_TOKEN"]
68
69
  .filter((key) => (env[key] ?? "") !== "")
69
70
  .flatMap((key) => ["-e", key]);
70
- return [
71
+ return typed([
71
72
  "docker", "run", "--rm", "--network", "platform-internal",
72
73
  "-e", "RENOVATE_TOKEN", "-e", "RENOVATE_PLATFORM", ...optional, "-e", "RENOVATE_REPOSITORIES",
73
74
  "-e", `RENOVATE_DRY_RUN=${dryRun ? "full" : "null"}`, "-e", "LOG_LEVEL=info",
74
75
  image,
75
- ];
76
+ ]);
76
77
  };
@@ -1,13 +1,14 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { owner as mintOwner, runId } from "./brand.js";
3
+ import { owner as mintOwner, runId } from "../brand.js";
4
4
  import { parseMeta } from "./records.js";
5
+ import { typed } from "../../lib/typed.js";
5
6
  /** Reading runs/: <owner>/<id>/{meta.json,log}. Only the deployer writes there. */
6
- const entries = (dir) => (existsSync(dir) ? readdirSync(dir).toSorted() : []);
7
- export const owners = (runs) => entries(runs).flatMap((name) => {
7
+ const entries = (dir) => (existsSync(dir) ? readdirSync(dir).toSorted() : typed([]));
8
+ export const owners = (runs) => Object.freeze(entries(runs).flatMap((name) => {
8
9
  const minted = mintOwner(name);
9
- return minted.ok ? [minted.value] : [];
10
- });
10
+ return minted.ok ? Object.freeze([minted.value]) : Object.freeze([]);
11
+ }));
11
12
  export const meta = (runs, who, id) => {
12
13
  const path = join(runs, who, id, "meta.json");
13
14
  if (!existsSync(path))
@@ -20,11 +21,11 @@ export const meta = (runs, who, id) => {
20
21
  }
21
22
  };
22
23
  /** Newest first. */
23
- export const runsOf = (runs, who) => entries(join(runs, who)).toReversed().flatMap((name) => {
24
+ export const runsOf = (runs, who) => Object.freeze(entries(join(runs, who)).toReversed().flatMap((name) => {
24
25
  const id = runId(name);
25
26
  const found = id.ok ? meta(runs, who, id.value) : undefined;
26
- return found === undefined ? [] : [found];
27
- });
27
+ return found === undefined ? Object.freeze([]) : Object.freeze([found]);
28
+ }));
28
29
  export const log = (runs, who, id) => {
29
30
  const path = join(runs, who, id, "log");
30
31
  return existsSync(path) ? readFileSync(path, "utf8") : undefined;
@@ -0,0 +1,2 @@
1
+ /** For a schema's `.transform`: what passed it, branded B. The one place a brand is minted without a check of its own. */
2
+ export const branded = () => (value) => value;