@fabrika/provider-zerops 0.9.0-dev.7 → 0.9.0-dev.9

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 (68) 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 +24 -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 +236 -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 +21 -7
  31. package/src/sandbox/base-image.ts +100 -0
  32. package/src/sandbox/constants.ts +43 -0
  33. package/src/sandbox/deploy.ts +471 -0
  34. package/src/sandbox/dev-artifact.ts +206 -0
  35. package/src/sandbox/lifecycle.ts +200 -0
  36. package/src/sandbox/scripts.ts +26 -0
  37. package/src/sandbox-host.ts +31 -0
  38. package/src/source/port.ts +5 -0
  39. package/src/zbox/client.ts +267 -0
  40. package/src/zbox/errors.ts +45 -0
  41. package/src/zbox/index.ts +23 -0
  42. package/src/zbox/types.ts +168 -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/topology.d.ts +1 -1
  47. package/types/src/manifest.d.ts +3 -8
  48. package/types/src/namespace/codec.d.ts +18 -0
  49. package/types/src/namespace/errors.d.ts +12 -0
  50. package/types/src/namespace/proxy-reads.d.ts +6 -1
  51. package/types/src/namespace/proxy-secrets.d.ts +1 -1
  52. package/types/src/namespace/sandbox-host.d.ts +23 -0
  53. package/types/src/namespace/subdomain.d.ts +43 -0
  54. package/types/src/namespace/types.d.ts +10 -0
  55. package/types/src/provider.d.ts +0 -3
  56. package/types/src/proxy-manifest-carrier.d.ts +8 -1
  57. package/types/src/sandbox/base-image.d.ts +28 -0
  58. package/types/src/sandbox/constants.d.ts +29 -0
  59. package/types/src/sandbox/deploy.d.ts +75 -0
  60. package/types/src/sandbox/dev-artifact.d.ts +51 -0
  61. package/types/src/sandbox/lifecycle.d.ts +27 -0
  62. package/types/src/sandbox/scripts.d.ts +11 -0
  63. package/types/src/sandbox-host.d.ts +18 -0
  64. package/types/src/source/port.d.ts +5 -0
  65. package/types/src/zbox/client.d.ts +2 -0
  66. package/types/src/zbox/errors.d.ts +25 -0
  67. package/types/src/zbox/index.d.ts +3 -0
  68. package/types/src/zbox/types.d.ts +462 -0
@@ -1,21 +1,34 @@
1
1
  import { appEnvironmentId, proxySecretVariable } from '@fabrika/auth-core'
2
2
  import type { ProviderNamespaceMember } from '@fabrika/provider-contract'
3
- import { isApplicationEntry, type ProxyManifest } from '@fabrika/proxy-core/manifest'
3
+ import { devSandboxEntryId, isApplicationEntry, type ProxyManifest } from '@fabrika/proxy-core/manifest'
4
+
5
+ /** The secret Control handed for one manifest entry: a dev sandbox's own, else its member's. */
6
+ const entrySecret = (id: string, members: readonly ProviderNamespaceMember[]): string | undefined => {
7
+ for (const member of members) {
8
+ if (member.devSandboxes !== undefined) {
9
+ const sandbox = member.devSandboxes.find((candidate) => devSandboxEntryId(member.appId, candidate.workspaceId) === id)
10
+ if (sandbox !== undefined) return sandbox.proxySecret
11
+ continue
12
+ }
13
+ if (appEnvironmentId(member.appId, member.env) === id) return member.proxySecret
14
+ }
15
+ return undefined
16
+ }
4
17
 
5
18
  /**
6
19
  * The proxy service variables a manifest needs: for each contract application, the secret Caddy sends it
7
- * (ADR-0022 rule 5), keyed by `proxySecretVariable`. A contract member without a secret is refused, because
20
+ * (ADR-0022 rule 5), keyed by `proxySecretVariable`. A contract entry without a secret is refused, because
8
21
  * its application would refuse every request the proxy sends.
9
22
  */
10
23
  export function namespaceProxySecrets(manifest: ProxyManifest, members: readonly ProviderNamespaceMember[]): ReadonlyMap<string, string> {
11
24
  const secrets = new Map<string, string>()
12
25
  for (const app of manifest.apps) {
13
26
  if (!isApplicationEntry(app)) continue
14
- const member = members.find((candidate) => appEnvironmentId(candidate.appId, candidate.env) === app.id)
15
- if (member?.proxySecret === undefined || member.proxySecret === '') {
27
+ const secret = entrySecret(app.id, members)
28
+ if (secret === undefined || secret === '') {
16
29
  throw new Error(`Zerops proxy target ${app.id} is a contract application, and Control supplied no proxy secret for it`)
17
30
  }
18
- secrets.set(proxySecretVariable(app.id), member.proxySecret)
31
+ secrets.set(proxySecretVariable(app.id), secret)
19
32
  }
20
33
  return secrets
21
34
  }
@@ -0,0 +1,236 @@
1
+ import { waitForProcess, type ZeropsApi, type ZeropsService, type ZeropsServiceStatus } from '../api'
2
+ import { defaultSleep, type Sleeper } from '../collaborators'
3
+ import {
4
+ SANDBOX_HOST_API_PORT,
5
+ SANDBOX_HOST_DOMAIN,
6
+ SANDBOX_HOST_HOSTNAME,
7
+ SANDBOX_HOST_KEY_VARIABLE,
8
+ SANDBOX_HOST_SERVICE_TYPE,
9
+ SANDBOX_HOST_TYPE,
10
+ } from '../sandbox-host'
11
+ import { createZboxClient, ZboxApiError, type ZboxClient, type ZboxFetch, type ZboxWorkspace } from '../zbox'
12
+ import {
13
+ namespaceError,
14
+ ZEROPS_SANDBOX_HOST_API_OPEN,
15
+ ZEROPS_SANDBOX_HOST_DOMAIN_FORM,
16
+ ZEROPS_SANDBOX_HOST_KEY_REFUSED,
17
+ ZEROPS_SANDBOX_HOST_UNSUPPORTED,
18
+ } from './errors'
19
+ import { ensureSubdomainAccess, readSubdomainHosts } from './subdomain'
20
+ import type { NormalizedZeropsNamespaceTarget, ZeropsNamespaceSandboxHost } from './types'
21
+ import { validateService } from './validation'
22
+
23
+ export type ZeropsSandboxHostApi = Pick<
24
+ ZeropsApi,
25
+ | 'listProjectServices'
26
+ | 'importServices'
27
+ | 'getProcess'
28
+ | 'getService'
29
+ | 'putServiceEnv'
30
+ | 'startService'
31
+ | 'stopService'
32
+ | 'enableSubdomainAccess'
33
+ | 'listServiceEnv'
34
+ >
35
+
36
+ export interface ZeropsSandboxHostInput {
37
+ readonly namespaceId: string
38
+ readonly target: NormalizedZeropsNamespaceTarget
39
+ /** The Box API key Control composed from its vault; written to the service, sent as a bearer, never read back. */
40
+ readonly sandboxKey: string
41
+ readonly api: ZeropsSandboxHostApi
42
+ readonly zboxFetch?: ZboxFetch
43
+ readonly sleep?: Sleeper
44
+ readonly signal: AbortSignal
45
+ }
46
+
47
+ /** One service only, never the steady topology: re-applying that at a service carrying code activates an empty version. */
48
+ const SANDBOX_HOST_IMPORT_YAML = `services:
49
+ - hostname: ${SANDBOX_HOST_HOSTNAME}
50
+ type: ${SANDBOX_HOST_TYPE}
51
+ envIsolation: service
52
+ `
53
+
54
+ /** A host someone stopped is started again; UNVERIFIED which of these a stopped `zbox@1` service reads. */
55
+ const NOT_STARTED: ReadonlySet<ZeropsServiceStatus> = new Set(['READY_TO_DEPLOY', 'STOPPED', 'SERVICE_STOPPED'])
56
+
57
+ const POLL_INTERVAL_MS = 3000
58
+
59
+ /** A started Box answers within seconds; the subdomain's first request can lag it a little more. */
60
+ const BOX_REACH_ATTEMPTS = 20
61
+
62
+ const PROBE_TIMEOUT_MS = 30_000
63
+
64
+ /** A sandbox host on a `zerops-subdomain` namespace is refused: a dev environment's wildcard needs a custom domain. */
65
+ export const assertSandboxHostAllowed = (namespaceId: string, target: NormalizedZeropsNamespaceTarget): void => {
66
+ if (target.publicAccess !== 'zerops-subdomain') return
67
+ throw namespaceError(
68
+ ZEROPS_SANDBOX_HOST_UNSUPPORTED,
69
+ `deployment namespace \`${namespaceId}\` is published on zerops.app subdomains; a dev environment needs a custom-domain namespace`,
70
+ false,
71
+ )
72
+ }
73
+
74
+ const findSandboxHost = async (api: ZeropsSandboxHostApi, projectId: string, signal: AbortSignal): Promise<ZeropsService | null> => {
75
+ const matches = (await api.listProjectServices({ projectId, signal })).filter((service) => service.name === SANDBOX_HOST_HOSTNAME)
76
+ if (matches.length > 1) throw new Error(`Zerops namespace has multiple services named \`${SANDBOX_HOST_HOSTNAME}\``)
77
+ return matches[0] ?? null
78
+ }
79
+
80
+ const waitFor = async (input: ZeropsSandboxHostInput, processId: string, label: string): Promise<void> => {
81
+ await waitForProcess({ api: input.api, processId, sleep: input.sleep ?? defaultSleep, signal: input.signal, label })
82
+ }
83
+
84
+ /** The key is a credential: written sensitive, never compared, never read back (a sensitive value reads REDACTED). */
85
+ const writeKey = async (input: ZeropsSandboxHostInput, serviceId: string): Promise<void> => {
86
+ await input.api.putServiceEnv({ serviceId, key: SANDBOX_HOST_KEY_VARIABLE, value: input.sandboxKey, sensitive: true, signal: input.signal })
87
+ }
88
+
89
+ /**
90
+ * Create the service. The platform starts it at once with a key it generated itself (measured live), so Box first
91
+ * refuses ours and the rekey below is what keys it.
92
+ */
93
+ const createSandboxHost = async (input: ZeropsSandboxHostInput, projectId: string): Promise<ZeropsService> => {
94
+ const imported = await input.api.importServices({ projectId, yaml: SANDBOX_HOST_IMPORT_YAML, signal: input.signal })
95
+ for (const service of imported.services) {
96
+ for (const process of service.processes) await waitFor(input, process.id, 'sandbox host import')
97
+ }
98
+ const created = await findSandboxHost(input.api, projectId, input.signal)
99
+ if (created === null) throw new Error(`Zerops namespace project ${projectId} has no sandbox host after its import`)
100
+ return created
101
+ }
102
+
103
+ /** The Box API origin: the `https://` subdomain the platform published for the API port. */
104
+ const readApiOrigin = async (input: ZeropsSandboxHostInput, serviceId: string): Promise<string> => {
105
+ const host = (await readSubdomainHosts(input.api, serviceId, input.signal)).find((entry) => entry.port === SANDBOX_HOST_API_PORT)
106
+ if (host === undefined) {
107
+ throw namespaceError(
108
+ 'sandboxHostNotPublished',
109
+ `Zerops sandbox host ${serviceId} publishes no subdomain for port ${SANDBOX_HOST_API_PORT} yet`,
110
+ true,
111
+ )
112
+ }
113
+ return `https://${host.host}`
114
+ }
115
+
116
+ const isUnauthorized = (error: unknown): boolean => error instanceof ZboxApiError && (error.status === 401 || error.code === 'unauthorized')
117
+
118
+ /** Box not answering yet: unreachable, timed out, or the platform's balancer answering for a starting container. */
119
+ const isStarting = (error: unknown): boolean => error instanceof ZboxApiError && (error.status === 0 || error.status >= 500)
120
+
121
+ /** The workspace, or `unauthorized` when Box refuses the key. Retries only while Box is starting. */
122
+ const reachWorkspace = async (input: ZeropsSandboxHostInput, client: ZboxClient): Promise<ZboxWorkspace | 'unauthorized'> => {
123
+ for (let attempt = 1;; attempt += 1) {
124
+ try {
125
+ return await client.getWorkspace(input.signal)
126
+ } catch (error) {
127
+ if (isUnauthorized(error)) return 'unauthorized'
128
+ input.signal.throwIfAborted()
129
+ if (!isStarting(error) || attempt >= BOX_REACH_ATTEMPTS) throw error
130
+ }
131
+ await (input.sleep ?? defaultSleep)(POLL_INTERVAL_MS, input.signal)
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Box reads its key from its environment when it starts, so a refused key is written again and the service restarted.
137
+ * Measured live: a fresh host always takes this path, since the platform generated its own key at import.
138
+ */
139
+ const rekey = async (input: ZeropsSandboxHostInput, client: ZboxClient, serviceId: string): Promise<ZboxWorkspace> => {
140
+ console.info(`Zerops namespace ${input.namespaceId}: restarting sandbox host ${serviceId} with the namespace's key`)
141
+ await writeKey(input, serviceId)
142
+ await waitFor(input, (await input.api.stopService({ serviceId, signal: input.signal })).id, 'sandbox host stop')
143
+ await waitFor(input, (await input.api.startService({ serviceId, signal: input.signal })).id, 'sandbox host start')
144
+ const workspace = await reachWorkspace(input, client)
145
+ if (workspace === 'unauthorized') {
146
+ throw namespaceError(
147
+ ZEROPS_SANDBOX_HOST_KEY_REFUSED,
148
+ `Zerops sandbox host ${serviceId} still refuses the namespace's key after a restart with it`,
149
+ false,
150
+ )
151
+ }
152
+ return workspace
153
+ }
154
+
155
+ /** Whether Box refuses a request that carries no key. Body never read: Box echoes request data in it. */
156
+ const refusesWithoutKey = async (input: ZeropsSandboxHostInput, apiOrigin: string): Promise<boolean> => {
157
+ let response: Response
158
+ try {
159
+ response = await (input.zboxFetch ?? fetch)(`${apiOrigin}/api/rest/workspace`, {
160
+ method: 'GET',
161
+ headers: { accept: 'application/json' },
162
+ signal: AbortSignal.any([input.signal, AbortSignal.timeout(PROBE_TIMEOUT_MS)]),
163
+ })
164
+ } catch {
165
+ input.signal.throwIfAborted()
166
+ throw new ZboxApiError('probe workspace without a key', 0, 'unreachable')
167
+ }
168
+ await response.body?.cancel()
169
+ if (response.status === 401) return true
170
+ if (response.status >= 500 || response.status === 429) {
171
+ throw new ZboxApiError('probe workspace without a key', response.status, `http_${response.status}`)
172
+ }
173
+ return false
174
+ }
175
+
176
+ /** The DOT domain the proxy routes sandboxes by; the list is replaced whole, so every other domain is sent back. */
177
+ const ensureDomain = async (client: ZboxClient, workspace: ZboxWorkspace, serviceId: string, signal: AbortSignal): Promise<void> => {
178
+ const existing = workspace.domains.find((domain) => domain.domain === SANDBOX_HOST_DOMAIN)
179
+ if (existing?.form === 'DOT') return
180
+ if (existing !== undefined) {
181
+ throw namespaceError(
182
+ ZEROPS_SANDBOX_HOST_DOMAIN_FORM,
183
+ `Zerops sandbox host ${serviceId} routes ${SANDBOX_HOST_DOMAIN} in ${existing.form} form; the namespace proxy needs DOT`,
184
+ false,
185
+ )
186
+ }
187
+ await client.putDomains([...workspace.domains, { domain: SANDBOX_HOST_DOMAIN, form: 'DOT' }], signal)
188
+ }
189
+
190
+ /**
191
+ * Bring the namespace's sandbox host to what a dev environment needs: the `zbox` service, its key, its API subdomain,
192
+ * and the DOT domain the namespace proxy routes sandboxes by. Each step decides by reading back, so a reconcile
193
+ * converges a host any earlier attempt left half done and changes nothing on a complete one.
194
+ */
195
+ export const ensureSandboxHost = async (input: ZeropsSandboxHostInput): Promise<ZeropsNamespaceSandboxHost> => {
196
+ const { target, signal } = input
197
+ assertSandboxHostAllowed(input.namespaceId, target)
198
+ const projectId = target.projectId
199
+ if (projectId === undefined) throw new Error('Zerops namespace has no project id')
200
+ const found = await findSandboxHost(input.api, projectId, signal)
201
+ if (target.sandboxHost !== undefined && found?.id !== target.sandboxHost.serviceId) {
202
+ throw new Error('Checkpointed namespace sandbox host service identity changed')
203
+ }
204
+ const service = found ?? await createSandboxHost(input, projectId)
205
+ // Before the start: a service of another type that holds the name is never touched.
206
+ validateService(service, projectId, SANDBOX_HOST_SERVICE_TYPE, false)
207
+ if (found?.status !== undefined && NOT_STARTED.has(found.status)) {
208
+ await waitFor(input, (await input.api.startService({ serviceId: found.id, signal })).id, 'sandbox host start')
209
+ }
210
+ await ensureSubdomainAccess({
211
+ api: input.api,
212
+ serviceId: service.id,
213
+ label: 'Zerops namespace sandbox host',
214
+ consequence: 'Control cannot reach its API',
215
+ ...(input.sleep === undefined ? {} : { sleep: input.sleep }),
216
+ signal,
217
+ })
218
+ const apiOrigin = await readApiOrigin(input, service.id)
219
+ const client = createZboxClient({
220
+ baseUrl: apiOrigin,
221
+ apiKey: input.sandboxKey,
222
+ ...(input.zboxFetch === undefined ? {} : { fetch: input.zboxFetch }),
223
+ })
224
+ const reached = await reachWorkspace(input, client)
225
+ const rekeyed = reached === 'unauthorized'
226
+ let workspace = reached === 'unauthorized' ? await rekey(input, client, service.id) : reached
227
+ // A host whose API answers without a key is never recorded: one rekey, then a refusal.
228
+ if (!(await refusesWithoutKey(input, apiOrigin))) {
229
+ if (!rekeyed) workspace = await rekey(input, client, service.id)
230
+ if (!(await refusesWithoutKey(input, apiOrigin))) {
231
+ throw namespaceError(ZEROPS_SANDBOX_HOST_API_OPEN, `Zerops sandbox host ${service.id} answers its API without a key`, false)
232
+ }
233
+ }
234
+ await ensureDomain(client, workspace, service.id, signal)
235
+ return { serviceId: service.id, apiOrigin }
236
+ }
@@ -0,0 +1,113 @@
1
+ import type { ProviderNamespaceHost } from '@fabrika/provider-contract'
2
+ import { enableSubdomainAccessWhenHttp, readableContent, ZEROPS_SERVICE_NOT_HTTP, type ZeropsApi, ZeropsApiError } from '../api'
3
+ import { defaultSleep, type Sleeper } from '../collaborators'
4
+ import { ZEROPS_NAMESPACE_SUBDOMAIN_VARIABLE } from './constants'
5
+ import { namespaceError, ZEROPS_NAMESPACE_CANCELLED, ZEROPS_SUBDOMAIN_NOT_PUBLISHED } from './errors'
6
+
7
+ const POLL_INTERVAL_MS = 3000
8
+
9
+ /** The live enable finishes in under a second, but one run still read `false` once before flipping; ten reads is slack. */
10
+ const SUBDOMAIN_READBACK_ATTEMPTS = 10
11
+
12
+ /**
13
+ * One host per published HTTP port, out of the newline-separated URLs the platform writes.
14
+ *
15
+ * The form is `<hostname>-<hash>-<port>.<region>.zerops.app` (e.g. `proxy-2ec8-8080`). Read as URLs
16
+ * rather than split on `-`, so a hostname whose own first label ends in digits cannot be misread; a line
17
+ * that is not a URL, or whose first label carries no trailing port — the single portless line a proxy
18
+ * that has never deployed publishes — is skipped rather than guessed at.
19
+ */
20
+ export const parseZeropsSubdomainHosts = (value: string): ProviderNamespaceHost[] => {
21
+ const hosts: ProviderNamespaceHost[] = []
22
+ for (const line of value.split('\n')) {
23
+ const trimmed = line.trim()
24
+ if (trimmed === '') continue
25
+ let hostname: string
26
+ try {
27
+ hostname = new URL(trimmed).hostname
28
+ } catch {
29
+ continue
30
+ }
31
+ const port = /-(\d+)$/.exec(hostname.split('.')[0] ?? '')?.[1]
32
+ if (port === undefined) continue
33
+ hosts.push({ host: hostname, port: Number.parseInt(port, 10) })
34
+ }
35
+ return hosts.sort((left, right) => left.port - right.port)
36
+ }
37
+
38
+ /** The hosts a service publishes, off the platform-owned `zeropsSubdomain` variable; none while it names none. */
39
+ export const readSubdomainHosts = async (
40
+ api: Pick<ZeropsApi, 'listServiceEnv'>,
41
+ serviceId: string,
42
+ signal: AbortSignal,
43
+ ): Promise<ProviderNamespaceHost[]> => {
44
+ const variables = await api.listServiceEnv({ serviceId, signal })
45
+ const subdomains = readableContent(variables.find((variable) => variable.key === ZEROPS_NAMESPACE_SUBDOMAIN_VARIABLE))
46
+ return subdomains === undefined ? [] : parseZeropsSubdomainHosts(subdomains)
47
+ }
48
+
49
+ export interface SubdomainAccessInput {
50
+ readonly api: Pick<ZeropsApi, 'getService' | 'enableSubdomainAccess'>
51
+ readonly serviceId: string
52
+ /** Names the service in a refusal, e.g. `Zerops namespace proxy`. */
53
+ readonly label: string
54
+ /** What is missing when the subdomain stays off, e.g. `the namespace has no public entry point`. */
55
+ readonly consequence: string
56
+ readonly sleep?: Sleeper
57
+ readonly signal: AbortSignal
58
+ }
59
+
60
+ /**
61
+ * Publish a service on its `*.zerops.app` subdomain — the ONE thing the import document cannot do.
62
+ *
63
+ * `enableSubdomainAccess: true` is accepted by the import and then silently dropped, on a service the
64
+ * document CREATES as much as on one `override` leaves alone; a service imported with it reads back
65
+ * `subdomainAccess: false` for ever. The subdomain is established by
66
+ * `PUT /service-stack/{id}/enable-subdomain-access` and by nothing else, and that call needs a DEPLOYED
67
+ * HTTP port.
68
+ *
69
+ * It runs on RECONCILE too, so a subdomain someone turned off in the GUI comes back, and it either
70
+ * observes `subdomainAccess === true` or throws naming what is missing.
71
+ *
72
+ * The decision is the READ-BACK, never the call returning. On an already-published service the platform
73
+ * answers 2xx and then fails the process it handed back — live-verified — so a 2xx proves nothing.
74
+ *
75
+ * The HTTP ports lag the service's ACTIVE version, so `serviceStackIsNotHttp` is retried for a bounded
76
+ * window (`enableSubdomainAccessWhenHttp`) before it fails the namespace.
77
+ */
78
+ export const ensureSubdomainAccess = async (input: SubdomainAccessInput): Promise<void> => {
79
+ const { api, serviceId, signal } = input
80
+ const sleep = input.sleep ?? defaultSleep
81
+ const published = async (): Promise<boolean> => (await api.getService({ serviceId, signal })).subdomainAccess === true
82
+ if (await published()) {
83
+ return
84
+ }
85
+ try {
86
+ await enableSubdomainAccessWhenHttp({ api, serviceId, sleep, signal })
87
+ } catch (error) {
88
+ if (error instanceof ZeropsApiError && error.code === ZEROPS_SERVICE_NOT_HTTP) {
89
+ throw namespaceError(
90
+ ZEROPS_SERVICE_NOT_HTTP,
91
+ `${input.label} ${serviceId} cannot be published on a zerops.app subdomain: it still exposes no deployed HTTP port (${ZEROPS_SERVICE_NOT_HTTP}) minutes after its deploy`,
92
+ false,
93
+ )
94
+ }
95
+ throw error
96
+ }
97
+ for (let attempt = 0;; attempt += 1) {
98
+ if (signal.aborted) {
99
+ throw namespaceError(ZEROPS_NAMESPACE_CANCELLED, 'Zerops namespace provisioning was cancelled', true)
100
+ }
101
+ if (await published()) {
102
+ return
103
+ }
104
+ if (attempt >= SUBDOMAIN_READBACK_ATTEMPTS) {
105
+ throw namespaceError(
106
+ ZEROPS_SUBDOMAIN_NOT_PUBLISHED,
107
+ `${input.label} ${serviceId} accepted enable-subdomain-access but still reads subdomainAccess: false — ${input.consequence}`,
108
+ true,
109
+ )
110
+ }
111
+ await sleep(POLL_INTERVAL_MS, signal)
112
+ }
113
+ }
@@ -57,7 +57,7 @@ export const projectMarker = (namespace: ProviderDeploymentNamespace): string =>
57
57
  // Imports provision services only. The reserved upload-backed build selects the proxy setup.
58
58
  //
59
59
  // `enableSubdomainAccess` is a DECLARATION here and not a mechanism: the platform accepts it and drops it,
60
- // including on the service this document creates. `ensureSubdomainAccess` below is what establishes the
60
+ // including on the service this document creates. `ensureSubdomainAccess` (`subdomain.ts`) is what establishes the
61
61
  // subdomain, after the proxy's first deploy. Written anyway because it is what ADR-0022's
62
62
  // `assertOnlyPublicService` reads to prove no other service is claimed public.
63
63
  const proxyService = (publicAccess: ZeropsNamespacePublicAccess): ZeropsServiceSpec => ({
@@ -5,6 +5,7 @@ import type { ZeropsArtifactSourceDescriptor } from '../manifest'
5
5
  import type { ZeropsSourceRepository } from '../source'
6
6
  import type { ZeropsSourcePort } from '../source/port'
7
7
  import type { ZeropsSourceTarget } from '../types'
8
+ import type { ZboxFetch } from '../zbox'
8
9
 
9
10
  export type ZeropsNamespacePublicAccess = 'custom-domain' | 'zerops-subdomain'
10
11
 
@@ -60,9 +61,17 @@ export interface ZeropsNamespaceTarget {
60
61
  readonly proxyAppVersionId?: string
61
62
  /** The hosts the published proxy answers on, recorded once so a namespace read needs no platform call. */
62
63
  readonly proxyHosts?: readonly ProviderNamespaceHost[]
64
+ /** The namespace's dev sandbox host, recorded once provisioned; absent while no dev environment uses the namespace. */
65
+ readonly sandboxHost?: ZeropsNamespaceSandboxHost
63
66
  readonly ready?: boolean
64
67
  }
65
68
 
69
+ export interface ZeropsNamespaceSandboxHost {
70
+ readonly serviceId: string
71
+ /** The Box API origin: the service's public subdomain for `SANDBOX_HOST_API_PORT`. */
72
+ readonly apiOrigin: string
73
+ }
74
+
66
75
  export type ZeropsNamespacePolicy = Omit<ZeropsNamespaceTarget, 'proxySource'>
67
76
 
68
77
  export interface NormalizedZeropsNamespaceTarget extends ZeropsNamespaceTarget {
@@ -84,6 +93,8 @@ export interface ZeropsNamespaceOptions {
84
93
  /** The installation's own project, which no namespace may create into or adopt. Absent until `platform deploy` writes it. */
85
94
  readonly installationProjectId?: string
86
95
  readonly api: ZeropsApi
96
+ /** The transport of the sandbox host's Box API; absent, the global `fetch`. */
97
+ readonly zboxFetch?: ZboxFetch
87
98
  readonly sleep?: Sleeper
88
99
  }
89
100
 
@@ -45,6 +45,7 @@ const FIXED_FIELDS: { readonly [K in FixedField]: (target: ZeropsNamespaceTarget
45
45
  proxyBaselineSequence: (target) => target.proxyBaselineSequence,
46
46
  proxyAppVersionId: (target) => target.proxyAppVersionId,
47
47
  proxyHosts: (target) => target.proxyHosts,
48
+ sandboxHost: (target) => target.sandboxHost,
48
49
  ready: (target) => target.ready,
49
50
  }
50
51
 
package/src/provider.ts CHANGED
@@ -50,7 +50,6 @@ import {
50
50
  import {
51
51
  PLATFORM_TYPESCRIPT_VERSION,
52
52
  renderLockedExecutionDescriptor,
53
- type ZeropsDevExecution,
54
53
  zeropsJobProcesses,
55
54
  type ZeropsLockedExecution,
56
55
  zeropsStartMinRam,
@@ -96,8 +95,6 @@ export interface ZeropsDeployRun {
96
95
  readonly access?: ProviderApprovedAccess
97
96
  /** The run-scoped source-map destination Control minted; the build uploads to it. */
98
97
  readonly artifactUpload?: ProviderDeployInput['artifactUpload']
99
- /** Present for an environment of kind `dev`: the launcher starts instead of the serving entry, on one container. */
100
- readonly dev?: ZeropsDevExecution
101
98
  readonly dryRun: boolean
102
99
  readonly signal: AbortSignal
103
100
  readonly events: ProviderRunEvents
@@ -694,7 +691,6 @@ const withMinRam = (custom: ZeropsServiceAutoscaling, minRam: number): ZeropsSer
694
691
  */
695
692
  const raiseStartMemory = async (env: StepEnv): Promise<void> => {
696
693
  const { run, zerops, log, signal, dryRun } = env
697
- if (run.dev !== undefined) await pinOneContainer(env)
698
694
  const locked = lockedExecutionFor(run.artifact, run, dryRun)
699
695
  const minRam = locked === null ? null : zeropsStartMinRam(locked)
700
696
  const hostname = run.artifact.target.deployService
@@ -717,42 +713,6 @@ const raiseStartMemory = async (env: StepEnv): Promise<void> => {
717
713
  log(` minimum RAM of ${hostname}: ${before ?? 'the platform default'} → ${after} GB`)
718
714
  }
719
715
 
720
- /**
721
- * A dev environment runs on exactly one container: the launcher writes the files it syncs into that container, and a
722
- * second one would serve the bootstrap head. Sends the custom autoscaling whole with only the container counts changed,
723
- * and decides by reading it back.
724
- */
725
- const pinOneContainer = async (env: StepEnv): Promise<void> => {
726
- const { run, zerops, log, signal, dryRun } = env
727
- const hostname = run.artifact.target.deployService
728
- if (dryRun) {
729
- log(` [dry-run] would pin ${hostname} to one container`)
730
- return
731
- }
732
- assertRunning(signal)
733
- const service = await zerops.api.getService({ serviceId: run.target.serviceId, signal })
734
- const custom = service.customAutoscaling
735
- const horizontal = service.currentAutoscaling?.horizontal
736
- if (horizontal?.minContainerCount === 1 && horizontal.maxContainerCount === 1) {
737
- log(` ${hostname} runs on one container, unchanged`)
738
- return
739
- }
740
- if (custom === undefined) throw new Error(`zerops: ${hostname} did not report its autoscaling whole, so it cannot be pinned to one container`)
741
- const process = await zerops.api.configureCustomAutoscaling({
742
- serviceId: service.id,
743
- autoscaling: { ...custom, horizontal: { minContainerCount: 1, maxContainerCount: 1 } },
744
- signal,
745
- })
746
- if (process !== null) {
747
- await waitForProcess({ api: zerops.api, processId: process.id, sleep: zerops.sleep, signal, label: `the autoscaling change of ${hostname}` })
748
- }
749
- const after = (await zerops.api.getService({ serviceId: service.id, signal })).currentAutoscaling?.horizontal
750
- if (after?.minContainerCount !== 1 || after.maxContainerCount !== 1) {
751
- throw new Error(`zerops: ${hostname} reads back ${after?.maxContainerCount ?? 'no'} container(s) after it was pinned to one`)
752
- }
753
- log(` ${hostname} pinned to one container`)
754
- }
755
-
756
716
  /** What raising a minimum RAM calls; the deploy's collaborators, and the live platform-facts probe of the same path. */
757
717
  export interface MinRamRaise {
758
718
  zerops: Pick<ZeropsCollaborators, 'api' | 'sleep'>
@@ -34,17 +34,31 @@ export const zeropsProxyManifestCarrier = (descriptorContents: string, setup = '
34
34
  /** The build variable that marks a proxy source whose manifest parser knows `brand` (ADR-0066). */
35
35
  export const FABRIKA_PROXY_MANIFEST_BRAND = 'FABRIKA_PROXY_MANIFEST_BRAND'
36
36
 
37
- /**
38
- * Whether a pinned descriptor's proxy reads a manifest that carries the installation's client logo. An older parser
39
- * refuses the unknown key and fails the build, so a namespace kept on such a pin gets no logo and keeps the fabrika
40
- * mark until it is re-pinned (`--proxy-source=current`). Decided by the build section Zerops applies, as the carrier is.
41
- */
42
- export const zeropsProxyAcceptsBrand = (descriptorContents: string, setup = 'proxy'): boolean => {
37
+ /** The build variable that marks a proxy source whose manifest parser knows a dev sandbox entry's `audience` and `upstreamHost`. */
38
+ export const FABRIKA_PROXY_MANIFEST_SANDBOXES = 'FABRIKA_PROXY_MANIFEST_SANDBOXES'
39
+
40
+ /** Whether the build section Zerops applies to the descriptor's proxy setup declares `marker: "1"`, as the carrier is decided. */
41
+ const declaresMarker = (descriptorContents: string, marker: string, setup: string): boolean => {
43
42
  const parsed = parseZeropsDescriptor(descriptorContents)
44
43
  for (const entry of appliedZeropsSetups(parsed, selectZeropsDescriptorSetup(parsed, setup))) {
45
44
  const read = buildSectionSchema.safeParse(entry)
46
45
  if (!read.success) continue
47
- return read.data.build.envVariables?.[FABRIKA_PROXY_MANIFEST_BRAND] === '1'
46
+ return read.data.build.envVariables?.[marker] === '1'
48
47
  }
49
48
  return false
50
49
  }
50
+
51
+ /**
52
+ * Whether a pinned descriptor's proxy reads a manifest that carries the installation's client logo. An older parser
53
+ * refuses the unknown key and fails the build, so a namespace kept on such a pin gets no logo and keeps the fabrika
54
+ * mark until it is re-pinned (`--proxy-source=current`).
55
+ */
56
+ export const zeropsProxyAcceptsBrand = (descriptorContents: string, setup = 'proxy'): boolean =>
57
+ declaresMarker(descriptorContents, FABRIKA_PROXY_MANIFEST_BRAND, setup)
58
+
59
+ /**
60
+ * Whether a pinned descriptor's proxy reads dev sandbox entries. An older parser refuses their `audience` and
61
+ * `upstreamHost` and fails the build, so a namespace on such a pin serves no sandbox until it is re-pinned.
62
+ */
63
+ export const zeropsProxyAcceptsSandboxes = (descriptorContents: string, setup = 'proxy'): boolean =>
64
+ declaresMarker(descriptorContents, FABRIKA_PROXY_MANIFEST_SANDBOXES, setup)
@@ -0,0 +1,100 @@
1
+ // The base image of every dev workspace sandbox, built on the sandbox host from the Dockerfile context this package
2
+ // ships (`packages/provider-zerops/sandbox/`). Its name carries the hash of that context, so a release that changes the
3
+ // context builds a new base and every earlier one stays as it was.
4
+
5
+ import type { Sleeper } from '../collaborators'
6
+ import { type ZboxBase, type ZboxClient, ZboxOperationFailed } from '../zbox'
7
+
8
+ /** Every file of the build context; nothing else in the directory is sent. The scripts under `bin/` ship with each deploy. */
9
+ export const SANDBOX_BASE_CONTEXT_FILES = ['Dockerfile', 'init.sh'] as const
10
+
11
+ const CONTEXT_DIRECTORY = new URL('../../sandbox/', import.meta.url)
12
+
13
+ /** The first 12 hex of a sha256 over named files: the same bytes give the same version on every installation. */
14
+ export function contentVersion(files: Readonly<Record<string, Uint8Array>>): string {
15
+ const hash = new Bun.CryptoHasher('sha256')
16
+ for (const name of Object.keys(files).sort()) {
17
+ const content = files[name]
18
+ if (content === undefined) continue
19
+ hash.update(`${name}\u0000${content.byteLength}\u0000`)
20
+ hash.update(content)
21
+ }
22
+ return hash.digest('hex').slice(0, 12)
23
+ }
24
+
25
+ /** Reads `names` from the directory `relative` to the package's `sandbox/`. */
26
+ export async function readSandboxFiles(relative: string, names: readonly string[]): Promise<Record<string, Uint8Array>> {
27
+ const directory = new URL(relative, CONTEXT_DIRECTORY)
28
+ const files: Record<string, Uint8Array> = {}
29
+ for (const name of names) files[name] = await Bun.file(new URL(name, directory)).bytes()
30
+ return files
31
+ }
32
+
33
+ /** How long a base build may take. Measured: the package install and the flatten take well under a minute. */
34
+ const BASE_BUILD_DEADLINE_MS = 15 * 60_000
35
+
36
+ /** How often a base another call is building is read again. */
37
+ const BASE_POLL_MS = 3_000
38
+
39
+ export interface SandboxBaseContext {
40
+ /** `fabrika-dev-<first 12 hex of the context's sha256>`. */
41
+ readonly name: string
42
+ readonly files: Readonly<Record<string, Uint8Array>>
43
+ }
44
+
45
+ /** The name of the base a context builds: the same bytes name the same base on every installation. */
46
+ export function sandboxBaseName(files: Readonly<Record<string, Uint8Array>>): string {
47
+ return `fabrika-dev-${contentVersion(files)}`
48
+ }
49
+
50
+ /** The context this package ships. */
51
+ export async function readSandboxBaseContext(): Promise<SandboxBaseContext> {
52
+ const files = await readSandboxFiles('./', SANDBOX_BASE_CONTEXT_FILES)
53
+ return { name: sandboxBaseName(files), files }
54
+ }
55
+
56
+ /** The context as the plain tar archive `POST /base-build` takes. */
57
+ export async function sandboxBaseArchive(context: SandboxBaseContext): Promise<Uint8Array<ArrayBuffer>> {
58
+ return new Bun.Archive({ ...context.files }).bytes()
59
+ }
60
+
61
+ export interface EnsureSandboxBaseOptions {
62
+ readonly signal: AbortSignal
63
+ readonly sleep: Sleeper
64
+ }
65
+
66
+ const failedBase = (name: string, code: string | null): Error =>
67
+ new Error(
68
+ `zerops: the dev sandbox base \`${name}\` failed to build on the sandbox host${code === null ? '' : ` (${code})`}; `
69
+ + 'delete it on the sandbox host, then create the sandbox again',
70
+ )
71
+
72
+ /**
73
+ * The digest of the context's base on the sandbox host: the one it holds READY, or one this call builds. A base that
74
+ * FAILED is refused rather than rebuilt over, so the failure is seen once instead of retried on every workspace.
75
+ */
76
+ export async function ensureSandboxBase(client: ZboxClient, context: SandboxBaseContext, options: EnsureSandboxBaseOptions): Promise<string> {
77
+ const deadline = Date.now() + BASE_BUILD_DEADLINE_MS
78
+ const named = async (): Promise<ZboxBase | null> =>
79
+ (await client.listBases(options.signal)).find((base) => base.name === context.name && base.status !== 'DELETED') ?? null
80
+ let base = await named()
81
+ if (base === null) {
82
+ const started = await client.buildBase({ context: await sandboxBaseArchive(context), name: context.name }, options.signal)
83
+ try {
84
+ await client.awaitOperation(started, { signal: options.signal, deadlineMs: BASE_BUILD_DEADLINE_MS })
85
+ } catch (error) {
86
+ if (error instanceof ZboxOperationFailed) throw failedBase(context.name, error.code)
87
+ throw error
88
+ }
89
+ base = await named()
90
+ }
91
+ while (base !== null && (base.status === 'PULLING' || base.status === 'FLATTENING')) {
92
+ options.signal.throwIfAborted()
93
+ if (Date.now() > deadline) throw new Error(`zerops: the dev sandbox base \`${context.name}\` did not become ready in time`)
94
+ await options.sleep(BASE_POLL_MS, options.signal)
95
+ base = await named()
96
+ }
97
+ if (base === null) throw new Error(`zerops: the sandbox host does not list the dev sandbox base \`${context.name}\` it built`)
98
+ if (base.status === 'FAILED') throw failedBase(context.name, null)
99
+ return base.digest
100
+ }