@fabrika/provider-cloudflare 0.9.0-dev.1 → 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 (51) hide show
  1. package/package.json +17 -15
  2. package/src/authoring.ts +56 -6
  3. package/src/bounds.ts +145 -4
  4. package/src/cli-args.ts +2 -2
  5. package/src/cli.ts +14 -0
  6. package/src/command.ts +29 -4
  7. package/src/contract-support.ts +235 -0
  8. package/src/control.ts +55 -118
  9. package/src/deploy-order.ts +35 -0
  10. package/src/index.ts +19 -3
  11. package/src/installation/init.ts +11 -18
  12. package/src/installation/installation.ts +2 -4
  13. package/src/installation/scaffold.ts +29 -2
  14. package/src/installation/templates/README.md +30 -12
  15. package/src/installation/templates/platform.yml +12 -5
  16. package/src/managed-secrets.ts +61 -0
  17. package/src/plan.ts +13 -3
  18. package/src/provider.ts +467 -64
  19. package/src/proxy-worker.ts +40 -16
  20. package/src/proxy.ts +48 -16
  21. package/src/runner-protocol.ts +35 -2
  22. package/src/spa-assets.ts +176 -0
  23. package/types/src/assets.d.ts +8 -0
  24. package/types/src/authoring.d.ts +39 -0
  25. package/types/src/bounds.d.ts +84 -0
  26. package/types/src/checkout.d.ts +7 -0
  27. package/types/src/cli-args.d.ts +25 -0
  28. package/types/src/cli.d.ts +8 -0
  29. package/types/src/codec.d.ts +8 -0
  30. package/types/src/collaborators.d.ts +52 -0
  31. package/types/src/command.d.ts +54 -0
  32. package/types/src/config-schema.d.ts +9 -0
  33. package/types/src/contract-support.d.ts +80 -0
  34. package/types/src/control.d.ts +503 -0
  35. package/types/src/deploy-order.d.ts +8 -0
  36. package/types/src/index.d.ts +18 -0
  37. package/types/src/installation/cloudflare.d.ts +40 -0
  38. package/types/src/installation/envfile.d.ts +39 -0
  39. package/types/src/installation/index.d.ts +2 -0
  40. package/types/src/installation/init-options.d.ts +59 -0
  41. package/types/src/installation/init.d.ts +114 -0
  42. package/types/src/installation/installation.d.ts +2 -0
  43. package/types/src/installation/scaffold.d.ts +39 -0
  44. package/types/src/managed-secrets.d.ts +19 -0
  45. package/types/src/plan.d.ts +21 -0
  46. package/types/src/provider.d.ts +98 -0
  47. package/types/src/proxy-worker.d.ts +15 -0
  48. package/types/src/proxy.d.ts +72 -0
  49. package/types/src/runner-protocol.d.ts +142 -0
  50. package/types/src/schema.d.ts +17 -0
  51. package/types/src/spa-assets.d.ts +28 -0
package/src/provider.ts CHANGED
@@ -1,22 +1,36 @@
1
+ import { CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_APPLICATION_CLASS, CLOUDFLARE_FILES_BINDING, GENERATED_ENTRY_FILE } from '@fabrika/app/build'
1
2
  import {
2
3
  type AppEnvironment,
3
4
  appEnvironmentId,
5
+ type ApplicationObjects,
4
6
  type AppSchema,
5
7
  connectVariables,
6
8
  type ContractArtifact,
7
9
  contractDigest,
10
+ DEFAULT_APPLICATION_OBJECT,
11
+ FABRIKA_APPLICATION_OBJECT,
12
+ FABRIKA_APPLICATION_OBJECTS,
8
13
  FABRIKA_CONTRACT_DIGEST,
14
+ FABRIKA_IAM_APP_ID,
9
15
  FABRIKA_IAM_ISSUER,
16
+ FABRIKA_PROXY_SECRET,
10
17
  isFrameworkVariableName,
18
+ isManagedCredential,
19
+ managedValue,
20
+ OPS_REHEARSAL_OBJECT,
21
+ parseManagedEnvironment,
11
22
  } from '@fabrika/auth-core'
12
23
  import { type DeployStepResult, type ProviderManagedEnvironment, runSteps, type SchemaReconciler } from '@fabrika/provider-contract'
13
24
  import { isPolicyOrigin } from '@fabrika/proxy-core/headers'
14
25
  import { contractProxyTable } from '@fabrika/proxy-core/manifest'
15
- import { dirname, resolve } from 'node:path'
16
- import { type GeneratedConfig, ServiceReference, Worker } from 'oblaka-iac'
26
+ import { createHash } from 'node:crypto'
27
+ import { stat } from 'node:fs/promises'
28
+ import { basename, dirname, isAbsolute, relative, resolve } from 'node:path'
29
+ import { DurableObject, type GeneratedConfig, R2Bucket, ServiceReference, Worker } from 'oblaka-iac'
17
30
  import { assertLiteralAssets } from './assets'
18
31
  import type { CloudflareAppConfig } from './authoring'
19
32
  import {
33
+ type ApplicationRuntime,
20
34
  assertGeneratedConfigs,
21
35
  assertGeneration,
22
36
  assertStateNamespace,
@@ -27,10 +41,23 @@ import {
27
41
  import { runnerWorkerGraph } from './checkout'
28
42
  import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
29
43
  import { configSchema } from './config-schema'
44
+ import {
45
+ assertCloudflareContract,
46
+ capsJobSegments,
47
+ needsMinuteTick,
48
+ pinsGeneratedEntry,
49
+ runsInObject,
50
+ servesAlarms,
51
+ servesOps,
52
+ servesRawSql,
53
+ } from './contract-support'
54
+ import { deployOrder } from './deploy-order'
55
+ import { parseSecretNames, splitManagedEnvironment, staleManagedSecrets, withSecretsFile } from './managed-secrets'
30
56
  import { buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
31
- import { createCloudflareProxyWorker } from './proxy'
57
+ import { createCloudflareProxyWorker, IamApplicationReference, PROXY_MANIFEST_DEFINE } from './proxy'
32
58
  import type { RunnerApprovedAccess } from './runner-protocol'
33
59
  import { defaultReconcileSchema } from './schema'
60
+ import { type AssetMount, assetMounts, SPA_ASSETS, SPA_ASSETS_DIRECTORY, stageSpaAssets } from './spa-assets'
34
61
 
35
62
  const CANCELLED = 'deploy cancelled'
36
63
 
@@ -60,42 +87,207 @@ const assertRunning = (signal: AbortSignal): void => {
60
87
  }
61
88
  }
62
89
 
90
+ /** What composing an application's Worker graph reads of a run; a local run (`composeLocalApplication`) supplies it too. */
91
+ type ApplicationTarget = Pick<
92
+ CloudflareDeployRun,
93
+ 'appId' | 'env' | 'domain' | 'crossOrigins' | 'operationsOrigin' | 'managedEnvironment' | 'vars' | 'secrets' | 'applicationObjects'
94
+ >
95
+
96
+ /** The bindings the platform writes into a contract application's Worker (ADR-0065). */
97
+ const PLATFORM_BINDINGS: ReadonlySet<string> = new Set([CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_FILES_BINDING])
98
+
63
99
  /** An application never names a variable only the platform writes, whether or not this deploy writes it. */
64
- const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: CloudflareDeployRun): void => {
100
+ const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: ApplicationTarget): void => {
65
101
  const authored = [
66
102
  ...(config.pipeline?.vars ?? []),
103
+ ...(config.pipeline?.secrets ?? []),
67
104
  ...Object.keys(application.options.vars ?? {}),
68
105
  ...Object.keys(application.options.bindings ?? {}),
69
106
  ...Object.keys(run.vars),
107
+ ...Object.keys(run.secrets),
70
108
  ]
71
- const reserved = authored.find(isFrameworkVariableName)
109
+ const reserved = authored.find((name) => isFrameworkVariableName(name) || PLATFORM_BINDINGS.has(name))
72
110
  if (reserved !== undefined) {
73
111
  throw new Error(`cloudflare: application variable \`${reserved}\` is managed by Fabrika`)
74
112
  }
113
+ if (application.options.triggers !== undefined) {
114
+ throw new Error(`cloudflare: application Worker \`${application.options.name}\` sets \`triggers\`; the platform writes its cron triggers`)
115
+ }
75
116
  }
76
117
 
118
+ /**
119
+ * Write the managed values into the application Worker: the public ones as vars, and the credentials as Worker secrets
120
+ * the deploy uploads with the version (`withSecretsFile`), never as plain text in a generated config.
121
+ */
77
122
  const withManagedEnvironment = (
78
123
  config: CloudflareAppConfig,
79
124
  authored: Worker,
80
- run: CloudflareDeployRun,
125
+ run: ApplicationTarget,
81
126
  managed: ProviderManagedEnvironment,
82
- ): Worker => {
83
- const present: Record<string, string> = {}
84
- const declared = new Set(config.pipeline?.vars ?? [])
127
+ ): { readonly worker: Worker; readonly secrets: Readonly<Record<string, string>> } => {
128
+ const declared = new Set([...(config.pipeline?.vars ?? []), ...(config.pipeline?.secrets ?? [])])
85
129
  const application = applicationWorker(authored)
86
- for (const [name, value] of Object.entries(managed)) {
87
- if (declared.has(name) || application.options.vars?.[name] !== undefined || run.vars[name] !== undefined) {
130
+ for (const name of Object.keys(managed)) {
131
+ if (
132
+ declared.has(name) || application.options.vars?.[name] !== undefined || run.vars[name] !== undefined || run.secrets[name] !== undefined
133
+ ) {
88
134
  throw new Error(`cloudflare: application variable \`${name}\` is managed by Fabrika`)
89
135
  }
90
- if (value !== null) present[name] = value
91
136
  }
92
- if (Object.keys(present).length === 0) return authored
137
+ const { vars, secrets } = splitManagedEnvironment(managed)
138
+ if (Object.keys(vars).length === 0) return { worker: authored, secrets }
93
139
  const configured = new Worker({
94
140
  ...application.options,
95
141
  vars: {
96
- ...(application.options.vars ?? {}),
97
- ...present,
142
+ ...application.options.vars,
143
+ ...vars,
144
+ },
145
+ })
146
+ return { worker: replaceApplicationWorker(authored, configured), secrets }
147
+ }
148
+
149
+ /** R2's bucket names: 3 to 63 lowercase letters, digits and hyphens, starting and ending with a letter or a digit. */
150
+ const R2_BUCKET_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/
151
+
152
+ /** The environment's files bucket, before oblaka's environment prefix. */
153
+ const filesBucketName = (appId: string): string => `${appId}-files`
154
+
155
+ /** The remote name oblaka gives the files bucket; it prefixes a bucket with the environment, `local` included. */
156
+ const filesBucketRemote = (run: ApplicationTarget): string => {
157
+ const remote = `${run.env}-${filesBucketName(run.appId)}`
158
+ if (!R2_BUCKET_NAME.test(remote)) {
159
+ throw new Error(
160
+ `cloudflare: the files bucket \`${remote}\` of \`${run.appId}@${run.env}\` is not a valid R2 bucket name; shorten the app id or the environment`,
161
+ )
162
+ }
163
+ return remote
164
+ }
165
+
166
+ const MINUTE_TICK = '* * * * *'
167
+
168
+ /**
169
+ * The hourly repair tick of an environment that serves alarms, at a minute derived from `<env>-<app>`: stable across
170
+ * deploys, and spread so the fleet's environments do not all wake at once.
171
+ */
172
+ const repairTick = (run: ApplicationTarget): string => {
173
+ const minute = createHash('sha256').update(`${run.env}-${run.appId}`).digest().readUInt32BE(0) % 60
174
+ return `${minute} * * * *`
175
+ }
176
+
177
+ /**
178
+ * What the platform gives a contract application's Worker; the deployer writes exactly this and the bounds check it.
179
+ * Only a release Control names serves alarms; a local deploy keeps the minute tick.
180
+ */
181
+ const applicationRuntime = (run: ApplicationTarget, contract: ContractArtifact, entry: string | null, alarms: boolean): ApplicationRuntime => ({
182
+ filesBucket: filesBucketRemote(run),
183
+ crons: needsMinuteTick(contract) ? [alarms ? repairTick(run) : MINUTE_TICK] : [],
184
+ entry,
185
+ })
186
+
187
+ /** Where `fabrika app build` runs: the application directory, beside its config and contract, and the config it reads. */
188
+ interface EntryBuild {
189
+ readonly cwd: string
190
+ readonly config: string
191
+ /** The directory the runner installed the checkout's dependencies in; the CLI is looked for no higher. */
192
+ readonly root: string
193
+ }
194
+
195
+ /** The application's own CLI, where the checkout's `bun install` links it, as the Zerops build runs it. */
196
+ const APPLICATION_CLI = ['node_modules', '.bin', 'fabrika']
197
+
198
+ const ENTRY_BUILD_ARGS = ['app', 'build', '--provider=cloudflare']
199
+
200
+ /** All the CLI gets of the executor's environment: what Bun needs to run, as the generated tests of `fabrika db` get. */
201
+ const ENTRY_BUILD_VARIABLES: readonly string[] = ['PATH', 'HOME', 'TMPDIR']
202
+
203
+ const isFile = async (path: string): Promise<boolean> => {
204
+ try {
205
+ return (await stat(path)).isFile()
206
+ } catch {
207
+ return false
208
+ }
209
+ }
210
+
211
+ /** The first `node_modules/.bin/fabrika` from the application directory up to `root`: a workspace links it at its root. */
212
+ const applicationCli = async ({ cwd, root }: EntryBuild): Promise<string> => {
213
+ for (let dir = cwd; isWithin(root, dir); dir = dirname(dir)) {
214
+ const candidate = resolve(dir, ...APPLICATION_CLI)
215
+ if (await isFile(candidate)) return candidate
216
+ if (dir === root) break
217
+ }
218
+ throw new Error(
219
+ `fabrika app build: no \`${APPLICATION_CLI.join('/')}\` from \`${cwd}\` up to \`${root}\`; the application installs \`@fabrika/cli\``,
220
+ )
221
+ }
222
+
223
+ const isWithin = (root: string, dir: string): boolean => {
224
+ const path = relative(root, dir)
225
+ return path === '' || (!path.startsWith('..') && !isAbsolute(path))
226
+ }
227
+
228
+ /**
229
+ * The executor's environment carries the application's and the managed secrets, and the CLI is checkout code whose
230
+ * failed output reaches the log: it inherits nothing and gets only `ENTRY_BUILD_VARIABLES`.
231
+ */
232
+ const entryBuildEnvironment = (): { readonly env: Record<string, string>; readonly omitEnv: readonly string[] } => {
233
+ const env: Record<string, string> = {}
234
+ for (const name of ENTRY_BUILD_VARIABLES) {
235
+ const value = process.env[name]
236
+ if (value !== undefined) env[name] = value
237
+ }
238
+ return { env, omitEnv: Object.keys(process.env) }
239
+ }
240
+
241
+ /** Regenerate the entry and the inlined migrations from the checkout, with the application's own release of the CLI. */
242
+ const buildEntry = async (build: EntryBuild, run: CloudflareDeployRun, cf: CloudflareCollaborators): Promise<void> => {
243
+ const args = [...ENTRY_BUILD_ARGS, `--config=${build.config}`]
244
+ if (run.dryRun) {
245
+ run.log(` [dry-run] would run: fabrika ${args.join(' ')} in ${build.cwd}`)
246
+ return
247
+ }
248
+ assertRunning(run.signal)
249
+ const command = await applicationCli(build)
250
+ const result = await cf.runCommand({ command, args, cwd: build.cwd, ...entryBuildEnvironment(), signal: run.signal })
251
+ if (result.exitCode !== 0) throw commandError('fabrika app build', result)
252
+ }
253
+
254
+ /**
255
+ * The objects of a release that serves ops (ADR-0069) when Control names none: ordinary traffic reaches `application`,
256
+ * and ops requests reach it and the object a backup is rehearsed in (ADR-0070).
257
+ */
258
+ const DEFAULT_OBJECTS: ApplicationObjects = { object: DEFAULT_APPLICATION_OBJECT, objects: [DEFAULT_APPLICATION_OBJECT, OPS_REHEARSAL_OBJECT] }
259
+
260
+ /** The object variables written from the pointer Control records, so a deploy keeps one a side restore moved (ADR-0070 §9). */
261
+ const objectVariables = (objects: ApplicationObjects): Readonly<Record<string, string>> => ({
262
+ [FABRIKA_APPLICATION_OBJECT]: objects.object,
263
+ [FABRIKA_APPLICATION_OBJECTS]: objects.objects.join(','),
264
+ })
265
+
266
+ /**
267
+ * Bind the application's Durable Object, which runs the application over its SQLite, the environment's files bucket,
268
+ * and its cron trigger (ADR-0065), and on a release that serves ops name its objects. The object is bound first, so
269
+ * oblaka numbers its migration `v0001` whatever else the application binds, and the tag never moves. With `assets`,
270
+ * the Worker also gets the Workers Assets the deploy stages the mounts' files into (`SPA_ASSETS`).
271
+ */
272
+ const withApplicationRuntime = (
273
+ authored: Worker,
274
+ run: ApplicationTarget,
275
+ runtime: ApplicationRuntime,
276
+ ops: boolean,
277
+ assets: boolean,
278
+ ): Worker => {
279
+ const application = applicationWorker(authored)
280
+ const configured = new Worker({
281
+ ...application.options,
282
+ ...(ops ? { vars: { ...application.options.vars, ...objectVariables(run.applicationObjects ?? DEFAULT_OBJECTS) } } : {}),
283
+ ...(assets ? { assets: { ...SPA_ASSETS } } : {}),
284
+ bindings: {
285
+ [CLOUDFLARE_APPLICATION_BINDING]: new DurableObject({ name: `${run.appId}-application`, className: CLOUDFLARE_APPLICATION_CLASS }),
286
+ ...application.options.bindings,
287
+ [CLOUDFLARE_FILES_BINDING]: new R2Bucket({ name: filesBucketName(run.appId) }),
98
288
  },
289
+ // Always written: wrangler leaves a Worker's schedules alone when `triggers` is absent, and clears them on `[]`.
290
+ triggers: { crons: [...runtime.crons] },
99
291
  })
100
292
  return replaceApplicationWorker(authored, configured)
101
293
  }
@@ -115,13 +307,26 @@ const connectorBindings = (contract: ContractArtifact | null): Readonly<Record<s
115
307
  Object.entries(contract?.imports ?? {}).map(([name, imported]) => [connectVariables(name).binding, proxyWorkerName(imported.app)]),
116
308
  )
117
309
 
310
+ /** The application Worker's `IAM` binding, written by the deployer so that it names this deployment (ADR-0067 §3). */
311
+ const withIamIdentity = (authored: Worker, iamAppId: string): Worker => {
312
+ const application = applicationWorker(authored)
313
+ const declared = application.options.bindings?.['IAM']
314
+ // A resource under the name is no IAM binding; oblaka provisions it, and the bounds check whatever it emits.
315
+ if (declared === undefined || 'getId' in declared) return authored
316
+ const configured = new Worker({
317
+ ...application.options,
318
+ bindings: { ...application.options.bindings, IAM: new IamApplicationReference(iamAppId, declared) },
319
+ })
320
+ return replaceApplicationWorker(authored, configured)
321
+ }
322
+
118
323
  const withConnectorBindings = (authored: Worker, bindings: Readonly<Record<string, string>>): Worker => {
119
324
  if (Object.keys(bindings).length === 0) return authored
120
325
  const application = applicationWorker(authored)
121
326
  const configured = new Worker({
122
327
  ...application.options,
123
328
  bindings: {
124
- ...(application.options.bindings ?? {}),
329
+ ...application.options.bindings,
125
330
  ...Object.fromEntries(Object.entries(bindings).map(([binding, worker]) => [binding, new ServiceReference(worker)])),
126
331
  },
127
332
  })
@@ -134,27 +339,27 @@ interface ServedContract {
134
339
  readonly digest: string
135
340
  }
136
341
 
137
- /** A contract application starts only as the contract it was deployed with (ADR-0022 rule 5), so the platform writes its digest. */
342
+ /**
343
+ * A contract application starts only as the contract it was deployed with (ADR-0022 rule 5), so the platform writes its
344
+ * digest. Control never hands one: `parseManagedEnvironment` refuses the name.
345
+ */
138
346
  const contractEnvironment = (managed: ProviderManagedEnvironment, served: ServedContract | null): ProviderManagedEnvironment => {
139
347
  if (served === null) return managed
140
- const { digest } = served
141
- const sent = managed[FABRIKA_CONTRACT_DIGEST]
142
- if (sent !== undefined && sent !== null && sent !== digest) {
143
- throw new Error(`cloudflare: ${FABRIKA_CONTRACT_DIGEST} is \`${sent}\`, but the contract this deployment serves has digest \`${digest}\``)
144
- }
145
- return { ...managed, [FABRIKA_CONTRACT_DIGEST]: digest }
348
+ return { ...managed, [FABRIKA_CONTRACT_DIGEST]: { value: served.digest, credential: isManagedCredential(FABRIKA_CONTRACT_DIGEST) } }
146
349
  }
147
350
 
148
351
  /**
149
352
  * The lock-down follows the contract, not the config: a contract whose IAM schema does not say `contract: true`, or a
150
- * platform service's schema that does, would leave the proxy and IAM deciding under different rules.
353
+ * platform service's schema that does, would leave the proxy and IAM deciding under different rules. An application
354
+ * (`refuse`) may declare no schema, because Control writes the approved contract's own (ADR-0050); a platform deploy
355
+ * (`allow`) registers the schema itself (ADR-0058), so it must declare one.
151
356
  */
152
- const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifact | null): void => {
357
+ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifact | null, platformResources: 'refuse' | 'allow'): void => {
153
358
  const declared = schema?.contract === true
154
359
  if (contract === null && declared) {
155
360
  throw new Error('cloudflare: the IAM schema says `contract: true`, but the checkout has no `fabrika.contract.ts`')
156
361
  }
157
- if (contract !== null && !declared) {
362
+ if (contract !== null && !declared && (schema !== null || platformResources === 'allow')) {
158
363
  throw new Error('cloudflare: this deployment serves a contract, so its IAM schema is `schemaFromContract(artifact)` (`contract: true`)')
159
364
  }
160
365
  }
@@ -162,8 +367,9 @@ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifa
162
367
  /**
163
368
  * The proxy Worker is the platform's (ADR-0048): built here, from this package's own entrypoint, around the
164
369
  * application Worker the config returns, never taken from the checkout. A config that returns a proxy is refused.
370
+ * `ops` adds Control's ops row to the table.
165
371
  */
166
- const platformProxied = (authored: Worker, served: ServedContract, run: CloudflareDeployRun): Worker => {
372
+ const platformProxied = (authored: Worker, served: ServedContract, run: ApplicationTarget, ops: boolean): Worker => {
167
373
  if (authored.options.bindings?.['APP'] !== undefined) {
168
374
  throw new Error(
169
375
  `cloudflare: \`resources\` returns the Worker \`${authored.options.name}\` binding \`APP\`, a proxy of its own; return the application Worker, and the platform builds the proxy Worker from its contract`,
@@ -180,16 +386,18 @@ const platformProxied = (authored: Worker, served: ServedContract, run: Cloudfla
180
386
  appHost: run.domain ?? 'localhost',
181
387
  ...(run.domain === undefined ? {} : { domain: run.domain }),
182
388
  ...(run.crossOrigins === undefined ? {} : { crossOrigins: run.crossOrigins }),
183
- endpoints: contractProxyTable(served.contract, served.digest),
184
- ...operationsOrigin(run.managedEnvironment),
185
- iamUrl: run.managedEnvironment[FABRIKA_IAM_ISSUER] ?? '',
389
+ endpoints: contractProxyTable(served.contract, served.digest, { ops }),
390
+ ...operationsOrigin(run),
391
+ iamUrl: managedValue(run.managedEnvironment, FABRIKA_IAM_ISSUER) ?? '',
186
392
  })
187
393
  }
188
394
 
189
- /** The ingest origin of the application's Operations DSN: the proxy's `connect-src` admits it, as the framework's does. */
190
- const operationsOrigin = (managed: ProviderManagedEnvironment): { readonly operationsOrigin?: string } => {
191
- const dsn = managed['FABRIKA_OPERATIONS_DSN']
192
- if (dsn === undefined || dsn === null) return {}
395
+ /** The origin of the environment's Operations ingest, which the proxy's `connect-src` admits, as the framework's does. */
396
+ const operationsOrigin = (run: ApplicationTarget): { readonly operationsOrigin?: string } => {
397
+ if (run.operationsOrigin !== undefined) return { operationsOrigin: run.operationsOrigin }
398
+ // A job from an older Control names no origin; derive it from the DSN until no release in the window omits it.
399
+ const dsn = managedValue(run.managedEnvironment, 'FABRIKA_OPERATIONS_DSN')
400
+ if (dsn === null) return {}
193
401
  let origin: string
194
402
  try {
195
403
  origin = new URL(dsn).origin
@@ -212,7 +420,7 @@ const replaceApplicationWorker = (worker: Worker, replacement: Worker): Worker =
212
420
  return new Worker({
213
421
  ...worker.options,
214
422
  bindings: {
215
- ...(worker.options.bindings ?? {}),
423
+ ...worker.options.bindings,
216
424
  APP: replaceApplicationWorker(child, replacement),
217
425
  },
218
426
  })
@@ -249,9 +457,90 @@ interface StepEnv {
249
457
  readonly platformIam: PlatformIamTarget | undefined
250
458
  readonly reconcileSchema: SchemaReconciler
251
459
  readonly bounds: DeploymentBounds
460
+ /** The managed credentials the application Worker's version is uploaded with, as Worker secrets. */
461
+ readonly managedSecrets: Readonly<Record<string, string>>
462
+ /** Where the build step regenerates the entry, after `pipeline.build`; null for a release that keeps its authored `main`. */
463
+ readonly entryBuild: EntryBuild | null
464
+ /**
465
+ * The mounts whose files the deploy stages into the application Worker's assets, from the application's root; null
466
+ * when the Worker declares its own `assets` or no mount serves files.
467
+ */
468
+ readonly spaAssets: { readonly mounts: readonly AssetMount[]; readonly root: string } | null
252
469
  generatedConfigs: readonly GeneratedConfig[]
253
470
  }
254
471
 
472
+ /**
473
+ * `wrangler deploy`, with the managed secrets uploaded in the same version when there are any, so the version never
474
+ * serves without them, and a plain var of the same name an older release wrote goes with the old version.
475
+ */
476
+ const wranglerDeploy = async (env: StepEnv, cwd: string, secrets: Readonly<Record<string, string>>): Promise<void> => {
477
+ const { run, credentials, cf } = env
478
+ const names = Object.keys(secrets)
479
+ if (run.dryRun) {
480
+ run.log(` [dry-run] would run: wrangler deploy${names.length === 0 ? '' : ` with the secrets ${names.join(', ')}`} in ${cwd}`)
481
+ return
482
+ }
483
+ assertRunning(run.signal)
484
+ await withSecretsFile(secrets, async (path) => {
485
+ const args = path === null ? ['deploy'] : ['deploy', '--secrets-file', path]
486
+ const result = await cf.runCommand({ command: 'wrangler', args, cwd, env: wranglerEnv(credentials), signal: run.signal })
487
+ if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
488
+ })
489
+ }
490
+
491
+ /** Delete the framework secrets the application Worker holds that this deploy no longer writes, as Zerops removes them. */
492
+ const deleteStaleSecrets = async (env: StepEnv, cwd: string): Promise<void> => {
493
+ const { run, credentials, cf } = env
494
+ if (run.dryRun) {
495
+ run.log(` [dry-run] would delete the managed secrets this deploy no longer writes in ${cwd}`)
496
+ return
497
+ }
498
+ assertRunning(run.signal)
499
+ const listed = await cf.runCommand({
500
+ command: 'wrangler',
501
+ args: ['secret', 'list', '--format', 'json'],
502
+ cwd,
503
+ env: wranglerEnv(credentials),
504
+ signal: run.signal,
505
+ })
506
+ if (listed.exitCode !== 0) throw commandError('wrangler secret list', listed)
507
+ for (const name of staleManagedSecrets(parseSecretNames(listed.stdout), env.managedSecrets)) {
508
+ assertRunning(run.signal)
509
+ // A piped stdin keeps wrangler non-interactive, so its confirmation takes its fallback answer.
510
+ const result = await cf.runCommand({
511
+ command: 'wrangler',
512
+ args: ['secret', 'delete', name],
513
+ cwd,
514
+ env: wranglerEnv(credentials),
515
+ stdin: '',
516
+ signal: run.signal,
517
+ })
518
+ if (result.exitCode !== 0) throw commandError(`wrangler secret delete ${name}`, result)
519
+ run.log(` deleted the managed secret ${name}, which this deploy no longer writes`)
520
+ }
521
+ }
522
+
523
+ /** Stage the mounts' files beside the application Worker's generated config, where its `assets.directory` points. */
524
+ const stageAssets = async (env: StepEnv, assets: NonNullable<StepEnv['spaAssets']>, generatedDir: string): Promise<void> => {
525
+ const mounts = assets.mounts.map((mount) => `${mount.prefix} from ${mount.dir}`).join(', ')
526
+ if (env.run.dryRun) {
527
+ env.run.log(` [dry-run] would stage the SPA files into ${SPA_ASSETS_DIRECTORY}: ${mounts}`)
528
+ return
529
+ }
530
+ assertRunning(env.run.signal)
531
+ const staged = await stageSpaAssets(assets.mounts, assets.root, generatedDir)
532
+ env.run.log(` staged ${staged} SPA files into ${SPA_ASSETS_DIRECTORY}: ${mounts}`)
533
+ }
534
+
535
+ /**
536
+ * The secrets stored for the environment that `fabrika.config.ts` does not name in `pipeline.secrets`, by name. The deploy
537
+ * writes only declared ones, so these never reach the Worker; the run log says so, as an author would otherwise wonder.
538
+ */
539
+ export const undeclaredSecrets = (config: CloudflareAppConfig, run: Pick<CloudflareDeployRun, 'secrets'>): string[] => {
540
+ const declared = new Set(config.pipeline?.secrets ?? [])
541
+ return Object.keys(run.secrets).filter((name) => !declared.has(name)).sort()
542
+ }
543
+
255
544
  const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
256
545
  const { config, run, credentials, worker, dir, cf } = env
257
546
  const { signal, dryRun } = run
@@ -259,14 +548,14 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
259
548
  switch (spec.kind) {
260
549
  case 'build': {
261
550
  const build = config.pipeline?.build
262
- if (build === undefined) return
263
- if (dryRun) {
551
+ if (build !== undefined && dryRun) {
264
552
  run.log(` [dry-run] would run build: \`${build}\` in ${dir}`)
265
- return
553
+ } else if (build !== undefined) {
554
+ assertRunning(signal)
555
+ const result = await cf.runCommand({ command: 'sh', args: ['-c', build], cwd: dir, omitEnv: PLATFORM_CREDENTIAL_NAMES, signal })
556
+ if (result.exitCode !== 0) throw commandError(`build (\`${build}\`)`, result)
266
557
  }
267
- assertRunning(signal)
268
- const result = await cf.runCommand({ command: 'sh', args: ['-c', build], cwd: dir, omitEnv: PLATFORM_CREDENTIAL_NAMES, signal })
269
- if (result.exitCode !== 0) throw commandError(`build (\`${build}\`)`, result)
558
+ if (env.entryBuild !== null) await buildEntry(env.entryBuild, run, cf)
270
559
  return
271
560
  }
272
561
  case 'provision-resources': {
@@ -307,31 +596,31 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
307
596
  return
308
597
  }
309
598
  case 'deploy-worker': {
599
+ for (const name of undeclaredSecrets(config, run)) {
600
+ run.log(` the secret ${name} is stored for this environment but not named in pipeline.secrets, so the Worker does not get it`)
601
+ }
310
602
  const configs = env.generatedConfigs
311
603
  // The configs oblaka wrote, not the generation checked before the run: a stateful binding can emit differently twice.
312
604
  assertGeneratedConfigs(configs, env.bounds)
313
605
  if (configs.length === 0) {
314
- if (dryRun) {
315
- run.log(` [dry-run] would run: wrangler deploy in ${dir}`)
316
- return
317
- }
318
- assertRunning(signal)
319
- const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: dir, env: wranglerEnv(credentials), signal })
320
- if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
606
+ await wranglerDeploy(env, dir, env.managedSecrets)
321
607
  return
322
608
  }
323
- for (const generated of configs) {
609
+ const application = `${run.env}-${applicationWorker(worker).options.name}`
610
+ let applicationDir: string | undefined
611
+ for (const generated of deployOrder(configs)) {
324
612
  const generatedDir = dirname(resolve(dir, generated.path))
613
+ const isApplication = generated.config.name === application
614
+ // The checkout's build has written the mounts' directories; the walk below checks the staged copy.
615
+ if (isApplication && env.spaAssets !== null) await stageAssets(env, env.spaAssets, generatedDir)
325
616
  // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
326
617
  if (env.platformResources === 'refuse') await assertLiteralAssets(generated, generatedDir)
327
- if (dryRun) {
328
- run.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
329
- continue
330
- }
331
- assertRunning(signal)
332
- const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: generatedDir, env: wranglerEnv(credentials), signal })
333
- if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
618
+ await wranglerDeploy(env, generatedDir, isApplication ? env.managedSecrets : {})
619
+ if (isApplication) applicationDir = generatedDir
334
620
  }
621
+ // Swept only once every Worker is deployed: a failed sweep must not leave the new application behind the old proxy.
622
+ // A platform component's own secrets carry framework names (IAM's mail transport), so only an application's are swept.
623
+ if (applicationDir !== undefined && env.platformResources === 'refuse') await deleteStaleSecrets(env, applicationDir)
335
624
  return
336
625
  }
337
626
  case 'reconcile-schema': {
@@ -424,6 +713,8 @@ export interface CloudflareDeployRun {
424
713
  readonly domain?: string
425
714
  /** The environment's cross-origin list from Control's registry (ADR-0022); the proxy Worker's manifest entry lists it. */
426
715
  readonly crossOrigins?: readonly string[]
716
+ /** The origin of the environment's Operations ingest, from Control; the proxy Worker's `connect-src` admits it. */
717
+ readonly operationsOrigin?: string
427
718
  /** Every origin IAM may hand this environment a session at, registered under `<app>@<env>`. */
428
719
  readonly returnOrigins?: readonly string[]
429
720
  readonly cwd: string
@@ -440,6 +731,8 @@ export interface CloudflareDeployRun {
440
731
  readonly approved?: RunnerApprovedAccess
441
732
  /** Every Cloudflare deployment of the installation in Control's registry; a name of another application is refused. */
442
733
  readonly installationApps?: readonly AppEnvironment[]
734
+ /** The serving object and the listed objects Control records (ADR-0070 §9); absent, `application` and `rehearsal`. */
735
+ readonly applicationObjects?: ApplicationObjects
443
736
  readonly dryRun: boolean
444
737
  readonly signal: AbortSignal
445
738
  readonly log: (line: string) => void
@@ -475,18 +768,38 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
475
768
  if (platformResources === 'refuse' && served === null) {
476
769
  throw new Error('cloudflare: the checkout has no `fabrika.contract.ts`; Fabrika deploys an application only with a contract')
477
770
  }
771
+ // A local deploy reads the contract with this release and runs it in the object, so it is gated as this release is.
772
+ const framework = run.approved === undefined ? undefined : run.approved.framework
773
+ const gates = run.approved === undefined
774
+ ? { capsSegments: true, servesSql: true }
775
+ : { capsSegments: framework !== undefined && capsJobSegments(framework), servesSql: framework !== undefined && servesRawSql(framework) }
776
+ if (platformResources === 'refuse' && contract !== null) assertCloudflareContract(contract, gates)
478
777
  // Read once, before `resources()` runs the checkout's code again: nothing below reads the config's schema.
479
778
  const schema = configSchema(loaded.config)
480
- assertContractSchema(schema, contract)
779
+ assertContractSchema(schema, contract, platformResources)
481
780
  const authored = runnerWorkerGraph(loaded.config.resources({ env: run.env, domain: run.domain }))
482
- // Fabrika's own components compose their own proxies; every application gets the platform's.
483
- const proxied = platformResources === 'refuse' && served !== null ? platformProxied(authored, served, run) : authored
781
+ // Only a release Control named pins the entry or serves ops; a local deploy names none and keeps its authored `main`.
782
+ const release = run.approved?.framework
783
+ const opsRelease = release !== undefined && servesOps(release)
784
+ // Fabrika's own components compose their own proxies; every application gets the platform's. Without a domain no
785
+ // Custom Domain carries the ops channel, so the proxy gets no ops row (ADR-0069).
786
+ const proxied = platformResources === 'refuse' && served !== null
787
+ ? platformProxied(authored, served, run, opsRelease && run.domain !== undefined)
788
+ : authored
484
789
  if (platformResources === 'refuse') assertNoFrameworkVariables(loaded.config, applicationWorker(proxied), run)
485
790
  const connectors = platformResources === 'refuse' ? connectorBindings(contract) : {}
486
- const worker = withConnectorBindings(
487
- withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served)),
488
- connectors,
489
- )
791
+ // An older release's entry exports no object, and a Control older than the runner names no release (ADR-0062).
792
+ const objectRuntime = run.approved === undefined || (run.approved.framework !== undefined && runsInObject(run.approved.framework))
793
+ const entry = release !== undefined && pinsGeneratedEntry(release) ? resolve(loaded.cwd, GENERATED_ENTRY_FILE) : null
794
+ const alarms = release !== undefined && servesAlarms(release)
795
+ const runtime = platformResources === 'refuse' && contract !== null && objectRuntime ? applicationRuntime(run, contract, entry, alarms) : null
796
+ const managed = withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served))
797
+ const identified = platformResources === 'refuse' ? withIamIdentity(managed.worker, appEnvironmentId(run.appId, run.env)) : managed.worker
798
+ const connected = withConnectorBindings(identified, connectors)
799
+ // An application Worker that declares its own `assets` keeps them; otherwise the platform stages the mounts' files.
800
+ const mounts = runtime !== null && contract !== null ? assetMounts(contract) : []
801
+ const spaAssets = mounts.length > 0 && applicationWorker(connected).options.assets === undefined ? { mounts, root: loaded.cwd } : null
802
+ const worker = runtime === null ? connected : withApplicationRuntime(connected, run, runtime, opsRelease, spaAssets !== null)
490
803
  const dir = workerDir(loaded.config, loaded.cwd)
491
804
  const bounds: DeploymentBounds = {
492
805
  env: run.env,
@@ -501,6 +814,8 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
501
814
  application: frameworkValues(applicationWorker(worker).options.vars),
502
815
  proxy: proxied === authored ? null : frameworkValues(worker.options.vars),
503
816
  },
817
+ proxyManifest: proxied === authored ? null : (worker.options.define?.[PROXY_MANIFEST_DEFINE] ?? null),
818
+ application: runtime,
504
819
  }
505
820
  assertStateNamespace(stateNamespace(loaded.config, run), platformResources)
506
821
  assertGeneration(await generateWranglerConfigs(worker, run.env), bounds)
@@ -516,8 +831,96 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
516
831
  platformIam: options.platformIam,
517
832
  reconcileSchema: options.reconcileSchema ?? defaultReconcileSchema,
518
833
  bounds,
834
+ managedSecrets: managed.secrets,
835
+ entryBuild: runtime !== null && runtime.entry !== null
836
+ ? { cwd: loaded.cwd, config: basename(resolve(run.cwd, run.configPath)), root: resolve(run.cwd) }
837
+ : null,
838
+ spaAssets,
519
839
  generatedConfigs: [],
520
840
  }
521
- const result = await runSteps(buildPlan(loaded.config, worker), run, (step) => runStep(step, env))
841
+ const result = await runSteps(buildPlan(loaded.config, worker, env.entryBuild !== null), run, (step) => runStep(step, env))
522
842
  return { appId: run.appId, env: run.env, ...result }
523
843
  }
844
+
845
+ /** The SPA files `stageLocalAssets` staged for a local run: the mounts it copied, in the order a deploy stages them. */
846
+ export interface StagedLocalAssets {
847
+ readonly mounts: readonly AssetMount[]
848
+ readonly files: number
849
+ }
850
+
851
+ /**
852
+ * Stage the contract's SPA and link mounts for a local run, with the code a deploy stages them with: each mount's
853
+ * built directory under `root` into `root/fabrika/assets`, where the generated `wrangler.jsonc` beside the config points
854
+ * its `ASSETS`. Run it before oblaka generates the config (`await` at the top of `oblaka.ts`) and after the SPA build.
855
+ */
856
+ export const stageLocalAssets = async (contract: ContractArtifact, root: string): Promise<StagedLocalAssets> => {
857
+ const mounts = assetMounts(contract)
858
+ return { mounts, files: mounts.length === 0 ? 0 : await stageSpaAssets(mounts, root, root) }
859
+ }
860
+
861
+ const sameMounts = (left: readonly AssetMount[], right: readonly AssetMount[]): boolean =>
862
+ left.length === right.length && left.every((mount, index) => mount.prefix === right[index]?.prefix && mount.dir === right[index]?.dir)
863
+
864
+ /** What `composeLocalApplication` needs: the config, the contract it serves, and the IAM a local run reaches. */
865
+ export interface LocalApplicationOptions {
866
+ readonly config: CloudflareAppConfig
867
+ readonly contract: ContractArtifact
868
+ /** What `stageLocalAssets` staged; required when the contract has an SPA or link mount and the Worker no `assets`. */
869
+ readonly assets?: StagedLocalAssets
870
+ /** IAM's origin, the issuer of the local run's tokens. */
871
+ readonly iamOrigin: string
872
+ readonly env: string
873
+ readonly domain?: string
874
+ }
875
+
876
+ /**
877
+ * The proxy Worker and the application Worker of a local run (`oblaka.ts`, lopata), composed by the code a deploy runs:
878
+ * the platform's proxy over the contract's endpoint table, and the application's object, files bucket and repair tick,
879
+ * as a release that serves alarms gets them. No deploy takes it. With no Control to write them, the framework values
880
+ * come from here, and the proxy secret, which a deploy uploads as a Worker secret, is drawn anew on each call and
881
+ * written as a variable into the ignored `wrangler.jsonc`.
882
+ */
883
+ export const composeLocalApplication = (options: LocalApplicationOptions): Worker => {
884
+ const { config, contract, env } = options
885
+ const domain = options.domain === undefined ? {} : { domain: options.domain }
886
+ const iamAppId = appEnvironmentId(config.id, env)
887
+ const target: ApplicationTarget = {
888
+ appId: config.id,
889
+ env,
890
+ ...domain,
891
+ vars: {},
892
+ secrets: {},
893
+ managedEnvironment: parseManagedEnvironment({
894
+ [FABRIKA_IAM_ISSUER]: options.iamOrigin,
895
+ [FABRIKA_IAM_APP_ID]: iamAppId,
896
+ [FABRIKA_PROXY_SECRET]: `${crypto.randomUUID()}${crypto.randomUUID()}`.replaceAll('-', ''),
897
+ }),
898
+ }
899
+ // The local run reads the contract with this release, so it is gated as a local deploy is.
900
+ assertCloudflareContract(contract, { capsSegments: true, servesSql: true })
901
+ assertContractSchema(configSchema(config), contract, 'refuse')
902
+ const served: ServedContract = { contract, digest: contractDigest(contract) }
903
+ const proxied = platformProxied(config.resources({ env, ...domain }), served, target, false)
904
+ assertNoFrameworkVariables(config, applicationWorker(proxied), target)
905
+ const managed = withManagedEnvironment(config, proxied, target, contractEnvironment(target.managedEnvironment, served))
906
+ const application = applicationWorker(managed.worker)
907
+ const withSecrets = replaceApplicationWorker(
908
+ managed.worker,
909
+ new Worker({ ...application.options, vars: { ...application.options.vars, ...managed.secrets } }),
910
+ )
911
+ const identified = withIamIdentity(withSecrets, iamAppId)
912
+ const connected = withConnectorBindings(identified, connectorBindings(contract))
913
+ // As a deploy: a Worker that declares its own `assets` keeps them; otherwise the staged mounts are bound as `ASSETS`.
914
+ const mounts = assetMounts(contract)
915
+ const authoredAssets = applicationWorker(connected).options.assets !== undefined
916
+ if (authoredAssets && options.assets !== undefined) {
917
+ throw new Error('composeLocalApplication: the application Worker declares its own `assets`, so nothing is staged; drop `assets`')
918
+ }
919
+ const spaAssets = mounts.length > 0 && !authoredAssets
920
+ if (spaAssets && (options.assets === undefined || !sameMounts(options.assets.mounts, mounts))) {
921
+ throw new Error(
922
+ 'composeLocalApplication: the contract serves SPA files; stage them first with `await stageLocalAssets(contract, <application root>)` and pass its result as `assets`',
923
+ )
924
+ }
925
+ return withApplicationRuntime(connected, target, applicationRuntime(target, contract, null, true), false, spaAssets)
926
+ }