@yunuseon/kayra 0.19.0 → 0.20.1

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 (146) hide show
  1. package/agent/skills/kayra-release/SKILL.md +1 -4
  2. package/agent/skills/kayra-rollout/SKILL.md +1 -4
  3. package/ansible/roles/app/tasks/main.yml +24 -0
  4. package/ansible/roles/platform/defaults/main.yml +3 -0
  5. package/ansible/roles/platform/tasks/main.yml +6 -86
  6. package/ansible/roles/platform/templates/platform.env.j2 +2 -0
  7. package/bin/kayra-app-hook.js +6 -0
  8. package/bin/kayra-app-init.js +6 -0
  9. package/bin/kayra-app-launch.js +6 -0
  10. package/bin/kayra-app-values.js +6 -0
  11. package/cli/dist/app-hook.js +75 -0
  12. package/cli/dist/app-init.js +65 -0
  13. package/cli/dist/app-launch.js +89 -0
  14. package/cli/dist/app-values.js +37 -0
  15. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-BTotfTJu.woff +0 -0
  16. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-DZqxrq2p.woff2 +0 -0
  17. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-71GNu3SW.woff2 +0 -0
  18. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-BGq0mW3O.woff +0 -0
  19. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-Dsrv2Tcn.woff +0 -0
  20. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-g30qAdWV.woff2 +0 -0
  21. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-Bz0x94Yp.woff +0 -0
  22. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-DUMzJB7m.woff2 +0 -0
  23. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-D9ESIMu3.woff +0 -0
  24. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-_efipK4i.woff2 +0 -0
  25. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-D-CqTdkO.woff +0 -0
  26. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-DzTrcv_p.woff2 +0 -0
  27. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
  28. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
  29. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
  30. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
  31. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-C5H60-Va.woff2 +0 -0
  32. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-RBey6euL.woff +0 -0
  33. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DIrixKbi.woff +0 -0
  34. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DOrvGEcy.woff2 +0 -0
  35. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-DG4YqDda.woff2 +0 -0
  36. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-fK1oJ5dG.woff +0 -0
  37. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DgdngZtN.woff +0 -0
  38. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DpPYBSTl.woff2 +0 -0
  39. package/cli/dist/browser/assets/index-DzIVPXyL.css +1 -0
  40. package/cli/dist/browser/assets/index-SP8bCDrl.js +7 -0
  41. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  42. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  43. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  44. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  45. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
  46. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  47. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
  48. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
  49. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  50. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  52. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  53. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
  55. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
  56. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
  57. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  58. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  59. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  60. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  61. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  62. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  63. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
  64. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
  65. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  66. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  67. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  68. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  69. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  70. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
  71. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
  72. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
  73. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  74. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  75. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
  76. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
  77. package/cli/dist/browser/index.html +10 -3
  78. package/cli/dist/clients/api/start.js +1 -1
  79. package/cli/dist/clients/cli/invocation.js +25 -0
  80. package/cli/dist/clients/cli/parser.js +24 -7
  81. package/cli/dist/clients/cli/text.js +3 -3
  82. package/cli/dist/clients/cli/values.js +0 -1
  83. package/cli/dist/clients/cli/views.js +9 -2
  84. package/cli/dist/clients/mcp/tools.js +8 -1
  85. package/cli/dist/clients/ui/assets.js +1 -0
  86. package/cli/dist/clients/wire/contract.js +2 -2
  87. package/cli/dist/clients/wire/queries.js +1 -0
  88. package/cli/dist/clients/wire/schemas.js +4 -1
  89. package/cli/dist/clients/wire/words.js +14 -0
  90. package/cli/dist/core/adapters/opentofu.js +1 -1
  91. package/cli/dist/core/app-hook/hooks.js +90 -0
  92. package/cli/dist/core/app-hook/token.js +49 -0
  93. package/cli/dist/core/app-init/plan.js +208 -0
  94. package/cli/dist/core/app-values/model.js +45 -0
  95. package/cli/dist/core/app-values/store.js +124 -0
  96. package/cli/dist/core/ctl/answers.js +14 -9
  97. package/cli/dist/core/fleet/brand.js +10 -12
  98. package/cli/dist/core/fleet/settings.js +14 -9
  99. package/cli/dist/core/operations/catalog.js +46 -1
  100. package/cli/dist/core/operations/dispatch.js +37 -6
  101. package/cli/dist/core/recipes/app-check.js +14 -1
  102. package/cli/dist/core/recipes/app-hook.js +26 -0
  103. package/cli/dist/core/recipes/app-values.js +21 -0
  104. package/cli/dist/core/recipes/doctor.js +2 -2
  105. package/cli/dist/core/recipes/launch.js +51 -0
  106. package/cli/dist/core/validation/facts.js +1 -3
  107. package/cli/dist/deployer/brand.js +8 -5
  108. package/cli/dist/deployer/build/builder.js +10 -4
  109. package/cli/dist/deployer/build/client.js +44 -0
  110. package/cli/dist/deployer/build/routes.js +27 -6
  111. package/cli/dist/deployer/ctl/answers.js +6 -2
  112. package/cli/dist/deployer/ctl/ctl.js +66 -9
  113. package/cli/dist/deployer/deployer.js +113 -196
  114. package/cli/dist/deployer/forges/forge.js +0 -12
  115. package/cli/dist/deployer/forges/notify.js +3 -3
  116. package/cli/dist/deployer/http/http.js +0 -1
  117. package/cli/dist/deployer/http/page.js +4 -2
  118. package/cli/dist/deployer/http/webhook.js +0 -1
  119. package/cli/dist/deployer/runs/effects.js +70 -0
  120. package/cli/dist/deployer/runs/queue.js +5 -4
  121. package/cli/dist/deployer/runs/records.js +22 -3
  122. package/cli/dist/deployer/runs/restore.js +6 -0
  123. package/cli/dist/deployer/runs/run.js +51 -5
  124. package/cli/dist/deployer/runs/store.js +19 -3
  125. package/cli/dist/deployer/settings.js +69 -0
  126. package/cli/dist/lib/forge-repo.js +15 -0
  127. package/cli/dist/lib/names.js +13 -0
  128. package/cli/dist/main.js +46 -25
  129. package/compose/docker-compose.ci.yml +2 -0
  130. package/package.json +2 -2
  131. package/schema/app.json +5 -0
  132. package/schema/defaults.json +8 -0
  133. package/schema/vars-platform.json +8 -0
  134. package/scripts/local/verify.sh +9 -2
  135. package/terraform/modules/platform-dns/main.tf +66 -0
  136. package/terraform/modules/platform-dns/outputs.tf +9 -0
  137. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/blog/site/app.yml +3 -0
  138. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/shop/app.yml +6 -0
  139. package/terraform/modules/platform-dns/tests/fleet/servers/nested/server.yml +6 -0
  140. package/terraform/modules/platform-dns/tests/fleet/servers/shop/server.yml +7 -0
  141. package/terraform/modules/platform-dns/tests/fleet/servers/uncloned/server.yml +6 -0
  142. package/terraform/modules/platform-dns/tests/platform-dns.tftest.hcl +64 -0
  143. package/terraform/modules/platform-dns/variables.tf +25 -0
  144. package/cli/dist/browser/assets/index-C4HCL022.js +0 -7
  145. package/cli/dist/browser/assets/index-Ct0Eudk4.css +0 -1
  146. package/scripts/agent/guard.sh +0 -125
@@ -40,9 +40,7 @@ export const gather = async (root, server) => {
40
40
  stackDirs: server.files.stacks,
41
41
  appConfig: Object.fromEntries(server.apps.map((app) => [app.name, valuesOf(appText(`${app.name}.yml`))])),
42
42
  appSecrets: Object.fromEntries(appSecrets),
43
- manifests: Object.fromEntries(
44
- // eslint-disable-next-line functional/prefer-immutable-types -- an app.yml's values are unknown, read only
45
- server.apps.flatMap((app) => {
43
+ manifests: Object.fromEntries(server.apps.flatMap((app) => {
46
44
  const manifest = textAt(join(root, ".cache", "apps", app.name, app.path, "app.yml"));
47
45
  return manifest === undefined ? Object.freeze([]) : Object.freeze([[app.name, valuesOf(manifest)]]);
48
46
  })),
@@ -1,13 +1,16 @@
1
1
  import { err, ok } from "../lib/result.js";
2
- export const appName = (value) => /^[a-z][a-z0-9-]*$/.test(value) ? ok(value) : err(`'${value}' is not an app name`);
2
+ import { names } from "../lib/names.js";
3
+ /** A constructor for the brand B: the value, if it follows the name's rule (lib/names.ts, as the fleet's schemas do). */
4
+ const matching = ({ pattern, what }) => (value) => pattern.test(value) ? ok(value) : err(`'${value}' is not ${what}`);
5
+ export const appName = matching(names.app);
3
6
  export const sha = (value) => /^[0-9a-f]{40}$/.test(value) ? ok(value) : err(`'${value}' is not a full commit id`);
4
7
  export const runId = (value) => /^\d{8}T\d{6}Z-[0-9a-f]{6}$/.test(value) ? ok(value) : err(`'${value}' is not a run id`);
5
8
  export const newRunId = (now, random) => `${now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${random}`;
6
- export const subdomain = (value) => /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(value) ? ok(value) : err(`'${value}' is not a subdomain`);
7
- export const serviceName = (value) => /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(value) ? ok(value) : err(`'${value}' is not a compose service name`);
9
+ export const subdomain = matching(names.subdomain);
10
+ export const serviceName = matching(names.serviceName);
8
11
  export const port = (value) => Number.isInteger(value) && value >= 1 && value <= 65535 ? ok(value) : err(`${String(value)} is not a port`);
9
- export const routePath = (value) => /^\/[A-Za-z0-9._~%/-]*$/.test(value) ? ok(value) : err(`'${value}' is not a path (/, then letters, digits and ._~%/-)`);
10
- export const period = (value) => /^[1-9][0-9]*(ms|s|m|h)$/.test(value) ? ok(value) : err(`'${value}' is not a period such as 10s, 10m or 1h`);
12
+ export const routePath = matching(names.routePath);
13
+ export const period = matching(names.period);
11
14
  export const appOwner = (app) => app;
12
15
  export const jobOwner = (job) => `_${job}`;
13
16
  export const owner = (value) => /^(_gc|_renovate|[a-z][a-z0-9-]*)$/.test(value) ? ok(value) : err(`'${value}' has no runs`);
@@ -7,7 +7,8 @@ import { owner, runId, sha } from "../brand.js";
7
7
  import { body, json, send } from "../http/http.js";
8
8
  import { page, runPage } from "../http/page.js";
9
9
  import { spawnLines } from "../process.js";
10
- import { forgeRepo, signed } from "../forges/forge.js";
10
+ import { signed } from "../forges/forge.js";
11
+ import { forgeRepo } from "../../lib/forge-repo.js";
11
12
  import { pushedRef } from "../http/webhook.js";
12
13
  import { typed } from "../../lib/typed.js";
13
14
  const fromFile = (path) => () => (existsSync(path) ? readFileSync(path, "utf8").trim() : "");
@@ -20,6 +21,7 @@ const settings = (env) => {
20
21
  resolveImages: env["RESOLVE_IMAGES"] ?? "/opt/kayra/scripts/platform/resolve-images.sh",
21
22
  webhookSecret: () => env["WEBHOOK_SECRET"] ?? "",
22
23
  gitToken: fromFile("/run/platform-secrets/GIT_TOKEN"),
24
+ webhooks: env["WEBHOOKS"] !== "false",
23
25
  });
24
26
  };
25
27
  /** git with the platform's token as a header: neither in the clone's config nor in the process list. */
@@ -30,7 +32,7 @@ const gitEnv = (token) => typed({
30
32
  GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`,
31
33
  });
32
34
  /** A full commit id as it is; otherwise the branch or tag it names (a tag's commit, not the tag object). */
33
- export const resolveRef = async (app, ref, token) => {
35
+ const resolveRef = async (app, ref, token) => {
34
36
  const given = sha(ref);
35
37
  if (given.ok)
36
38
  return given;
@@ -186,8 +188,12 @@ export const serveBuilder = (env) => {
186
188
  createServer(failing(async (request, response) => {
187
189
  const path = new URL(request.url ?? "/", "http://builder").pathname;
188
190
  const hooked = /^\/hook\/([^/]+)\/?$/.exec(path);
189
- if (request.method === "POST" && hooked?.[1] !== undefined)
190
- await hook(s, hooked[1], request, response);
191
+ if (request.method === "POST" && hooked?.[1] !== undefined) {
192
+ if (s.webhooks)
193
+ await hook(s, hooked[1], request, response);
194
+ else
195
+ send(response, 404, "this server takes no webhooks: it polls (webhooks: false)\n");
196
+ }
191
197
  else if (request.method === "GET")
192
198
  pages(s, path, response);
193
199
  else
@@ -0,0 +1,44 @@
1
+ import { createInterface } from "node:readline";
2
+ import { Readable } from "node:stream";
3
+ import { err, ok } from "../../lib/result.js";
4
+ import { field } from "../app.js";
5
+ import { sha } from "../brand.js";
6
+ /** The builder as the deployer asks it, on platform-internal (:8081): what it answers is checked again later, never trusted. */
7
+ /** A branch, tag or full commit id to the commit it names. */
8
+ export const builderResolve = async (builder, app, ref) => {
9
+ const response = await fetch(`${builder}/resolve`, { method: "POST", body: JSON.stringify({ app: app.name, ref }) }).catch(() => undefined);
10
+ if (response === undefined)
11
+ return err("the builder did not answer");
12
+ const answer = await response.json().catch(() => undefined);
13
+ const given = typeof answer === "object" && answer !== null ? field(answer, "sha") : undefined;
14
+ const problem = typeof answer === "object" && answer !== null ? field(answer, "error") : undefined;
15
+ return typeof given === "string" ? sha(given) : err(typeof problem === "string" ? problem : `resolve: HTTP ${String(response.status)}`);
16
+ };
17
+ /** The builder's NDJSON: log lines as they come, then the bundle or an error. */
18
+ export const builderPrepare = async (builder, app, commit, log) => {
19
+ const response = await fetch(`${builder}/prepare`, {
20
+ method: "POST",
21
+ body: JSON.stringify({ app: app.name, sha: commit }),
22
+ signal: AbortSignal.timeout(45 * 60_000),
23
+ }).catch(() => undefined);
24
+ if (response?.body == null || !response.ok)
25
+ return err("the builder did not prepare a bundle");
26
+ const lines = createInterface({ input: Readable.fromWeb(response.body) });
27
+ const outcome = await Array.fromAsync(lines, (line) => {
28
+ try {
29
+ const message = JSON.parse(line);
30
+ if (typeof message !== "object" || message === null)
31
+ return undefined;
32
+ const text = field(message, "log");
33
+ if (typeof text === "string")
34
+ log(text);
35
+ const bundle = field(message, "bundle");
36
+ const problem = field(message, "error");
37
+ return bundle !== undefined ? ok(bundle) : typeof problem === "string" ? err(problem) : undefined;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ });
43
+ return outcome.findLast((item) => item !== undefined) ?? err("the builder stopped without a bundle");
44
+ };
@@ -24,19 +24,20 @@ const rateLimit = (value) => {
24
24
  return per;
25
25
  return ok({ average: average.value, period: per.value, burst: burst.value });
26
26
  };
27
+ const optionalPath = (value, name) => value === undefined ? ok(undefined) : flatMap(text(value, name), routePath);
27
28
  const route = (value, index) => {
28
29
  const where = (problem) => `route ${String(index)}: ${problem}`;
29
30
  if (typeof value !== "object" || value === null)
30
31
  return err(where("not a mapping"));
31
- const extra = unknownKey(value, ["host", "path", "service", "port", "rate_limit"]);
32
+ const extra = unknownKey(value, ["host", "path", "service", "port", "rate_limit", "check"]);
32
33
  if (extra !== undefined)
33
34
  return err(where(`${extra} is not a route field`));
34
35
  const host = flatMap(text(field(value, "host"), "host"), subdomain);
35
36
  const service = flatMap(text(field(value, "service"), "service"), serviceName);
36
37
  const rawPort = field(value, "port");
37
38
  const listens = typeof rawPort === "number" ? port(rawPort) : err(`port ${String(rawPort)} is not a port`);
38
- const rawPath = field(value, "path");
39
- const path = rawPath === undefined ? ok(undefined) : flatMap(text(rawPath, "path"), routePath);
39
+ const path = optionalPath(field(value, "path"), "path");
40
+ const check = optionalPath(field(value, "check"), "check");
40
41
  const limit = rateLimit(field(value, "rate_limit"));
41
42
  if (!host.ok)
42
43
  return err(where(host.error));
@@ -46,10 +47,14 @@ const route = (value, index) => {
46
47
  return err(where(listens.error));
47
48
  if (!path.ok)
48
49
  return err(where(path.error));
50
+ if (!check.ok)
51
+ return err(where(check.error));
49
52
  if (!limit.ok)
50
53
  return err(where(limit.error));
51
- return ok({ host: host.value, path: path.value, service: service.value, port: listens.value, rateLimit: limit.value });
54
+ return ok({ host: host.value, path: path.value, service: service.value, port: listens.value, rateLimit: limit.value, check: check.value });
52
55
  };
56
+ /** A route's readiness URL: its check path, or its own path. */
57
+ export const readinessUrl = (route, domain) => `https://${route.host}.${domain}${route.check ?? route.path ?? "/"}`;
53
58
  /** app.yml's routes as the builder read them at the commit: untrusted, so every field is checked. */
54
59
  export const parseRoutes = (json) => Array.isArray(json) ? all(json.map((item, index) => route(item, index))) : err("routes is not a list");
55
60
  /** Routes as app.yml writes them, for the compose policy. */
@@ -101,12 +106,28 @@ const networksOf = (config, service) => {
101
106
  const networks = field(definition, "networks");
102
107
  return ok(typeof networks === "object" && networks !== null ? { ...networks } : { default: null });
103
108
  };
109
+ /** Each service of the admitted config without a restart policy, unless-stopped, beside what the routes give it. */
110
+ const withRestart = (config, routed) => {
111
+ const services = typeof config === "object" && config !== null ? field(config, "services") : undefined;
112
+ if (typeof services !== "object" || services === null)
113
+ return routed;
114
+ const unset = Object.keys(services).filter((name) => {
115
+ const definition = field(services, name);
116
+ return typeof definition === "object" && definition !== null && field(definition, "restart") === undefined;
117
+ });
118
+ return Object.fromEntries([
119
+ ...Object.entries(routed).map(([name, entry]) => [name, unset.includes(name) && typeof entry === "object" && entry !== null ? { ...entry, restart: "unless-stopped" } : entry]),
120
+ ...unset.filter((name) => !Object.hasOwn(routed, name)).map((name) => [name, { restart: "unless-stopped" }]),
121
+ ]);
122
+ };
104
123
  /**
105
124
  * The platform's part of an app's compose project, from its admitted config
106
125
  * and its routes: each routed service joins platform-public, beside the
107
126
  * networks it has (restated, or the override would replace them), and gets the
108
127
  * Traefik labels its routes become. Apps write no Traefik label themselves:
109
- * the policy refuses them.
128
+ * the policy refuses them. Every service without a restart policy of its own
129
+ * gets unless-stopped: a Docker update or a reboot stops every container, and
130
+ * one without a policy would stay down until the app's next deploy.
110
131
  */
111
132
  export const routesOverride = (app, domain, routes, admitted) => flatMap(attempt(() => ok(JSON.parse(admitted)), (why) => `the admitted config is not JSON: ${why}`), (config) => {
112
133
  const routed = [...new Set(routes.map((route) => route.service))];
@@ -122,7 +143,7 @@ export const routesOverride = (app, domain, routes, admitted) => flatMap(attempt
122
143
  },
123
144
  ]))));
124
145
  return flatMap(services, (entries) => ok(`${JSON.stringify({
125
- services: Object.fromEntries(entries),
146
+ services: withRestart(config, Object.fromEntries(entries)),
126
147
  ...(entries.length === 0 ? {} : { networks: { "platform-public": { name: "platform-public", external: true } } }),
127
148
  }, null, 2)}\n`));
128
149
  });
@@ -2,7 +2,8 @@ import { typed } from "../../lib/typed.js";
2
2
  /** A release record's compact UTC time, 20261018T101500Z, as ISO 8601. */
3
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");
4
4
  const deployed = (release) => typed({ sha: release.sha, time: iso(release.time) });
5
- const answer = (run) => typed({
5
+ /** One run as data: `ctl runs --json` lists them, `ctl deploy --json` answers with the one it followed. */
6
+ export const runAnswer = (run) => typed({
6
7
  id: run.id,
7
8
  state: run.state,
8
9
  why: run.why,
@@ -10,11 +11,14 @@ const answer = (run) => typed({
10
11
  ...(run.sha === undefined ? {} : { sha: run.sha }),
11
12
  started: run.started,
12
13
  ...(run.finished === undefined ? {} : { finished: run.finished }),
14
+ ...(run.error === undefined ? {} : { error: run.error }),
15
+ ...(run.urls === undefined ? {} : { urls: run.urls }),
16
+ ...(run.checks === undefined ? {} : { checks: run.checks }),
13
17
  });
14
18
  export const runsAnswer = (app, runs, live) => typed({
15
19
  app,
16
20
  ...(live === undefined ? {} : { live: deployed(live) }),
17
- runs: runs.map(answer),
21
+ runs: runs.map(runAnswer),
18
22
  });
19
23
  export const releasesAnswer = (app, releases) => typed({
20
24
  app,
@@ -1,9 +1,11 @@
1
1
  import { existsSync, readdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { releasesAnswer, runsAnswer } from "./answers.js";
3
+ import { releasesAnswer, runAnswer, runsAnswer } from "./answers.js";
4
+ import { field } from "../app.js";
4
5
  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";
6
+ import { ended, releases } from "../runs/records.js";
7
+ import { log, meta, runsOf } from "../runs/store.js";
8
+ import { typed } from "../../lib/typed.js";
7
9
  /**
8
10
  * The operator's side, run inside the deployer container by `kayra app …` and
9
11
  * `kayra job …` over SSH. Reads runs/ and releases/ directly; anything that
@@ -17,12 +19,62 @@ const fail = (message) => {
17
19
  console.error(message);
18
20
  return 1;
19
21
  };
22
+ /** What the control port answers a request it took: the run's id, whose run it is. */
23
+ const accepted = (text) => {
24
+ try {
25
+ const json = JSON.parse(text);
26
+ const id = runId(String(typeof json === "object" && json !== null ? field(json, "id") : ""));
27
+ const owner = mintOwner(String(typeof json === "object" && json !== null ? field(json, "owner") : ""));
28
+ return typed(id.ok && owner.ok ? { id: id.value, owner: owner.value } : undefined);
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ };
20
34
  const post = async (path, payload) => {
21
35
  const response = await fetch(`http://127.0.0.1:8091${path}`, { method: "POST", body: JSON.stringify(payload) }).catch(() => undefined);
22
36
  if (response === undefined)
23
- return fail("the deployer is not running");
24
- process.stdout.write(await response.text());
25
- return response.ok ? 0 : 1;
37
+ return typed({ code: fail("the deployer is not running") });
38
+ const text = await response.text();
39
+ if (!response.ok)
40
+ return typed({ code: fail(text.trim()) });
41
+ const run = accepted(text);
42
+ return typed(run === undefined ? { code: fail(`the deployer answered what this ctl cannot read: ${text.trim()}`) } : { code: 0, run });
43
+ };
44
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
45
+ /** The run's end, in a few lines: what runs where, or why not. */
46
+ const summary = (run) => {
47
+ const commit = run.sha === undefined ? "" : ` ${run.sha.slice(0, 7)}`;
48
+ if (run.state === "superseded")
49
+ return typed([`↷ ${run.owner}: a newer request replaced this one before it started (run ${run.id})`]);
50
+ if (run.state === "failure")
51
+ return typed([`✗ ${run.owner}${commit}: ${run.error ?? "failed; see the log"} (run ${run.id})`]);
52
+ return typed([`✓ ${run.owner}${commit} deployed (run ${run.id})`, ...(run.urls ?? []).map((url) => ` ${url}`)]);
53
+ };
54
+ /**
55
+ * Follows a run until it ends: its log as it grows (unless `json`), then its
56
+ * end — the run as data with `json`. Exits 0 only on success.
57
+ */
58
+ const follow = async (who, id, json, shown = 0) => {
59
+ const text = log(runs, who, id) ?? "";
60
+ if (!json && text.length > shown)
61
+ process.stdout.write(text.slice(shown));
62
+ const now = meta(runs, who, id);
63
+ if (now === undefined)
64
+ return fail(`run ${id} of ${who} is gone`);
65
+ if (!ended(now.state)) {
66
+ await pause(1_000);
67
+ return follow(who, id, json, text.length);
68
+ }
69
+ if (json)
70
+ console.log(JSON.stringify(runAnswer(now)));
71
+ else
72
+ summary(now).forEach((line) => { console.log(line); });
73
+ return now.state === "success" ? 0 : 1;
74
+ };
75
+ const start = async (payload, json) => {
76
+ const posted = await post("/deploy", payload);
77
+ return posted.run === undefined ? posted.code : follow(posted.run.owner, posted.run.id, json);
26
78
  };
27
79
  const releasesOf = (app) => {
28
80
  const dir = join(platformDir, "releases", app);
@@ -55,7 +107,7 @@ const commands = {
55
107
  process.stdout.write(text);
56
108
  return 0;
57
109
  },
58
- deploy: ([app, ref]) => post("/deploy", { app, ref: ref ?? "", why: "deploy" }),
110
+ deploy: ([app, ref], json) => start({ app, ref: ref ?? "", why: "deploy" }, json),
59
111
  rollback: ([app, commit], json) => {
60
112
  const name = appName(app ?? "");
61
113
  if (!name.ok)
@@ -78,9 +130,14 @@ const commands = {
78
130
  const target = earlier.find((release) => release.sha.startsWith(commit));
79
131
  if (target === undefined || commit.length < 7)
80
132
  return fail(`${commit} is not an earlier release of ${name.value}`);
81
- return post("/deploy", { app: name.value, ref: target.sha, why: "rollback" });
133
+ return start({ app: name.value, ref: target.sha, why: "rollback" }, json);
134
+ },
135
+ job: async ([job, flag]) => {
136
+ const posted = await post("/job", { job, dryRun: flag === "--dry-run" });
137
+ if (posted.run !== undefined)
138
+ console.log(`${String(job)}: run ${posted.run.id}; kayra app logs <server> ${String(job)} shows its log`);
139
+ return posted.code;
82
140
  },
83
- job: ([job, flag]) => post("/job", { job, dryRun: flag === "--dry-run" }),
84
141
  };
85
142
  export const ctl = async (args) => {
86
143
  const [name, ...rest] = args;