@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,5 @@
1
1
  import { z } from "zod";
2
+ import { valueKeySchema } from "../app-values/model.js";
2
3
  /**
3
4
  * Every kayra operation, once: what each client (the command line, the API,
4
5
  * the web interface) offers, and what it may ask for. A client names an
@@ -19,6 +20,7 @@ const server = z.string().min(1).describe("A server of the fleet (servers/<name>
19
20
  const app = z.string().min(1).describe("An app name, including a removed app whose records or data remain");
20
21
  const serverInput = z.strictObject({ server });
21
22
  const appInput = z.strictObject({ server, app });
23
+ const dir = z.string().min(1).optional().describe("Local app directory containing app.yml; otherwise use the fleet cache");
22
24
  export const operations = {
23
25
  up: {
24
26
  summary: "Provision, set up everything, point /etc/hosts at it.",
@@ -78,6 +80,16 @@ export const operations = {
78
80
  kind: "plan",
79
81
  input: serverInput,
80
82
  },
83
+ "app.init": {
84
+ summary: "Make an existing project with a compose file or Dockerfile deployable: write app.yml and the platform's overlay, then check it.",
85
+ scope: "repo",
86
+ effect: "changes",
87
+ kind: "plan",
88
+ input: z.strictObject({
89
+ dir: z.string().min(1).default(".").describe("The project's repository"),
90
+ name: z.string().min(1).optional().describe("The app's name; the directory's by default"),
91
+ }),
92
+ },
81
93
  "app.check": {
82
94
  summary: "What the platform checks at deploy (app.yml, images, compose policy), in an app's repository. No fleet needed.",
83
95
  scope: "repo",
@@ -85,6 +97,39 @@ export const operations = {
85
97
  kind: "plan",
86
98
  input: z.strictObject({ dir: z.string().min(1).default(".").describe("The app's repository") }),
87
99
  },
100
+ "app.values": {
101
+ summary: "Which configuration and secrets app.yml declares, and whether each has a value; never the values.",
102
+ scope: "app", effect: "reads", kind: "query", input: z.strictObject({ server, app, dir }),
103
+ },
104
+ "app.config.set": {
105
+ summary: "Prepare a declared configuration value in the local fleet; apply separately with apps.",
106
+ scope: "app", effect: "changes", kind: "plan", local: true,
107
+ input: z.strictObject({ server, app, dir, key: valueKeySchema, value: z.string().min(1).refine((value) => !value.includes("\0"), "NUL is not an environment value") }),
108
+ },
109
+ "app.secret.import": {
110
+ summary: "Import a declared secret from a local file into the fleet vault; never print its value.",
111
+ scope: "app", effect: "changes", kind: "plan", local: true,
112
+ input: z.strictObject({ server, app, dir, key: valueKeySchema, file: z.string().min(1).describe("Local file containing the secret, not YAML; one trailing newline is removed") }),
113
+ },
114
+ "app.secret.generate": {
115
+ summary: "Generate a 32-byte random secret in the fleet only if missing; preserve existing values.",
116
+ scope: "app", effect: "changes", kind: "plan", local: true,
117
+ input: z.strictObject({ server, app, dir, key: valueKeySchema }),
118
+ },
119
+ "app.launch": {
120
+ summary: "From a repository to a URL that answers: register the app, check its values, apply the apps, deploy and follow it. Run it again after a stop.",
121
+ scope: "app", effect: "changes", kind: "plan",
122
+ input: z.strictObject({
123
+ server, app, dir,
124
+ repo: z.string().min(1).optional().describe("The app's repository, https://; needed until server.yml registers it"),
125
+ ref: z.string().min(1).optional().describe("The branch that deploys (default main)"),
126
+ path: z.string().min(1).optional().describe("The app's root inside the repository (default .)"),
127
+ }),
128
+ },
129
+ "app.hook": {
130
+ summary: "Wire an app's repository (GitHub, GitLab, Forgejo, Gitea) to a server that takes webhooks: check the platform's token reads it, create or update its push hook.",
131
+ scope: "app", effect: "changes", kind: "plan", input: appInput,
132
+ },
88
133
  "app.purge": { summary: "Delete a removed app's volumes: its data, irreversibly.", scope: "app", effect: "destroys", kind: "plan", input: appInput },
89
134
  "app.runs": {
90
135
  summary: "What runs now, and the app's latest runs: state, commit, why, when, how long.",
@@ -166,4 +211,4 @@ export const operationNames = Object.keys(operations).filter((name) => Object.ha
166
211
  export const isOperation = (name) => Object.hasOwn(operations, name);
167
212
  /** An operation as every client reads it, whatever its own entry spells out. */
168
213
  const described = operations;
169
- export const operation = (name) => Object.freeze(described[name]);
214
+ export const operation = (name) => described[name];
@@ -1,7 +1,11 @@
1
+ import { inspectValues } from "../app-values/store.js";
2
+ import { appValues } from "../recipes/app-values.js";
1
3
  import { resolve } from "node:path";
2
4
  import { z } from "zod";
3
5
  import { absolutePath, appName, domain, subdomain, within } from "../fleet/brand.js";
4
- import { appCheck } from "../recipes/app-check.js";
6
+ import { appCheck, appInit } from "../recipes/app-check.js";
7
+ import { launch } from "../recipes/launch.js";
8
+ import { appHook } from "../recipes/app-hook.js";
5
9
  import { doctor } from "../recipes/doctor.js";
6
10
  import { appPurge, apps, deployer } from "../recipes/apps.js";
7
11
  import { adopt, deploy, down, hosts, preview, provision, setup, up, verify } from "../recipes/host.js";
@@ -19,7 +23,7 @@ import { resolve as substitute, spawned } from "../interpreter/process.js";
19
23
  /** The context for a fleet, with the files read from disk: what every client runs the core with. */
20
24
  export const contextFor = (parts) => {
21
25
  const { kayra, ...rest } = parts;
22
- return typed({ ...rest, engine: { kayra, fleet: parts.fleet.root }, read: textAt });
26
+ return typed({ ...rest, engine: { kayra, fleet: parts.fleet.root, version: parts.version }, read: textAt });
23
27
  };
24
28
  /** Every operation with its input: what a client sends, parsed in one go. */
25
29
  const invocations = z.discriminatedUnion("name", [
@@ -36,7 +40,14 @@ const invocations = z.discriminatedUnion("name", [
36
40
  z.strictObject({ name: z.literal("down"), input: operations.down.input }),
37
41
  z.strictObject({ name: z.literal("adopt"), input: operations.adopt.input }),
38
42
  z.strictObject({ name: z.literal("backup.test"), input: operations["backup.test"].input }),
43
+ z.strictObject({ name: z.literal("app.init"), input: operations["app.init"].input }),
39
44
  z.strictObject({ name: z.literal("app.check"), input: operations["app.check"].input }),
45
+ z.strictObject({ name: z.literal("app.values"), input: operations["app.values"].input }),
46
+ z.strictObject({ name: z.literal("app.launch"), input: operations["app.launch"].input }),
47
+ z.strictObject({ name: z.literal("app.hook"), input: operations["app.hook"].input }),
48
+ z.strictObject({ name: z.literal("app.config.set"), input: operations["app.config.set"].input }),
49
+ z.strictObject({ name: z.literal("app.secret.import"), input: operations["app.secret.import"].input }),
50
+ z.strictObject({ name: z.literal("app.secret.generate"), input: operations["app.secret.generate"].input }),
40
51
  z.strictObject({ name: z.literal("app.purge"), input: operations["app.purge"].input }),
41
52
  z.strictObject({ name: z.literal("app.runs"), input: operations["app.runs"].input }),
42
53
  z.strictObject({ name: z.literal("app.log"), input: operations["app.log"].input }),
@@ -68,9 +79,9 @@ const onServer = (ctx, name) => {
68
79
  * app's runs, logs and volumes stay the deployer's to answer for and purge.
69
80
  */
70
81
  const onApp = (ctx, input) => flatMap(onServer(ctx, input.server), (target) => map(appName(input.app), (app) => [target, app]));
82
+ const appDir = (ctx, dir) => dir === undefined ? ok(undefined) : absolutePath(resolve(ctx.here, dir));
71
83
  const withServer = (make) => (ctx, input) => flatMap(onServer(ctx, input.server), (target) => make(ctx.engine, target));
72
84
  const onDeployer = (command) => (ctx, input) => flatMap(onApp(ctx, input), ([target, app]) => deployer(target, command(app, input)));
73
- const optional = (value) => (typeof value === "string" ? value : undefined);
74
85
  /** Each plan operation, as the plan that does it: the compiler refuses one that has none. */
75
86
  const plans = {
76
87
  up: withServer(up),
@@ -86,15 +97,21 @@ const plans = {
86
97
  "backup.test": withServer(backupTest),
87
98
  ssh: (ctx, input) => flatMap(onServer(ctx, input.server), (target) => ssh(target, [])),
88
99
  "ssh.exec": (ctx, input) => flatMap(onServer(ctx, input.server), (target) => ssh(target, input.command)),
100
+ "app.init": (ctx, input) => map(absolutePath(resolve(ctx.here, input.dir)), (dir) => appInit(ctx.engine.kayra, dir, input.name)),
89
101
  "app.check": (ctx, input) => flatMap(absolutePath(resolve(ctx.here, input.dir)), (dir) => appCheck(ctx.engine.kayra, dir, ctx.read(within(dir, "app.yml")))),
102
+ "app.config.set": (ctx, input) => flatMap(onApp(ctx, input), ([server, app]) => flatMap(appDir(ctx, input.dir), (dir) => appValues(ctx.engine, server, app, { kind: "config", key: input.key, value: input.value }, ctx.here, ctx.read, dir))),
103
+ "app.secret.import": (ctx, input) => flatMap(onApp(ctx, input), ([server, app]) => flatMap(appDir(ctx, input.dir), (dir) => appValues(ctx.engine, server, app, { kind: "import", key: input.key, file: input.file }, ctx.here, ctx.read, dir))),
104
+ "app.secret.generate": (ctx, input) => flatMap(onApp(ctx, input), ([server, app]) => flatMap(appDir(ctx, input.dir), (dir) => appValues(ctx.engine, server, app, { kind: "generate", key: input.key }, ctx.here, ctx.read, dir))),
105
+ "app.launch": (ctx, input) => flatMap(onApp(ctx, input), ([server, app]) => flatMap(appDir(ctx, input.dir), (dir) => launch(ctx.engine, ctx.fleet.root, server, { app, repo: input.repo, ref: input.ref, path: input.path, dir }))),
106
+ "app.hook": (ctx, input) => flatMap(onApp(ctx, input), ([server, app]) => appHook(ctx.engine, ctx.fleet.root, server, app)),
90
107
  "app.purge": (ctx, input) => flatMap(onApp(ctx, input), ([target, app]) => appPurge(ctx.engine, target, app)),
91
108
  "app.runs": onDeployer((app) => ({ kind: "runs", app, more: undefined })),
92
- "app.log": onDeployer((app, input) => ({ kind: "logs", app, more: optional(input["run"]) })),
93
- "app.deploy": onDeployer((app, input) => ({ kind: "deploy", app, more: optional(input["ref"]) })),
109
+ "app.log": onDeployer((app, input) => ({ kind: "logs", app, more: input.run })),
110
+ "app.deploy": onDeployer((app, input) => ({ kind: "deploy", app, more: input.ref })),
94
111
  "app.releases": onDeployer((app) => ({ kind: "rollback", app, more: undefined })),
95
- "app.rollback": onDeployer((app, input) => ({ kind: "rollback", app, more: optional(input["sha"]) })),
112
+ "app.rollback": onDeployer((app, input) => ({ kind: "rollback", app, more: input.sha })),
96
113
  job: (ctx, input) => flatMap(onServer(ctx, input.server), (target) => deployer(target, { kind: "job", job: input.job, noPrs: input.noPrs })),
97
- doctor: (ctx) => ok(doctor(ctx.fleet, ctx.engine.kayra)),
114
+ doctor: (ctx) => ok(doctor(ctx.fleet, ctx.engine)),
98
115
  certs: (ctx, input) => flatMap(domain(input.domain), (named) => flatMap(all(input.subdomains.map(subdomain)), (subdomains) => certsFor(ctx.engine, named, subdomains))),
99
116
  };
100
117
  export const planOf = (ctx, call) => plans[call.name](ctx, call.input);
@@ -116,6 +133,20 @@ const deployerAnswer = async (ctx, name, input) => {
116
133
  return exit.code === 0 ? ok(exit.stdout) : err(exit.stderr.trim() || "the deployer query failed");
117
134
  };
118
135
  const queries = {
136
+ "app.values": async (ctx, input) => {
137
+ const target = onApp(ctx, input);
138
+ if (!target.ok)
139
+ return target;
140
+ const dir = appDir(ctx, input.dir);
141
+ if (!dir.ok)
142
+ return dir;
143
+ try {
144
+ return await inspectValues(ctx.fleet.root, target.value[0], target.value[1], dir.value);
145
+ }
146
+ catch {
147
+ return err("app values could not be inspected; check file access and vault configuration");
148
+ }
149
+ },
119
150
  "app.runs": (ctx, input) => deployerAnswer(ctx, "app.runs", input),
120
151
  "app.releases": (ctx, input) => deployerAnswer(ctx, "app.releases", input),
121
152
  "app.log": (ctx, input) => deployerAnswer(ctx, "app.log", input),
@@ -123,13 +154,13 @@ const queries = {
123
154
  const chosen = input.server === undefined ? ok(ctx.fleet.servers) : map(onServer(ctx, input.server), (one) => Object.freeze([one]));
124
155
  if (!chosen.ok)
125
156
  return chosen;
126
- return ok(await Promise.all(chosen.value.map(async (each) => ({ server: each, findings: findings(await gather(ctx.fleet.root, each)) }))));
157
+ return ok(Object.freeze(await Promise.all(chosen.value.map(async (each) => typed({ server: each, findings: findings(await gather(ctx.fleet.root, each)) })))));
127
158
  },
128
159
  version: (ctx) => Promise.resolve(ok(ctx.version)),
129
160
  };
130
161
  export const query = (ctx, name, input) => queries[name](ctx, input);
131
162
  const streams = {
132
- status: (ctx, input) => look(ctx.fleet, ctx.tofu, input.offline ? undefined : ctx.network),
163
+ status: (ctx, input) => look(ctx.fleet, ctx.version, ctx.tofu, input.offline ? undefined : ctx.network),
133
164
  };
134
165
  /** A stream's first state and the updates still to land. */
135
166
  export const stream = (ctx, name, input) => streams[name](ctx, input);
@@ -13,10 +13,23 @@ const tool = (program, hint) => onPath(`${program} is installed`, program, hint,
13
13
  * image plan and the compose policy, the same scripts the builder and the
14
14
  * deployer run). Needs no fleet and no server.
15
15
  */
16
+ /**
17
+ * In an existing project without app.yml: what app init writes (app.yml, an
18
+ * overlay of the project's compose file, an image manifest per built service),
19
+ * then the same check as app check, which names what is left to do.
20
+ */
21
+ export const appInit = (kayra, root, name) => typed([
22
+ tool("git", "brew install git"),
23
+ tool("jq", "brew install jq"),
24
+ tool("yq", "brew install yq"),
25
+ tool("docker", "the docker CLI with Compose; no daemon is needed"),
26
+ run("Write app.yml and the platform's overlay", [process.execPath, within(kayra, "bin", "kayra-app-init.js"), JSON.stringify({ root, ...(name === undefined ? {} : { name }) })]),
27
+ run("Image plan and compose policy", ["bash", within(kayra, "scripts", "local", "app-check.sh"), root]),
28
+ ]);
16
29
  export const appCheck = (kayra, root, manifest) => {
17
30
  if (manifest === undefined)
18
31
  return err(`no app.yml in ${root}`);
19
- const shaped = flatMap(mapError(yamlOf(manifest), (problem) => `app.yml ${problem}`), (values) => checkShape("app.yml", values, appManifestSchema));
32
+ const shaped = flatMap(mapError(yamlOf(manifest), (problem) => `app.yml ${problem}`), (values) => map(checkShape("app.yml", values, appManifestSchema), () => manifest));
20
33
  return map(shaped, () => typed([
21
34
  tool("git", "brew install git"),
22
35
  tool("jq", "brew install jq"),
@@ -0,0 +1,26 @@
1
+ import { within } from "../fleet/brand.js";
2
+ import { run } from "../plan/model.js";
3
+ import { err, flatMap, ok } from "../../lib/result.js";
4
+ import { vaulted } from "./steps.js";
5
+ /** Whether a server takes push webhooks: its vars.yml's `webhooks` (default true), and a forge able to reach it. */
6
+ export const takesWebhooks = (server) => {
7
+ if (server.kind !== "platform")
8
+ return err(`'${server.name}' is a ${server.kind} server: only platform servers run apps.`);
9
+ if (server.vars["webhooks"] === false)
10
+ return err(`${server.name} takes no webhooks (webhooks: false in its vars.yml): pushes deploy by deploy_poll`);
11
+ if (server.target === "multipass")
12
+ return err(`no forge can reach ${server.name}, a multipass VM: deploy there with kayra app deploy`);
13
+ return ok(true);
14
+ };
15
+ /**
16
+ * The app's repository wired to its deployer: the platform's token can read
17
+ * it, and one push hook posts to deploy.<domain>/hook/<app> with the platform's
18
+ * secret (kayra-app-hook.js, over the forge's REST API as the operator).
19
+ */
20
+ export const appHook = (engine, root, server, app) => flatMap(takesWebhooks(server), () => {
21
+ if (!server.apps.some((each) => each.name === app))
22
+ return err(`${app} is not in ${server.name}'s server.yml`);
23
+ return ok([
24
+ vaulted(run(`Hook ${app}'s repository to ${server.name}`, [process.execPath, within(engine.kayra, "bin", "kayra-app-hook.js"), JSON.stringify({ root, server: server.name, app })]), server),
25
+ ]);
26
+ });
@@ -0,0 +1,21 @@
1
+ import { resolve } from "node:path";
2
+ import { editSchema, requirements } from "../app-values/model.js";
3
+ import { within } from "../fleet/brand.js";
4
+ import { run } from "../plan/model.js";
5
+ import { vaulted } from "./steps.js";
6
+ import { err, ok } from "../../lib/result.js";
7
+ export const appValues = (engine, server, app, edit, here, read, dir) => {
8
+ if (!editSchema.safeParse(edit).success)
9
+ return err("invalid app value input");
10
+ const required = requirements(engine.fleet, server, app, read, dir);
11
+ if (!required.ok)
12
+ return required;
13
+ const keys = edit.kind === "config" ? required.value.config : required.value.secrets;
14
+ if (!keys.includes(edit.key))
15
+ return err(`${edit.key} is not a declared ${edit.kind === "config" ? "configuration" : "secret"} key`);
16
+ const input = { ...(dir === undefined ? {} : { dir }), root: engine.fleet, server: server.name, app, edit: edit.kind === "import" ? { ...edit, file: resolve(here, edit.file) } : edit };
17
+ const step = run(`Prepare ${app}'s ${edit.kind === "config" ? "configuration" : "secret"} ${edit.key} in the fleet`, [
18
+ process.execPath, within(engine.kayra, "bin", "kayra-app-values.js"), JSON.stringify(input),
19
+ ]);
20
+ return ok([edit.kind === "config" ? step : vaulted(step, server)]);
21
+ };
@@ -34,7 +34,7 @@ const toolChecks = (fleet) => Object.freeze(tools.flatMap((tool) => {
34
34
  // ansible-vault opens whole-file vaults only; values vaulted inline are opened by setup.
35
35
  const vaultChecks = (fleet) => Object.freeze(fleet.servers.flatMap((server) => server.vault.kind === "file" && server.hasVaultedSecrets
36
36
  ? Object.freeze([
37
- {
37
+ typed({
38
38
  kind: "check",
39
39
  label: `vault password opens ${server.name}'s secrets.yml`,
40
40
  probe: {
@@ -43,7 +43,7 @@ const vaultChecks = (fleet) => Object.freeze(fleet.servers.flatMap((server) => s
43
43
  },
44
44
  hint: `the password file is ${server.vault.file}`,
45
45
  onFailure: "continue",
46
- },
46
+ }),
47
47
  ])
48
48
  : Object.freeze([])));
49
49
  /** The apps' repositories are cloned on this Mac with the operator's own git credentials. */
@@ -54,11 +54,11 @@ const repoChecks = (fleet) => Object.freeze([...new Set(fleet.servers.flatMap((s
54
54
  hint: "gh auth login && gh auth setup-git (or git credentials of your own for that host)",
55
55
  onFailure: "continue",
56
56
  })));
57
- const reachChecks = (fleet, kayra) => Object.freeze(fleet.servers.filter((server) => server.target === "home").map((server) => homeReach({ kayra, fleet: fleet.root }, server, "continue")));
57
+ const reachChecks = (fleet, engine) => Object.freeze(fleet.servers.filter((server) => server.target === "home").map((server) => homeReach(engine, server, "continue")));
58
58
  /** Is this Mac ready to run every command on every server? Each check reports; none stops the others. */
59
- export const doctor = (fleet, kayra) => typed([
59
+ export const doctor = (fleet, engine) => typed([
60
60
  ...toolChecks(fleet),
61
61
  ...vaultChecks(fleet),
62
62
  ...repoChecks(fleet),
63
- ...reachChecks(fleet, kayra),
63
+ ...reachChecks(fleet, engine),
64
64
  ]);
@@ -14,7 +14,7 @@ export const provision = (engine, server) => ok(partOf("provision", [
14
14
  ]
15
15
  : []),
16
16
  ]));
17
- /** The playbook for the server's kind, as setup runs it; plan adds check mode. */
17
+ /** The playbook for the server's kind, as setup runs it; plan adds check mode. It records which kayra ran it (the kayra-version role). */
18
18
  const hostPlaybook = (engine, server, extra = []) => vaulted(run(`Host layer · ${server.kind}.yml${extra.includes("--check") ? ", check mode" : ""}`, [
19
19
  "ansible-playbook",
20
20
  "-i",
@@ -28,6 +28,8 @@ const hostPlaybook = (engine, server, extra = []) => vaulted(run(`Host layer ·
28
28
  `domain=${server.domain}`,
29
29
  "-e",
30
30
  `target=${server.target}`,
31
+ "-e",
32
+ `kayra_version=${engine.version}`,
31
33
  ...extra,
32
34
  ], ansibleEnv(engine, {})), server);
33
35
  /** The host layer: the playbook for the server's kind. */
@@ -70,9 +72,12 @@ export const hosts = (engine, server) => ok(partOf("hosts", server.target === "m
70
72
  ]), [{ kind: "sudo" }])
71
73
  ]
72
74
  : [{ kind: "note", text: `hosts: ${server.target} uses real DNS, nothing to do.` }]));
73
- /** Whether a platform server works as its users see it (scripts/local/verify.sh); other kinds have nothing to check yet. */
75
+ /**
76
+ * Whether a platform server works as its users see it (scripts/local/verify.sh),
77
+ * and runs the kayra this is; other kinds have nothing to check yet.
78
+ */
74
79
  const verifyStep = (engine, server) => typed({
75
- ...run("Verify", ["bash", script(engine, "verify.sh"), server.name], fleetEnv(engine)),
80
+ ...run("Verify", ["bash", script(engine, "verify.sh"), server.name], { ...fleetEnv(engine), KAYRA_VERSION: engine.version }),
76
81
  part: "verify",
77
82
  });
78
83
  export const verify = (engine, server) => server.kind === "platform"
@@ -0,0 +1,51 @@
1
+ import { within } from "../fleet/brand.js";
2
+ import { appEntrySchema } from "../fleet/settings.js";
3
+ import { run } from "../plan/model.js";
4
+ import { err, flatMap, map, ok } from "../../lib/result.js";
5
+ import { apps, deployer } from "./apps.js";
6
+ import { appHook, takesWebhooks } from "./app-hook.js";
7
+ import { forgeRepo } from "../../lib/forge-repo.js";
8
+ import { vaulted } from "./steps.js";
9
+ import { typed } from "../../lib/typed.js";
10
+ /** The server.yml entry the launch registers, or the one already there; a different one given is refused, never overwritten. */
11
+ const entryOf = (server, launch) => {
12
+ const registered = server.apps.find((app) => app.name === launch.app);
13
+ if (registered === undefined) {
14
+ if (launch.repo === undefined)
15
+ return err(`${launch.app} is not in ${server.name}'s server.yml yet: give its repository with --repo https://…`);
16
+ return ok({ name: launch.app, repo: launch.repo, ...(launch.ref === undefined ? {} : { ref: launch.ref }), ...(launch.path === undefined ? {} : { path: launch.path }) });
17
+ }
18
+ const differs = ["repo", "ref", "path"].filter((key) => launch[key] !== undefined && launch[key] !== (registered.entry[key] ?? (key === "path" ? "." : key === "ref" ? "main" : undefined)));
19
+ return differs.length === 0
20
+ ? ok(registered.entry)
21
+ : err(`${server.name}'s server.yml registers ${launch.app} with another ${differs.join(", ")}: change it there, not through launch`);
22
+ };
23
+ /**
24
+ * An app from its repository to a URL that answers, in one plan that may be
25
+ * run again until it ends: register it in server.yml and check that every value
26
+ * it declares is set (kayra-app-launch.js), apply the apps (kayra apps, the new
27
+ * entry included), deploy it and follow the run (its readiness included), then,
28
+ * where the server takes webhooks and the repository is on a forge kayra knows,
29
+ * its push hook.
30
+ * On a server changed only from main, the server.yml change stops the apply
31
+ * at its guard until it is merged: the launch says so, and a rerun goes on.
32
+ */
33
+ export const launch = (engine, root, server, wanted) => {
34
+ if (server.kind !== "platform")
35
+ return err(`'${server.name}' is a ${server.kind} server: only platform servers run apps.`);
36
+ return flatMap(entryOf(server, wanted), (raw) => {
37
+ const parsed = appEntrySchema.safeParse(raw);
38
+ if (!parsed.success)
39
+ return err(`not an app entry: ${parsed.error.issues.map((issue) => `${issue.path.join(".")} ${issue.message}`).join("; ")}`);
40
+ const app = typed({ name: parsed.data.name, repo: parsed.data.repo, path: parsed.data.path, entry: raw });
41
+ const registered = server.apps.some((each) => each.name === app.name);
42
+ const withApp = registered ? server : { ...server, apps: [...server.apps, app] };
43
+ const prepare = vaulted(run(`Register ${app.name} and check its values`, [
44
+ process.execPath,
45
+ within(engine.kayra, "bin", "kayra-app-launch.js"),
46
+ JSON.stringify({ root, server: server.name, entry: raw, ...(wanted.dir === undefined ? {} : { dir: wanted.dir }) }),
47
+ ]), server);
48
+ const hook = takesWebhooks(server).ok && forgeRepo(app.repo) !== undefined ? appHook(engine, root, withApp, app.name) : ok([]);
49
+ return flatMap(apps(engine, withApp), (applied) => flatMap(deployer(server, { kind: "deploy", app: app.name, more: undefined }), (deploy) => map(hook, (hooked) => typed([prepare, ...applied, ...deploy, ...hooked]))));
50
+ });
51
+ };
@@ -1,4 +1,4 @@
1
- import { host, sshDefaultPort, within } from "../fleet/brand.js";
1
+ import { host, kayraVersion, sshDefaultPort, within } from "../fleet/brand.js";
2
2
  import { isMachine } from "./model.js";
3
3
  import { typed } from "../../lib/typed.js";
4
4
  /** The inventory names the address: hand-written at home, written by provision elsewhere. */
@@ -22,34 +22,54 @@ export const sshPort = (server) => server.inventory?.port ?? sshDefaultPort;
22
22
  export const authUrl = (server) => `https://auth.${server.domain}/`;
23
23
  const pending = { kind: "pending" };
24
24
  const skipped = { kind: "skipped" };
25
+ const notAsked = { kind: "skipped" };
26
+ /** What the server's version file holds, as a version: none where setup never recorded one. */
27
+ const running = (read) => {
28
+ if (!read.ok)
29
+ return typed({ kind: "unreadable", reason: read.error });
30
+ const text = read.value.trim();
31
+ if (text === "")
32
+ return typed({ kind: "unrecorded" });
33
+ const version = kayraVersion(text);
34
+ return version.ok ? typed({ kind: "recorded", version: version.value }) : typed({ kind: "unreadable", reason: version.error });
35
+ };
36
+ /** Which kayra set the server up, once SSH answered: its version file, over SSH as the inventory says. */
37
+ const recorded = (server, network, ssh) => ssh.kind === "open" && server.inventory !== undefined && server.versionFile !== undefined
38
+ ? network.read(server.inventory, server.versionFile).then(running)
39
+ : Promise.resolve(notAsked);
25
40
  const at = (index, change) => (looks) => typed(looks.map((look, each) => (each === index ? { ...look, ...change } : look)));
41
+ /** What the network answers: SSH, then the version file once SSH is open; on a platform server, Authelia's health. */
42
+ const probes = (server, index, machine, network) => {
43
+ const ssh = machine.then((found) => found.kind === "found" && found.address !== undefined ? network.connect(found.address, sshPort(server)) : skipped);
44
+ return typed([
45
+ ssh.then((answer) => at(index, { ssh: answer })),
46
+ ssh.then((answer) => recorded(server, network, answer)).then((answer) => at(index, { kayra: answer })),
47
+ ...(server.kind === "platform" ? [network.get(`${authUrl(server)}api/health`).then((answer) => at(index, { https: answer }))] : []),
48
+ ]);
49
+ };
26
50
  /**
27
51
  * Every server as far as the fleet's files tell, and the answers still to
28
52
  * come, each an update to it: OpenTofu's state where no inventory names the
29
- * address, then a TCP connect to SSH, and on platform servers HTTPS on
30
- * auth.<domain> (Authelia's health), all at once. Without a network
31
- * (--offline), only OpenTofu.
53
+ * address, then a TCP connect to SSH and, once it is open, the version file
54
+ * its setup wrote, over SSH; on platform servers HTTPS on auth.<domain>
55
+ * (Authelia's health), all at once. Without a network (--offline), only
56
+ * OpenTofu.
32
57
  */
33
- export const look = (fleet, tofu, network) => fleet.servers.reduce((so, server, index) => {
58
+ export const look = (fleet, pin, tofu, network) => fleet.servers.reduce((so, server, index) => {
34
59
  const known = listed(server);
35
60
  const machine = known === undefined ? provisioned(server, tofu) : Promise.resolve(known);
36
61
  const platform = server.kind === "platform";
37
62
  const updates = [
38
63
  ...(known === undefined ? [machine.then((answer) => at(index, { machine: answer }))] : []),
39
- ...(network === undefined
40
- ? []
41
- : [
42
- machine
43
- .then((found) => found.kind === "found" && found.address !== undefined ? network.connect(found.address, sshPort(server)) : skipped)
44
- .then((answer) => at(index, { ssh: answer })),
45
- ...(platform ? [network.get(`${authUrl(server)}api/health`).then((answer) => at(index, { https: answer }))] : []),
46
- ]),
64
+ ...(network === undefined ? [] : probes(server, index, machine, network)),
47
65
  ];
48
66
  const first = {
49
67
  server,
50
68
  machine: known ?? pending,
51
69
  ssh: network === undefined ? skipped : pending,
52
70
  https: platform ? (network === undefined ? skipped : pending) : undefined,
71
+ kayra: network === undefined ? notAsked : pending,
72
+ pin,
53
73
  };
54
74
  return { initial: [...so.initial, first], updates: [...so.updates, ...updates] };
55
75
  }, { initial: [], updates: [] });
@@ -1,5 +1,7 @@
1
1
  /** Every state a probe's cell can be in, as the API names them. */
2
2
  export const reachStates = ["pending", "open", "answered", "refused", "no-answer", "unreachable", "unknown-host", "bad-certificate", "failed", "skipped"];
3
+ /** Every state the running kayra's cell can be in. */
4
+ export const runningStates = ["pending", "recorded", "unrecorded", "unreadable", "skipped"];
3
5
  /** Every state a machine's cell can be in. */
4
6
  export const machineStates = ["pending", "found", "not-provisioned", "no-machine", "unreadable"];
5
7
  /** A machine kayra's modules create, by its resource type; a data source is none. */
@@ -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,8 +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}`;
9
+ export const subdomain = matching(names.subdomain);
10
+ export const serviceName = matching(names.serviceName);
11
+ export const port = (value) => Number.isInteger(value) && value >= 1 && value <= 65535 ? ok(value) : err(`${String(value)} is not a port`);
12
+ export const routePath = matching(names.routePath);
13
+ export const period = matching(names.period);
6
14
  export const appOwner = (app) => app;
7
15
  export const jobOwner = (job) => `_${job}`;
8
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;
@@ -103,10 +105,15 @@ export const prepare = async (app, commit, s, line) => {
103
105
  const missing = files.find((file) => !existsSync(join(root, file)));
104
106
  if (missing !== undefined)
105
107
  return err(`app.yml: compose file ${missing} does not exist at ${commit}`);
108
+ const routes = await run(["yq", "-o=json", ".routes // []", join(root, "app.yml")], { capture: true }, line);
109
+ if (!routes.ok)
110
+ return routes;
111
+ const routed = JSON.parse(routes.value);
106
112
  return ok({
107
113
  sha: commit,
108
114
  images: artifacts.map(([, variable, ref]) => ({ variable, ref })),
109
115
  compose: files.map((file) => ({ path: file, content: readFileSync(join(root, file), "utf8") })),
116
+ routes: routed,
110
117
  });
111
118
  };
112
119
  const hook = async (s, name, request, response) => {
@@ -181,8 +188,12 @@ export const serveBuilder = (env) => {
181
188
  createServer(failing(async (request, response) => {
182
189
  const path = new URL(request.url ?? "/", "http://builder").pathname;
183
190
  const hooked = /^\/hook\/([^/]+)\/?$/.exec(path);
184
- if (request.method === "POST" && hooked?.[1] !== undefined)
185
- 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
+ }
186
197
  else if (request.method === "GET")
187
198
  pages(s, path, response);
188
199
  else
@@ -2,6 +2,7 @@ import { err, ok } from "../../lib/result.js";
2
2
  import { field } from "../app.js";
3
3
  import { sha } from "../brand.js";
4
4
  import { typed } from "../../lib/typed.js";
5
+ import { parseRoutes } from "./routes.js";
5
6
  const relative = (path) => path !== "" && !path.startsWith("/") && !path.split("/").some((segment) => segment === ".." || segment === "");
6
7
  export const parseBundle = (app, expected, json) => {
7
8
  if (typeof json !== "object" || json === null)
@@ -40,10 +41,14 @@ export const parseBundle = (app, expected, json) => {
40
41
  const problem = [...parsedImages, ...parsedCompose].find((item) => typeof item === "string");
41
42
  if (problem !== undefined)
42
43
  return err(`bundle: ${problem}`);
44
+ const routes = parseRoutes(field(json, "routes"));
45
+ if (!routes.ok)
46
+ return err(`bundle: ${routes.error}`);
43
47
  return ok({
44
48
  sha: minted.value,
45
49
  images: parsedImages.filter((item) => typeof item !== "string"),
46
50
  compose: parsedCompose.filter((item) => typeof item !== "string"),
51
+ routes: routes.value,
47
52
  });
48
53
  };
49
54
  /** images.env, as compose reads it next to the app's own .env. */
@@ -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
+ };