@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
@@ -0,0 +1,206 @@
1
+ // What a dev workspace sandbox runs, derived from the application's artifact: the refusals of what a sandbox cannot
2
+ // give an application, the launcher's environment and configuration, and the build script. PURE — no network.
3
+
4
+ import { contractRecipe } from '@fabrika/app/build'
5
+ import { DEV_LAUNCHER_CONFIG_FILE, type DevLauncherConfig, FABRIKA_CONTRACT_DIGEST } from '@fabrika/auth-core'
6
+ import type { JsonValue, ProviderManagedEnvironment } from '@fabrika/provider-contract'
7
+ import { parseZeropsDescriptor, selectZeropsDescriptorSetup } from '../descriptor'
8
+ import { lockedAuthoredBuild, ZEROPS_APPLICATION_PORT, type ZeropsContractRun } from '../execution'
9
+ import { isObjectStorageType } from '../exposure'
10
+ import { assertAuthoredManagedDocument } from '../managed-env'
11
+ import { applicationDatabaseOf, type FabrikaManifest } from '../manifest'
12
+ import { SANDBOX_APP_ROOT, SANDBOX_DATABASE_CONNECTIONS, SANDBOX_DATABASE_URL, SANDBOX_STATE_DIR } from './constants'
13
+
14
+ const SANDBOX = 'a dev environment runs in workspace sandboxes'
15
+
16
+ const isMapping = (value: JsonValue | undefined): value is { readonly [key: string]: JsonValue } =>
17
+ typeof value === 'object' && value !== null && !Array.isArray(value)
18
+
19
+ /** Refuse what a sandbox cannot give an application, one line each: object storage, the ClamAV scan, runtime packages. */
20
+ export function assertSandboxArtifact(
21
+ manifest: FabrikaManifest,
22
+ contract: Pick<ZeropsContractRun, 'scan'> | undefined = manifest.target.contract,
23
+ ): void {
24
+ const storage = manifest.target.importDocument.services.find((service) =>
25
+ typeof service['type'] === 'string' && isObjectStorageType(service['type'])
26
+ )
27
+ if (storage !== undefined) {
28
+ throw new Error(`zerops: ${SANDBOX}, which have no object storage; remove \`${String(storage['hostname'])}\` from the dev environment's config`)
29
+ }
30
+ if (contract?.scan === true) {
31
+ throw new Error(`zerops: ${SANDBOX}, which have no ClamAV scan; the contract scans uploads (scan: true)`)
32
+ }
33
+ const packages = manifest.target.runtimePackages ?? []
34
+ if (packages.length > 0) {
35
+ throw new Error(
36
+ `zerops: ${SANDBOX}, which install no runtime package; remove runtimePackages (${packages.join(', ')}) from the dev environment's config`,
37
+ )
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Replaces each value of `values` long enough to be a credential in `text`, longest first: what the sandbox prints is
43
+ * application output, which may echo one. The launcher masks its own log the same way.
44
+ */
45
+ export function maskValues(text: string, values: readonly string[]): string {
46
+ let masked = text
47
+ for (const value of [...new Set(values)].filter((value) => value.length >= 8).sort((left, right) => right.length - left.length)) {
48
+ masked = masked.replaceAll(value, '[redacted]')
49
+ }
50
+ return masked
51
+ }
52
+
53
+ /** Refuse a handed variable or secret whose value holds a `${…}` reference, naming it and never its value. */
54
+ export function assertNoSandboxReferences(kind: 'variable' | 'secret', values: Readonly<Record<string, string>>): void {
55
+ for (const [name, value] of Object.entries(values)) {
56
+ if (value.includes('${')) throw new Error(`zerops: ${SANDBOX}, which resolve no \`\${…}\` reference; the ${kind} \`${name}\` holds one`)
57
+ }
58
+ }
59
+
60
+ export interface SandboxEnvironmentInput {
61
+ readonly artifact: FabrikaManifest
62
+ readonly secrets: Readonly<Record<string, string>>
63
+ readonly managed: ProviderManagedEnvironment
64
+ readonly contractDigest: string
65
+ }
66
+
67
+ /**
68
+ * The launcher's environment, as a Zerops deploy composes a service's: the secrets (on Zerops, sensitive service
69
+ * variables), the managed values Control handed, then the literals the generated run section carries. A declared variable
70
+ * only fills the import document, which a sandbox has none of. The local superuser stands in for the database service's,
71
+ * as the provisioning credential of the application's role family (ADR-0017).
72
+ */
73
+ export function sandboxEnvironment(input: SandboxEnvironmentInput): Record<string, string> {
74
+ assertNoSandboxReferences('secret', input.secrets)
75
+ const environment: Record<string, string> = { ...input.secrets }
76
+ for (const [name, { value }] of Object.entries(input.managed)) {
77
+ if (value !== null) environment[name] = value
78
+ }
79
+ environment['PORT'] = String(ZEROPS_APPLICATION_PORT)
80
+ environment[FABRIKA_CONTRACT_DIGEST] = input.contractDigest
81
+ if (applicationDatabaseOf(input.artifact) !== null) {
82
+ environment['FABRIKA_APP_DATABASE_URL'] = SANDBOX_DATABASE_URL
83
+ environment['FABRIKA_APP_DATABASE_CONNECTIONS'] = String(SANDBOX_DATABASE_CONNECTIONS)
84
+ }
85
+ return environment
86
+ }
87
+
88
+ const VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
89
+
90
+ /** The env file the base image's launcher script sources with `set -a`: one single-quoted assignment per variable. */
91
+ export function renderSandboxEnvFile(environment: Readonly<Record<string, string>>): string {
92
+ return Object.entries(environment).map(([name, value]) => {
93
+ if (!VARIABLE_NAME.test(name)) throw new Error(`zerops: \`${name}\` is not a variable name a shell can assign`)
94
+ if (value.includes('\u0000')) throw new Error(`zerops: the value of \`${name}\` holds a NUL byte`)
95
+ return `${name}='${value.replaceAll("'", "'\\''")}'\n`
96
+ }).join('')
97
+ }
98
+
99
+ /** The authored SPA commands of the artifact's selected setup: the only part of the authored build that survives. */
100
+ export function authoredSpaCommands(artifact: FabrikaManifest): string[] {
101
+ const parsed = parseZeropsDescriptor(artifact.target.sourceDescriptor.contents)
102
+ assertAuthoredManagedDocument(parsed.document)
103
+ const selected = selectZeropsDescriptorSetup(parsed, artifact.target.zeropsSetup)
104
+ const entries = parsed.document['zerops']
105
+ const entry = Array.isArray(entries) ? entries.find((candidate) => isMapping(candidate) && candidate['setup'] === selected) : undefined
106
+ if (!isMapping(entry)) throw new Error('zerops: descriptor requires setup entries')
107
+ return lockedAuthoredBuild(entry, selected).commands
108
+ }
109
+
110
+ export interface SandboxRecipeInput {
111
+ readonly appId: string
112
+ readonly checkRelease: string
113
+ readonly contract: ZeropsContractRun
114
+ }
115
+
116
+ /** `@fabrika/app/build`'s recipe in a sandbox: built and run in place, with no database at build, as on Zerops. */
117
+ export const sandboxRecipe = (input: SandboxRecipeInput) =>
118
+ contractRecipe({
119
+ appId: input.appId,
120
+ checkRelease: input.checkRelease,
121
+ sourceRoot: SANDBOX_APP_ROOT,
122
+ runtimeRoot: SANDBOX_APP_ROOT,
123
+ database: false,
124
+ sourceMaps: false,
125
+ jobs: input.contract.jobs,
126
+ files: input.contract.files === true,
127
+ scan: false,
128
+ })
129
+
130
+ /** What the dev launcher reads (`DEV_LAUNCHER_CONFIG_FILE`), written after the build's checks passed. */
131
+ export function sandboxLauncherConfig(
132
+ input: SandboxRecipeInput & { readonly head: string; readonly spaBuild: readonly string[] },
133
+ ): DevLauncherConfig {
134
+ if (!/^[0-9a-f]{40}$/.test(input.head)) throw new Error('zerops: a dev environment builds an exact commit')
135
+ const recipe = sandboxRecipe(input)
136
+ return {
137
+ format: 1,
138
+ appId: input.appId,
139
+ head: input.head,
140
+ port: ZEROPS_APPLICATION_PORT,
141
+ healthPath: input.contract.readinessPath,
142
+ serve: recipe.serve,
143
+ migrate: recipe.migrate,
144
+ spaBuild: input.spaBuild,
145
+ checks: recipe.checks,
146
+ }
147
+ }
148
+
149
+ export const SANDBOX_LAUNCHER_CONFIG_PATH = `${SANDBOX_APP_ROOT}/${DEV_LAUNCHER_CONFIG_FILE}`
150
+
151
+ const STEP_DIRECTORY = `${SANDBOX_STATE_DIR}/build`
152
+ const STEP_END = 'FABRIKA_BUILD_STEP_EOF'
153
+ const FILE_END = 'FABRIKA_BUILD_FILE_EOF'
154
+ const GENERATED_PATH = /^[A-Za-z0-9_][A-Za-z0-9._/-]*$/
155
+
156
+ const heredoc = (target: string, lines: readonly string[], end: string): string[] => {
157
+ if (lines.includes(end)) throw new Error('zerops: a build step holds the line that ends its here-document')
158
+ return [`cat > ${target} <<'${end}'`, ...lines, end]
159
+ }
160
+
161
+ const sha256 = (text: string): string => new Bun.CryptoHasher('sha256').update(text).digest('hex')
162
+
163
+ /** Writes `lines` to `target` through a quoted here-document, then checks the file holds exactly them. */
164
+ const verifiedHeredoc = (target: string, lines: readonly string[], end: string): string[] => [
165
+ ...heredoc(target, lines, end),
166
+ `echo '${sha256(`${lines.join('\n')}\n`)} ${target}' | sha256sum -c -s`,
167
+ ]
168
+
169
+ /**
170
+ * The generated part of the build, run as root: it writes each step to its own file (the authored SPA commands, then
171
+ * the recipe's steps), checks each was written whole, and hands over to the uploaded runner, which runs them as the
172
+ * unprivileged build user. Nothing here holds a credential.
173
+ */
174
+ export function renderSandboxBuildScript(authoredSpa: readonly string[], recipe: ReturnType<typeof sandboxRecipe>, runner: string): string {
175
+ const steps = [...authoredSpa.map((run) => ({ run })), ...recipe.build]
176
+ const lines = [
177
+ '#!/bin/sh',
178
+ '# Generated by the dev sandbox deploy.',
179
+ 'set -eu',
180
+ 'exec 2>&1',
181
+ 'umask 022',
182
+ `rm -rf ${STEP_DIRECTORY}`,
183
+ `mkdir -p ${STEP_DIRECTORY}`,
184
+ ]
185
+ for (const [index, step] of steps.entries()) {
186
+ const file = `${STEP_DIRECTORY}/${index + 1}.sh`
187
+ if ('run' in step) {
188
+ lines.push(...verifiedHeredoc(file, step.run.split('\n'), STEP_END))
189
+ } else {
190
+ if (!GENERATED_PATH.test(step.write) || step.write.includes('..')) throw new Error('zerops: a generated file path is not a plain relative path')
191
+ const slash = step.write.lastIndexOf('/')
192
+ // The file's lines sit inside the step's here-document too, so neither delimiter may appear among them.
193
+ if (step.lines.includes(STEP_END)) throw new Error('zerops: a build step holds the line that ends its here-document')
194
+ const write = [...(slash < 0 ? [] : [`mkdir -p ${step.write.slice(0, slash)}`]), ...heredoc(step.write, step.lines, FILE_END)]
195
+ lines.push(...verifiedHeredoc(file, write, STEP_END))
196
+ }
197
+ }
198
+ lines.push(`exec /bin/sh ${runner} ${steps.length}`)
199
+ return `${lines.join('\n')}\n`
200
+ }
201
+
202
+ /** One line per build step, as the run log lists them before the build starts. */
203
+ export function sandboxBuildStepLabels(authoredSpa: readonly string[], recipe: ReturnType<typeof sandboxRecipe>): string[] {
204
+ const steps = [...authoredSpa.map((run) => ({ run })), ...recipe.build]
205
+ return steps.map((step, index) => `${index + 1}: ${'run' in step ? (step.run.split('\n')[0] ?? '') : `write ${step.write}`}`)
206
+ }
@@ -0,0 +1,204 @@
1
+ // The per-workspace sandboxes of a `dev` environment outside a run (`ProviderDevSandboxes`): one Box sandbox per MCP
2
+ // workspace on the namespace's sandbox host, found again by its name, so every call converges instead of duplicating.
3
+
4
+ import {
5
+ PROVIDER_DEV_CAPACITY,
6
+ PROVIDER_DEV_HOST_PENDING,
7
+ type ProviderDevSandbox,
8
+ type ProviderDevSandboxes,
9
+ type ProviderEnvironment,
10
+ ProviderNamespaceError,
11
+ } from '@fabrika/provider-contract'
12
+ import type { Sleeper } from '../collaborators'
13
+ import { ZEROPS_APPLICATION_PORT } from '../execution'
14
+ import { sandboxUpstreamHost } from '../sandbox-host'
15
+ import { isZboxNotFound, isZboxWorkspaceFull, type ZboxClient, ZboxOperationFailed, type ZboxSandbox } from '../zbox'
16
+ import { ensureSandboxBase, readSandboxBaseContext, type SandboxBaseContext } from './base-image'
17
+ import { SANDBOX_CPUS, SANDBOX_DISK_BYTES, SANDBOX_INIT_COMMAND, SANDBOX_MEMORY_BYTES } from './constants'
18
+
19
+ /** A workspace id is a UUIDv7, so the sandbox name it makes is a fixed shape. */
20
+ const WORKSPACE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
21
+
22
+ /** How long a sandbox in a transition (creating, parking, waking) is waited for. Measured: each takes under 2 s. */
23
+ const TRANSITION_DEADLINE_MS = 120_000
24
+ const TRANSITION_POLL_MS = 1_000
25
+
26
+ const TRANSITIONS: ReadonlySet<ZboxSandbox['status']> = new Set(['CREATING', 'PARKING', 'WAKING', 'FORKING', 'RESTORING'])
27
+
28
+ /** A sandbox that will not run again. Box archives one past its absolute TTL. */
29
+ const ENDED: ReadonlySet<ZboxSandbox['status']> = new Set(['FAILED', 'TERMINATED', 'ARCHIVED'])
30
+
31
+ /** The sandbox name of a workspace: what `ensure` finds it again by. */
32
+ export function sandboxName(workspaceId: string): string {
33
+ if (!WORKSPACE_ID.test(workspaceId)) throw new Error('zerops: a workspace id is a lower-case UUID')
34
+ return `fabrika-${workspaceId}`
35
+ }
36
+
37
+ /** A deterministic `Idempotency-Key` in UUID form: the same delete after a lost answer gets Box's first answer. */
38
+ export function sandboxIdempotencyKey(...parts: readonly string[]): string {
39
+ const hex = new Bun.CryptoHasher('sha256').update(['fabrika-dev-sandbox', ...parts].join('\u0000')).digest('hex')
40
+ const variant = ((Number.parseInt(hex.slice(16, 17), 16) & 0x3) | 0x8).toString(16)
41
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`
42
+ }
43
+
44
+ /** A full sandbox host is the operator's to relieve, so it surfaces as the contract's capacity code. */
45
+ export async function withSandboxCapacity<T>(run: () => Promise<T>): Promise<T> {
46
+ try {
47
+ return await run()
48
+ } catch (error) {
49
+ if (isZboxWorkspaceFull(error) || (error instanceof ZboxOperationFailed && error.code === 'workspaceFull')) {
50
+ throw new ProviderNamespaceError(
51
+ "zerops: the namespace's sandbox host has no room for another running sandbox; park or remove another workspace's sandbox and retry",
52
+ PROVIDER_DEV_CAPACITY,
53
+ true,
54
+ )
55
+ }
56
+ throw error
57
+ }
58
+ }
59
+
60
+ export interface ZeropsDevSandboxesOptions {
61
+ /** The Box client of the environment's namespace sandbox host, authenticated with `sandboxKey`. */
62
+ /** Null while the namespace has no sandbox host yet. */
63
+ readonly client: (environment: ProviderEnvironment, sandboxKey: string) => ZboxClient | null
64
+ /** Refuses an environment whose placement cannot serve a workspace sandbox; see `ProviderDevSandboxes.admit`. */
65
+ readonly admit: (environment: ProviderEnvironment) => void
66
+ readonly sleep: Sleeper
67
+ /** Where `ensure` says it replaced a dead sandbox: the seam has no run log outside a run. */
68
+ readonly log: (line: string) => void
69
+ /** The base image's build context; the one this package ships unless a test passes another. */
70
+ readonly baseContext?: () => Promise<SandboxBaseContext>
71
+ }
72
+
73
+ const assertDevEnvironment = (environment: ProviderEnvironment): void => {
74
+ if (environment.kind !== 'dev') throw new Error('zerops: only a dev environment has workspace sandboxes')
75
+ }
76
+
77
+ /** Wait out a transition; answers the sandbox in a settled state. */
78
+ export async function settledSandbox(client: ZboxClient, sandbox: ZboxSandbox, sleep: Sleeper, signal: AbortSignal): Promise<ZboxSandbox> {
79
+ const deadline = Date.now() + TRANSITION_DEADLINE_MS
80
+ let current = sandbox
81
+ while (TRANSITIONS.has(current.status)) {
82
+ signal.throwIfAborted()
83
+ if (Date.now() > deadline) throw new Error(`zerops: sandbox ${current.id} stayed ${current.status}`)
84
+ await sleep(TRANSITION_POLL_MS, signal)
85
+ current = await client.getSandbox(current.id, signal)
86
+ }
87
+ return current
88
+ }
89
+
90
+ /** The sandbox running: a parked one is woken, a transition waited out. */
91
+ export async function runningSandbox(client: ZboxClient, sandboxId: string, sleep: Sleeper, signal: AbortSignal): Promise<ZboxSandbox> {
92
+ let sandbox = await settledSandbox(client, await existingSandbox(client, sandboxId, signal), sleep, signal)
93
+ if (sandbox.status === 'PARKED') {
94
+ await withSandboxCapacity(() => client.wake(sandbox.id, signal))
95
+ sandbox = await settledSandbox(client, await client.getSandbox(sandbox.id, signal), sleep, signal)
96
+ }
97
+ if (sandbox.status !== 'RUNNING') throw new Error(`zerops: sandbox ${sandbox.id} is ${sandbox.status} and cannot run`)
98
+ return sandbox
99
+ }
100
+
101
+ const existingSandbox = async (client: ZboxClient, sandboxId: string, signal: AbortSignal): Promise<ZboxSandbox> => {
102
+ try {
103
+ return await client.getSandbox(sandboxId, signal)
104
+ } catch (error) {
105
+ if (isZboxNotFound(error)) throw new Error(`zerops: the workspace's sandbox ${sandboxId} no longer exists; bind the workspace again`)
106
+ throw error
107
+ }
108
+ }
109
+
110
+ const sandboxOf = (sandbox: ZboxSandbox): ProviderDevSandbox => ({
111
+ sandboxId: sandbox.id,
112
+ baseDigest: sandbox.baseDigest,
113
+ upstreamHost: sandboxUpstreamHost(sandbox.id),
114
+ })
115
+
116
+ export function createZeropsDevSandboxes(options: ZeropsDevSandboxesOptions): ProviderDevSandboxes {
117
+ const baseContext = options.baseContext ?? readSandboxBaseContext
118
+
119
+ const create = async (client: ZboxClient, workspaceId: string, signal: AbortSignal): Promise<ZboxSandbox> => {
120
+ const baseDigest = await ensureSandboxBase(client, await baseContext(), { signal, sleep: options.sleep })
121
+ const { sandbox } = await withSandboxCapacity(() =>
122
+ client.createSandbox({
123
+ name: sandboxName(workspaceId),
124
+ baseDigest,
125
+ cpus: SANDBOX_CPUS,
126
+ memoryBytes: SANDBOX_MEMORY_BYTES,
127
+ diskBytes: SANDBOX_DISK_BYTES,
128
+ networkMode: 'INTERNET',
129
+ launch: { entrypoint: SANDBOX_INIT_COMMAND.slice(0, 1), cmd: SANDBOX_INIT_COMMAND.slice(1) },
130
+ ports: [{ port: ZEROPS_APPLICATION_PORT, access: 'PROJECT', wakeOnRequest: true }],
131
+ // Fresh per call: a key that repeats after a removal could replay Box's answer naming the removed sandbox. A lost
132
+ // answer is found again by name, which a live sandbox holds alone.
133
+ idempotencyKey: crypto.randomUUID(),
134
+ }, signal)
135
+ )
136
+ return sandbox
137
+ }
138
+
139
+ const hostClient = (environment: ProviderEnvironment, sandboxKey: string): ZboxClient => {
140
+ const client = options.client(environment, sandboxKey)
141
+ if (client === null) {
142
+ throw new ProviderNamespaceError(
143
+ "zerops: the namespace's sandbox host is not created yet; a namespace republish creates it",
144
+ PROVIDER_DEV_HOST_PENDING,
145
+ true,
146
+ )
147
+ }
148
+ return client
149
+ }
150
+
151
+ return {
152
+ admit: (input) => {
153
+ assertDevEnvironment(input.environment)
154
+ options.admit(input.environment)
155
+ },
156
+ ensure: async (input) => {
157
+ assertDevEnvironment(input.environment)
158
+ options.admit(input.environment)
159
+ const client = hostClient(input.environment, input.sandboxKey)
160
+ const found = await client.findSandboxByName(sandboxName(input.workspaceId), input.signal)
161
+ let replaced: string | null = null
162
+ if (found !== null) {
163
+ const sandbox = await settledSandbox(client, found, options.sleep, input.signal)
164
+ if (!ENDED.has(sandbox.status)) {
165
+ // A sandbox on an older base is kept: a new one would change its id, which the published proxy entry names.
166
+ return sandboxOf(await runningSandbox(client, sandbox.id, options.sleep, input.signal))
167
+ }
168
+ await client.deleteSandbox(sandbox.id, sandboxIdempotencyKey('delete', sandbox.id), input.signal)
169
+ replaced = sandbox.id
170
+ }
171
+ const created = await create(client, input.workspaceId, input.signal)
172
+ if (replaced !== null) {
173
+ options.log(
174
+ `zerops: workspace ${input.workspaceId}'s sandbox ${replaced} had ended; it is replaced by sandbox ${created.id}, with an empty database`,
175
+ )
176
+ }
177
+ return sandboxOf(await runningSandbox(client, created.id, options.sleep, input.signal))
178
+ },
179
+ park: async (input) => {
180
+ assertDevEnvironment(input.environment)
181
+ const client = hostClient(input.environment, input.sandboxKey)
182
+ const sandbox = await settledSandbox(client, await existingSandbox(client, input.sandbox.sandboxId, input.signal), options.sleep, input.signal)
183
+ if (sandbox.status === 'PARKED') return
184
+ if (sandbox.status !== 'RUNNING') throw new Error(`zerops: sandbox ${sandbox.id} is ${sandbox.status} and cannot be parked`)
185
+ await client.park(sandbox.id, { memory: true }, input.signal)
186
+ },
187
+ wake: async (input) => {
188
+ assertDevEnvironment(input.environment)
189
+ const client = hostClient(input.environment, input.sandboxKey)
190
+ await runningSandbox(client, input.sandbox.sandboxId, options.sleep, input.signal)
191
+ },
192
+ remove: async (input) => {
193
+ assertDevEnvironment(input.environment)
194
+ const client = options.client(input.environment, input.sandboxKey)
195
+ // No sandbox host, so no sandbox of the workspace can exist.
196
+ if (client === null) return
197
+ const recorded = input.sandbox?.sandboxId
198
+ if (recorded !== undefined) await client.deleteSandbox(recorded, sandboxIdempotencyKey('delete', recorded), input.signal)
199
+ // An `ensure` that raced the removal may have created another sandbox under the workspace's name.
200
+ const named = (await client.findSandboxByName(sandboxName(input.workspaceId), input.signal))?.id
201
+ if (named !== undefined && named !== recorded) await client.deleteSandbox(named, sandboxIdempotencyKey('delete', named), input.signal)
202
+ },
203
+ }
204
+ }
@@ -0,0 +1,26 @@
1
+ // The helper scripts every deploy uploads into a sandbox (`packages/provider-zerops/sandbox/bin/`), under a directory
2
+ // named by their hash: a fix reaches every existing sandbox with its next deploy, without a new base image.
3
+
4
+ import { contentVersion, readSandboxFiles } from './base-image'
5
+ import { SANDBOX_BIN_DIR } from './constants'
6
+
7
+ export const SANDBOX_SCRIPT_FILES = ['postgres-auth.sh', 'reset.sh', 'run-build.sh', 'run-launcher.sh', 'start-launcher.sh', 'stop.sh'] as const
8
+
9
+ export type SandboxScript = (typeof SANDBOX_SCRIPT_FILES)[number]
10
+
11
+ export interface SandboxScripts {
12
+ readonly version: string
13
+ readonly files: Readonly<Record<string, Uint8Array>>
14
+ /** The absolute path of a script of this version inside a sandbox. */
15
+ path(script: SandboxScript): string
16
+ }
17
+
18
+ export function sandboxScripts(files: Readonly<Record<string, Uint8Array>>): SandboxScripts {
19
+ const version = contentVersion(files)
20
+ return { version, files, path: (script) => `${SANDBOX_BIN_DIR}/${version}/${script}` }
21
+ }
22
+
23
+ /** The scripts this package ships. */
24
+ export async function readSandboxScripts(): Promise<SandboxScripts> {
25
+ return sandboxScripts(await readSandboxFiles('./bin/', SANDBOX_SCRIPT_FILES))
26
+ }
@@ -0,0 +1,28 @@
1
+ import { ZEROPS_APPLICATION_PORT } from './execution'
2
+
3
+ /** The hostname of a namespace's dev sandbox host: a Zerops Box Workspace, which runs one sandbox per MCP workspace. */
4
+ export const SANDBOX_HOST_HOSTNAME = 'zbox'
5
+
6
+ /** The type an import declares. */
7
+ export const SANDBOX_HOST_TYPE = 'zbox@1'
8
+
9
+ /** The type the platform reads back for it (measured live): the OS-qualified form of `SANDBOX_HOST_TYPE`. */
10
+ export const SANDBOX_HOST_SERVICE_TYPE = 'ubuntu/zbox@1'
11
+
12
+ /** The Box API port. Control reaches it over the service's public subdomain, with the key Fabrika generated for it. */
13
+ export const SANDBOX_HOST_API_PORT = 8080
14
+
15
+ /** The Box router port: the namespace proxy reaches a sandbox's project-only application port here, by Host. */
16
+ export const SANDBOX_HOST_ROUTER_PORT = 8081
17
+
18
+ /** The service variable Box reads its API key from; Fabrika writes it sensitive and never reads it back. */
19
+ export const SANDBOX_HOST_KEY_VARIABLE = 'ZBOX_WORKSPACE_API_KEY'
20
+
21
+ /** The dial address of the Box router from the namespace proxy. */
22
+ export const SANDBOX_UPSTREAM = `${SANDBOX_HOST_HOSTNAME}:${SANDBOX_HOST_ROUTER_PORT}`
23
+
24
+ /** The Host the namespace proxy sends the Box router to reach a sandbox's application port: the bare form, no domain. */
25
+ export function sandboxUpstreamHost(sandboxId: string): string {
26
+ if (!/^[a-z0-9]{1,32}$/.test(sandboxId)) throw new Error('zerops: a sandbox id is lower-case letters and digits')
27
+ return `${ZEROPS_APPLICATION_PORT}-${sandboxId}`
28
+ }
@@ -38,6 +38,11 @@ export interface ZeropsSourceUploadInput {
38
38
  readonly archive: ZeropsSourceArchive
39
39
  /** A credential in transit: never logged, persisted, or returned in an error. */
40
40
  readonly uploadUrl: string
41
+ /**
42
+ * Present for a dev sandbox: `uploadUrl` is the sandbox host's file endpoint for one sandbox, and the PUT carries this
43
+ * bearer. A credential in transit, like `uploadUrl`.
44
+ */
45
+ readonly uploadBearer?: string
41
46
  readonly signal: AbortSignal
42
47
  }
43
48