@caelo-cms/provisioning 0.12.9 → 0.12.11

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 (123) hide show
  1. package/dist/agent-db.js +76 -3
  2. package/dist/cli.js +23 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/collection-stores.d.ts +5 -0
  5. package/dist/collection-stores.d.ts.map +1 -0
  6. package/dist/collection-stores.js +21 -0
  7. package/dist/collection-stores.js.map +1 -0
  8. package/dist/collections-setup.d.ts +66 -0
  9. package/dist/collections-setup.d.ts.map +1 -0
  10. package/dist/collections-setup.js +252 -0
  11. package/dist/collections-setup.js.map +1 -0
  12. package/dist/compose.d.ts +27 -0
  13. package/dist/compose.d.ts.map +1 -1
  14. package/dist/compose.js +52 -1
  15. package/dist/compose.js.map +1 -1
  16. package/dist/gateway-edge.d.ts +13 -0
  17. package/dist/gateway-edge.d.ts.map +1 -1
  18. package/dist/gateway-edge.js +22 -0
  19. package/dist/gateway-edge.js.map +1 -1
  20. package/dist/gcp-names.d.ts +18 -48
  21. package/dist/gcp-names.d.ts.map +1 -1
  22. package/dist/gcp-names.js +11 -69
  23. package/dist/gcp-names.js.map +1 -1
  24. package/dist/infra-contract.d.ts +1 -1
  25. package/dist/infra-contract.d.ts.map +1 -1
  26. package/dist/infra-contract.js +35 -1
  27. package/dist/infra-contract.js.map +1 -1
  28. package/dist/reporting-job-catalog.d.ts +111 -0
  29. package/dist/reporting-job-catalog.d.ts.map +1 -0
  30. package/dist/reporting-job-catalog.js +306 -0
  31. package/dist/reporting-job-catalog.js.map +1 -0
  32. package/dist/reporting-job-setup.d.ts +11 -68
  33. package/dist/reporting-job-setup.d.ts.map +1 -1
  34. package/dist/reporting-job-setup.js +44 -100
  35. package/dist/reporting-job-setup.js.map +1 -1
  36. package/dist/runtime-secrets.d.ts.map +1 -1
  37. package/dist/runtime-secrets.js +3 -0
  38. package/dist/runtime-secrets.js.map +1 -1
  39. package/dist/self-hosted-backup.d.ts.map +1 -1
  40. package/dist/self-hosted-backup.js +18 -6
  41. package/dist/self-hosted-backup.js.map +1 -1
  42. package/dist/stack-contract.d.ts +75 -22
  43. package/dist/stack-contract.d.ts.map +1 -1
  44. package/dist/stack-contract.js +142 -51
  45. package/dist/stack-contract.js.map +1 -1
  46. package/dist/stack-converge.d.ts +20 -1
  47. package/dist/stack-converge.d.ts.map +1 -1
  48. package/dist/stack-converge.js +105 -2
  49. package/dist/stack-converge.js.map +1 -1
  50. package/dist/staging-gateway-setup.d.ts.map +1 -1
  51. package/dist/staging-gateway-setup.js +10 -5
  52. package/dist/staging-gateway-setup.js.map +1 -1
  53. package/dist/upgrade/admin-image-jobs.d.ts +4 -3
  54. package/dist/upgrade/admin-image-jobs.d.ts.map +1 -1
  55. package/dist/upgrade/admin-image-jobs.js +9 -16
  56. package/dist/upgrade/admin-image-jobs.js.map +1 -1
  57. package/dist/upgrade/app-roll.d.ts.map +1 -1
  58. package/dist/upgrade/app-roll.js +8 -7
  59. package/dist/upgrade/app-roll.js.map +1 -1
  60. package/dist/upgrade/converge.d.ts.map +1 -1
  61. package/dist/upgrade/converge.js +78 -50
  62. package/dist/upgrade/converge.js.map +1 -1
  63. package/dist/upgrader-iam-preflight.d.ts.map +1 -1
  64. package/dist/upgrader-iam-preflight.js +8 -18
  65. package/dist/upgrader-iam-preflight.js.map +1 -1
  66. package/dist/upgrader-setup.d.ts.map +1 -1
  67. package/dist/upgrader-setup.js +7 -15
  68. package/dist/upgrader-setup.js.map +1 -1
  69. package/dist/visitor-query-logs.d.ts +40 -0
  70. package/dist/visitor-query-logs.d.ts.map +1 -0
  71. package/dist/visitor-query-logs.js +41 -0
  72. package/dist/visitor-query-logs.js.map +1 -0
  73. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  74. package/dist/wizards/gcp-cost.js +17 -9
  75. package/dist/wizards/gcp-cost.js.map +1 -1
  76. package/dist/wizards/gcp.d.ts.map +1 -1
  77. package/dist/wizards/gcp.js +45 -35
  78. package/dist/wizards/gcp.js.map +1 -1
  79. package/package.json +2 -2
  80. package/src/admin-memory.test.ts +57 -1
  81. package/src/cli.ts +23 -1
  82. package/src/collection-stores.ts +28 -0
  83. package/src/collections-setup.test.ts +237 -0
  84. package/src/collections-setup.ts +317 -0
  85. package/src/compose.ts +54 -1
  86. package/src/gateway-edge.test.ts +28 -0
  87. package/src/gateway-edge.ts +24 -0
  88. package/src/gateway-env-isolation.test.ts +141 -3
  89. package/src/gcp-names.ts +28 -84
  90. package/src/infra-contract.test.ts +5 -3
  91. package/src/infra-contract.ts +35 -1
  92. package/src/remote-mcp.test.ts +13 -1
  93. package/src/reporting-job-catalog.test.ts +156 -0
  94. package/src/reporting-job-catalog.ts +426 -0
  95. package/src/reporting-job-setup.test.ts +119 -6
  96. package/src/reporting-job-setup.ts +51 -158
  97. package/src/runtime-secrets.test.ts +19 -4
  98. package/src/runtime-secrets.ts +3 -0
  99. package/src/self-hosted-backup.test.ts +2 -2
  100. package/src/self-hosted-backup.ts +18 -6
  101. package/src/self-hosted-compose.test.ts +9 -3
  102. package/src/stack-contract.test.ts +62 -4
  103. package/src/stack-contract.ts +172 -59
  104. package/src/stack-converge-secrets.test.ts +4 -0
  105. package/src/stack-converge.test.ts +81 -3
  106. package/src/stack-converge.ts +124 -3
  107. package/src/staging-gateway-setup.test.ts +4 -0
  108. package/src/staging-gateway-setup.ts +16 -6
  109. package/src/upgrade/admin-image-jobs.ts +13 -25
  110. package/src/upgrade/app-roll.ts +7 -6
  111. package/src/upgrade/converge.ts +94 -77
  112. package/src/upgrade/upgrade.test.ts +97 -2
  113. package/src/upgrader-iam-preflight.ts +7 -20
  114. package/src/upgrader-job.test.ts +3 -0
  115. package/src/upgrader-setup.test.ts +3 -0
  116. package/src/upgrader-setup.ts +6 -17
  117. package/src/visitor-query-logs.ts +46 -0
  118. package/src/wizards/gcp-cost.ts +19 -9
  119. package/src/wizards/gcp.ts +51 -45
  120. package/stacks/aws/index.ts +18 -9
  121. package/stacks/azure/index.ts +19 -8
  122. package/stacks/gcp/index.ts +54 -1
  123. package/stacks/gcp-firebase/index.ts +28 -1
@@ -4,6 +4,7 @@ import { describe, expect, it } from "bun:test";
4
4
  import type { GcloudResult } from "./gcloud.js";
5
5
  import {
6
6
  ABSENT_DEFAULT_FIREWALL_RULES,
7
+ GATEWAY_CDN_POLICY,
7
8
  STATIC_CDN_POLICY,
8
9
  stackIamInvariants,
9
10
  } from "./stack-contract.js";
@@ -55,6 +56,9 @@ const IN_SHAPE_BACKEND = {
55
56
  customResponseHeaders: GCP_STATIC_RESPONSE_HEADERS,
56
57
  };
57
58
 
59
+ /** Epic #1644 — the gcp live gateway's backend already at {@link GATEWAY_CDN_POLICY}. */
60
+ const IN_SHAPE_GATEWAY_BACKEND = { enableCDN: true, cdnPolicy: GATEWAY_CDN_POLICY };
61
+
58
62
  const policy = (bindings: { role: string; members: string[]; condition?: unknown }[]) =>
59
63
  ok(JSON.stringify({ bindings }));
60
64
 
@@ -342,7 +346,7 @@ describe("planContractEnv", () => {
342
346
  // and gate key onto an install that predates it.
343
347
  expect(plan.services.admin.flags).toEqual([
344
348
  // #1329 — and the staging database's pool onto one that predates it.
345
- "--update-env-vars=PUBLIC_STAGING_ADMIN_DATABASE_URL=postgresql://admin_role@db1.p-label.europe-west1.sql-psa.goog:5432/cms_public_staging?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem,CAELO_SITE_URL=https://acme.com,MEDIA_ROOT_DIR=/app/apps/admin/data/media,CAELO_MCP_IAP_SERVICE_ACCOUNT=caelo-mcp@acme.iam.gserviceaccount.com,CAELO_OPERATOR_ACCESS_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-operator-access-sync,CAELO_UPGRADER_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-upgrader,CAELO_CONVERGE_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-converge,CAELO_AUDIT_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-audit,CAELO_AUDIT_RESULTS_BUCKET=acme-caelo-production-audit-results,CAELO_CAPTURE_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-capture,CAELO_CAPTURE_BUCKET=acme-caelo-production-capture,CAELO_MEDIA_BUCKET=acme-caelo-production-media,CAELO_AUDIT_RUNNER_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-audit-run,CAELO_AUDIT_RUNNER_SERVICE_ACCOUNT=caelo-production-audit-run@acme.iam.gserviceaccount.com,CAELO_IMPORT_CRAWL_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-import,CAELO_IMPORT_CRAWL_SERVICE_ACCOUNT=caelo-production-import@acme.iam.gserviceaccount.com,CAELO_BUILD_CARRIER_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-build,CAELO_BUILD_CARRIER_SERVICE_ACCOUNT=caelo-production-build@acme.iam.gserviceaccount.com,CAELO_SCHEDULER_SERVICE_ACCOUNT=caelo-production-scheduler@acme.iam.gserviceaccount.com,CAELO_OPERATOR_OAUTH_CLIENT_STORE=projects/acme/secrets/caelo-production-operator-oauth-client,CAELO_STAGING_BUCKET=acme-caelo-production-staging,CAELO_FIREBASE_STAGING_SITE=caelo-production-stg-6eace1,CAELO_GATEWAY_SERVICE=caelo-production-data-gateway,CAELO_STAGING_HOST=staging.acme.com",
349
+ "--update-env-vars=PUBLIC_STAGING_ADMIN_DATABASE_URL=postgresql://admin_role@db1.p-label.europe-west1.sql-psa.goog:5432/cms_public_staging?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem,CAELO_SITE_URL=https://acme.com,MEDIA_ROOT_DIR=/app/apps/admin/data/media,CAELO_MCP_IAP_SERVICE_ACCOUNT=caelo-mcp@acme.iam.gserviceaccount.com,CAELO_OPERATOR_ACCESS_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-operator-access-sync,CAELO_UPGRADER_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-upgrader,CAELO_CONVERGE_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-converge,CAELO_AUDIT_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-audit,CAELO_AUDIT_RESULTS_BUCKET=acme-caelo-production-audit-results,CAELO_CAPTURE_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-capture,CAELO_CAPTURE_BUCKET=acme-caelo-production-capture,CAELO_MEDIA_BUCKET=acme-caelo-production-media,CAELO_AUDIT_RUNNER_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-audit-run,CAELO_AUDIT_RUNNER_SERVICE_ACCOUNT=caelo-production-audit-run@acme.iam.gserviceaccount.com,CAELO_IMPORT_CRAWL_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-import,CAELO_IMPORT_CRAWL_SERVICE_ACCOUNT=caelo-production-import@acme.iam.gserviceaccount.com,CAELO_BUILD_CARRIER_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-build,CAELO_BUILD_CARRIER_SERVICE_ACCOUNT=caelo-production-build@acme.iam.gserviceaccount.com,CAELO_COLLECTION_INDEX_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-index,CAELO_COLLECTION_INDEX_SERVICE_ACCOUNT=caelo-production-index@acme.iam.gserviceaccount.com,CAELO_PLUGIN_BATCH_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-plugin-batch,CAELO_PLUGIN_BATCH_SERVICE_ACCOUNT=caelo-production-plugin-batch@acme.iam.gserviceaccount.com,CAELO_COLLECTIONS_STAGING_STORE=gs://acme-caelo-production-coll-staging,CAELO_COLLECTIONS_LIVE_STORE=gs://acme-caelo-production-coll-live,CAELO_SCHEDULER_SERVICE_ACCOUNT=caelo-production-scheduler@acme.iam.gserviceaccount.com,CAELO_OPERATOR_OAUTH_CLIENT_STORE=projects/acme/secrets/caelo-production-operator-oauth-client,CAELO_VISITOR_AI_KEY_STORE=projects/acme/secrets/caelo-production-visitor-ai-key,CAELO_VISITOR_AI_STAGING_KEY_STORE=projects/acme/secrets/caelo-production-visitor-ai-staging-key,CAELO_STAGING_BUCKET=acme-caelo-production-staging,CAELO_FIREBASE_STAGING_SITE=caelo-production-stg-6eace1,CAELO_GATEWAY_SERVICE=caelo-production-data-gateway,CAELO_STAGING_HOST=staging.acme.com",
346
350
  "--update-secrets=PUBLIC_STAGING_ADMIN_DATABASE_PASSWORD=caelo-production-postgres-password:latest,CAELO_STAGING_GATE_SECRET=caelo-production-staging-gate-secret:latest",
347
351
  ]);
348
352
  // #1328 — the Firebase rewrite follows the data gateway (above), which
@@ -350,7 +354,7 @@ describe("planContractEnv", () => {
350
354
  expect(plan.services.gateway.flags).toEqual([
351
355
  // The gateway learns which forwarded address is the visitor (#845),
352
356
  // (#1329) that it is the live site's, and whose refresh pings it takes.
353
- "--update-env-vars=CAELO_GATEWAY_ENVIRONMENT=live,CAELO_TRUSTED_PROXY_HOPS=1,CAELO_GATEWAY_REFRESH_ACCOUNT=caelo-production-run-sa@acme.iam.gserviceaccount.com",
357
+ "--update-env-vars=CAELO_GATEWAY_ENVIRONMENT=live,CAELO_TRUSTED_PROXY_HOPS=1,CAELO_COLLECTIONS_LIVE_STORE=gs://acme-caelo-production-coll-live,CAELO_GATEWAY_REFRESH_ACCOUNT=caelo-production-run-sa@acme.iam.gserviceaccount.com,CAELO_VISITOR_AI_KEY_FILE=/secrets/visitor-ai/key.json",
354
358
  ]);
355
359
  // The old gateway service becomes the proxy in one revision: every
356
360
  // database and site var goes, its own contract arrives.
@@ -856,6 +860,9 @@ describe("ensureStackInvariants", () => {
856
860
  policy([{ role: "roles/run.invoker", members: [IAP_AGENT, "allUsers"] }]),
857
861
  ],
858
862
  "compute backend-buckets list": [ok("caelo-production-static-backend-9f8e7d6\n")],
863
+ // Epic #1644 — the live gateway's backend, already at its CDN policy.
864
+ "compute backend-services list": [ok("caelo-production-gateway-backend-1a2b3c4\n")],
865
+ "compute backend-services describe": [ok(JSON.stringify(IN_SHAPE_GATEWAY_BACKEND))],
859
866
  "compute firewall-rules list": [ok("[]")],
860
867
  // #891 — every live SVG already served as a download.
861
868
  "storage objects list": [
@@ -921,6 +928,72 @@ describe("ensureStackInvariants", () => {
921
928
  expect(report.outcomes.find((o) => o.id.startsWith("Cloud CDN"))?.status).toBe("applied");
922
929
  });
923
930
 
931
+ // Epic #1644 — visitors' repeated searches answered at the edge.
932
+ it("turns Cloud CDN on for the live gateway's backend, caching only what the gateway marks cacheable", async () => {
933
+ const answers = {
934
+ ...fullGcp(),
935
+ "compute backend-buckets describe": [ok(JSON.stringify(IN_SHAPE_BACKEND))],
936
+ "compute backend-services describe": [ok(JSON.stringify({ enableCDN: false }))],
937
+ };
938
+ const { run, calls } = fakeGcloud(answers);
939
+ const report = await ensureStackInvariants(gcp, { run, sleep: async () => {} });
940
+ expect(report.mustAbort).toBe(false);
941
+ expect(calls).toContain(
942
+ "compute backend-services list --project=acme --global --filter=name~^caelo-production-gateway-backend --format=value(name)",
943
+ );
944
+ expect(calls).toContain(
945
+ "compute backend-services update caelo-production-gateway-backend-1a2b3c4 --project=acme --global --enable-cdn --cache-mode=USE_ORIGIN_HEADERS --no-negative-caching --serve-while-stale=0 --cache-key-include-host --cache-key-include-protocol --cache-key-include-query-string --quiet",
946
+ );
947
+ expect(
948
+ report.outcomes.find((o) =>
949
+ o.id.startsWith("Cloud CDN on caelo-production-gateway-backend"),
950
+ )?.status,
951
+ ).toBe("applied");
952
+ });
953
+
954
+ it("re-applies the gateway CDN policy when the cache key lost the query string", async () => {
955
+ const drifted = {
956
+ enableCDN: true,
957
+ cdnPolicy: {
958
+ ...GATEWAY_CDN_POLICY,
959
+ cacheKeyPolicy: { includeHost: true, includeProtocol: true },
960
+ },
961
+ };
962
+ const answers = {
963
+ ...fullGcp(),
964
+ "compute backend-buckets describe": [ok(JSON.stringify(IN_SHAPE_BACKEND))],
965
+ "compute backend-services describe": [ok(JSON.stringify(drifted))],
966
+ };
967
+ const { run, calls } = fakeGcloud(answers);
968
+ await ensureStackInvariants(gcp, { run, sleep: async () => {} });
969
+ expect(calls.some((c) => c.startsWith("compute backend-services update"))).toBe(true);
970
+ });
971
+
972
+ it("leaves an install without a deployed gateway alone, and refuses to guess between two backends", async () => {
973
+ const none = fakeGcloud({
974
+ ...fullGcp(),
975
+ "compute backend-buckets describe": [ok(JSON.stringify(IN_SHAPE_BACKEND))],
976
+ "compute backend-services list": [ok("")],
977
+ });
978
+ const r1 = await ensureStackInvariants(gcp, { run: none.run, sleep: async () => {} });
979
+ expect(none.calls.some((c) => c.startsWith("compute backend-services update"))).toBe(false);
980
+ expect(r1.outcomes.every((o) => o.status === "present")).toBe(true);
981
+ const two = fakeGcloud({
982
+ ...fullGcp(),
983
+ "compute backend-buckets describe": [ok(JSON.stringify(IN_SHAPE_BACKEND))],
984
+ "compute backend-services list": [
985
+ ok("caelo-production-gateway-backend-a\ncaelo-production-gateway-backend-b\n"),
986
+ ],
987
+ });
988
+ const r2 = await ensureStackInvariants(gcp, { run: two.run, sleep: async () => {} });
989
+ expect(two.calls.some((c) => c.startsWith("compute backend-services update"))).toBe(false);
990
+ const outcome = r2.outcomes.find((o) =>
991
+ o.id.startsWith("Cloud CDN on caelo-production-gateway-backend"),
992
+ );
993
+ expect(outcome?.status).toBe("failed");
994
+ expect(r2.mustAbort).toBe(false);
995
+ });
996
+
924
997
  it("warns (no abort) when the CDN update fails", async () => {
925
998
  const answers = {
926
999
  ...fullGcp(),
@@ -1014,6 +1087,8 @@ describe("ensureStackInvariants", () => {
1014
1087
  // password only.
1015
1088
  expect(gatewayGrants).toEqual([
1016
1089
  `secrets add-iam-policy-binding caelo-production-public-role-password --project=acme --member=${GW_SA} --role=roles/secretmanager.secretAccessor --quiet --format=none`,
1090
+ // #1654 — and the live site's visitor-AI key, which no admin reads.
1091
+ `secrets add-iam-policy-binding caelo-production-visitor-ai-key --project=acme --member=${GW_SA} --role=roles/secretmanager.secretAccessor --quiet --format=none`,
1017
1092
  ]);
1018
1093
  // #1328 — the remote-MCP broker's seal key and OAuth client file are
1019
1094
  // the MCP-Auth-Proxy's, and those two secrets are all its SA reads.
@@ -1027,10 +1102,13 @@ describe("ensureStackInvariants", () => {
1027
1102
  expect(
1028
1103
  calls.some((c) => c.startsWith("projects add-iam-policy-binding") && c.includes(PROXY_SA)),
1029
1104
  ).toBe(false);
1030
- // #806 — the admin may add versions to the OAuth client secret, and to no other.
1105
+ // #806 — the admin may add versions to the OAuth client secret and
1106
+ // (#1654) the two visitor-AI keys, and to no other.
1031
1107
  const adders = calls.filter((c) => c.includes("roles/secretmanager.secretVersionAdder"));
1032
1108
  expect(adders).toEqual([
1033
1109
  `secrets add-iam-policy-binding caelo-production-operator-oauth-client --project=acme --member=${RUN_SA} --role=roles/secretmanager.secretVersionAdder --quiet --format=none`,
1110
+ `secrets add-iam-policy-binding caelo-production-visitor-ai-key --project=acme --member=${RUN_SA} --role=roles/secretmanager.secretVersionAdder --quiet --format=none`,
1111
+ `secrets add-iam-policy-binding caelo-production-visitor-ai-staging-key --project=acme --member=${RUN_SA} --role=roles/secretmanager.secretVersionAdder --quiet --format=none`,
1034
1112
  ]);
1035
1113
  for (const secret of ["internal-secret", "tool-approval-secret", "secret-kek"]) {
1036
1114
  expect(calls).toContain(
@@ -46,7 +46,9 @@ import {
46
46
  type CloudRunSlug,
47
47
  DATABASE_URL_VARS,
48
48
  databaseUrls,
49
+ GATEWAY_CDN_POLICY,
49
50
  type GcpProvider,
51
+ gatewayBackendPrefix,
50
52
  gatewayEnvContract,
51
53
  type IamInvariant,
52
54
  type IamTarget,
@@ -60,6 +62,7 @@ import {
60
62
  type RetiredIamBinding,
61
63
  type RetiredSecretFile,
62
64
  type RuntimeEnvInputs,
65
+ SERVICE_MEMORY_FLOOR,
63
66
  type SecretFileContract,
64
67
  type ServiceEnvInputs,
65
68
  STATIC_CDN_POLICY,
@@ -631,6 +634,104 @@ async function ensureCdnPolicy(
631
634
  : { ...base, status: "failed", error: update.stderr.trim() };
632
635
  }
633
636
 
637
+ /**
638
+ * Epic #1644 (#1649) — bring the `gcp` stack's live gateway backend to
639
+ * {@link GATEWAY_CDN_POLICY}: Cloud CDN on, caching only what the gateway
640
+ * marks cacheable, the query string in the key. Without it every visitor's
641
+ * search reaches the gateway; with it a repeated query is answered at the
642
+ * edge.
643
+ */
644
+ export async function ensureGatewayCdnPolicy(
645
+ install: InstallTarget,
646
+ run: GcloudRunner,
647
+ ): Promise<InvariantOutcome> {
648
+ const prefix = gatewayBackendPrefix(install.env);
649
+ const base = {
650
+ id: `Cloud CDN on ${prefix}*`,
651
+ onFailure: "warn" as const,
652
+ why: "visitors' repeated searches are answered at the edge instead of by the gateway (#1649)",
653
+ };
654
+ const project = `--project=${install.projectId}`;
655
+ const list = await run([
656
+ "compute",
657
+ "backend-services",
658
+ "list",
659
+ project,
660
+ "--global",
661
+ `--filter=name~^${prefix}`,
662
+ "--format=value(name)",
663
+ ]);
664
+ if (!list.ok) return { ...base, status: "failed", error: list.stderr.trim() };
665
+ const names = list.stdout
666
+ .split("\n")
667
+ .map((l) => l.trim())
668
+ .filter(Boolean);
669
+ // The gateway is declared with `deployGateways` only; an install that
670
+ // has not deployed it yet has no backend to cache in front of.
671
+ if (names.length === 0) return { ...base, status: "present" };
672
+ if (names.length > 1) {
673
+ return {
674
+ ...base,
675
+ status: "failed",
676
+ error: `more than one backend service starts with ${prefix} (${names.join(", ")}); remove the one the load balancer does not use`,
677
+ };
678
+ }
679
+ const name = names[0] as string;
680
+ const describe = await run([
681
+ "compute",
682
+ "backend-services",
683
+ "describe",
684
+ name,
685
+ project,
686
+ "--global",
687
+ "--format=json",
688
+ ]);
689
+ if (describe.ok) {
690
+ const live = JSON.parse(describe.stdout) as {
691
+ enableCDN?: boolean;
692
+ cdnPolicy?: {
693
+ cacheMode?: string;
694
+ negativeCaching?: boolean;
695
+ serveWhileStale?: number;
696
+ cacheKeyPolicy?: Record<string, unknown>;
697
+ };
698
+ };
699
+ const cdn = live.cdnPolicy;
700
+ const key = cdn?.cacheKeyPolicy ?? {};
701
+ const inShape =
702
+ live.enableCDN === true &&
703
+ cdn?.cacheMode === GATEWAY_CDN_POLICY.cacheMode &&
704
+ (cdn.negativeCaching ?? false) === GATEWAY_CDN_POLICY.negativeCaching &&
705
+ (cdn.serveWhileStale ?? 0) === GATEWAY_CDN_POLICY.serveWhileStale &&
706
+ Object.entries(GATEWAY_CDN_POLICY.cacheKeyPolicy).every(([k, v]) => key[k] === v);
707
+ if (inShape) return { ...base, status: "present" };
708
+ }
709
+ const update = await run(gatewayCdnUpdateArgs(name, install.projectId));
710
+ return update.ok
711
+ ? { ...base, status: "applied" }
712
+ : { ...base, status: "failed", error: update.stderr.trim() };
713
+ }
714
+
715
+ /** The `gcloud compute backend-services update` argv that applies {@link GATEWAY_CDN_POLICY}. */
716
+ export function gatewayCdnUpdateArgs(name: string, projectId: string): string[] {
717
+ return [
718
+ "compute",
719
+ "backend-services",
720
+ "update",
721
+ name,
722
+ `--project=${projectId}`,
723
+ "--global",
724
+ "--enable-cdn",
725
+ `--cache-mode=${GATEWAY_CDN_POLICY.cacheMode}`,
726
+ GATEWAY_CDN_POLICY.negativeCaching ? "--negative-caching" : "--no-negative-caching",
727
+ `--serve-while-stale=${GATEWAY_CDN_POLICY.serveWhileStale}`,
728
+ "--cache-key-include-host",
729
+ "--cache-key-include-protocol",
730
+ "--cache-key-include-query-string",
731
+ "--quiet",
732
+ ];
733
+ }
734
+
634
735
  /** The ingress of a described service (`all`, `internal-and-cloud-load-balancing`, …; null: unset). */
635
736
  export function liveIngress(serviceJson: string): string | null {
636
737
  const svc = JSON.parse(serviceJson) as {
@@ -737,6 +838,7 @@ export async function ensureStackInvariants(
737
838
  outcomes.push(...(await ensureIam(checkable, install, projectNumber, run, sleep)));
738
839
  if (install.provider === "gcp") {
739
840
  outcomes.push(await ensureCdnPolicy(install, run));
841
+ outcomes.push(await ensureGatewayCdnPolicy(install, run));
740
842
  outcomes.push(await ensureSvgDownloads(install, run));
741
843
  }
742
844
  if (install.provider === "gcp-firebase") {
@@ -876,16 +978,35 @@ const CLOUD_RUN_DEFAULT_MEMORY = "512Mi";
876
978
  export function planAdminMemory(
877
979
  live: string | null,
878
980
  desired: string = ADMIN_MEMORY_DEFAULT,
879
- ):
981
+ ): MemoryPlan {
982
+ return planMemoryFloor(live, desired, "admin");
983
+ }
984
+
985
+ /** What {@link planServiceMemory} decided. */
986
+ export type MemoryPlan =
880
987
  | { readonly ok: true; readonly flags: readonly string[]; readonly from: string | null }
881
- | { readonly ok: false; readonly error: string } {
988
+ | { readonly ok: false; readonly error: string };
989
+
990
+ /**
991
+ * #553, epic #1644 — raise a Cloud Run service to its memory floor
992
+ * ({@link SERVICE_MEMORY_FLOOR}: the admin for the quality audit, both
993
+ * gateways for the collection index files they keep in memory). Never
994
+ * lowers; a service without a floor keeps what the stack gave it.
995
+ */
996
+ export function planServiceMemory(slug: CloudRunSlug, live: string | null): MemoryPlan {
997
+ const floor = SERVICE_MEMORY_FLOOR[slug];
998
+ if (floor === null) return { ok: true, flags: [], from: live };
999
+ return planMemoryFloor(live, floor, slug);
1000
+ }
1001
+
1002
+ function planMemoryFloor(live: string | null, desired: string, service: string): MemoryPlan {
882
1003
  const desiredMiB = memoryQuantityMiB(desired);
883
1004
  if (desiredMiB === null) return { ok: false, error: `invalid desired memory "${desired}"` };
884
1005
  const liveMiB = memoryQuantityMiB(live ?? CLOUD_RUN_DEFAULT_MEMORY);
885
1006
  if (liveMiB === null) {
886
1007
  return {
887
1008
  ok: false,
888
- error: `the admin's memory "${live}" is not a quantity upgrade understands`,
1009
+ error: `the ${service}'s memory "${live}" is not a quantity upgrade understands`,
889
1010
  };
890
1011
  }
891
1012
  if (liveMiB >= desiredMiB) return { ok: true, flags: [], from: live };
@@ -99,6 +99,10 @@ describe("the staging gateway service", () => {
99
99
  expect.stringMatching(
100
100
  /^secrets add-iam-policy-binding caelo-production-public-staging-role-password .*secretAccessor/,
101
101
  ),
102
+ // #1654 — staging's own visitor-AI key, never the live one's.
103
+ expect.stringMatching(
104
+ /^secrets add-iam-policy-binding caelo-production-visitor-ai-staging-key .*secretAccessor/,
105
+ ),
102
106
  expect.stringMatching(
103
107
  /^storage buckets add-iam-policy-binding gs:\/\/acme-caelo-production-staging .*--role=roles\/storage\.objectViewer/,
104
108
  ),
@@ -61,8 +61,11 @@ import {
61
61
  cloudRunServicePrefix,
62
62
  databaseUrls,
63
63
  fixedCloudRunServiceName,
64
+ GATEWAY_MEMORY_DEFAULT,
64
65
  type GcpProvider,
66
+ SERVICE_SECRET_FILES,
65
67
  STAGING_GATEWAY_TIMEOUT_SECONDS,
68
+ secretFilePath,
66
69
  serviceSecrets,
67
70
  stagingGatewayEnvContract,
68
71
  } from "./stack-contract.js";
@@ -144,11 +147,17 @@ export function stagingGatewayDeployArgs(inputs: StagingGatewayServiceInputs): s
144
147
  // stacks set the same on the live gateway.
145
148
  ...GATEWAY_POOL_ENV.map((e) => `${e.name}=${e.value}`),
146
149
  ];
147
- const secrets = env.flatMap((e) =>
148
- "valueSource" in e
149
- ? [`${e.name}=${e.valueSource.secretKeyRef.secret}:${e.valueSource.secretKeyRef.version}`]
150
- : [],
151
- );
150
+ const secrets = [
151
+ ...env.flatMap((e) =>
152
+ "valueSource" in e
153
+ ? [`${e.name}=${e.valueSource.secretKeyRef.secret}:${e.valueSource.secretKeyRef.version}`]
154
+ : [],
155
+ ),
156
+ // #1654 — its own visitor-AI key, as a file (read at `latest` on every turn).
157
+ ...SERVICE_SECRET_FILES["staging-gateway"].map(
158
+ (f) => `${secretFilePath(f)}=${gcpSecretId(inputs.env, f.secret)}:${f.version}`,
159
+ ),
160
+ ];
152
161
  return [
153
162
  "run",
154
163
  "deploy",
@@ -162,7 +171,8 @@ export function stagingGatewayDeployArgs(inputs: StagingGatewayServiceInputs): s
162
171
  "--min-instances=0",
163
172
  `--max-instances=${DEFAULT_STAGING_GATEWAY_MAX_INSTANCES}`,
164
173
  "--cpu=1",
165
- "--memory=512Mi",
174
+ // Epic #1644 — the staging collection index files are cached in memory.
175
+ `--memory=${GATEWAY_MEMORY_DEFAULT}`,
166
176
  "--cpu-throttling",
167
177
  `--timeout=${STAGING_GATEWAY_TIMEOUT_SECONDS}`,
168
178
  `--network=${inputs.vpc.network}`,
@@ -3,9 +3,10 @@
3
3
  /**
4
4
  * The Cloud Run jobs that run the admin image: the quality-audit job (#875,
5
5
  * admin-core quality/audit-task.ts), the capture job (#1217, admin-core
6
- * capture/capture-task.ts), the quality-audit runner (#1359), the
7
- * site-import crawler (#1360) and the build carrier (#1574, all three
8
- * admin-core reporting-jobs/job-entry.ts).
6
+ * capture/capture-task.ts) and every reporting job of the catalog
7
+ * (reporting-job-catalog.ts: the quality-audit runner, the site-import
8
+ * crawler, the build carrier, the collection index job, the plugin batch
9
+ * job; all run admin-core reporting-jobs/job-entry.ts).
9
10
  * Each refuses an order from an admin on another version, so every app-roll
10
11
  * moves them onto the admin's new image right after the services rolled,
11
12
  * and a rollback moves them back.
@@ -16,13 +17,8 @@
16
17
  */
17
18
 
18
19
  import type { GcloudRunner } from "../gcloud-retry.js";
19
- import {
20
- auditJobName,
21
- auditRunnerJobName,
22
- buildCarrierJobName,
23
- captureJobName,
24
- importCrawlJobName,
25
- } from "../gcp-names.js";
20
+ import { auditJobName, captureJobName } from "../gcp-names.js";
21
+ import { REPORTING_JOB_CATALOG, reportingJobName } from "../reporting-job-catalog.js";
26
22
 
27
23
  /** One job that follows the admin's image. */
28
24
  export interface AdminImageJob {
@@ -48,21 +44,13 @@ export function adminImageJobs(env: string): readonly AdminImageJob[] {
48
44
  label: "capture job",
49
45
  lagging: "server-side screenshots fail",
50
46
  },
51
- {
52
- name: auditRunnerJobName(env),
53
- label: "quality-audit runner",
54
- lagging: "Stage audits wait for it and fail after their last attempt",
55
- },
56
- {
57
- name: importCrawlJobName(env),
58
- label: "site-import crawler",
59
- lagging: "site imports wait for it and fail after their last attempt",
60
- },
61
- {
62
- name: buildCarrierJobName(env),
63
- label: "build carrier",
64
- lagging: "an agent's Stage and the Stage and Publish live buttons fail (Stage again)",
65
- },
47
+ // Every reporting job (#1359, #1360, #1574, epic #1644), in catalog
48
+ // order: the quality-audit runner first, after the audit job above.
49
+ ...REPORTING_JOB_CATALOG.map((e) => ({
50
+ name: reportingJobName(e, env),
51
+ label: e.label,
52
+ lagging: e.lagging,
53
+ })),
66
54
  ];
67
55
  }
68
56
 
@@ -58,7 +58,6 @@ import {
58
58
  liveMaxInstances,
59
59
  liveTimeoutSeconds,
60
60
  liveVolumes,
61
- planAdminMemory,
62
61
  planContractEnv,
63
62
  planCpuIdle,
64
63
  planMaxInstances,
@@ -66,6 +65,7 @@ import {
66
65
  planNoVpc,
67
66
  planRequestTimeout,
68
67
  planSecretFiles,
68
+ planServiceMemory,
69
69
  rollService,
70
70
  serviceRollArgs,
71
71
  } from "../stack-converge.js";
@@ -309,10 +309,11 @@ export async function planAppRoll(
309
309
  }
310
310
  const warnings: string[] = [];
311
311
  const rolls = services.map((s): RollPlan => {
312
- // #553 — the admin runs the Lighthouse quality audit; raise it to the
313
- // stack's memory default (never lowered; an unparsable value is kept).
314
- const memory = s.slug === "admin" ? planAdminMemory(s.liveMemory) : null;
315
- if (memory && !memory.ok) warnings.push(`admin memory left as is: ${memory.error}`);
312
+ // #553 — the admin runs the Lighthouse quality audit; epic #1644 — both
313
+ // gateways keep collection index files in memory. Raise each to its
314
+ // floor (never lowered; an unparsable value is kept).
315
+ const memory = planServiceMemory(s.slug, s.liveMemory);
316
+ if (!memory.ok) warnings.push(`${s.slug} memory left as is: ${memory.error}`);
316
317
  // #806 — the MCP-Auth-Proxy streams remote-MCP chat turns
317
318
  // (stack-contract.ts MCP_AUTH_PROXY_TIMEOUT_SECONDS). The other services'
318
319
  // timeouts are the stacks' alone.
@@ -320,7 +321,7 @@ export async function planAppRoll(
320
321
  s.slug === "mcp-auth-proxy"
321
322
  ? planRequestTimeout(s.liveTimeout, MCP_AUTH_PROXY_TIMEOUT_SECONDS)
322
323
  : null;
323
- const memoryFlags = memory?.ok ? memory.flags : [];
324
+ const memoryFlags = memory.ok ? memory.flags : [];
324
325
  const timeoutFlags = timeout?.ok ? timeout.flags : [];
325
326
  const cpu = planCpuIdle(s.liveCpuIdle, SERVICE_CPU_IDLE[s.slug]);
326
327
  const cpuFlags = cpu.ok ? cpu.flags : [];