@yunuseon/kayra 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/agent/skills/kayra-release/SKILL.md +1 -4
  2. package/agent/skills/kayra-rollout/SKILL.md +4 -6
  3. package/ansible/playbooks/edge.yml +5 -0
  4. package/ansible/playbooks/nas.yml +9 -1
  5. package/ansible/playbooks/platform.yml +8 -2
  6. package/ansible/roles/app/tasks/main.yml +33 -3
  7. package/ansible/roles/kayra-version/defaults/main.yml +5 -0
  8. package/ansible/roles/kayra-version/tasks/main.yml +18 -0
  9. package/ansible/roles/platform/defaults/main.yml +3 -0
  10. package/ansible/roles/platform/tasks/main.yml +6 -84
  11. package/ansible/roles/platform/templates/platform.env.j2 +2 -0
  12. package/bin/kayra-app-hook.js +6 -0
  13. package/bin/kayra-app-init.js +6 -0
  14. package/bin/kayra-app-launch.js +6 -0
  15. package/bin/kayra-app-values.js +6 -0
  16. package/cli/dist/app-hook.js +75 -0
  17. package/cli/dist/app-init.js +65 -0
  18. package/cli/dist/app-launch.js +89 -0
  19. package/cli/dist/app-values.js +37 -0
  20. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-BTotfTJu.woff +0 -0
  21. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-DZqxrq2p.woff2 +0 -0
  22. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-71GNu3SW.woff2 +0 -0
  23. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-BGq0mW3O.woff +0 -0
  24. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-Dsrv2Tcn.woff +0 -0
  25. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-g30qAdWV.woff2 +0 -0
  26. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-Bz0x94Yp.woff +0 -0
  27. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-DUMzJB7m.woff2 +0 -0
  28. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-D9ESIMu3.woff +0 -0
  29. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-_efipK4i.woff2 +0 -0
  30. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-D-CqTdkO.woff +0 -0
  31. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-DzTrcv_p.woff2 +0 -0
  32. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
  33. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
  34. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
  35. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
  36. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-C5H60-Va.woff2 +0 -0
  37. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-RBey6euL.woff +0 -0
  38. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DIrixKbi.woff +0 -0
  39. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DOrvGEcy.woff2 +0 -0
  40. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-DG4YqDda.woff2 +0 -0
  41. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-fK1oJ5dG.woff +0 -0
  42. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DgdngZtN.woff +0 -0
  43. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DpPYBSTl.woff2 +0 -0
  44. package/cli/dist/browser/assets/index-DzIVPXyL.css +1 -0
  45. package/cli/dist/browser/assets/index-SP8bCDrl.js +7 -0
  46. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  47. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  48. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  49. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  50. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
  51. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  52. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
  53. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
  54. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  55. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  56. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  57. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  58. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  59. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
  60. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
  61. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
  62. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  63. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  64. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  65. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  66. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  67. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  68. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
  69. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
  70. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  71. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  72. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  73. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  74. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  75. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
  76. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
  77. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
  78. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  79. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  80. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
  81. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
  82. package/cli/dist/browser/index.html +10 -3
  83. package/cli/dist/clients/api/start.js +1 -1
  84. package/cli/dist/clients/cli/invocation.js +25 -0
  85. package/cli/dist/clients/cli/parser.js +24 -7
  86. package/cli/dist/clients/cli/status.js +28 -7
  87. package/cli/dist/clients/cli/text.js +3 -3
  88. package/cli/dist/clients/cli/values.js +0 -1
  89. package/cli/dist/clients/cli/views.js +9 -2
  90. package/cli/dist/clients/mcp/tools.js +8 -1
  91. package/cli/dist/clients/ui/assets.js +1 -0
  92. package/cli/dist/clients/wire/contract.js +2 -2
  93. package/cli/dist/clients/wire/queries.js +1 -0
  94. package/cli/dist/clients/wire/schemas.js +6 -2
  95. package/cli/dist/clients/wire/status.js +7 -1
  96. package/cli/dist/clients/wire/words.js +14 -0
  97. package/cli/dist/core/adapters/network.js +20 -1
  98. package/cli/dist/core/adapters/opentofu.js +1 -1
  99. package/cli/dist/core/app-hook/hooks.js +90 -0
  100. package/cli/dist/core/app-hook/token.js +49 -0
  101. package/cli/dist/core/app-init/plan.js +208 -0
  102. package/cli/dist/core/app-values/model.js +45 -0
  103. package/cli/dist/core/app-values/store.js +124 -0
  104. package/cli/dist/core/ctl/answers.js +14 -9
  105. package/cli/dist/core/fleet/brand.js +10 -7
  106. package/cli/dist/core/fleet/parse.js +10 -1
  107. package/cli/dist/core/fleet/settings.js +32 -12
  108. package/cli/dist/core/operations/catalog.js +46 -1
  109. package/cli/dist/core/operations/dispatch.js +40 -9
  110. package/cli/dist/core/recipes/app-check.js +14 -1
  111. package/cli/dist/core/recipes/app-hook.js +26 -0
  112. package/cli/dist/core/recipes/app-values.js +21 -0
  113. package/cli/dist/core/recipes/doctor.js +5 -5
  114. package/cli/dist/core/recipes/host.js +8 -3
  115. package/cli/dist/core/recipes/launch.js +51 -0
  116. package/cli/dist/core/status/look.js +33 -13
  117. package/cli/dist/core/status/model.js +2 -0
  118. package/cli/dist/core/validation/facts.js +1 -3
  119. package/cli/dist/deployer/brand.js +9 -1
  120. package/cli/dist/deployer/build/builder.js +15 -4
  121. package/cli/dist/deployer/build/bundle.js +5 -0
  122. package/cli/dist/deployer/build/client.js +44 -0
  123. package/cli/dist/deployer/build/compose.js +21 -8
  124. package/cli/dist/deployer/build/routes.js +149 -0
  125. package/cli/dist/deployer/ctl/answers.js +6 -2
  126. package/cli/dist/deployer/ctl/ctl.js +66 -9
  127. package/cli/dist/deployer/deployer.js +114 -191
  128. package/cli/dist/deployer/forges/forge.js +0 -12
  129. package/cli/dist/deployer/forges/notify.js +3 -3
  130. package/cli/dist/deployer/http/http.js +0 -1
  131. package/cli/dist/deployer/http/page.js +4 -2
  132. package/cli/dist/deployer/http/webhook.js +0 -1
  133. package/cli/dist/deployer/runs/effects.js +70 -0
  134. package/cli/dist/deployer/runs/queue.js +5 -4
  135. package/cli/dist/deployer/runs/records.js +22 -3
  136. package/cli/dist/deployer/runs/restore.js +6 -0
  137. package/cli/dist/deployer/runs/run.js +64 -11
  138. package/cli/dist/deployer/runs/store.js +19 -3
  139. package/cli/dist/deployer/settings.js +69 -0
  140. package/cli/dist/lib/forge-repo.js +15 -0
  141. package/cli/dist/lib/names.js +13 -0
  142. package/cli/dist/main.js +46 -25
  143. package/compose/docker-compose.ci.yml +2 -0
  144. package/package.json +2 -2
  145. package/schema/app.json +69 -8
  146. package/schema/defaults.json +8 -0
  147. package/schema/vars-platform.json +8 -0
  148. package/scripts/local/app-check.sh +12 -9
  149. package/scripts/local/app-manifests.sh +11 -6
  150. package/scripts/local/verify.sh +30 -12
  151. package/scripts/platform/compose-policy.sh +37 -40
  152. package/terraform/modules/platform-dns/main.tf +66 -0
  153. package/terraform/modules/platform-dns/outputs.tf +9 -0
  154. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/blog/site/app.yml +3 -0
  155. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/shop/app.yml +6 -0
  156. package/terraform/modules/platform-dns/tests/fleet/servers/nested/server.yml +6 -0
  157. package/terraform/modules/platform-dns/tests/fleet/servers/shop/server.yml +7 -0
  158. package/terraform/modules/platform-dns/tests/fleet/servers/uncloned/server.yml +6 -0
  159. package/terraform/modules/platform-dns/tests/platform-dns.tftest.hcl +64 -0
  160. package/terraform/modules/platform-dns/variables.tf +25 -0
  161. package/cli/dist/browser/assets/index-Ct0Eudk4.css +0 -1
  162. package/cli/dist/browser/assets/index-hcyM6f6T.js +0 -7
  163. package/compose/traefik/dynamic/ratelimit.yml +0 -21
  164. package/scripts/agent/guard.sh +0 -125
@@ -1,4 +1,13 @@
1
+ import { wireRoutes } from "./routes.js";
1
2
  import { typed } from "../../lib/typed.js";
3
+ /**
4
+ * The run's directory: the app's compose files under app/, at their paths in
5
+ * the app; the platform's files beside it, where no app file can stand in for
6
+ * them.
7
+ */
8
+ export const appFiles = "app";
9
+ export const imagesFile = "images.env";
10
+ export const routesFile = "routes.yml";
2
11
  /**
3
12
  * The app's compose project, run in the run's directory: its .env from the
4
13
  * platform (operator config), the image refs from this run, the compose files
@@ -8,20 +17,24 @@ import { typed } from "../../lib/typed.js";
8
17
  const project = (app, appsDir, bundle) => {
9
18
  const dir = `${appsDir}/${app.name}`;
10
19
  return typed([
11
- "compose", "-p", app.name, "--project-directory", dir, "--env-file", `${dir}/.env`, "--env-file", "images.env",
12
- ...bundle.compose.flatMap((file) => ["-f", file.path]),
20
+ "compose", "-p", app.name, "--project-directory", dir, "--env-file", `${dir}/.env`, "--env-file", imagesFile,
21
+ ...bundle.compose.flatMap((file) => ["-f", `${appFiles}/${file.path}`]),
13
22
  ]);
14
23
  };
15
24
  /**
16
- * What admission checks. --no-env-resolution: otherwise compose reads every
17
- * env_file here, from any path (another app's secrets included), and bakes it
18
- * into the config; unresolved, the allow-list sees env_file and refuses it.
25
+ * What admission checks: the app's files alone. --no-env-resolution:
26
+ * otherwise compose reads every env_file here, from any path (another app's
27
+ * secrets included), and bakes it into the config; unresolved, the allow-list
28
+ * sees env_file and refuses it.
19
29
  */
20
30
  export const config = (app, appsDir, bundle) => typed([
21
31
  "docker", ...project(app, appsDir, bundle), "config", "--no-env-resolution", "--format", "json",
22
32
  ]);
23
- export const policy = (app, script) => typed(["bash", script, app.name, ...app.hosts]);
24
- /** --remove-orphans: a service the app dropped from its compose files must not keep running. */
33
+ export const policy = (app, script, domain, bundle) => typed(["bash", script, app.name, domain, JSON.stringify(wireRoutes(bundle.routes)), ...app.hosts]);
34
+ /**
35
+ * The app's files, then the platform's routes. --remove-orphans: a service the
36
+ * app dropped from its compose files must not keep running.
37
+ */
25
38
  export const up = (app, appsDir, bundle) => typed([
26
- "docker", ...project(app, appsDir, bundle), "up", "-d", "--wait", "--wait-timeout", "180", "--remove-orphans",
39
+ "docker", ...project(app, appsDir, bundle), "-f", routesFile, "up", "-d", "--wait", "--wait-timeout", "180", "--remove-orphans",
27
40
  ]);
@@ -0,0 +1,149 @@
1
+ import { all, attempt, err, flatMap, ok } from "../../lib/result.js";
2
+ import { typed } from "../../lib/typed.js";
3
+ import { field } from "../app.js";
4
+ import { period, port, routePath, serviceName, subdomain } from "../brand.js";
5
+ const unknownKey = (value, known) => Object.keys(value).find((key) => !known.includes(key));
6
+ const count = (value, name) => typeof value === "number" && Number.isInteger(value) && value > 0 ? ok(value) : err(`${name} ${String(value)} is not a positive whole number`);
7
+ const text = (value, name) => (typeof value === "string" ? ok(value) : err(`${name} is missing or not text`));
8
+ const rateLimit = (value) => {
9
+ if (value === undefined)
10
+ return ok(undefined);
11
+ if (typeof value !== "object" || value === null)
12
+ return err("rate_limit is not a mapping");
13
+ const extra = unknownKey(value, ["average", "period", "burst"]);
14
+ if (extra !== undefined)
15
+ return err(`rate_limit.${extra} is not a rate limit field`);
16
+ const average = count(field(value, "average"), "rate_limit.average");
17
+ const burst = count(field(value, "burst"), "rate_limit.burst");
18
+ const per = flatMap(text(field(value, "period"), "rate_limit.period"), period);
19
+ if (!average.ok)
20
+ return average;
21
+ if (!burst.ok)
22
+ return burst;
23
+ if (!per.ok)
24
+ return per;
25
+ return ok({ average: average.value, period: per.value, burst: burst.value });
26
+ };
27
+ const optionalPath = (value, name) => value === undefined ? ok(undefined) : flatMap(text(value, name), routePath);
28
+ const route = (value, index) => {
29
+ const where = (problem) => `route ${String(index)}: ${problem}`;
30
+ if (typeof value !== "object" || value === null)
31
+ return err(where("not a mapping"));
32
+ const extra = unknownKey(value, ["host", "path", "service", "port", "rate_limit", "check"]);
33
+ if (extra !== undefined)
34
+ return err(where(`${extra} is not a route field`));
35
+ const host = flatMap(text(field(value, "host"), "host"), subdomain);
36
+ const service = flatMap(text(field(value, "service"), "service"), serviceName);
37
+ const rawPort = field(value, "port");
38
+ const listens = typeof rawPort === "number" ? port(rawPort) : err(`port ${String(rawPort)} is not a port`);
39
+ const path = optionalPath(field(value, "path"), "path");
40
+ const check = optionalPath(field(value, "check"), "check");
41
+ const limit = rateLimit(field(value, "rate_limit"));
42
+ if (!host.ok)
43
+ return err(where(host.error));
44
+ if (!service.ok)
45
+ return err(where(service.error));
46
+ if (!listens.ok)
47
+ return err(where(listens.error));
48
+ if (!path.ok)
49
+ return err(where(path.error));
50
+ if (!check.ok)
51
+ return err(where(check.error));
52
+ if (!limit.ok)
53
+ return err(where(limit.error));
54
+ return ok({ host: host.value, path: path.value, service: service.value, port: listens.value, rateLimit: limit.value, check: check.value });
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 ?? "/"}`;
58
+ /** app.yml's routes as the builder read them at the commit: untrusted, so every field is checked. */
59
+ export const parseRoutes = (json) => Array.isArray(json) ? all(json.map((item, index) => route(item, index))) : err("routes is not a list");
60
+ /** Routes as app.yml writes them, for the compose policy. */
61
+ export const wireRoutes = (routes) => Object.freeze(routes.map((route) => typed({
62
+ host: route.host,
63
+ ...(route.path === undefined ? {} : { path: route.path }),
64
+ service: route.service,
65
+ port: route.port,
66
+ ...(route.rateLimit === undefined ? {} : { rate_limit: route.rateLimit }),
67
+ })));
68
+ /** One line for the run's log: `www → web:3000, api/signup → api:3000 (rate limited)`. */
69
+ export const describeRoutes = (routes) => routes.length === 0
70
+ ? "none"
71
+ : routes
72
+ .map((route) => `${route.host}${route.path ?? ""} → ${route.service}:${String(route.port)}${route.rateLimit === undefined ? "" : " (rate limited)"}`)
73
+ .join(", ");
74
+ /** A router per route: unique on the server through the app's prefix, readable in Traefik's dashboard. */
75
+ const routerName = (app, index, route) => `${app}-${String(index)}-${route.host}`;
76
+ /** A Traefik service per service and port, so one container can serve two ports. */
77
+ const backendName = (app, route) => `${app}-${route.service}-${String(route.port)}`;
78
+ const rule = (route, domain) => [`Host(\`${route.host}.${domain}\`)`, ...(route.path === undefined ? [] : [`PathPrefix(\`${route.path}\`)`])].join(" && ");
79
+ /** A route's labels. Security headers need none: the websecure entrypoint gives them to every router. */
80
+ const routeLabels = (app, domain, route, index) => {
81
+ const router = `traefik.http.routers.${routerName(app, index, route)}`;
82
+ const limit = `${routerName(app, index, route)}-limit`;
83
+ const backend = backendName(app, route);
84
+ return typed([
85
+ [`${router}.rule`, rule(route, domain)],
86
+ [`${router}.entrypoints`, "websecure"],
87
+ [`${router}.tls.certresolver`, "le"],
88
+ [`${router}.service`, backend],
89
+ [`traefik.http.services.${backend}.loadbalancer.server.port`, String(route.port)],
90
+ ...(route.rateLimit === undefined
91
+ ? []
92
+ : [
93
+ [`${router}.middlewares`, limit],
94
+ [`traefik.http.middlewares.${limit}.ratelimit.average`, String(route.rateLimit.average)],
95
+ [`traefik.http.middlewares.${limit}.ratelimit.period`, route.rateLimit.period],
96
+ [`traefik.http.middlewares.${limit}.ratelimit.burst`, String(route.rateLimit.burst)],
97
+ ]),
98
+ ]);
99
+ };
100
+ /** The networks the admitted config gives a service; Compose spells out the implicit default. */
101
+ const networksOf = (config, service) => {
102
+ const services = typeof config === "object" && config !== null ? field(config, "services") : undefined;
103
+ const definition = typeof services === "object" && services !== null ? field(services, service) : undefined;
104
+ if (typeof definition !== "object" || definition === null)
105
+ return err(`route to ${service}: no such service in the compose files`);
106
+ const networks = field(definition, "networks");
107
+ return ok(typeof networks === "object" && networks !== null ? { ...networks } : { default: null });
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
+ };
123
+ /**
124
+ * The platform's part of an app's compose project, from its admitted config
125
+ * and its routes: each routed service joins platform-public, beside the
126
+ * networks it has (restated, or the override would replace them), and gets the
127
+ * Traefik labels its routes become. Apps write no Traefik label themselves:
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.
131
+ */
132
+ export const routesOverride = (app, domain, routes, admitted) => flatMap(attempt(() => ok(JSON.parse(admitted)), (why) => `the admitted config is not JSON: ${why}`), (config) => {
133
+ const routed = [...new Set(routes.map((route) => route.service))];
134
+ const services = all(routed.map((service) => flatMap(networksOf(config, service), (networks) => ok([
135
+ service,
136
+ {
137
+ networks: { ...networks, "platform-public": null },
138
+ labels: Object.fromEntries([
139
+ ["traefik.enable", "true"],
140
+ ["traefik.docker.network", "platform-public"],
141
+ ...routes.flatMap((route, index) => (route.service === service ? routeLabels(app, domain, route, index) : [])),
142
+ ]),
143
+ },
144
+ ]))));
145
+ return flatMap(services, (entries) => ok(`${JSON.stringify({
146
+ services: withRestart(config, Object.fromEntries(entries)),
147
+ ...(entries.length === 0 ? {} : { networks: { "platform-public": { name: "platform-public", external: true } } }),
148
+ }, null, 2)}\n`));
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;