@fabrika/provider-cloudflare 0.9.0-cloudflare.1 → 0.9.0-cloudflare.3

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.
package/src/provider.ts CHANGED
@@ -2,6 +2,7 @@ import { CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_APPLICATION_CLASS, CLOUDFLAR
2
2
  import {
3
3
  type AppEnvironment,
4
4
  appEnvironmentId,
5
+ type ApplicationObjects,
5
6
  type AppSchema,
6
7
  connectVariables,
7
8
  type ContractArtifact,
@@ -10,14 +11,19 @@ import {
10
11
  FABRIKA_APPLICATION_OBJECT,
11
12
  FABRIKA_APPLICATION_OBJECTS,
12
13
  FABRIKA_CONTRACT_DIGEST,
14
+ FABRIKA_IAM_APP_ID,
13
15
  FABRIKA_IAM_ISSUER,
16
+ FABRIKA_PROXY_SECRET,
14
17
  isFrameworkVariableName,
15
18
  isManagedCredential,
16
19
  managedValue,
20
+ OPS_REHEARSAL_OBJECT,
21
+ parseManagedEnvironment,
17
22
  } from '@fabrika/auth-core'
18
23
  import { type DeployStepResult, type ProviderManagedEnvironment, runSteps, type SchemaReconciler } from '@fabrika/provider-contract'
19
24
  import { isPolicyOrigin } from '@fabrika/proxy-core/headers'
20
25
  import { contractProxyTable } from '@fabrika/proxy-core/manifest'
26
+ import { createHash } from 'node:crypto'
21
27
  import { stat } from 'node:fs/promises'
22
28
  import { basename, dirname, isAbsolute, relative, resolve } from 'node:path'
23
29
  import { DurableObject, type GeneratedConfig, R2Bucket, ServiceReference, Worker } from 'oblaka-iac'
@@ -35,12 +41,23 @@ import {
35
41
  import { runnerWorkerGraph } from './checkout'
36
42
  import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
37
43
  import { configSchema } from './config-schema'
38
- import { assertCloudflareContract, needsMinuteTick, pinsGeneratedEntry, runsInObject, servesOps } from './contract-support'
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'
39
55
  import { parseSecretNames, splitManagedEnvironment, staleManagedSecrets, withSecretsFile } from './managed-secrets'
40
56
  import { buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
41
57
  import { createCloudflareProxyWorker, IamApplicationReference, PROXY_MANIFEST_DEFINE } from './proxy'
42
58
  import type { RunnerApprovedAccess } from './runner-protocol'
43
59
  import { defaultReconcileSchema } from './schema'
60
+ import { type AssetMount, assetMounts, SPA_ASSETS, SPA_ASSETS_DIRECTORY, stageSpaAssets } from './spa-assets'
44
61
 
45
62
  const CANCELLED = 'deploy cancelled'
46
63
 
@@ -70,11 +87,17 @@ const assertRunning = (signal: AbortSignal): void => {
70
87
  }
71
88
  }
72
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
+
73
96
  /** The bindings the platform writes into a contract application's Worker (ADR-0065). */
74
97
  const PLATFORM_BINDINGS: ReadonlySet<string> = new Set([CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_FILES_BINDING])
75
98
 
76
99
  /** An application never names a variable only the platform writes, whether or not this deploy writes it. */
77
- const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: CloudflareDeployRun): void => {
100
+ const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: ApplicationTarget): void => {
78
101
  const authored = [
79
102
  ...(config.pipeline?.vars ?? []),
80
103
  ...(config.pipeline?.secrets ?? []),
@@ -99,7 +122,7 @@ const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Wo
99
122
  const withManagedEnvironment = (
100
123
  config: CloudflareAppConfig,
101
124
  authored: Worker,
102
- run: CloudflareDeployRun,
125
+ run: ApplicationTarget,
103
126
  managed: ProviderManagedEnvironment,
104
127
  ): { readonly worker: Worker; readonly secrets: Readonly<Record<string, string>> } => {
105
128
  const declared = new Set([...(config.pipeline?.vars ?? []), ...(config.pipeline?.secrets ?? [])])
@@ -116,7 +139,7 @@ const withManagedEnvironment = (
116
139
  const configured = new Worker({
117
140
  ...application.options,
118
141
  vars: {
119
- ...(application.options.vars ?? {}),
142
+ ...application.options.vars,
120
143
  ...vars,
121
144
  },
122
145
  })
@@ -130,7 +153,7 @@ const R2_BUCKET_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/
130
153
  const filesBucketName = (appId: string): string => `${appId}-files`
131
154
 
132
155
  /** The remote name oblaka gives the files bucket; it prefixes a bucket with the environment, `local` included. */
133
- const filesBucketRemote = (run: CloudflareDeployRun): string => {
156
+ const filesBucketRemote = (run: ApplicationTarget): string => {
134
157
  const remote = `${run.env}-${filesBucketName(run.appId)}`
135
158
  if (!R2_BUCKET_NAME.test(remote)) {
136
159
  throw new Error(
@@ -142,10 +165,22 @@ const filesBucketRemote = (run: CloudflareDeployRun): string => {
142
165
 
143
166
  const MINUTE_TICK = '* * * * *'
144
167
 
145
- /** What the platform gives a contract application's Worker; the deployer writes exactly this and the bounds check it. */
146
- const applicationRuntime = (run: CloudflareDeployRun, contract: ContractArtifact, entry: string | null): ApplicationRuntime => ({
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 => ({
147
182
  filesBucket: filesBucketRemote(run),
148
- crons: needsMinuteTick(contract) ? [MINUTE_TICK] : [],
183
+ crons: needsMinuteTick(contract) ? [alarms ? repairTick(run) : MINUTE_TICK] : [],
149
184
  entry,
150
185
  })
151
186
 
@@ -216,25 +251,39 @@ const buildEntry = async (build: EntryBuild, run: CloudflareDeployRun, cf: Cloud
216
251
  if (result.exitCode !== 0) throw commandError('fabrika app build', result)
217
252
  }
218
253
 
219
- /** The object variables of a release that serves ops (ADR-0069): ordinary traffic and ops requests reach `application`. */
220
- const OBJECT_VARIABLES: Readonly<Record<string, string>> = {
221
- [FABRIKA_APPLICATION_OBJECT]: DEFAULT_APPLICATION_OBJECT,
222
- [FABRIKA_APPLICATION_OBJECTS]: DEFAULT_APPLICATION_OBJECT,
223
- }
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
+ })
224
265
 
225
266
  /**
226
267
  * Bind the application's Durable Object, which runs the application over its SQLite, the environment's files bucket,
227
- * and the minute tick (ADR-0065), and on a release that serves ops name its objects. The object is bound first, so
228
- * oblaka numbers its migration `v0001` whatever else the application binds, and the tag never moves.
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`).
229
271
  */
230
- const withApplicationRuntime = (authored: Worker, run: CloudflareDeployRun, runtime: ApplicationRuntime, ops: boolean): Worker => {
272
+ const withApplicationRuntime = (
273
+ authored: Worker,
274
+ run: ApplicationTarget,
275
+ runtime: ApplicationRuntime,
276
+ ops: boolean,
277
+ assets: boolean,
278
+ ): Worker => {
231
279
  const application = applicationWorker(authored)
232
280
  const configured = new Worker({
233
281
  ...application.options,
234
- ...(ops ? { vars: { ...(application.options.vars ?? {}), ...OBJECT_VARIABLES } } : {}),
282
+ ...(ops ? { vars: { ...application.options.vars, ...objectVariables(run.applicationObjects ?? DEFAULT_OBJECTS) } } : {}),
283
+ ...(assets ? { assets: { ...SPA_ASSETS } } : {}),
235
284
  bindings: {
236
285
  [CLOUDFLARE_APPLICATION_BINDING]: new DurableObject({ name: `${run.appId}-application`, className: CLOUDFLARE_APPLICATION_CLASS }),
237
- ...(application.options.bindings ?? {}),
286
+ ...application.options.bindings,
238
287
  [CLOUDFLARE_FILES_BINDING]: new R2Bucket({ name: filesBucketName(run.appId) }),
239
288
  },
240
289
  // Always written: wrangler leaves a Worker's schedules alone when `triggers` is absent, and clears them on `[]`.
@@ -277,7 +326,7 @@ const withConnectorBindings = (authored: Worker, bindings: Readonly<Record<strin
277
326
  const configured = new Worker({
278
327
  ...application.options,
279
328
  bindings: {
280
- ...(application.options.bindings ?? {}),
329
+ ...application.options.bindings,
281
330
  ...Object.fromEntries(Object.entries(bindings).map(([binding, worker]) => [binding, new ServiceReference(worker)])),
282
331
  },
283
332
  })
@@ -301,14 +350,16 @@ const contractEnvironment = (managed: ProviderManagedEnvironment, served: Served
301
350
 
302
351
  /**
303
352
  * The lock-down follows the contract, not the config: a contract whose IAM schema does not say `contract: true`, or a
304
- * 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.
305
356
  */
306
- const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifact | null): void => {
357
+ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifact | null, platformResources: 'refuse' | 'allow'): void => {
307
358
  const declared = schema?.contract === true
308
359
  if (contract === null && declared) {
309
360
  throw new Error('cloudflare: the IAM schema says `contract: true`, but the checkout has no `fabrika.contract.ts`')
310
361
  }
311
- if (contract !== null && !declared) {
362
+ if (contract !== null && !declared && (schema !== null || platformResources === 'allow')) {
312
363
  throw new Error('cloudflare: this deployment serves a contract, so its IAM schema is `schemaFromContract(artifact)` (`contract: true`)')
313
364
  }
314
365
  }
@@ -318,7 +369,7 @@ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifa
318
369
  * application Worker the config returns, never taken from the checkout. A config that returns a proxy is refused.
319
370
  * `ops` adds Control's ops row to the table.
320
371
  */
321
- const platformProxied = (authored: Worker, served: ServedContract, run: CloudflareDeployRun, ops: boolean): Worker => {
372
+ const platformProxied = (authored: Worker, served: ServedContract, run: ApplicationTarget, ops: boolean): Worker => {
322
373
  if (authored.options.bindings?.['APP'] !== undefined) {
323
374
  throw new Error(
324
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`,
@@ -342,7 +393,7 @@ const platformProxied = (authored: Worker, served: ServedContract, run: Cloudfla
342
393
  }
343
394
 
344
395
  /** The origin of the environment's Operations ingest, which the proxy's `connect-src` admits, as the framework's does. */
345
- const operationsOrigin = (run: CloudflareDeployRun): { readonly operationsOrigin?: string } => {
396
+ const operationsOrigin = (run: ApplicationTarget): { readonly operationsOrigin?: string } => {
346
397
  if (run.operationsOrigin !== undefined) return { operationsOrigin: run.operationsOrigin }
347
398
  // A job from an older Control names no origin; derive it from the DSN until no release in the window omits it.
348
399
  const dsn = managedValue(run.managedEnvironment, 'FABRIKA_OPERATIONS_DSN')
@@ -369,7 +420,7 @@ const replaceApplicationWorker = (worker: Worker, replacement: Worker): Worker =
369
420
  return new Worker({
370
421
  ...worker.options,
371
422
  bindings: {
372
- ...(worker.options.bindings ?? {}),
423
+ ...worker.options.bindings,
373
424
  APP: replaceApplicationWorker(child, replacement),
374
425
  },
375
426
  })
@@ -410,6 +461,11 @@ interface StepEnv {
410
461
  readonly managedSecrets: Readonly<Record<string, string>>
411
462
  /** Where the build step regenerates the entry, after `pipeline.build`; null for a release that keeps its authored `main`. */
412
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
413
469
  generatedConfigs: readonly GeneratedConfig[]
414
470
  }
415
471
 
@@ -464,6 +520,18 @@ const deleteStaleSecrets = async (env: StepEnv, cwd: string): Promise<void> => {
464
520
  }
465
521
  }
466
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
+
467
535
  const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
468
536
  const { config, run, credentials, worker, dir, cf } = env
469
537
  const { signal, dryRun } = run
@@ -527,15 +595,20 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
527
595
  return
528
596
  }
529
597
  const application = `${run.env}-${applicationWorker(worker).options.name}`
530
- for (const generated of configs) {
598
+ let applicationDir: string | undefined
599
+ for (const generated of deployOrder(configs)) {
531
600
  const generatedDir = dirname(resolve(dir, generated.path))
601
+ const isApplication = generated.config.name === application
602
+ // The checkout's build has written the mounts' directories; the walk below checks the staged copy.
603
+ if (isApplication && env.spaAssets !== null) await stageAssets(env, env.spaAssets, generatedDir)
532
604
  // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
533
605
  if (env.platformResources === 'refuse') await assertLiteralAssets(generated, generatedDir)
534
- const isApplication = generated.config.name === application
535
606
  await wranglerDeploy(env, generatedDir, isApplication ? env.managedSecrets : {})
536
- // A platform component's own secrets carry framework names (IAM's mail transport), so only an application's are swept.
537
- if (isApplication && env.platformResources === 'refuse') await deleteStaleSecrets(env, generatedDir)
607
+ if (isApplication) applicationDir = generatedDir
538
608
  }
609
+ // Swept only once every Worker is deployed: a failed sweep must not leave the new application behind the old proxy.
610
+ // A platform component's own secrets carry framework names (IAM's mail transport), so only an application's are swept.
611
+ if (applicationDir !== undefined && env.platformResources === 'refuse') await deleteStaleSecrets(env, applicationDir)
539
612
  return
540
613
  }
541
614
  case 'reconcile-schema': {
@@ -646,6 +719,8 @@ export interface CloudflareDeployRun {
646
719
  readonly approved?: RunnerApprovedAccess
647
720
  /** Every Cloudflare deployment of the installation in Control's registry; a name of another application is refused. */
648
721
  readonly installationApps?: readonly AppEnvironment[]
722
+ /** The serving object and the listed objects Control records (ADR-0070 §9); absent, `application` and `rehearsal`. */
723
+ readonly applicationObjects?: ApplicationObjects
649
724
  readonly dryRun: boolean
650
725
  readonly signal: AbortSignal
651
726
  readonly log: (line: string) => void
@@ -681,10 +756,15 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
681
756
  if (platformResources === 'refuse' && served === null) {
682
757
  throw new Error('cloudflare: the checkout has no `fabrika.contract.ts`; Fabrika deploys an application only with a contract')
683
758
  }
684
- if (platformResources === 'refuse' && contract !== null) assertCloudflareContract(contract)
759
+ // A local deploy reads the contract with this release and runs it in the object, so it is gated as this release is.
760
+ const framework = run.approved === undefined ? undefined : run.approved.framework
761
+ const gates = run.approved === undefined
762
+ ? { capsSegments: true, servesSql: true }
763
+ : { capsSegments: framework !== undefined && capsJobSegments(framework), servesSql: framework !== undefined && servesRawSql(framework) }
764
+ if (platformResources === 'refuse' && contract !== null) assertCloudflareContract(contract, gates)
685
765
  // Read once, before `resources()` runs the checkout's code again: nothing below reads the config's schema.
686
766
  const schema = configSchema(loaded.config)
687
- assertContractSchema(schema, contract)
767
+ assertContractSchema(schema, contract, platformResources)
688
768
  const authored = runnerWorkerGraph(loaded.config.resources({ env: run.env, domain: run.domain }))
689
769
  // Only a release Control named pins the entry or serves ops; a local deploy names none and keeps its authored `main`.
690
770
  const release = run.approved?.framework
@@ -699,11 +779,15 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
699
779
  // An older release's entry exports no object, and a Control older than the runner names no release (ADR-0062).
700
780
  const objectRuntime = run.approved === undefined || (run.approved.framework !== undefined && runsInObject(run.approved.framework))
701
781
  const entry = release !== undefined && pinsGeneratedEntry(release) ? resolve(loaded.cwd, GENERATED_ENTRY_FILE) : null
702
- const runtime = platformResources === 'refuse' && contract !== null && objectRuntime ? applicationRuntime(run, contract, entry) : null
782
+ const alarms = release !== undefined && servesAlarms(release)
783
+ const runtime = platformResources === 'refuse' && contract !== null && objectRuntime ? applicationRuntime(run, contract, entry, alarms) : null
703
784
  const managed = withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served))
704
785
  const identified = platformResources === 'refuse' ? withIamIdentity(managed.worker, appEnvironmentId(run.appId, run.env)) : managed.worker
705
786
  const connected = withConnectorBindings(identified, connectors)
706
- const worker = runtime === null ? connected : withApplicationRuntime(connected, run, runtime, opsRelease)
787
+ // An application Worker that declares its own `assets` keeps them; otherwise the platform stages the mounts' files.
788
+ const mounts = runtime !== null && contract !== null ? assetMounts(contract) : []
789
+ const spaAssets = mounts.length > 0 && applicationWorker(connected).options.assets === undefined ? { mounts, root: loaded.cwd } : null
790
+ const worker = runtime === null ? connected : withApplicationRuntime(connected, run, runtime, opsRelease, spaAssets !== null)
707
791
  const dir = workerDir(loaded.config, loaded.cwd)
708
792
  const bounds: DeploymentBounds = {
709
793
  env: run.env,
@@ -739,8 +823,92 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
739
823
  entryBuild: runtime !== null && runtime.entry !== null
740
824
  ? { cwd: loaded.cwd, config: basename(resolve(run.cwd, run.configPath)), root: resolve(run.cwd) }
741
825
  : null,
826
+ spaAssets,
742
827
  generatedConfigs: [],
743
828
  }
744
829
  const result = await runSteps(buildPlan(loaded.config, worker, env.entryBuild !== null), run, (step) => runStep(step, env))
745
830
  return { appId: run.appId, env: run.env, ...result }
746
831
  }
832
+
833
+ /** The SPA files `stageLocalAssets` staged for a local run: the mounts it copied, in the order a deploy stages them. */
834
+ export interface StagedLocalAssets {
835
+ readonly mounts: readonly AssetMount[]
836
+ readonly files: number
837
+ }
838
+
839
+ /**
840
+ * Stage the contract's SPA and link mounts for a local run, with the code a deploy stages them with: each mount's
841
+ * built directory under `root` into `root/fabrika/assets`, where the generated `wrangler.jsonc` beside the config points
842
+ * its `ASSETS`. Run it before oblaka generates the config (`await` at the top of `oblaka.ts`) and after the SPA build.
843
+ */
844
+ export const stageLocalAssets = async (contract: ContractArtifact, root: string): Promise<StagedLocalAssets> => {
845
+ const mounts = assetMounts(contract)
846
+ return { mounts, files: mounts.length === 0 ? 0 : await stageSpaAssets(mounts, root, root) }
847
+ }
848
+
849
+ const sameMounts = (left: readonly AssetMount[], right: readonly AssetMount[]): boolean =>
850
+ left.length === right.length && left.every((mount, index) => mount.prefix === right[index]?.prefix && mount.dir === right[index]?.dir)
851
+
852
+ /** What `composeLocalApplication` needs: the config, the contract it serves, and the IAM a local run reaches. */
853
+ export interface LocalApplicationOptions {
854
+ readonly config: CloudflareAppConfig
855
+ readonly contract: ContractArtifact
856
+ /** What `stageLocalAssets` staged; required when the contract has an SPA or link mount and the Worker no `assets`. */
857
+ readonly assets?: StagedLocalAssets
858
+ /** IAM's origin, the issuer of the local run's tokens. */
859
+ readonly iamOrigin: string
860
+ readonly env: string
861
+ readonly domain?: string
862
+ }
863
+
864
+ /**
865
+ * The proxy Worker and the application Worker of a local run (`oblaka.ts`, lopata), composed by the code a deploy runs:
866
+ * the platform's proxy over the contract's endpoint table, and the application's object, files bucket and repair tick,
867
+ * as a release that serves alarms gets them. No deploy takes it. With no Control to write them, the framework values
868
+ * come from here, and the proxy secret, which a deploy uploads as a Worker secret, is drawn anew on each call and
869
+ * written as a variable into the ignored `wrangler.jsonc`.
870
+ */
871
+ export const composeLocalApplication = (options: LocalApplicationOptions): Worker => {
872
+ const { config, contract, env } = options
873
+ const domain = options.domain === undefined ? {} : { domain: options.domain }
874
+ const iamAppId = appEnvironmentId(config.id, env)
875
+ const target: ApplicationTarget = {
876
+ appId: config.id,
877
+ env,
878
+ ...domain,
879
+ vars: {},
880
+ secrets: {},
881
+ managedEnvironment: parseManagedEnvironment({
882
+ [FABRIKA_IAM_ISSUER]: options.iamOrigin,
883
+ [FABRIKA_IAM_APP_ID]: iamAppId,
884
+ [FABRIKA_PROXY_SECRET]: `${crypto.randomUUID()}${crypto.randomUUID()}`.replaceAll('-', ''),
885
+ }),
886
+ }
887
+ // The local run reads the contract with this release, so it is gated as a local deploy is.
888
+ assertCloudflareContract(contract, { capsSegments: true, servesSql: true })
889
+ assertContractSchema(configSchema(config), contract, 'refuse')
890
+ const served: ServedContract = { contract, digest: contractDigest(contract) }
891
+ const proxied = platformProxied(config.resources({ env, ...domain }), served, target, false)
892
+ assertNoFrameworkVariables(config, applicationWorker(proxied), target)
893
+ const managed = withManagedEnvironment(config, proxied, target, contractEnvironment(target.managedEnvironment, served))
894
+ const application = applicationWorker(managed.worker)
895
+ const withSecrets = replaceApplicationWorker(
896
+ managed.worker,
897
+ new Worker({ ...application.options, vars: { ...application.options.vars, ...managed.secrets } }),
898
+ )
899
+ const identified = withIamIdentity(withSecrets, iamAppId)
900
+ const connected = withConnectorBindings(identified, connectorBindings(contract))
901
+ // As a deploy: a Worker that declares its own `assets` keeps them; otherwise the staged mounts are bound as `ASSETS`.
902
+ const mounts = assetMounts(contract)
903
+ const authoredAssets = applicationWorker(connected).options.assets !== undefined
904
+ if (authoredAssets && options.assets !== undefined) {
905
+ throw new Error('composeLocalApplication: the application Worker declares its own `assets`, so nothing is staged; drop `assets`')
906
+ }
907
+ const spaAssets = mounts.length > 0 && !authoredAssets
908
+ if (spaAssets && (options.assets === undefined || !sameMounts(options.assets.mounts, mounts))) {
909
+ throw new Error(
910
+ 'composeLocalApplication: the contract serves SPA files; stage them first with `await stageLocalAssets(contract, <application root>)` and pass its result as `assets`',
911
+ )
912
+ }
913
+ return withApplicationRuntime(connected, target, applicationRuntime(target, contract, null, true), false, spaAssets)
914
+ }
@@ -1,5 +1,5 @@
1
1
  import { contractArtifactSchema } from '@fabrika/app/contract'
2
- import { type ContractArtifact, isDigest } from '@fabrika/auth-core'
2
+ import { type ContractArtifact, isDigest, parseApplicationObjects } from '@fabrika/auth-core'
3
3
  import { FRAMEWORK_RELEASE_PATTERN } from '@fabrika/provider-contract'
4
4
  import { z } from 'zod'
5
5
 
@@ -29,6 +29,22 @@ export const CROSS_ORIGINS_ENV = 'FABRIKA_CROSS_ORIGINS'
29
29
  /** The executor's copy of `CloudflareRunnerJob.operationsOrigin`: the origin of the environment's Operations ingest. */
30
30
  export const OPERATIONS_ORIGIN_ENV = 'FABRIKA_OPERATIONS_ORIGIN'
31
31
 
32
+ /** The executor's copy of `CloudflareRunnerJob.applicationObjects`: JSON `{ object, objects }`, the pointer Control records. */
33
+ export const APPLICATION_OBJECTS_ENV = 'FABRIKA_RUNNER_APPLICATION_OBJECTS'
34
+
35
+ /**
36
+ * The serving object and the listed objects as the job and the executor carry them: the shape `parseApplicationObjects`
37
+ * accepts, so a pointer the application would refuse never reaches a deploy.
38
+ */
39
+ export const applicationObjectsSchema = z.object({ object: z.string(), objects: z.array(z.string()) }).strict().transform((value, ctx) => {
40
+ const parsed = parseApplicationObjects(value.object, value.objects.join(','))
41
+ if (parsed === null) {
42
+ ctx.addIssue({ code: 'custom', message: 'not a valid serving object and object list' })
43
+ return z.NEVER
44
+ }
45
+ return parsed
46
+ })
47
+
32
48
  /**
33
49
  * The access Control approved for a run (ADR-0050): the contract it read at the commit, in this release's model, and
34
50
  * the digest the application's own framework release computes for it. The proxy table and `FABRIKA_CONTRACT_DIGEST`
@@ -40,8 +56,10 @@ export interface RunnerApprovedAccess {
40
56
  readonly contract: ContractArtifact
41
57
  readonly contractDigest: string
42
58
  /**
43
- * The framework release whose reader read the application. It picks the Worker's shape: the Durable Object from
44
- * 0.9, the stateless Worker before it. Absent from a Control older than the runner, which deploys the older shape.
59
+ * The framework release the application pins (`applicationRelease`), which every release gate of the deployer reads:
60
+ * the Durable Object from 0.9, the stateless Worker before it. An older Control sends its reader's
61
+ * release here, a newer patch of the same minor. Absent from a Control older than the runner, which deploys the
62
+ * older shape.
45
63
  */
46
64
  readonly framework?: string
47
65
  }
@@ -0,0 +1,176 @@
1
+ // The SPA files of a contract application on Cloudflare. Workers Assets gives a Worker one directory, and a contract may
2
+ // declare several SPA and link mounts, each with a build directory of its own, so the deploy stages every mount's files
3
+ // into one directory that mirrors the request paths (`/admin/app.js` is `admin/app.js`), and the application's object
4
+ // serves a mount's paths from it (`bindingAssets` of `@fabrika/app`).
5
+
6
+ import { CLOUDFLARE_ASSETS_BINDING } from '@fabrika/app/build'
7
+ import type { ContractArtifact } from '@fabrika/auth-core'
8
+ import ignore, { type Ignore } from 'ignore'
9
+ import type { Stats } from 'node:fs'
10
+ import { copyFile, lstat, mkdir, readdir, readFile, rm } from 'node:fs/promises'
11
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
12
+
13
+ /** Where the deploy stages the mounts' files, beside the generated `wrangler.jsonc` of the application Worker. */
14
+ export const SPA_ASSETS_DIRECTORY = 'fabrika/assets'
15
+
16
+ /** The `assets` the platform writes into an application Worker that declares none and has a mount with files. */
17
+ export const SPA_ASSETS = { directory: SPA_ASSETS_DIRECTORY, binding: CLOUDFLARE_ASSETS_BINDING, run_worker_first: true } as const
18
+
19
+ /**
20
+ * The files Workers Assets reads as its own configuration at the root of the directory: a build that wrote them would
21
+ * steer the platform's asset routing and headers, so they are never staged.
22
+ */
23
+ const ASSET_CONFIG_PATHS: ReadonlySet<string> = new Set(['/_headers', '/_redirects', '/.assetsignore'])
24
+
25
+ /** A mount's own ignore file, read as wrangler reads the one at the root of an `assets.directory`. */
26
+ const ASSETS_IGNORE_FILE = '.assetsignore'
27
+
28
+ /** Version control metadata, never staged under any name or depth, whatever a mount's ignore file says. */
29
+ const VCS_NAMES: ReadonlySet<string> = new Set(['.git', '.hg', '.svn', '.bzr'])
30
+
31
+ /** A ceiling on the staging walk, as on the check of a published directory. */
32
+ const MAX_ASSET_ENTRIES = 50_000
33
+
34
+ /** A mount that serves files: its prefix, and its build directory relative to the application's root. */
35
+ export interface AssetMount {
36
+ readonly name: string
37
+ readonly prefix: string
38
+ readonly dir: string
39
+ }
40
+
41
+ /** Every SPA and link mount of the contract with the directory its files come from, the most specific prefix first. */
42
+ export const assetMounts = (contract: ContractArtifact): readonly AssetMount[] =>
43
+ Object.entries(contract.mounts)
44
+ .flatMap(([name, mount]): AssetMount[] =>
45
+ mount.kind === 'spa'
46
+ ? [{ name, prefix: mount.prefix, dir: mount.dir }]
47
+ : mount.kind === 'link'
48
+ ? [{ name, prefix: mount.prefix, dir: mount.spa }]
49
+ : []
50
+ )
51
+ .sort((left, right) => right.prefix.length - left.prefix.length || (left.prefix < right.prefix ? -1 : left.prefix > right.prefix ? 1 : 0))
52
+
53
+ /** The request path of `file` (relative, `/`-separated) of the mount at `prefix`. */
54
+ const requestPath = (prefix: string, file: string): string => (prefix === '/' ? `/${file}` : `${prefix}/${file}`)
55
+
56
+ /** Whether `path` is the mount at `prefix` or lies below it: the proxy routes it there, never to a shorter prefix. */
57
+ const isUnder = (path: string, prefix: string): boolean => prefix !== '/' && (path === prefix || path.startsWith(`${prefix}/`))
58
+
59
+ const lstatOrNull = async (path: string): Promise<Stats | null> => {
60
+ try {
61
+ return await lstat(path)
62
+ } catch (err) {
63
+ const code: unknown = err instanceof Error ? Reflect.get(err, 'code') : undefined
64
+ if (code === 'ENOENT' || code === 'ENOTDIR') return null
65
+ throw err
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Whether some segment of `relativePath` below `base` is a symbolic link, from the first segment to the last. `resolve`
71
+ * only reads the text, so `x/etc` with `x -> /` passes it; this reads the disk. A segment that does not exist ends it.
72
+ */
73
+ const linkOnPath = async (base: string, relativePath: string): Promise<string | null> => {
74
+ let current = base
75
+ for (const segment of relativePath.split('/').filter((part) => part !== '' && part !== '.')) {
76
+ current = join(current, segment)
77
+ const stats = await lstatOrNull(current)
78
+ if (stats === null) return null
79
+ if (stats.isSymbolicLink()) return relative(base, current)
80
+ }
81
+ return null
82
+ }
83
+
84
+ /**
85
+ * The mount's `.assetsignore` with wrangler's semantics (the `ignore` package, gitignore syntax, relative to the mount's
86
+ * directory), which also ignores the file itself. Workers Assets reads only the one at the root of the uploaded
87
+ * directory, so the deploy applies each mount's before it stages anything: a build excludes its files as it would with
88
+ * its own `assets`.
89
+ */
90
+ const mountIgnore = async (source: string, refuse: (detail: string) => Error): Promise<Ignore> => {
91
+ const rules = ignore().add(`/${ASSETS_IGNORE_FILE}`)
92
+ const path = join(source, ASSETS_IGNORE_FILE)
93
+ const stats = await lstatOrNull(path)
94
+ if (stats === null) return rules
95
+ if (!stats.isFile()) throw refuse(`contains \`${ASSETS_IGNORE_FILE}\`, which is not a regular file`)
96
+ return rules.add(await readFile(path, 'utf8'))
97
+ }
98
+
99
+ const isWithin = (root: string, path: string): boolean => {
100
+ const between = relative(root, path)
101
+ return between === '' || (!between.startsWith('..') && !isAbsolute(between))
102
+ }
103
+
104
+ /**
105
+ * Copy each mount's build directory under `root` into `target` at its prefix, after removing whatever `target` held. A
106
+ * file of a mount that lies under a longer mount's prefix is that mount's path, so it is left out; a source map is never
107
+ * served (the platform build uploads it to Operations), so it is left out too, and so is Workers Assets' own
108
+ * configuration at the root (`ASSET_CONFIG_PATHS`), what the mount's `.assetsignore` excludes, and version control
109
+ * metadata (`VCS_NAMES`) at any depth. A mount whose directory is missing, a symbolic link anywhere on
110
+ * its path or in its tree, or anything but a regular file or a directory is refused: the staged tree is uploaded
111
+ * publicly, and a link would publish its target. `target` is `SPA_ASSETS_DIRECTORY` under `base`, with no link on the
112
+ * way either. Returns how many files it staged.
113
+ */
114
+ export const stageSpaAssets = async (mounts: readonly AssetMount[], root: string, base: string): Promise<number> => {
115
+ const target = resolve(base, SPA_ASSETS_DIRECTORY)
116
+ const targetLink = await linkOnPath(base, SPA_ASSETS_DIRECTORY)
117
+ if (targetLink !== null) {
118
+ throw new Error(`cloudflare: \`${targetLink}\` is a symbolic link, and the deploy stages the SPA files into \`${SPA_ASSETS_DIRECTORY}\``)
119
+ }
120
+ const sources = mounts.map((mount) => {
121
+ const source = resolve(root, mount.dir)
122
+ const segments = mount.dir.split('/')
123
+ if (isAbsolute(mount.dir) || segments.includes('..') || segments.includes('.git') || !isWithin(root, source) || source === root) {
124
+ throw new Error(`cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which is no directory inside the application`)
125
+ }
126
+ if (isWithin(source, target) || isWithin(target, source)) {
127
+ throw new Error(
128
+ `cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which overlaps \`${SPA_ASSETS_DIRECTORY}\`, where the deploy stages the SPA files`,
129
+ )
130
+ }
131
+ return { mount, source }
132
+ })
133
+ await rm(target, { recursive: true, force: true })
134
+ await mkdir(target, { recursive: true })
135
+ let entries = 0
136
+ let staged = 0
137
+ for (const { mount, source } of sources) {
138
+ const refuse = (detail: string): Error => new Error(`cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which ${detail}`)
139
+ const link = await linkOnPath(root, mount.dir)
140
+ if (link !== null) throw refuse(`passes \`${link}\`, a symbolic link; the deploy would publish its target`)
141
+ const stats = await lstatOrNull(source)
142
+ if (stats === null) {
143
+ throw refuse('the build did not produce; build it in `pipeline.build`')
144
+ }
145
+ if (!stats.isDirectory()) {
146
+ throw refuse(stats.isSymbolicLink() ? 'is a symbolic link; the deploy would publish its target' : 'is not a directory')
147
+ }
148
+ const ignored = await mountIgnore(source, refuse)
149
+ const longer = mounts.filter((other) => other.prefix.length > mount.prefix.length).map((other) => other.prefix)
150
+ const walk = async (prefix: string): Promise<void> => {
151
+ for (const name of (await readdir(join(source, prefix))).sort()) {
152
+ entries += 1
153
+ if (entries > MAX_ASSET_ENTRIES) throw refuse(`holds more than ${MAX_ASSET_ENTRIES} entries with the other mounts`)
154
+ const file = prefix === '' ? name : `${prefix}/${name}`
155
+ const path = requestPath(mount.prefix, file)
156
+ if (VCS_NAMES.has(name) || longer.some((other) => isUnder(path, other)) || ASSET_CONFIG_PATHS.has(path)) continue
157
+ const entry = await lstat(join(source, file))
158
+ // The trailing `/` is how the matcher tells a directory, so `secret/` excludes the directory and all below it.
159
+ if (ignored.ignores(entry.isDirectory() ? `${file}/` : file)) continue
160
+ if (entry.isSymbolicLink()) throw refuse(`contains \`${file}\`, a symbolic link; the deploy would publish its target`)
161
+ if (entry.isDirectory()) {
162
+ await walk(file)
163
+ } else if (!entry.isFile()) {
164
+ throw refuse(`contains \`${file}\`, which is neither a regular file nor a directory`)
165
+ } else if (!file.endsWith('.map')) {
166
+ const destination = join(target, path.slice(1))
167
+ await mkdir(dirname(destination), { recursive: true })
168
+ await copyFile(join(source, file), destination)
169
+ staged += 1
170
+ }
171
+ }
172
+ }
173
+ await walk('')
174
+ }
175
+ return staged
176
+ }