@fabrika/provider-zerops 0.9.0-cloudflare.3 → 0.9.0-dev.10

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 (69) hide show
  1. package/package.json +11 -10
  2. package/sandbox/Dockerfile +16 -0
  3. package/sandbox/bin/postgres-auth.sh +38 -0
  4. package/sandbox/bin/reset.sh +12 -0
  5. package/sandbox/bin/run-build.sh +35 -0
  6. package/sandbox/bin/run-launcher.sh +18 -0
  7. package/sandbox/bin/start-launcher.sh +25 -0
  8. package/sandbox/bin/stop.sh +47 -0
  9. package/sandbox/init.sh +61 -0
  10. package/src/api/client.ts +3 -1
  11. package/src/api/errors.ts +7 -3
  12. package/src/control.ts +150 -35
  13. package/src/execution.ts +12 -77
  14. package/src/installation/topology/setups.ts +3 -1
  15. package/src/installation/topology/topology.ts +1 -1
  16. package/src/manifest.ts +2 -7
  17. package/src/namespace/claims.ts +4 -0
  18. package/src/namespace/codec.ts +17 -0
  19. package/src/namespace/errors.ts +21 -0
  20. package/src/namespace/manifest.ts +31 -5
  21. package/src/namespace/provisioning.ts +68 -112
  22. package/src/namespace/proxy-reads.ts +16 -1
  23. package/src/namespace/proxy-secrets.ts +18 -5
  24. package/src/namespace/sandbox-host.ts +212 -0
  25. package/src/namespace/subdomain.ts +113 -0
  26. package/src/namespace/topology.ts +1 -1
  27. package/src/namespace/types.ts +11 -0
  28. package/src/namespace/update.ts +1 -0
  29. package/src/provider.ts +0 -40
  30. package/src/proxy-manifest-carrier.ts +26 -5
  31. package/src/sandbox/base-image.ts +100 -0
  32. package/src/sandbox/constants.ts +44 -0
  33. package/src/sandbox/deploy.ts +471 -0
  34. package/src/sandbox/dev-artifact.ts +206 -0
  35. package/src/sandbox/lifecycle.ts +204 -0
  36. package/src/sandbox/scripts.ts +26 -0
  37. package/src/sandbox-host.ts +28 -0
  38. package/src/source/port.ts +5 -0
  39. package/src/zbox/client.ts +259 -0
  40. package/src/zbox/errors.ts +45 -0
  41. package/src/zbox/index.ts +22 -0
  42. package/src/zbox/types.ts +165 -0
  43. package/types/src/api/errors.d.ts +3 -1
  44. package/types/src/control.d.ts +12 -1
  45. package/types/src/execution.d.ts +2 -13
  46. package/types/src/installation/topology/installation-schemas.d.ts +14 -14
  47. package/types/src/installation/topology/topology.d.ts +1 -1
  48. package/types/src/manifest.d.ts +3 -8
  49. package/types/src/namespace/codec.d.ts +18 -0
  50. package/types/src/namespace/errors.d.ts +10 -0
  51. package/types/src/namespace/proxy-reads.d.ts +6 -1
  52. package/types/src/namespace/proxy-secrets.d.ts +1 -1
  53. package/types/src/namespace/sandbox-host.d.ts +23 -0
  54. package/types/src/namespace/subdomain.d.ts +43 -0
  55. package/types/src/namespace/types.d.ts +10 -0
  56. package/types/src/provider.d.ts +0 -3
  57. package/types/src/proxy-manifest-carrier.d.ts +14 -1
  58. package/types/src/sandbox/base-image.d.ts +28 -0
  59. package/types/src/sandbox/constants.d.ts +30 -0
  60. package/types/src/sandbox/deploy.d.ts +75 -0
  61. package/types/src/sandbox/dev-artifact.d.ts +51 -0
  62. package/types/src/sandbox/lifecycle.d.ts +27 -0
  63. package/types/src/sandbox/scripts.d.ts +11 -0
  64. package/types/src/sandbox-host.d.ts +16 -0
  65. package/types/src/source/port.d.ts +5 -0
  66. package/types/src/zbox/client.d.ts +2 -0
  67. package/types/src/zbox/errors.d.ts +25 -0
  68. package/types/src/zbox/index.d.ts +3 -0
  69. package/types/src/zbox/types.d.ts +433 -0
package/src/execution.ts CHANGED
@@ -5,10 +5,6 @@
5
5
  import { type ContractRecipe, contractRecipe } from '@fabrika/app/build'
6
6
  import {
7
7
  type ContractArtifact,
8
- DEV_LAUNCHER_BOOTED_FILE,
9
- DEV_LAUNCHER_CONFIG_FILE,
10
- DEV_LAUNCHER_MODULE,
11
- type DevLauncherConfig,
12
8
  FABRIKA_CONTRACT_DIGEST,
13
9
  FABRIKA_SOURCE_MAP_UPLOAD,
14
10
  FABRIKA_SOURCE_MAP_UPLOAD_KEY,
@@ -105,16 +101,6 @@ export interface ZeropsLockedExecution {
105
101
  readonly runtimePackages: readonly ZeropsRuntimePackage[]
106
102
  /** Where the build uploads its source maps, without the bearer; null when Control minted no upload for the run. */
107
103
  readonly sourceMaps: OperationsSourceMapBuildUpload | null
108
- /**
109
- * Present for an environment of kind `dev` (ADR-0049): `run.start` runs the dev launcher instead of the serving
110
- * entry. The environment's kind selects it; an application never authors it.
111
- */
112
- readonly dev?: ZeropsDevExecution
113
- }
114
-
115
- export interface ZeropsDevExecution {
116
- /** The commit the bootstrap run builds: what a new container holds before the launcher's first sync. */
117
- readonly head: string
118
104
  }
119
105
 
120
106
  /** The application ids the generated scripts may name: the contract's own id rule, so a script needs no quoting. */
@@ -274,79 +260,32 @@ const sourceMapBuildVariables = (upload: OperationsSourceMapBuildUpload): Record
274
260
 
275
261
  // The readiness check is retried no sooner than every 10 s (the platform's floor), and a server is rarely listening at
276
262
  // the first attempt, one second after `run.start`. So one attempt waits for the health endpoint itself, for less than
277
- // the retry period; it passes only on a 2xx, like the `httpGet` it replaces. A dev container also passes once its launcher
278
- // reported the boot, served or failed: the launcher keeps running and reports a failed migration with its remedy.
279
- const readinessCommand = (path: string, dev: boolean): string => {
263
+ // the retry period; it passes only on a 2xx, like the `httpGet` it replaces.
264
+ const readinessCommand = (path: string): string => {
280
265
  if (!READINESS_PATH_PATTERN.test(path)) throw new Error('zerops: a readiness path must be a literal path of unreserved characters')
281
266
  const url = `http://127.0.0.1:${ZEROPS_APPLICATION_PORT}${path}`
282
- const booted = dev ? `if (await Bun.file('${RUNTIME_ROOT}/${DEV_LAUNCHER_BOOTED_FILE}').exists()) process.exit(0); ` : ''
283
- return `bun -e "const end = Date.now() + 9000; while (Date.now() < end) { ${booted}try { if ((await fetch('${url}', { signal: AbortSignal.timeout(2000) })).ok) process.exit(0) } catch {} await Bun.sleep(200) } process.exit(1)"`
267
+ return `bun -e "const end = Date.now() + 9000; while (Date.now() < end) { try { if ((await fetch('${url}', { signal: AbortSignal.timeout(2000) })).ok) process.exit(0) } catch {} await Bun.sleep(200) } process.exit(1)"`
284
268
  }
285
269
 
286
- /** `@fabrika/app/build`'s recipe at this installation's paths; the dev launcher checks in the runtime root. */
287
- const recipeOf = (execution: ZeropsLockedExecution, sourceRoot: string = SOURCE_ROOT): ContractRecipe =>
270
+ /** `@fabrika/app/build`'s recipe at this installation's paths. */
271
+ const recipeOf = (execution: ZeropsLockedExecution): ContractRecipe =>
288
272
  contractRecipe({
289
273
  appId: execution.appId,
290
274
  checkRelease: execution.checkRelease,
291
- sourceRoot,
275
+ sourceRoot: SOURCE_ROOT,
292
276
  runtimeRoot: RUNTIME_ROOT,
293
277
  // The build has no database; a container's init commands run the migrations and schema checks, and the readiness
294
278
  // window opens only with `run.start`, after them (both verified live), so the CRM's ~3 minutes does not race it.
295
- // A dev container has none: its init would run before Control says whether a reset is pending, over the schema the
296
- // previous container left, so its launcher migrates and verifies after that answer.
297
- database: execution.databaseUrl !== null && execution.dev === undefined,
279
+ database: execution.databaseUrl !== null,
298
280
  sourceMaps: execution.sourceMaps !== null,
299
281
  jobs: execution.contract.jobs,
300
282
  files: execution.contract.files === true,
301
283
  scan: execution.contract.scan === true,
302
284
  })
303
285
 
304
- // A dev environment starts the launcher of the application's own framework release, which runs the serving entry as its
305
- // child. Double quotes inside: a generated file line may hold no single quote.
306
- const devStartScript: readonly string[] = [
307
- '#!/bin/sh',
308
- 'set -eu',
309
- `cd ${RUNTIME_ROOT}`,
310
- `exec bun -e "await import(\\"${DEV_LAUNCHER_MODULE}\\").then((dev) => dev.runDevLauncher(process.env))"`,
311
- ]
312
-
313
- /** One command writing `content` to `path` through base64: the content may hold quotes and expansions, the command none. */
314
- const writeBase64Command = (path: string, content: string): string => {
315
- const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(content)))
316
- return `printf '%s' '${encoded}' | base64 -d > ${path}`
317
- }
318
-
319
- /** What the dev launcher reads (`DEV_LAUNCHER_CONFIG_FILE`): the platform's, written after the checks. */
320
- export function devLauncherConfig(execution: ZeropsLockedExecution, authoredSpa: readonly string[]): DevLauncherConfig {
321
- const dev = execution.dev
322
- if (dev === undefined) throw new Error('zerops: a dev launcher configuration needs a dev environment')
323
- if (!/^[0-9a-f]{40}$/.test(dev.head)) throw new Error('zerops: a dev environment builds an exact commit')
324
- const recipe = recipeOf(execution)
325
- return {
326
- format: 1,
327
- appId: execution.appId,
328
- head: dev.head,
329
- port: ZEROPS_APPLICATION_PORT,
330
- healthPath: execution.contract.readinessPath,
331
- serve: recipe.serve,
332
- migrate: recipe.migrate,
333
- spaBuild: authoredSpa,
334
- // The build's check chain, in its order, on what the container holds.
335
- checks: recipeOf(execution, RUNTIME_ROOT).checks,
336
- }
337
- }
338
-
339
286
  /** The generated build commands, in order; the authored SPA commands run before all of them. */
340
- export function generatedBuildCommands(execution: ZeropsLockedExecution, authoredSpa: readonly string[] = []): readonly string[] {
341
- const recipe = recipeOf(execution)
342
- return recipe.build.flatMap((step) => {
343
- if ('run' in step) return [step.run]
344
- if (execution.dev === undefined || step.write !== recipe.start) return [writeFileCommand(step.write, step.lines)]
345
- return [
346
- writeFileCommand(recipe.start, devStartScript),
347
- writeBase64Command(DEV_LAUNCHER_CONFIG_FILE, JSON.stringify(devLauncherConfig(execution, authoredSpa))),
348
- ]
349
- })
287
+ export function generatedBuildCommands(execution: ZeropsLockedExecution): readonly string[] {
288
+ return recipeOf(execution).build.map((step) => 'run' in step ? step.run : writeFileCommand(step.write, step.lines))
350
289
  }
351
290
 
352
291
  const sortedUnique = (values: readonly string[]): string[] => [...new Set(values)].sort()
@@ -407,14 +346,14 @@ export function renderLockedSetup(
407
346
  build: {
408
347
  base: authored.base ?? [ZEROPS_APPLICATION_RUNTIME],
409
348
  ...(authored.os === null ? {} : { os: authored.os }),
410
- buildCommands: [...authored.commands, ...generatedBuildCommands(execution, authored.commands)],
349
+ buildCommands: [...authored.commands, ...generatedBuildCommands(execution)],
411
350
  ...(execution.sourceMaps === null ? {} : { envVariables: sourceMapBuildVariables(execution.sourceMaps) }),
412
351
  deployFiles: ['./'],
413
352
  cache: ['node_modules'],
414
353
  },
415
354
  deploy: {
416
355
  readinessCheck: {
417
- exec: { command: readinessCommand(contract.readinessPath, execution.dev !== undefined) },
356
+ exec: { command: readinessCommand(contract.readinessPath) },
418
357
  retryPeriod: '10s',
419
358
  failureTimeout: '180s',
420
359
  },
@@ -425,11 +364,7 @@ export function renderLockedSetup(
425
364
  ...(initCommands.length === 0 ? {} : { initCommands }),
426
365
  start: `sh ${RUNTIME_ROOT}/${recipeOf(execution).start}`,
427
366
  ports: [{ port: ZEROPS_APPLICATION_PORT, httpSupport: true }],
428
- // A dev container keeps its launcher running while the application it respawns fails: Zerops restarting it
429
- // would only boot the same failing head again.
430
- ...(execution.dev === undefined
431
- ? { healthCheck: { httpGet: probe, execPeriod: '10s', disconnectTimeout: '30s', recoveryTimeout: '10s', failureTimeout: '120s' } }
432
- : {}),
367
+ healthCheck: { httpGet: probe, execPeriod: '10s', disconnectTimeout: '30s', recoveryTimeout: '10s', failureTimeout: '120s' },
433
368
  ...(crontab.length === 0 ? {} : { crontab }),
434
369
  envVariables,
435
370
  },
@@ -92,7 +92,7 @@
92
92
  // arrives fully resolved). Only the proxy needs this, and it declares it explicitly below.
93
93
 
94
94
  import type { ZeropsHealthCheckSpec, ZeropsReadinessCheckSpec, ZeropsYamlSetupSpec, ZeropsYamlSpec } from '../../index'
95
- import { FABRIKA_PROXY_MANIFEST_BRAND } from '../../proxy-manifest-carrier'
95
+ import { FABRIKA_PROXY_MANIFEST_BRAND, FABRIKA_PROXY_MANIFEST_SANDBOXES, FABRIKA_PROXY_MANIFEST_SANDBOXES_VALUE } from '../../proxy-manifest-carrier'
96
96
 
97
97
  // ── Readiness and liveness: two mechanisms, two questions ──────────────────────────────────────────
98
98
  //
@@ -406,6 +406,8 @@ const proxy: ZeropsYamlSetupSpec = {
406
406
  // `brand`, so Control may send the installation's client logo (ADR-0066). An older pin's parser refuses the
407
407
  // key and fails its build, so it is sent only where this is (`zeropsProxyAcceptsBrand`).
408
408
  [FABRIKA_PROXY_MANIFEST_BRAND]: '1',
409
+ // The same kind of marker for dev sandbox entries (`zeropsProxyAcceptsSandboxes`); its value says what the hop does.
410
+ [FABRIKA_PROXY_MANIFEST_SANDBOXES]: FABRIKA_PROXY_MANIFEST_SANDBOXES_VALUE,
409
411
  },
410
412
  // CGO off makes the binary static, which is what lets it run on Alpine/musl.
411
413
  prepareCommands: ['CGO_ENABLED=0 GOBIN=/tmp/gobin go install github.com/caddyserver/caddy/v2/cmd/caddy@v2.10.2'],
@@ -69,7 +69,7 @@ import { assertTopologyInvariants } from './invariants'
69
69
  * `enableSubdomainAccess` on a service the document CREATES and then silently drops it, so the service
70
70
  * reads back `subdomainAccess: false` and stays there. The subdomain is established afterwards, by
71
71
  * `PUT /service-stack/{id}/enable-subdomain-access` on a service that already publishes an HTTP port —
72
- * which the namespace lifecycle does for itself (`ensureSubdomainAccess` in `src/namespace/provisioning.ts`)
72
+ * which the namespace lifecycle does for itself (`ensureSubdomainAccess` in `src/namespace/subdomain.ts`)
73
73
  * and which an operator applying the generated platform artifacts must do by hand; the artifact's header
74
74
  * names the call. So `true` here records the INTENT and feeds ADR-0022's `assertOnlyPublicService`; it
75
75
  * does not turn anything on.
package/src/manifest.ts CHANGED
@@ -18,7 +18,6 @@ import {
18
18
  zeropsAssetRoots,
19
19
  type ZeropsContractRun,
20
20
  zeropsContractRun,
21
- type ZeropsDevExecution,
22
21
  type ZeropsLockedExecution,
23
22
  type ZeropsRuntimePackage,
24
23
  } from './execution'
@@ -474,11 +473,8 @@ export const lockedExecutionOf = (manifest: FabrikaManifest): ZeropsLockedExecut
474
473
  }
475
474
  }
476
475
 
477
- /**
478
- * What Control lets a provider publish for one environment (`ProviderEnvironment.access`), and, for an environment of
479
- * kind `dev`, the commit its bootstrap builds.
480
- */
481
- export type ZeropsAccess = Pick<ProviderEnvironment, 'access'> & { readonly dev?: ZeropsDevExecution }
476
+ /** What Control lets a provider publish for one environment (`ProviderEnvironment.access`). */
477
+ export type ZeropsAccess = Pick<ProviderEnvironment, 'access'>
482
478
 
483
479
  /**
484
480
  * The execution descriptor's lock-down at deploy (ADR-0050): Control's approved contract decides it, not the artifact,
@@ -507,7 +503,6 @@ export function lockedExecutionFor(
507
503
  storageHostname: applicationStorageHostname(manifest.target.importDocument.services),
508
504
  runtimePackages: manifest.target.runtimePackages ?? [],
509
505
  sourceMaps: artifactUpload === undefined ? null : sourceMapUpload(artifactUpload, access.contract),
510
- ...(granted.dev === undefined ? {} : { dev: granted.dev }),
511
506
  }
512
507
  }
513
508
 
@@ -7,6 +7,7 @@ import type {
7
7
  import { isProxyHost } from '@fabrika/proxy-core/manifest'
8
8
  import { type ZeropsApi, ZeropsApiError } from '../api'
9
9
  import { assertFabrikaManifestCoordinates, manifestServiceHostnames, zeropsArtifactCodec } from '../manifest'
10
+ import { SANDBOX_HOST_HOSTNAME } from '../sandbox-host'
10
11
  import { zeropsSharedServicePrefix } from '../service-names'
11
12
  import { decodeEnvelope } from './codec'
12
13
  import { ZEROPS_NAMESPACE_POSTGRES_HOSTNAME, ZEROPS_NAMESPACE_PROXY_HOSTNAME } from './constants'
@@ -17,6 +18,7 @@ export const namespaceResourceClaims = (namespace: ProviderDeploymentNamespace):
17
18
  return [
18
19
  `service:${ZEROPS_NAMESPACE_PROXY_HOSTNAME}`,
19
20
  ...(target.postgres === undefined ? [] : [`service:${ZEROPS_NAMESPACE_POSTGRES_HOSTNAME}`]),
21
+ ...(target.sandboxHost === undefined ? [] : [`service:${SANDBOX_HOST_HOSTNAME}`]),
20
22
  ]
21
23
  }
22
24
 
@@ -40,6 +42,8 @@ export const registrationResourceClaims = (registration: ProviderRegistration):
40
42
  appId: registration.app.id,
41
43
  env: registration.environment.env,
42
44
  })
45
+ // A dev environment owns no Zerops service: each workspace runs in a sandbox of the namespace's own sandbox host.
46
+ if (registration.environment.kind === 'dev') return []
43
47
  // A proxy target is routed by HOST, so a registration with no domain has nothing the proxy can serve:
44
48
  // refuse it here, where nothing has been created yet, instead of at the first deploy's manifest compile.
45
49
  if (manifest.target.proxy !== undefined) {
@@ -42,6 +42,21 @@ const singlePostgresSchema = z.object({
42
42
  profile: z.enum(['oltp-hobby', 'oltp-staging', 'oltp-production', 'olap-production', 'writeheavy-production']).optional(),
43
43
  })
44
44
 
45
+ /** The Box API origin is exactly an `https:` origin: the key is sent there as a bearer. */
46
+ const isHttpsOrigin = (value: string): boolean => {
47
+ try {
48
+ const url = new URL(value)
49
+ return url.protocol === 'https:' && url.origin === value
50
+ } catch {
51
+ return false
52
+ }
53
+ }
54
+
55
+ const sandboxHostSchema = z.object({
56
+ serviceId: z.string().min(1),
57
+ apiOrigin: z.string().refine(isHttpsOrigin),
58
+ }).strict()
59
+
45
60
  export const postgresSchema = z.discriminatedUnion('type', [haPostgresSchema, singlePostgresSchema]).transform((value) => {
46
61
  if (value.profile === undefined) delete value.profile
47
62
  return value
@@ -63,6 +78,7 @@ const namespaceTargetShape = z.object({
63
78
  proxyBaselineSequence: z.number().int().min(-1).optional(),
64
79
  proxyAppVersionId: z.string().min(1).optional(),
65
80
  proxyHosts: z.array(z.object({ host: z.string().min(1), port: z.number().int().positive() })).optional(),
81
+ sandboxHost: sandboxHostSchema.optional(),
66
82
  ready: z.boolean().optional(),
67
83
  })
68
84
 
@@ -120,6 +136,7 @@ export const zeropsNamespaceTargetCodec: ProviderCodec<ZeropsNamespaceTarget> =
120
136
  ...(target.proxyBaselineSequence !== undefined ? { proxyBaselineSequence: target.proxyBaselineSequence } : {}),
121
137
  ...(target.proxyAppVersionId !== undefined ? { proxyAppVersionId: target.proxyAppVersionId } : {}),
122
138
  ...(target.proxyHosts === undefined ? {} : { proxyHosts: target.proxyHosts.map((entry) => ({ host: entry.host, port: entry.port })) }),
139
+ ...(target.sandboxHost === undefined ? {} : { sandboxHost: { serviceId: target.sandboxHost.serviceId, apiOrigin: target.sandboxHost.apiOrigin } }),
123
140
  ...(target.ready !== undefined ? { ready: target.ready } : {}),
124
141
  }),
125
142
  decode: (payload) => {
@@ -1,6 +1,7 @@
1
1
  import { ProviderNamespaceError } from '@fabrika/provider-contract'
2
2
  import { ZeropsApiError, ZeropsServiceEnvValueTooLargeError } from '../api'
3
3
  import { ZeropsSourceRateLimitedError } from '../source/port'
4
+ import { ZboxApiError, ZboxOperationFailed } from '../zbox'
4
5
 
5
6
  /**
6
7
  * Lifecycle codes this provider defines where the platform has none of its own. They are an
@@ -19,6 +20,21 @@ export const ZEROPS_SUBDOMAIN_NOT_PUBLISHED = 'subdomainNotPublished'
19
20
 
20
21
  export const ZEROPS_SOURCE_RATE_LIMITED = 'githubRateLimited'
21
22
 
23
+ /** A dev sandbox entry would be published to a namespace whose pinned proxy cannot parse one. */
24
+ export const ZEROPS_PROXY_SANDBOXES_UNSUPPORTED = 'proxySandboxesUnsupported'
25
+
26
+ /** A sandbox host was asked of a namespace that serves no custom domain, which a dev environment's wildcard needs. */
27
+ export const ZEROPS_SANDBOX_HOST_UNSUPPORTED = 'sandboxHostUnsupported'
28
+
29
+ /** The Box API did not accept the namespace's key after the service restarted with it. */
30
+ export const ZEROPS_SANDBOX_HOST_KEY_REFUSED = 'sandboxHostKeyRefused'
31
+
32
+ /** The Box API answered a request that carried no key, even after a restart with the namespace's key. */
33
+ export const ZEROPS_SANDBOX_HOST_API_OPEN = 'sandboxHostApiOpen'
34
+
35
+ /** A dev environment an older release registered with its own Zerops service, which runs in no sandbox. */
36
+ export const ZEROPS_DEV_TARGET_RETIRED = 'devTargetRetired'
37
+
22
38
  export const namespaceError = (code: string, message: string, retryable: boolean, detail?: string): ProviderNamespaceError =>
23
39
  new ProviderNamespaceError(message, code, retryable, detail)
24
40
 
@@ -48,6 +64,11 @@ export const asNamespaceError = (cause: unknown, mode: 'provision' | 'reconcile'
48
64
  if (cause instanceof ZeropsServiceEnvValueTooLargeError) return namespaceError(cause.code, cause.message, false)
49
65
  // The limit resets on its own: the namespace stays `provisioning` and the cron's reconcile retries it.
50
66
  if (cause instanceof ZeropsSourceRateLimitedError) return namespaceError(ZEROPS_SOURCE_RATE_LIMITED, cause.message, true)
67
+ // The message is the operation, the status and Box's code only: Box echoes request data in its bodies.
68
+ if (cause instanceof ZboxApiError) {
69
+ return namespaceError(cause.code, cause.message, cause.status === 0 || cause.status === 429 || cause.status >= 500)
70
+ }
71
+ if (cause instanceof ZboxOperationFailed) return namespaceError(cause.code ?? 'zboxOperationFailed', cause.message, false)
51
72
  if (cause instanceof ZeropsApiError) {
52
73
  const { summary, detail } = splitApiMessage(cause.message, cause.code)
53
74
  return namespaceError(
@@ -1,14 +1,43 @@
1
1
  import { appEnvironmentId } from '@fabrika/auth-core'
2
2
  import { decodeEnvelope, type ProviderNamespaceMember } from '@fabrika/provider-contract'
3
- import { contractProxyEntry, contractProxyTable, type ProxyManifest } from '@fabrika/proxy-core/manifest'
3
+ import { contractProxyEntry, contractProxyTable, devSandboxEntryId, type ProxyManifest } from '@fabrika/proxy-core/manifest'
4
4
  import { assertFabrikaManifestCoordinates, zeropsArtifactCodec } from '../manifest'
5
+ import { SANDBOX_UPSTREAM } from '../sandbox-host'
5
6
 
6
7
  /** Compile every public member of one deployment namespace into its strict proxy manifest. */
7
8
  export function compileNamespaceProxyManifest(namespaceId: string, members: readonly ProviderNamespaceMember[]): ProxyManifest {
8
9
  const apps: ProxyManifest['apps'] = []
9
10
  const ids = new Set<string>()
10
11
  const hosts = new Set<string>()
12
+ const claim = (id: string, host: string): void => {
13
+ if (ids.has(id)) throw new Error(`duplicate proxy app id \`${id}\` in deployment namespace ${namespaceId}`)
14
+ if (hosts.has(host)) throw new Error(`duplicate proxy host \`${host}\` in deployment namespace ${namespaceId}`)
15
+ ids.add(id)
16
+ hosts.add(host)
17
+ }
11
18
  for (const member of members) {
19
+ // A dev member is served only through its workspaces' sandboxes, each behind the namespace's own sandbox host; its
20
+ // upstream is never the artifact's, so the artifact is not decoded.
21
+ if (member.devSandboxes !== undefined) {
22
+ const audience = appEnvironmentId(member.appId, member.env)
23
+ for (const sandbox of member.devSandboxes) {
24
+ const id = devSandboxEntryId(member.appId, sandbox.workspaceId)
25
+ const host = sandbox.host.toLowerCase()
26
+ claim(id, host)
27
+ apps.push(contractProxyEntry({
28
+ id,
29
+ audience,
30
+ hosts: [host],
31
+ upstream: SANDBOX_UPSTREAM,
32
+ upstreamHost: sandbox.upstreamHost,
33
+ scheme: 'https',
34
+ table: contractProxyTable(sandbox.access.contract, sandbox.access.contractDigest),
35
+ ...(member.operationsOrigin === undefined ? {} : { operationsOrigin: member.operationsOrigin }),
36
+ ...(member.crossOrigins === undefined ? {} : { crossOrigins: member.crossOrigins }),
37
+ }))
38
+ }
39
+ continue
40
+ }
12
41
  // Only Control decides what routes a member (ADR-0050): its approved contract's endpoint table. A member without
13
42
  // one is not routed, and its artifact is not decoded, so a legacy one cannot stop the others' republish.
14
43
  const access = member.access
@@ -23,10 +52,7 @@ export function compileNamespaceProxyManifest(namespaceId: string, members: read
23
52
  const host = member.domain.toLowerCase()
24
53
  // The proxy mints for the IAM application id of this environment (ADR-0022 rule 6).
25
54
  const id = appEnvironmentId(member.appId, member.env)
26
- if (ids.has(id)) throw new Error(`duplicate proxy app id \`${id}\` in deployment namespace ${namespaceId}`)
27
- if (hosts.has(host)) throw new Error(`duplicate proxy host \`${host}\` in deployment namespace ${namespaceId}`)
28
- ids.add(id)
29
- hosts.add(host)
55
+ claim(id, host)
30
56
  apps.push(contractProxyEntry({
31
57
  id,
32
58
  hosts: [host],
@@ -6,62 +6,26 @@ import {
6
6
  type ProviderNamespaceRepublishInput,
7
7
  type ProviderNamespaceRepublishResult,
8
8
  } from '@fabrika/provider-contract'
9
- import {
10
- enableSubdomainAccessWhenHttp,
11
- readableContent,
12
- waitForProcess,
13
- ZEROPS_SERVICE_NOT_HTTP,
14
- ZEROPS_TERMINAL,
15
- ZeropsApiError,
16
- type ZeropsProject,
17
- type ZeropsService,
18
- } from '../api'
9
+ import { waitForProcess, ZEROPS_TERMINAL, type ZeropsProject, type ZeropsService } from '../api'
19
10
  import { defaultSleep } from '../collaborators'
11
+ import { SANDBOX_HOST_HOSTNAME } from '../sandbox-host'
20
12
  import { claimedResources, namespaceResourceClaims, projectExists, registrationResourceClaims, ZEROPS_PROJECT_NOT_FOUND } from './claims'
21
13
  import { checkpoint, decodeEnvelope, normalizedNamespace, normalizeTarget } from './codec'
22
- import { ZEROPS_NAMESPACE_POSTGRES_HOSTNAME, ZEROPS_NAMESPACE_PROXY_HOSTNAME, ZEROPS_NAMESPACE_SUBDOMAIN_VARIABLE } from './constants'
23
- import { asNamespaceError, namespaceError, ZEROPS_NAMESPACE_CANCELLED, ZEROPS_SUBDOMAIN_NOT_PUBLISHED } from './errors'
14
+ import { ZEROPS_NAMESPACE_POSTGRES_HOSTNAME, ZEROPS_NAMESPACE_PROXY_HOSTNAME } from './constants'
15
+ import { asNamespaceError, namespaceError } from './errors'
24
16
  import { compileNamespaceProxyManifest } from './manifest'
25
17
  import { createZeropsNamespaceOperator } from './operator'
26
18
  import { republishProxy } from './proxy-attempt'
19
+ import { assertNamespaceProxyAcceptsSandboxes } from './proxy-reads'
27
20
  import { namespaceProxySecrets } from './proxy-secrets'
28
21
  import { verifyZeropsNamespaceProxySource } from './proxy-source'
22
+ import { assertSandboxHostAllowed, ensureSandboxHost } from './sandbox-host'
23
+ import { ensureSubdomainAccess, readSubdomainHosts } from './subdomain'
29
24
  import { compileZeropsNamespaceTopology, projectMarker, PROXY_TYPE } from './topology'
30
- import type { NormalizedZeropsNamespaceTarget, ZeropsNamespaceOptions, ZeropsNamespaceProxySource } from './types'
25
+ import type { NormalizedZeropsNamespaceTarget, ZeropsNamespaceOptions, ZeropsNamespaceProxySource, ZeropsNamespaceSandboxHost } from './types'
31
26
  import { createZeropsNamespaceUpdates } from './update'
32
27
  import { validateService } from './validation'
33
28
 
34
- const POLL_INTERVAL_MS = 3000
35
-
36
- /** The live enable finishes in under a second, but one run still read `false` once before flipping; ten reads is slack. */
37
- const SUBDOMAIN_READBACK_ATTEMPTS = 10
38
-
39
- /**
40
- * One host per published HTTP port, out of the newline-separated URLs the platform writes.
41
- *
42
- * The form is `<hostname>-<hash>-<port>.<region>.zerops.app` (e.g. `proxy-2ec8-8080`). Read as URLs
43
- * rather than split on `-`, so a hostname whose own first label ends in digits cannot be misread; a line
44
- * that is not a URL, or whose first label carries no trailing port — the single portless line a proxy
45
- * that has never deployed publishes — is skipped rather than guessed at.
46
- */
47
- const parseZeropsProxyHosts = (value: string): ProviderNamespaceHost[] => {
48
- const hosts: ProviderNamespaceHost[] = []
49
- for (const line of value.split('\n')) {
50
- const trimmed = line.trim()
51
- if (trimmed === '') continue
52
- let hostname: string
53
- try {
54
- hostname = new URL(trimmed).hostname
55
- } catch {
56
- continue
57
- }
58
- const port = /-(\d+)$/.exec(hostname.split('.')[0] ?? '')?.[1]
59
- if (port === undefined) continue
60
- hosts.push({ host: hostname, port: Number.parseInt(port, 10) })
61
- }
62
- return hosts.sort((left, right) => left.port - right.port)
63
- }
64
-
65
29
  const validateProject = (
66
30
  namespace: ProviderDeploymentNamespace,
67
31
  target: NormalizedZeropsNamespaceTarget,
@@ -168,6 +132,7 @@ const resolveServices = async (
168
132
  const reserved = new Set([
169
133
  ZEROPS_NAMESPACE_PROXY_HOSTNAME,
170
134
  ...(target.postgres === undefined ? [] : [ZEROPS_NAMESPACE_POSTGRES_HOSTNAME]),
135
+ ...(target.sandboxHost === undefined ? [] : [SANDBOX_HOST_HOSTNAME]),
171
136
  ])
172
137
  const unexpected = services.filter((service) => !reserved.has(service.name))
173
138
  if (unexpected.length > 0) {
@@ -195,9 +160,7 @@ const readProxyHosts = async (
195
160
  throw new Error('Zerops namespace has no proxy service id')
196
161
  }
197
162
  try {
198
- const variables = await options.api.listServiceEnv({ serviceId: proxyServiceId, signal })
199
- const subdomains = readableContent(variables.find((variable) => variable.key === ZEROPS_NAMESPACE_SUBDOMAIN_VARIABLE))
200
- return subdomains === undefined ? [] : parseZeropsProxyHosts(subdomains)
163
+ return await readSubdomainHosts(options.api, proxyServiceId, signal)
201
164
  } catch {
202
165
  // A host listing is a convenience; the proxy is already built, deployed and published. Failing the
203
166
  // namespace over it would report a placement that WORKS as broken. Never the cause: it can carry
@@ -256,6 +219,37 @@ const deployProxy = async (
256
219
  return { namespace: currentNamespace, target: { ...target, ...result } }
257
220
  }
258
221
 
222
+ /**
223
+ * Refused before any platform write: an older pin's strict parser would fail the build on a sandbox entry, and a sandbox
224
+ * host on such a pin could serve nothing. Never dropped silently.
225
+ */
226
+ const assertSandboxesAccepted = (input: ProviderNamespaceMutationInput, namespaceId: string, target: NormalizedZeropsNamespaceTarget): void => {
227
+ if (input.sandboxKey === undefined && !input.members.some((member) => (member.devSandboxes?.length ?? 0) > 0)) return
228
+ assertNamespaceProxyAcceptsSandboxes(namespaceId, target.proxySource)
229
+ }
230
+
231
+ const sandboxHost = async (
232
+ input: ProviderNamespaceMutationInput,
233
+ sandboxKey: string,
234
+ namespace: ProviderDeploymentNamespace,
235
+ target: NormalizedZeropsNamespaceTarget,
236
+ options: ZeropsNamespaceOptions,
237
+ ): Promise<ZeropsNamespaceSandboxHost> => {
238
+ try {
239
+ return await ensureSandboxHost({
240
+ namespaceId: namespace.id,
241
+ target,
242
+ sandboxKey,
243
+ api: options.api,
244
+ ...(options.zboxFetch === undefined ? {} : { zboxFetch: options.zboxFetch }),
245
+ ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
246
+ signal: input.signal,
247
+ })
248
+ } catch (cause) {
249
+ throw asNamespaceError(cause, 'reconcile')
250
+ }
251
+ }
252
+
259
253
  /** Rebuild a ready namespace's proxy from its current members; provisioning stays with `provision`/`reconcile`. */
260
254
  const republishNamespace = async (
261
255
  input: ProviderNamespaceRepublishInput,
@@ -266,70 +260,15 @@ const republishNamespace = async (
266
260
  if (target.proxyServiceId === undefined || (target.proxyBuild === undefined && !target.ready)) {
267
261
  throw new Error(`Namespace ${namespace.id} is not ready`)
268
262
  }
269
- const deployed = await deployProxy(input, namespace, target, options, input.wait, true)
270
- return { namespace: deployed.namespace, settled: deployed.target.proxyBuild === undefined && deployed.target.ready }
271
- }
272
-
273
- /**
274
- * Publish the proxy on its `*.zerops.app` subdomain — the ONE thing the import document cannot do.
275
- *
276
- * `enableSubdomainAccess: true` is accepted by the import and then silently dropped, on a service the
277
- * document CREATES as much as on one `override` leaves alone; a service imported with it reads back
278
- * `subdomainAccess: false` for ever. The subdomain is established by
279
- * `PUT /service-stack/{id}/enable-subdomain-access` and by nothing else, and that call needs a DEPLOYED
280
- * HTTP port — which is why this runs after `deployProxy` rather than beside the import.
281
- *
282
- * It runs on RECONCILE too, so a subdomain someone turned off in the GUI comes back. What it must never
283
- * do is finish quietly: `zerops-subdomain` is the only public entry a namespace has, so this either
284
- * observes `subdomainAccess === true` or throws naming what is missing.
285
- *
286
- * The decision is the READ-BACK, never the call returning. On an already-published service the platform
287
- * answers 2xx and then fails the process it handed back — live-verified — so a 2xx proves nothing.
288
- *
289
- * The HTTP ports lag the proxy's ACTIVE version, so `serviceStackIsNotHttp` is retried for a bounded
290
- * window (`enableSubdomainAccessWhenHttp`) before it fails the namespace.
291
- */
292
- const ensureSubdomainAccess = async (
293
- target: NormalizedZeropsNamespaceTarget,
294
- options: ZeropsNamespaceOptions,
295
- signal: AbortSignal,
296
- ): Promise<void> => {
297
- const proxyServiceId = target.proxyServiceId
298
- if (proxyServiceId === undefined) {
299
- throw new Error('Zerops namespace has no proxy service id')
300
- }
301
- const published = async (): Promise<boolean> => (await options.api.getService({ serviceId: proxyServiceId, signal })).subdomainAccess === true
302
- if (await published()) {
303
- return
304
- }
305
- try {
306
- await enableSubdomainAccessWhenHttp({ api: options.api, serviceId: proxyServiceId, sleep: options.sleep ?? defaultSleep, signal })
307
- } catch (error) {
308
- if (error instanceof ZeropsApiError && error.code === ZEROPS_SERVICE_NOT_HTTP) {
309
- throw namespaceError(
310
- ZEROPS_SERVICE_NOT_HTTP,
311
- `Zerops namespace proxy ${proxyServiceId} cannot be published on a zerops.app subdomain: it still exposes no deployed HTTP port (${ZEROPS_SERVICE_NOT_HTTP}) minutes after its deploy`,
312
- false,
313
- )
314
- }
315
- throw error
316
- }
317
- for (let attempt = 0;; attempt += 1) {
318
- if (signal.aborted) {
319
- throw namespaceError(ZEROPS_NAMESPACE_CANCELLED, 'Zerops namespace provisioning was cancelled', true)
320
- }
321
- if (await published()) {
322
- return
323
- }
324
- if (attempt >= SUBDOMAIN_READBACK_ATTEMPTS) {
325
- throw namespaceError(
326
- ZEROPS_SUBDOMAIN_NOT_PUBLISHED,
327
- `Zerops namespace proxy ${proxyServiceId} accepted enable-subdomain-access but still reads subdomainAccess: false — the namespace has no public entry point`,
328
- true,
329
- )
330
- }
331
- await (options.sleep ?? defaultSleep)(POLL_INTERVAL_MS, signal)
263
+ assertSandboxesAccepted(input, namespace.id, target)
264
+ let current = namespace
265
+ let ready = target
266
+ if (input.sandboxKey !== undefined && target.sandboxHost === undefined) {
267
+ ready = { ...target, sandboxHost: await sandboxHost(input, input.sandboxKey, namespace, target, options) }
268
+ current = await checkpoint(input, namespace, ready)
332
269
  }
270
+ const deployed = await deployProxy(input, current, ready, options, input.wait, true)
271
+ return { namespace: deployed.namespace, settled: deployed.target.proxyBuild === undefined && deployed.target.ready }
333
272
  }
334
273
 
335
274
  /** Every exit from the lifecycle below is a `ProviderNamespaceError`, so a caller never has to guess. */
@@ -359,6 +298,8 @@ const runNamespaceMutation = async (
359
298
  throw new Error('Proxy build is missing checkpointed project or service identity')
360
299
  }
361
300
  await verifyZeropsNamespaceProxySource(target.proxySource)
301
+ assertSandboxesAccepted(input, namespace.id, target)
302
+ if (input.sandboxKey !== undefined) assertSandboxHostAllowed(namespace.id, target)
362
303
  input.signal.throwIfAborted()
363
304
  if (target.proxyBuild === undefined && target.proxyDeployment !== undefined) {
364
305
  try {
@@ -458,7 +399,16 @@ const runNamespaceMutation = async (
458
399
  // After the deploy, because the platform refuses a service with no HTTP port — and never before `ready`
459
400
  // is checkpointed, because a namespace with no public entry point is not ready.
460
401
  if (target.publicAccess === 'zerops-subdomain') {
461
- await ensureSubdomainAccess(target, options, input.signal)
402
+ const proxyServiceId = target.proxyServiceId
403
+ if (proxyServiceId === undefined) throw new Error('Zerops namespace has no proxy service id')
404
+ await ensureSubdomainAccess({
405
+ api: options.api,
406
+ serviceId: proxyServiceId,
407
+ label: 'Zerops namespace proxy',
408
+ consequence: 'the namespace has no public entry point',
409
+ ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
410
+ signal: input.signal,
411
+ })
462
412
  }
463
413
  const proxyHosts = target.publicAccess === 'zerops-subdomain' ? await readProxyHosts(namespace, target, options, input.signal) : []
464
414
  target = {
@@ -469,7 +419,13 @@ const runNamespaceMutation = async (
469
419
  proxyHosts: proxyHosts.length === 0 ? undefined : proxyHosts,
470
420
  ready: true,
471
421
  }
472
- return checkpoint(input, namespace, target)
422
+ namespace = await checkpoint(input, namespace, target)
423
+ // After the proxy converged and `ready` is recorded, so a sandbox host failure never holds back the namespace's proxy.
424
+ if (input.sandboxKey !== undefined) {
425
+ target = { ...target, sandboxHost: await sandboxHost(input, input.sandboxKey, namespace, target, options) }
426
+ namespace = await checkpoint(input, namespace, target)
427
+ }
428
+ return namespace
473
429
  }
474
430
 
475
431
  /** Build the provider-owned namespace lifecycle capability. */
@@ -3,8 +3,10 @@
3
3
  // republish; and it has no terminal sign-out. So a deploy that would publish either, or a terminal, is refused before
4
4
  // publication while the namespace's proxy source is not this control plane's own.
5
5
 
6
- import type { ProviderApprovedAccess } from '@fabrika/provider-contract'
6
+ import { type ProviderApprovedAccess, ProviderNamespaceError } from '@fabrika/provider-contract'
7
7
  import { contractProxyTable, type OlderProxyReaders } from '@fabrika/proxy-core/manifest'
8
+ import { zeropsProxyAcceptsSandboxes } from '../proxy-manifest-carrier'
9
+ import { ZEROPS_PROXY_SANDBOXES_UNSUPPORTED } from './errors'
8
10
  import type { ZeropsNamespaceProxySource } from './types'
9
11
 
10
12
  export type { OlderProxyReader, OlderProxyReaders } from '@fabrika/proxy-core/manifest'
@@ -53,3 +55,16 @@ export function assertNamespaceProxyReads(
53
55
  }; re-pin it with \`fabrika control namespaces update --namespace=${namespace} --proxy-source=current\`, then deploy again`,
54
56
  )
55
57
  }
58
+
59
+ /**
60
+ * Refuses dev sandbox entries for a namespace whose pinned proxy cannot parse their `audience` and `upstreamHost`: its
61
+ * strict parser would fail the proxy build. The row and CSP judges above see neither field, so this marker is their gate.
62
+ */
63
+ export function assertNamespaceProxyAcceptsSandboxes(namespace: string, pinned: ZeropsNamespaceProxySource): void {
64
+ if (zeropsProxyAcceptsSandboxes(pinned.descriptor.contents)) return
65
+ throw new ProviderNamespaceError(
66
+ `the proxy of deployment namespace \`${namespace}\` is pinned to a source that cannot serve dev sandboxes; re-pin it with \`fabrika control namespaces update --namespace=${namespace} --proxy-source=current\`, then try again`,
67
+ ZEROPS_PROXY_SANDBOXES_UNSUPPORTED,
68
+ false,
69
+ )
70
+ }