@caelo-cms/provisioning 0.10.47 → 0.10.49

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 (321) hide show
  1. package/caddy/Caddyfile.production +1 -1
  2. package/caddy/Caddyfile.staging +1 -1
  3. package/dist/agent/apply.d.ts +45 -0
  4. package/dist/agent/apply.d.ts.map +1 -0
  5. package/dist/agent/apply.js +83 -0
  6. package/dist/agent/apply.js.map +1 -0
  7. package/dist/agent/cli-provenance.d.ts +42 -0
  8. package/dist/agent/cli-provenance.d.ts.map +1 -0
  9. package/dist/agent/cli-provenance.js +138 -0
  10. package/dist/agent/cli-provenance.js.map +1 -0
  11. package/dist/agent/command.d.ts +79 -0
  12. package/dist/agent/command.d.ts.map +1 -0
  13. package/dist/agent/command.js +454 -0
  14. package/dist/agent/command.js.map +1 -0
  15. package/dist/agent/config.d.ts +30 -0
  16. package/dist/agent/config.d.ts.map +1 -0
  17. package/dist/agent/config.js +60 -0
  18. package/dist/agent/config.js.map +1 -0
  19. package/dist/agent/lock.d.ts +13 -0
  20. package/dist/agent/lock.d.ts.map +1 -0
  21. package/dist/agent/lock.js +100 -0
  22. package/dist/agent/lock.js.map +1 -0
  23. package/dist/agent/queue.d.ts +35 -0
  24. package/dist/agent/queue.d.ts.map +1 -0
  25. package/dist/agent/queue.js +50 -0
  26. package/dist/agent/queue.js.map +1 -0
  27. package/dist/agent/run.d.ts +97 -0
  28. package/dist/agent/run.d.ts.map +1 -0
  29. package/dist/agent/run.js +198 -0
  30. package/dist/agent/run.js.map +1 -0
  31. package/dist/agent/systemd.d.ts +55 -0
  32. package/dist/agent/systemd.d.ts.map +1 -0
  33. package/dist/agent/systemd.js +171 -0
  34. package/dist/agent/systemd.js.map +1 -0
  35. package/dist/agent/units.d.ts +44 -0
  36. package/dist/agent/units.d.ts.map +1 -0
  37. package/dist/agent/units.js +127 -0
  38. package/dist/agent/units.js.map +1 -0
  39. package/dist/agent-db.js +18402 -0
  40. package/dist/cli.js +119 -16
  41. package/dist/cli.js.map +1 -1
  42. package/dist/cloudsql-iam-user.d.ts +39 -0
  43. package/dist/cloudsql-iam-user.d.ts.map +1 -0
  44. package/dist/cloudsql-iam-user.js +119 -0
  45. package/dist/cloudsql-iam-user.js.map +1 -0
  46. package/dist/compose.d.ts +16 -0
  47. package/dist/compose.d.ts.map +1 -1
  48. package/dist/compose.js +26 -1
  49. package/dist/compose.js.map +1 -1
  50. package/dist/dns/index.d.ts +2 -0
  51. package/dist/dns/index.d.ts.map +1 -1
  52. package/dist/dns/index.js +3 -2
  53. package/dist/dns/index.js.map +1 -1
  54. package/dist/dns/manual.d.ts +5 -0
  55. package/dist/dns/manual.d.ts.map +1 -1
  56. package/dist/dns/manual.js +28 -12
  57. package/dist/dns/manual.js.map +1 -1
  58. package/dist/gcloud.d.ts +2 -0
  59. package/dist/gcloud.d.ts.map +1 -1
  60. package/dist/gcloud.js +1 -1
  61. package/dist/gcloud.js.map +1 -1
  62. package/dist/gcp-names.d.ts +15 -0
  63. package/dist/gcp-names.d.ts.map +1 -1
  64. package/dist/gcp-names.js +23 -0
  65. package/dist/gcp-names.js.map +1 -1
  66. package/dist/index.d.ts +6 -0
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +4 -0
  69. package/dist/index.js.map +1 -1
  70. package/dist/infra-contract.d.ts +1 -1
  71. package/dist/infra-contract.js +7 -1
  72. package/dist/infra-contract.js.map +1 -1
  73. package/dist/install-job-runner.d.ts +13 -0
  74. package/dist/install-job-runner.d.ts.map +1 -0
  75. package/dist/install-job-runner.js +155 -0
  76. package/dist/install-job-runner.js.map +1 -0
  77. package/dist/install-job.d.ts +210 -0
  78. package/dist/install-job.d.ts.map +1 -0
  79. package/dist/install-job.js +449 -0
  80. package/dist/install-job.js.map +1 -0
  81. package/dist/install-state.d.ts +10 -1
  82. package/dist/install-state.d.ts.map +1 -1
  83. package/dist/install-state.js +10 -2
  84. package/dist/install-state.js.map +1 -1
  85. package/dist/lifecycle.d.ts.map +1 -1
  86. package/dist/lifecycle.js +19 -4
  87. package/dist/lifecycle.js.map +1 -1
  88. package/dist/migration-runner.d.ts +5 -0
  89. package/dist/migration-runner.d.ts.map +1 -1
  90. package/dist/migration-runner.js +1 -1
  91. package/dist/migration-runner.js.map +1 -1
  92. package/dist/operator-access.d.ts +14 -8
  93. package/dist/operator-access.d.ts.map +1 -1
  94. package/dist/operator-access.js +16 -102
  95. package/dist/operator-access.js.map +1 -1
  96. package/dist/release-manifest.d.ts +2 -41
  97. package/dist/release-manifest.d.ts.map +1 -1
  98. package/dist/release-manifest.js +18 -121
  99. package/dist/release-manifest.js.map +1 -1
  100. package/dist/run-mode.d.ts +27 -0
  101. package/dist/run-mode.d.ts.map +1 -0
  102. package/dist/run-mode.js +22 -0
  103. package/dist/run-mode.js.map +1 -0
  104. package/dist/runtime-secrets.d.ts +19 -0
  105. package/dist/runtime-secrets.d.ts.map +1 -1
  106. package/dist/runtime-secrets.js +44 -0
  107. package/dist/runtime-secrets.js.map +1 -1
  108. package/dist/self-hosted-roles.d.ts +22 -1
  109. package/dist/self-hosted-roles.d.ts.map +1 -1
  110. package/dist/self-hosted-roles.js +81 -12
  111. package/dist/self-hosted-roles.js.map +1 -1
  112. package/dist/self-hosted-upgrade.d.ts +17 -0
  113. package/dist/self-hosted-upgrade.d.ts.map +1 -1
  114. package/dist/self-hosted-upgrade.js +16 -1
  115. package/dist/self-hosted-upgrade.js.map +1 -1
  116. package/dist/stack-contract.d.ts +6 -0
  117. package/dist/stack-contract.d.ts.map +1 -1
  118. package/dist/stack-contract.js +10 -1
  119. package/dist/stack-contract.js.map +1 -1
  120. package/dist/upgrade/converge.d.ts +6 -0
  121. package/dist/upgrade/converge.d.ts.map +1 -1
  122. package/dist/upgrade/converge.js +59 -2
  123. package/dist/upgrade/converge.js.map +1 -1
  124. package/dist/upgrade/gcp-lookup.d.ts +6 -0
  125. package/dist/upgrade/gcp-lookup.d.ts.map +1 -1
  126. package/dist/upgrade/gcp-lookup.js +25 -0
  127. package/dist/upgrade/gcp-lookup.js.map +1 -1
  128. package/dist/upgrade/release-images.d.ts +26 -2
  129. package/dist/upgrade/release-images.d.ts.map +1 -1
  130. package/dist/upgrade/release-images.js +35 -2
  131. package/dist/upgrade/release-images.js.map +1 -1
  132. package/dist/upgrade/upgrade.d.ts +5 -0
  133. package/dist/upgrade/upgrade.d.ts.map +1 -1
  134. package/dist/upgrade/upgrade.js +28 -1
  135. package/dist/upgrade/upgrade.js.map +1 -1
  136. package/dist/upgrader-assess.d.ts +85 -0
  137. package/dist/upgrader-assess.d.ts.map +1 -0
  138. package/dist/upgrader-assess.js +122 -0
  139. package/dist/upgrader-assess.js.map +1 -0
  140. package/dist/upgrader-gcp.d.ts +17 -0
  141. package/dist/upgrader-gcp.d.ts.map +1 -0
  142. package/dist/upgrader-gcp.js +87 -0
  143. package/dist/upgrader-gcp.js.map +1 -0
  144. package/dist/upgrader-job.d.ts +133 -0
  145. package/dist/upgrader-job.d.ts.map +1 -0
  146. package/dist/upgrader-job.js +259 -0
  147. package/dist/upgrader-job.js.map +1 -0
  148. package/dist/upgrader-reporter.d.ts +35 -0
  149. package/dist/upgrader-reporter.d.ts.map +1 -0
  150. package/dist/upgrader-reporter.js +79 -0
  151. package/dist/upgrader-reporter.js.map +1 -0
  152. package/dist/upgrader-setup.d.ts +59 -0
  153. package/dist/upgrader-setup.d.ts.map +1 -0
  154. package/dist/upgrader-setup.js +308 -0
  155. package/dist/upgrader-setup.js.map +1 -0
  156. package/dist/wizard.d.ts +6 -0
  157. package/dist/wizard.d.ts.map +1 -1
  158. package/dist/wizard.js +32 -4
  159. package/dist/wizard.js.map +1 -1
  160. package/dist/wizards/gcp-firebase.d.ts +3 -0
  161. package/dist/wizards/gcp-firebase.d.ts.map +1 -1
  162. package/dist/wizards/gcp-firebase.js +1 -0
  163. package/dist/wizards/gcp-firebase.js.map +1 -1
  164. package/dist/wizards/gcp-install-job.d.ts +74 -0
  165. package/dist/wizards/gcp-install-job.d.ts.map +1 -0
  166. package/dist/wizards/gcp-install-job.js +398 -0
  167. package/dist/wizards/gcp-install-job.js.map +1 -0
  168. package/dist/wizards/gcp-prompts.d.ts +3 -0
  169. package/dist/wizards/gcp-prompts.d.ts.map +1 -0
  170. package/dist/wizards/gcp-prompts.js +25 -0
  171. package/dist/wizards/gcp-prompts.js.map +1 -0
  172. package/dist/wizards/gcp-pulumi.d.ts +4 -2
  173. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  174. package/dist/wizards/gcp-pulumi.js +1 -1
  175. package/dist/wizards/gcp-pulumi.js.map +1 -1
  176. package/dist/wizards/gcp.d.ts +40 -0
  177. package/dist/wizards/gcp.d.ts.map +1 -1
  178. package/dist/wizards/gcp.js +223 -59
  179. package/dist/wizards/gcp.js.map +1 -1
  180. package/package.json +6 -4
  181. package/src/adapter.ts +97 -0
  182. package/src/adc-impersonation.ts +176 -0
  183. package/src/admin-domain.test.ts +254 -0
  184. package/src/admin-domain.ts +245 -0
  185. package/src/admin-memory.test.ts +151 -0
  186. package/src/agent/apply.test.ts +185 -0
  187. package/src/agent/apply.ts +124 -0
  188. package/src/agent/cli-provenance.test.ts +159 -0
  189. package/src/agent/cli-provenance.ts +191 -0
  190. package/src/agent/command.test.ts +77 -0
  191. package/src/agent/command.ts +564 -0
  192. package/src/agent/config.ts +86 -0
  193. package/src/agent/lock-config.test.ts +97 -0
  194. package/src/agent/lock.ts +110 -0
  195. package/src/agent/queue.test.ts +10 -0
  196. package/src/agent/queue.ts +91 -0
  197. package/src/agent/run.test.ts +437 -0
  198. package/src/agent/run.ts +295 -0
  199. package/src/agent/systemd.ts +209 -0
  200. package/src/agent/units.test.ts +223 -0
  201. package/src/agent/units.ts +163 -0
  202. package/src/azure-front-door.test.ts +119 -0
  203. package/src/azure-front-door.ts +56 -0
  204. package/src/bootstrap-token.ts +20 -0
  205. package/src/caddy.ts +112 -0
  206. package/src/cdn-copy.ts +91 -0
  207. package/src/cert-wait.test.ts +194 -0
  208. package/src/cert-wait.ts +163 -0
  209. package/src/checkpoint-secrets.test.ts +380 -0
  210. package/src/checkpoint-secrets.ts +283 -0
  211. package/src/cli-routing.test.ts +45 -0
  212. package/src/cli-routing.ts +43 -0
  213. package/src/cli.ts +1491 -0
  214. package/src/cloudsql-iam-user.ts +147 -0
  215. package/src/compose.ts +334 -0
  216. package/src/default-firewall.test.ts +411 -0
  217. package/src/default-firewall.ts +342 -0
  218. package/src/deployed-release.test.ts +231 -0
  219. package/src/deployed-release.ts +220 -0
  220. package/src/dns/cloudflare.ts +182 -0
  221. package/src/dns/groups.test.ts +76 -0
  222. package/src/dns/groups.ts +86 -0
  223. package/src/dns/index.ts +56 -0
  224. package/src/dns/manual.ts +130 -0
  225. package/src/dns/types.ts +27 -0
  226. package/src/gateway-credentials.test.ts +180 -0
  227. package/src/gateway-credentials.ts +144 -0
  228. package/src/gcloud-components.test.ts +76 -0
  229. package/src/gcloud-components.ts +85 -0
  230. package/src/gcloud-retry.ts +41 -0
  231. package/src/gcloud-runner.test.ts +61 -0
  232. package/src/gcloud.test.ts +99 -0
  233. package/src/gcloud.ts +322 -0
  234. package/src/gcp-names.ts +135 -0
  235. package/src/index.test.ts +332 -0
  236. package/src/index.ts +114 -0
  237. package/src/infra-contract.ts +32 -0
  238. package/src/install-job-runner.ts +166 -0
  239. package/src/install-job.test.ts +566 -0
  240. package/src/install-job.ts +542 -0
  241. package/src/install-state.test.ts +239 -0
  242. package/src/install-state.ts +583 -0
  243. package/src/internal-token.ts +35 -0
  244. package/src/lifecycle.ts +900 -0
  245. package/src/mcp-iap-stacks.test.ts +58 -0
  246. package/src/mcp-iap.test.ts +149 -0
  247. package/src/mcp-iap.ts +131 -0
  248. package/src/media-volume.test.ts +296 -0
  249. package/src/migration-runner.ts +365 -0
  250. package/src/operator-access-stacks.test.ts +55 -0
  251. package/src/operator-access.test.ts +332 -0
  252. package/src/operator-access.ts +554 -0
  253. package/src/ops-backend.test.ts +320 -0
  254. package/src/ops-backend.ts +414 -0
  255. package/src/provisioner-identity.test.ts +482 -0
  256. package/src/provisioner-identity.ts +407 -0
  257. package/src/redirects-emit.ts +175 -0
  258. package/src/region-data.ts +428 -0
  259. package/src/regions.test.ts +277 -0
  260. package/src/regions.ts +370 -0
  261. package/src/release-contract.ts +57 -0
  262. package/src/release-manifest.test.ts +300 -0
  263. package/src/release-manifest.ts +310 -0
  264. package/src/run-mode.ts +40 -0
  265. package/src/runtime-secrets.test.ts +627 -0
  266. package/src/runtime-secrets.ts +754 -0
  267. package/src/self-command.test.ts +14 -0
  268. package/src/self-command.ts +21 -0
  269. package/src/self-hosted-compose.test.ts +177 -0
  270. package/src/self-hosted-release.ts +240 -0
  271. package/src/self-hosted-roles.integration.test.ts +161 -0
  272. package/src/self-hosted-roles.test.ts +124 -0
  273. package/src/self-hosted-roles.ts +203 -0
  274. package/src/self-hosted-upgrade.test.ts +394 -0
  275. package/src/self-hosted-upgrade.ts +548 -0
  276. package/src/stack-contract-parity.test.ts +199 -0
  277. package/src/stack-contract.test.ts +391 -0
  278. package/src/stack-contract.ts +888 -0
  279. package/src/stack-converge-secrets.test.ts +421 -0
  280. package/src/stack-converge.test.ts +833 -0
  281. package/src/stack-converge.ts +909 -0
  282. package/src/staging-admin.test.ts +246 -0
  283. package/src/staging-admin.ts +324 -0
  284. package/src/state-attach.test.ts +211 -0
  285. package/src/state-attach.ts +132 -0
  286. package/src/state-backend.test.ts +145 -0
  287. package/src/state-backend.ts +262 -0
  288. package/src/state-command.ts +293 -0
  289. package/src/state-migrate.test.ts +479 -0
  290. package/src/state-migrate.ts +434 -0
  291. package/src/state-pulumi.ts +289 -0
  292. package/src/state-store.test.ts +212 -0
  293. package/src/state-store.ts +243 -0
  294. package/src/upgrade/app-roll.ts +486 -0
  295. package/src/upgrade/backup.ts +109 -0
  296. package/src/upgrade/converge.ts +437 -0
  297. package/src/upgrade/gcp-lookup.ts +167 -0
  298. package/src/upgrade/health.test.ts +279 -0
  299. package/src/upgrade/health.ts +305 -0
  300. package/src/upgrade/release-images.test.ts +119 -0
  301. package/src/upgrade/release-images.ts +393 -0
  302. package/src/upgrade/reporter.ts +46 -0
  303. package/src/upgrade/upgrade.test.ts +626 -0
  304. package/src/upgrade/upgrade.ts +249 -0
  305. package/src/upgrader-assess.test.ts +306 -0
  306. package/src/upgrader-assess.ts +250 -0
  307. package/src/upgrader-gcp.ts +123 -0
  308. package/src/upgrader-job.test.ts +411 -0
  309. package/src/upgrader-job.ts +502 -0
  310. package/src/upgrader-reporter.test.ts +46 -0
  311. package/src/upgrader-reporter.ts +105 -0
  312. package/src/upgrader-setup.test.ts +169 -0
  313. package/src/upgrader-setup.ts +355 -0
  314. package/src/wizard.ts +425 -0
  315. package/src/wizards/gcp-cost.ts +188 -0
  316. package/src/wizards/gcp-firebase.ts +72 -0
  317. package/src/wizards/gcp-install-job.ts +506 -0
  318. package/src/wizards/gcp-prompts.ts +26 -0
  319. package/src/wizards/gcp-pulumi.test.ts +246 -0
  320. package/src/wizards/gcp-pulumi.ts +516 -0
  321. package/src/wizards/gcp.ts +1935 -0
@@ -0,0 +1,486 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * The app-roll half of an upgrade (epic #696): migrations with the new admin
5
+ * image, then admin and gateway onto their new images with the env contract
6
+ * riding the same revision, traffic onto the new revisions, a deep health
7
+ * check, and — on any failure — traffic back onto the revisions that served
8
+ * before.
9
+ *
10
+ * It never changes IAM, never creates a service account or secret and never
11
+ * touches other cloud resources: everything here works under an identity
12
+ * that may only deploy Cloud Run revisions, run the migration job and take a
13
+ * Cloud SQL backup. That is the identity the in-cloud upgrader job runs as.
14
+ * Whatever needs more lives in converge.ts; `cms-provision upgrade` runs
15
+ * both, and the upgrader job refuses to run while the install needs a
16
+ * converge (`needsConverge`).
17
+ *
18
+ * Converge steps that must sit between app-roll steps — a database role that
19
+ * a migration creates gets its password after migrations and before the
20
+ * gateway rolls — come in through {@link AppRollHooks}. The upgrader job
21
+ * passes none.
22
+ *
23
+ * All gcloud calls go through the injected runner, all output through the
24
+ * injected reporter, so the whole sequence runs against a fake in tests.
25
+ */
26
+
27
+ import type { GcloudRunner, Sleep } from "../gcloud-retry.js";
28
+ import { gatewayServiceAccountEmail, runServiceAccountEmail } from "../gcp-names.js";
29
+ import type { ImageDigests } from "../install-state.js";
30
+ import { adminMediaVolume } from "../stack-contract.js";
31
+ import {
32
+ type DeployedService,
33
+ type EnvChange,
34
+ type LiveEnvValue,
35
+ type LiveVolumes,
36
+ liveContainerEnv,
37
+ liveContainerMemory,
38
+ liveVolumes,
39
+ planAdminMemory,
40
+ planContractEnv,
41
+ planMediaVolume,
42
+ rollService,
43
+ serviceRollArgs,
44
+ } from "../stack-converge.js";
45
+ import { restoreCommand, type SqlBackup } from "./backup.js";
46
+ import {
47
+ describeServiceJson,
48
+ findCurrentRevision,
49
+ findServiceUrl,
50
+ pinTraffic,
51
+ resolveGcpResourceName,
52
+ } from "./gcp-lookup.js";
53
+ import type { HealthProbe } from "./health.js";
54
+ import type { UpgradeReporter } from "./reporter.js";
55
+
56
+ export type RollSlug = "admin" | "gateway";
57
+
58
+ /** The roll order: the gateway follows the admin, never the other way round. */
59
+ export const ROLL_ORDER: readonly RollSlug[] = ["admin", "gateway"];
60
+
61
+ /** The install an app-roll acts on. */
62
+ export interface AppRollInstall {
63
+ readonly provider: "gcp" | "gcp-firebase";
64
+ readonly projectId: string;
65
+ readonly region: string;
66
+ /** Pulumi stack name (`production`). */
67
+ readonly env: string;
68
+ readonly domain: string;
69
+ /** The protected staging host the admin is told about (#650). */
70
+ readonly stagingHost: string;
71
+ }
72
+
73
+ /** The release image one service rolls to. */
74
+ export interface ReleaseImage {
75
+ /** Fully qualified, digest-pinned reference (`…/admin@sha256:…`). */
76
+ readonly imageRef: string;
77
+ readonly digest: string;
78
+ }
79
+
80
+ /** A service as it runs now, plus the image it rolls to. */
81
+ export interface ServicePlan {
82
+ readonly slug: RollSlug;
83
+ readonly serviceName: string;
84
+ readonly imageRef: string;
85
+ readonly digest: string;
86
+ readonly priorRevision: string;
87
+ readonly liveEnv: ReadonlyMap<string, LiveEnvValue>;
88
+ /** Container memory limit now (null = Cloud Run's default). */
89
+ readonly liveMemory: string | null;
90
+ readonly liveVolumes: LiveVolumes;
91
+ }
92
+
93
+ /** A service plan plus the changes its roll applies. */
94
+ export interface RollPlan extends ServicePlan {
95
+ readonly envFlags: readonly string[];
96
+ readonly envChanges: readonly EnvChange[];
97
+ /** #553 — e.g. `--memory=2Gi` when the admin runs below the stack default. */
98
+ readonly resourceFlags: readonly string[];
99
+ /** The admin's media bucket volume when it is (partly) missing; empty otherwise. */
100
+ readonly volumeFlags: readonly string[];
101
+ readonly volumeChanges: readonly string[];
102
+ }
103
+
104
+ /** Everything an app-roll will do, computed read-only before anything changes. */
105
+ export interface AppRollPlan {
106
+ readonly install: AppRollInstall;
107
+ /** In {@link ROLL_ORDER}. */
108
+ readonly services: readonly RollPlan[];
109
+ /** Notes for the operator (e.g. a memory limit left as is). */
110
+ readonly warnings: readonly string[];
111
+ }
112
+
113
+ export type PlanResult =
114
+ | { readonly ok: true; readonly plan: AppRollPlan }
115
+ | { readonly ok: false; readonly error: string };
116
+
117
+ /**
118
+ * Read both services and plan their rolls: prior revisions (the rollback
119
+ * targets), env-contract changes, the admin's memory and media volume. Makes
120
+ * no change; fails when anything a roll needs is missing.
121
+ */
122
+ export async function planAppRoll(
123
+ install: AppRollInstall,
124
+ images: Readonly<Record<RollSlug, ReleaseImage>>,
125
+ run: GcloudRunner,
126
+ ): Promise<PlanResult> {
127
+ const services: ServicePlan[] = [];
128
+ for (const slug of ROLL_ORDER) {
129
+ const prefix = `caelo-${install.env}-${slug}`;
130
+ const serviceName = await resolveGcpResourceName(
131
+ run,
132
+ "run-service",
133
+ prefix,
134
+ install.projectId,
135
+ install.region,
136
+ );
137
+ if (!serviceName)
138
+ return { ok: false, error: `Could not find the ${prefix}* Cloud Run service` };
139
+ const priorRevision = await findCurrentRevision(
140
+ run,
141
+ install.projectId,
142
+ install.region,
143
+ serviceName,
144
+ );
145
+ if (!priorRevision) {
146
+ return {
147
+ ok: false,
148
+ error: `Could not capture the current ${slug} revision — refusing to roll`,
149
+ };
150
+ }
151
+ const json = await describeServiceJson(run, install.projectId, install.region, serviceName);
152
+ if (!json) {
153
+ return {
154
+ ok: false,
155
+ error: `Could not read the ${slug} service's configuration — refusing to roll`,
156
+ };
157
+ }
158
+ services.push({
159
+ slug,
160
+ serviceName,
161
+ ...images[slug],
162
+ priorRevision,
163
+ liveEnv: liveContainerEnv(json),
164
+ liveMemory: liveContainerMemory(json),
165
+ liveVolumes: liveVolumes(json),
166
+ });
167
+ }
168
+ const env = planEnv(install, services, []);
169
+ if (!env.ok)
170
+ return { ok: false, error: `the install's env contract can't be applied: ${env.error}` };
171
+ // Without the media volume every upload is lost on the next revision or
172
+ // scale-to-zero, so a volume the roll cannot add fails the plan.
173
+ const admin = services.find((s) => s.slug === "admin") as ServicePlan;
174
+ const media = planMediaVolume(
175
+ admin.liveVolumes,
176
+ adminMediaVolume(install.projectId, install.env),
177
+ );
178
+ if (!media.ok)
179
+ return { ok: false, error: `the admin's media volume can't be set up: ${media.error}` };
180
+ const warnings: string[] = [];
181
+ const rolls = services.map((s): RollPlan => {
182
+ // #553 — the admin runs the Lighthouse quality audit; raise it to the
183
+ // stack's memory default (never lowered; an unparsable value is kept).
184
+ const memory = s.slug === "admin" ? planAdminMemory(s.liveMemory) : null;
185
+ if (memory && !memory.ok) warnings.push(`admin memory left as is: ${memory.error}`);
186
+ return {
187
+ ...s,
188
+ envFlags: env.services[s.slug].flags,
189
+ envChanges: env.services[s.slug].changes,
190
+ resourceFlags: memory?.ok ? memory.flags : [],
191
+ volumeFlags: s.slug === "admin" ? media.flags : [],
192
+ volumeChanges: s.slug === "admin" ? media.changes : [],
193
+ };
194
+ });
195
+ return { ok: true, plan: { install, services: rolls, warnings } };
196
+ }
197
+
198
+ function planEnv(
199
+ install: AppRollInstall,
200
+ services: readonly ServicePlan[],
201
+ leaveUntouched: readonly string[],
202
+ ) {
203
+ const deployed = Object.fromEntries(
204
+ services.map((s) => [s.slug, { serviceName: s.serviceName, liveEnv: s.liveEnv }]),
205
+ ) as Record<RollSlug, DeployedService>;
206
+ return planContractEnv(
207
+ {
208
+ provider: install.provider,
209
+ projectId: install.projectId,
210
+ env: install.env,
211
+ domain: install.domain,
212
+ region: install.region,
213
+ stagingHost: install.stagingHost,
214
+ },
215
+ deployed,
216
+ { leaveUntouched },
217
+ );
218
+ }
219
+
220
+ /**
221
+ * The plan with `names` left exactly as the services have them — for env
222
+ * vars that point at something a converge step could not set up.
223
+ */
224
+ export function leavingEnvUntouched(plan: AppRollPlan, names: readonly string[]): AppRollPlan {
225
+ if (names.length === 0) return plan;
226
+ const env = planEnv(plan.install, plan.services, names);
227
+ if (!env.ok) return plan;
228
+ return {
229
+ ...plan,
230
+ services: plan.services.map((s) => ({
231
+ ...s,
232
+ envFlags: env.services[s.slug].flags,
233
+ envChanges: env.services[s.slug].changes,
234
+ })),
235
+ };
236
+ }
237
+
238
+ /** Print what the plan will change, one line per change. */
239
+ export function reportPlan(plan: AppRollPlan, reporter: UpgradeReporter): void {
240
+ for (const w of plan.warnings) reporter.warn(w);
241
+ for (const s of plan.services) {
242
+ for (const c of s.volumeChanges) reporter.info(`${s.slug} media: ${c}`);
243
+ for (const f of s.resourceFlags) {
244
+ reporter.info(`${s.slug} resources: ${s.liveMemory ?? "(default)"} → ${f}`);
245
+ }
246
+ for (const c of s.envChanges) {
247
+ reporter.info(
248
+ `${s.slug} env ${c.name}: ${c.from === undefined ? "(unset)" : c.from} → ${c.to === undefined ? "(removed)" : c.to}`,
249
+ );
250
+ }
251
+ }
252
+ }
253
+
254
+ /** Converge steps that must sit between app-roll steps (none for the upgrader job). */
255
+ export interface AppRollHooks {
256
+ /**
257
+ * After migrations, before any service rolls. Returns the contract env
258
+ * vars the rolls must leave untouched because what they point at could
259
+ * not be set up; `ok: false` aborts the upgrade (nothing rolled yet).
260
+ */
261
+ afterMigrations?(): Promise<
262
+ { readonly ok: true; readonly leaveUntouched: readonly string[] } | { readonly ok: false }
263
+ >;
264
+ /** Right before `slug` rolls; `ok: false` aborts and rolls back what rolled. */
265
+ beforeRoll?(
266
+ slug: RollSlug,
267
+ ): Promise<{ readonly ok: true } | { readonly ok: false; readonly error: string }>;
268
+ /** After `slug` went back to its prior revision (or its roll failed). */
269
+ afterRollback?(slug: RollSlug): Promise<void>;
270
+ }
271
+
272
+ export interface AppRollDeps {
273
+ readonly run: GcloudRunner;
274
+ readonly sleep?: Sleep;
275
+ readonly reporter: UpgradeReporter;
276
+ /** Runs both migration targets with `imageRef` (the NEW admin image). */
277
+ readonly migrate: (
278
+ imageRef: string,
279
+ ) => Promise<{ readonly ok: boolean; readonly error?: string }>;
280
+ /** The deep health check, or null when the operator explicitly skipped it. */
281
+ readonly health: HealthProbe | null;
282
+ /** Persist the digests now serving (install.json, stack config, …). */
283
+ readonly recordDigests: (digests: ImageDigests) => Promise<void>;
284
+ }
285
+
286
+ export interface AppRollInput {
287
+ readonly plan: AppRollPlan;
288
+ /**
289
+ * The backup taken before this roll. Required: migrations never run
290
+ * without a backup to go back to.
291
+ */
292
+ readonly backup: SqlBackup;
293
+ /** The release version rolled to, when known (`0.11.0`; null for a channel tag). */
294
+ readonly targetVersion: string | null;
295
+ /**
296
+ * Whether the release's migrations are contract-type (destructive for the
297
+ * previous release; from the signed release manifest). null = unknown.
298
+ */
299
+ readonly migrationsContract: boolean | null;
300
+ }
301
+
302
+ export type AppRollPhase = "health-baseline" | "migrations" | "converge" | "roll" | "health";
303
+
304
+ export type AppRollResult =
305
+ | { readonly ok: true; readonly digests: ImageDigests }
306
+ | {
307
+ readonly ok: false;
308
+ readonly phase: AppRollPhase;
309
+ /** Whether migrations ran before the failure (the backup matters then). */
310
+ readonly migrated: boolean;
311
+ };
312
+
313
+ /** Run the app-roll. See the file comment for the sequence. */
314
+ export async function executeAppRoll(
315
+ input: AppRollInput,
316
+ hooks: AppRollHooks,
317
+ deps: AppRollDeps,
318
+ ): Promise<AppRollResult> {
319
+ const { reporter: r, run } = deps;
320
+ const { install } = input.plan;
321
+ let plan = input.plan;
322
+ const fail = (phase: AppRollPhase, migrated: boolean): AppRollResult => ({
323
+ ok: false,
324
+ phase,
325
+ migrated,
326
+ });
327
+
328
+ // A probe that cannot reach the install now would only fail after the
329
+ // migrations, and roll a healthy release back.
330
+ if (deps.health) {
331
+ const s = r.step("Checking the health check can reach admin + gateway...");
332
+ const base = await deps.health.baseline().catch((e: unknown) => ({
333
+ ok: false as const,
334
+ error: e instanceof Error ? e.message : String(e),
335
+ }));
336
+ if (!base.ok) {
337
+ s.failed(`Health check can't reach the install: ${base.error}`);
338
+ r.warn(
339
+ "No migrations ran and no traffic moved. Fix the access problem, or re-run with --skip-health-check to roll with Cloud Run's readiness check only.",
340
+ );
341
+ return fail("health-baseline", false);
342
+ }
343
+ s.done(`Health check reaches the install (${base.detail})`);
344
+ } else {
345
+ r.warn("--skip-health-check set — the new revisions get Cloud Run's readiness check only.");
346
+ }
347
+
348
+ // Migrations BEFORE any traffic moves, with the NEW admin image: the old
349
+ // image does not carry the release's migration files (v0.9.2).
350
+ const admin = plan.services.find((s) => s.slug === "admin") as RollPlan;
351
+ const sMig = r.step("Applying DB migrations (idempotent)...");
352
+ const mig = await deps.migrate(admin.imageRef);
353
+ if (!mig.ok) {
354
+ sMig.failed(`Migrations failed (${mig.error ?? "unknown"}). Aborting upgrade.`);
355
+ r.warn(
356
+ `No traffic was shifted. Inspect the Cloud Run Job logs:\n gcloud logging read 'resource.type=cloud_run_job AND resource.labels.job_name=~"caelo-migrate-.*"' --project=${install.projectId} --limit=50\n${restoreHint(input, "if a migration left the schema half-applied")}`,
357
+ );
358
+ return fail("migrations", true);
359
+ }
360
+ sMig.done("Migrations applied");
361
+
362
+ if (hooks.afterMigrations) {
363
+ const converged = await hooks.afterMigrations();
364
+ if (!converged.ok) return fail("converge", true);
365
+ plan = leavingEnvUntouched(plan, converged.leaveUntouched);
366
+ }
367
+
368
+ const rolled: RollPlan[] = [];
369
+ const rollBack = async (alsoCurrent?: RollPlan): Promise<void> => {
370
+ const services = alsoCurrent ? [...rolled, alsoCurrent] : rolled;
371
+ if (services.length === 0) return;
372
+ r.warn(`Rolling back ${services.length} service(s) to the revisions that served before...`);
373
+ for (const p of [...services].reverse()) {
374
+ const ok = await pinTraffic(
375
+ run,
376
+ install.projectId,
377
+ install.region,
378
+ p.serviceName,
379
+ p.priorRevision,
380
+ );
381
+ if (ok) r.info(` ${p.slug} traffic restored to ${p.priorRevision}`);
382
+ else r.error(` ${p.slug} rollback FAILED — pin ${p.priorRevision} by hand`);
383
+ await hooks.afterRollback?.(p.slug);
384
+ }
385
+ };
386
+
387
+ for (const p of plan.services) {
388
+ const s = r.step(`Rolling ${p.slug} → ${p.digest.slice(0, 19)}...`);
389
+ const before = (await hooks.beforeRoll?.(p.slug)) ?? { ok: true as const };
390
+ if (!before.ok) {
391
+ s.failed(before.error);
392
+ await rollBack();
393
+ return fail("roll", true);
394
+ }
395
+ const upd = await rollService(
396
+ serviceRollArgs({
397
+ serviceName: p.serviceName,
398
+ region: install.region,
399
+ projectId: install.projectId,
400
+ imageRef: p.imageRef,
401
+ serviceAccount:
402
+ p.slug === "admin"
403
+ ? runServiceAccountEmail(install.projectId, install.env)
404
+ : gatewayServiceAccountEmail(install.projectId, install.env),
405
+ envFlags: p.envFlags,
406
+ resourceFlags: p.resourceFlags,
407
+ volumeFlags: p.volumeFlags,
408
+ }),
409
+ { run, ...(deps.sleep ? { sleep: deps.sleep } : {}) },
410
+ );
411
+ if (!upd.ok) {
412
+ s.failed(`Failed: ${upd.stderr.trim()}`);
413
+ // The failed update created no serving revision; only undo what the
414
+ // hook changed for it, then the services that rolled before.
415
+ await hooks.afterRollback?.(p.slug);
416
+ await rollBack();
417
+ return fail("roll", true);
418
+ }
419
+ // `update --image` only moves traffic when the service has no explicit
420
+ // traffic config — but a rollback pins traffic to the prior revision,
421
+ // and that pin survives later updates. Moving traffic to latest on
422
+ // every roll is idempotent and un-pins services an earlier failed
423
+ // upgrade left pinned.
424
+ const flip = await run([
425
+ "run",
426
+ "services",
427
+ "update-traffic",
428
+ p.serviceName,
429
+ "--region",
430
+ install.region,
431
+ "--project",
432
+ install.projectId,
433
+ "--to-latest",
434
+ "--quiet",
435
+ ]);
436
+ if (!flip.ok) {
437
+ s.failed(`Traffic flip to latest failed: ${flip.stderr.trim()}`);
438
+ await rollBack(p);
439
+ return fail("roll", true);
440
+ }
441
+ if (!(await findServiceUrl(run, install.projectId, install.region, p.serviceName))) {
442
+ s.failed(`Could not resolve the service URL for ${p.slug} — rolling back`);
443
+ await rollBack(p);
444
+ return fail("roll", true);
445
+ }
446
+ s.done(`${p.slug} rolled to ${p.digest.slice(0, 19)}...`);
447
+ rolled.push(p);
448
+ }
449
+
450
+ if (deps.health) {
451
+ const s = r.step("Deep health check (database, migrations, version)...");
452
+ // A probe that throws is a failed check: roll back, never leave the
453
+ // new revisions serving unverified.
454
+ const deep = await deps.health.deep({ version: input.targetVersion }).catch((e: unknown) => ({
455
+ ok: false as const,
456
+ error: e instanceof Error ? e.message : String(e),
457
+ }));
458
+ if (!deep.ok) {
459
+ s.failed(`Deep health check failed: ${deep.error}`);
460
+ await rollBack();
461
+ r.warn(restoreHint(input, "if the previous release now fails against the migrated schema"));
462
+ return fail("health", true);
463
+ }
464
+ s.done(`Healthy: ${deep.detail}`);
465
+ }
466
+
467
+ const digests: ImageDigests = {
468
+ admin: (plan.services.find((s) => s.slug === "admin") as RollPlan).digest,
469
+ gateway: (plan.services.find((s) => s.slug === "gateway") as RollPlan).digest,
470
+ };
471
+ await deps.recordDigests(digests);
472
+ return { ok: true, digests };
473
+ }
474
+
475
+ /**
476
+ * The restore hint after migrations ran and the roll failed. Expand-only
477
+ * migrations leave a schema the previous release still runs on, so restoring
478
+ * is only advised outright for contract-type migrations.
479
+ */
480
+ function restoreHint(input: AppRollInput, when: string): string {
481
+ const cmd = restoreCommand(input.backup);
482
+ if (input.migrationsContract === true) {
483
+ return `This release's migrations are contract-type: the previous release may not work against the migrated schema. Restore the pre-upgrade backup ${input.backup.backupId} (overwrites all data written since):\n ${cmd}`;
484
+ }
485
+ return `Pre-upgrade backup: ${input.backup.backupId}. Restore it only ${when} (overwrites all data written since):\n ${cmd}`;
486
+ }
@@ -0,0 +1,109 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * On-demand Cloud SQL backups (epic #696): the `backup` lifecycle command and
5
+ * the backup every upgrade takes before its migrations. Both GCP providers
6
+ * (`gcp`, `gcp-firebase`) keep their data in the same `caelo-<env>-pg*` Cloud
7
+ * SQL instance, so one implementation serves both.
8
+ *
9
+ * The backup id is what makes the pre-upgrade backup useful: it lands in the
10
+ * upgrade's output and in the restore hint printed when the upgrade has to
11
+ * roll back after migrations ran.
12
+ */
13
+
14
+ import type { GcloudRunner } from "../gcloud-retry.js";
15
+ import { gcpNamePrefix } from "../gcp-names.js";
16
+ import { resolveGcpResourceName } from "./gcp-lookup.js";
17
+
18
+ /** A finished on-demand backup. */
19
+ export interface SqlBackup {
20
+ readonly projectId: string;
21
+ /** Cloud SQL instance name (Pulumi-suffixed). */
22
+ readonly instance: string;
23
+ /** Cloud SQL backup run id. */
24
+ readonly backupId: string;
25
+ }
26
+
27
+ export type SqlBackupResult =
28
+ | { readonly ok: true; readonly backup: SqlBackup }
29
+ | { readonly ok: false; readonly error: string };
30
+
31
+ /**
32
+ * Take an on-demand backup of the install's Cloud SQL instance and return its
33
+ * id. `gcloud sql backups create` waits for the backup to finish but does not
34
+ * print the id in a stable shape, so the backup carries a unique description
35
+ * and is looked up by it afterwards.
36
+ *
37
+ * @param purpose short reason recorded in the backup's description, e.g. "pre-upgrade to 0.11.0"
38
+ */
39
+ export async function takeSqlBackup(
40
+ run: GcloudRunner,
41
+ install: { readonly projectId: string; readonly env: string },
42
+ purpose: string,
43
+ now: () => Date = () => new Date(),
44
+ ): Promise<SqlBackupResult> {
45
+ const instance = await resolveGcpResourceName(
46
+ run,
47
+ "sql-instance",
48
+ `${gcpNamePrefix(install.env)}-pg`,
49
+ install.projectId,
50
+ );
51
+ if (!instance) {
52
+ return {
53
+ ok: false,
54
+ error: `no ${gcpNamePrefix(install.env)}-pg* Cloud SQL instance in project ${install.projectId} (or listing it was denied)`,
55
+ };
56
+ }
57
+ const description = `caelo-cms ${purpose} ${now().toISOString()}`;
58
+ const project = ["--project", install.projectId];
59
+ const create = await run([
60
+ "sql",
61
+ "backups",
62
+ "create",
63
+ "--instance",
64
+ instance,
65
+ ...project,
66
+ "--description",
67
+ description,
68
+ ]);
69
+ if (!create.ok) {
70
+ return { ok: false, error: `backup of ${instance} failed: ${create.stderr.trim()}` };
71
+ }
72
+ const list = await run([
73
+ "sql",
74
+ "backups",
75
+ "list",
76
+ "--instance",
77
+ instance,
78
+ ...project,
79
+ `--filter=description="${description}"`,
80
+ "--format=value(id)",
81
+ ]);
82
+ const backupId = list.ok ? list.stdout.trim().split("\n")[0]?.trim() : "";
83
+ if (!backupId) {
84
+ return {
85
+ ok: false,
86
+ error: `backup of ${instance} was created but its id could not be read (${list.ok ? "no backup carries the description" : list.stderr.trim()}); find it with: gcloud sql backups list --instance=${instance} --project=${install.projectId}`,
87
+ };
88
+ }
89
+ return { ok: true, backup: { projectId: install.projectId, instance, backupId } };
90
+ }
91
+
92
+ /** The command that restores `backup` over its instance (overwrites the current data). */
93
+ export function restoreCommand(backup: SqlBackup): string {
94
+ return `gcloud sql backups restore ${backup.backupId} --restore-instance=${backup.instance} --project=${backup.projectId}`;
95
+ }
96
+
97
+ /**
98
+ * What to tell the operator when a pre-upgrade backup failed: why nothing
99
+ * happened, and how to get past it.
100
+ */
101
+ export function backupFailureHelp(install: { readonly projectId: string }): string {
102
+ return [
103
+ "Nothing was changed: no migrations ran and no traffic moved.",
104
+ "Fix the cause and re-run upgrade. Common causes:",
105
+ ` - the account lacks Cloud SQL backup rights (roles/cloudsql.editor or owner on ${install.projectId})`,
106
+ " - another backup or maintenance operation is running on the instance (wait, then retry)",
107
+ ` - the instance is stopped: gcloud sql instances describe <instance> --project=${install.projectId}`,
108
+ ].join("\n");
109
+ }