@fabrika/provider-cloudflare 0.9.0-cloudflare.2 → 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,7 +41,17 @@ 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'
@@ -71,11 +87,17 @@ const assertRunning = (signal: AbortSignal): void => {
71
87
  }
72
88
  }
73
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
+
74
96
  /** The bindings the platform writes into a contract application's Worker (ADR-0065). */
75
97
  const PLATFORM_BINDINGS: ReadonlySet<string> = new Set([CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_FILES_BINDING])
76
98
 
77
99
  /** An application never names a variable only the platform writes, whether or not this deploy writes it. */
78
- const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: CloudflareDeployRun): void => {
100
+ const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: ApplicationTarget): void => {
79
101
  const authored = [
80
102
  ...(config.pipeline?.vars ?? []),
81
103
  ...(config.pipeline?.secrets ?? []),
@@ -100,7 +122,7 @@ const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Wo
100
122
  const withManagedEnvironment = (
101
123
  config: CloudflareAppConfig,
102
124
  authored: Worker,
103
- run: CloudflareDeployRun,
125
+ run: ApplicationTarget,
104
126
  managed: ProviderManagedEnvironment,
105
127
  ): { readonly worker: Worker; readonly secrets: Readonly<Record<string, string>> } => {
106
128
  const declared = new Set([...(config.pipeline?.vars ?? []), ...(config.pipeline?.secrets ?? [])])
@@ -117,7 +139,7 @@ const withManagedEnvironment = (
117
139
  const configured = new Worker({
118
140
  ...application.options,
119
141
  vars: {
120
- ...(application.options.vars ?? {}),
142
+ ...application.options.vars,
121
143
  ...vars,
122
144
  },
123
145
  })
@@ -131,7 +153,7 @@ const R2_BUCKET_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/
131
153
  const filesBucketName = (appId: string): string => `${appId}-files`
132
154
 
133
155
  /** The remote name oblaka gives the files bucket; it prefixes a bucket with the environment, `local` included. */
134
- const filesBucketRemote = (run: CloudflareDeployRun): string => {
156
+ const filesBucketRemote = (run: ApplicationTarget): string => {
135
157
  const remote = `${run.env}-${filesBucketName(run.appId)}`
136
158
  if (!R2_BUCKET_NAME.test(remote)) {
137
159
  throw new Error(
@@ -143,10 +165,22 @@ const filesBucketRemote = (run: CloudflareDeployRun): string => {
143
165
 
144
166
  const MINUTE_TICK = '* * * * *'
145
167
 
146
- /** What the platform gives a contract application's Worker; the deployer writes exactly this and the bounds check it. */
147
- 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 => ({
148
182
  filesBucket: filesBucketRemote(run),
149
- crons: needsMinuteTick(contract) ? [MINUTE_TICK] : [],
183
+ crons: needsMinuteTick(contract) ? [alarms ? repairTick(run) : MINUTE_TICK] : [],
150
184
  entry,
151
185
  })
152
186
 
@@ -217,21 +251,27 @@ const buildEntry = async (build: EntryBuild, run: CloudflareDeployRun, cf: Cloud
217
251
  if (result.exitCode !== 0) throw commandError('fabrika app build', result)
218
252
  }
219
253
 
220
- /** The object variables of a release that serves ops (ADR-0069): ordinary traffic and ops requests reach `application`. */
221
- const OBJECT_VARIABLES: Readonly<Record<string, string>> = {
222
- [FABRIKA_APPLICATION_OBJECT]: DEFAULT_APPLICATION_OBJECT,
223
- [FABRIKA_APPLICATION_OBJECTS]: DEFAULT_APPLICATION_OBJECT,
224
- }
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
+ })
225
265
 
226
266
  /**
227
267
  * Bind the application's Durable Object, which runs the application over its SQLite, the environment's files bucket,
228
- * and the minute tick (ADR-0065), and on a release that serves ops name its objects. The object is bound first, so
268
+ * and its cron trigger (ADR-0065), and on a release that serves ops name its objects. The object is bound first, so
229
269
  * oblaka numbers its migration `v0001` whatever else the application binds, and the tag never moves. With `assets`,
230
270
  * the Worker also gets the Workers Assets the deploy stages the mounts' files into (`SPA_ASSETS`).
231
271
  */
232
272
  const withApplicationRuntime = (
233
273
  authored: Worker,
234
- run: CloudflareDeployRun,
274
+ run: ApplicationTarget,
235
275
  runtime: ApplicationRuntime,
236
276
  ops: boolean,
237
277
  assets: boolean,
@@ -239,11 +279,11 @@ const withApplicationRuntime = (
239
279
  const application = applicationWorker(authored)
240
280
  const configured = new Worker({
241
281
  ...application.options,
242
- ...(ops ? { vars: { ...(application.options.vars ?? {}), ...OBJECT_VARIABLES } } : {}),
282
+ ...(ops ? { vars: { ...application.options.vars, ...objectVariables(run.applicationObjects ?? DEFAULT_OBJECTS) } } : {}),
243
283
  ...(assets ? { assets: { ...SPA_ASSETS } } : {}),
244
284
  bindings: {
245
285
  [CLOUDFLARE_APPLICATION_BINDING]: new DurableObject({ name: `${run.appId}-application`, className: CLOUDFLARE_APPLICATION_CLASS }),
246
- ...(application.options.bindings ?? {}),
286
+ ...application.options.bindings,
247
287
  [CLOUDFLARE_FILES_BINDING]: new R2Bucket({ name: filesBucketName(run.appId) }),
248
288
  },
249
289
  // Always written: wrangler leaves a Worker's schedules alone when `triggers` is absent, and clears them on `[]`.
@@ -286,7 +326,7 @@ const withConnectorBindings = (authored: Worker, bindings: Readonly<Record<strin
286
326
  const configured = new Worker({
287
327
  ...application.options,
288
328
  bindings: {
289
- ...(application.options.bindings ?? {}),
329
+ ...application.options.bindings,
290
330
  ...Object.fromEntries(Object.entries(bindings).map(([binding, worker]) => [binding, new ServiceReference(worker)])),
291
331
  },
292
332
  })
@@ -310,14 +350,16 @@ const contractEnvironment = (managed: ProviderManagedEnvironment, served: Served
310
350
 
311
351
  /**
312
352
  * The lock-down follows the contract, not the config: a contract whose IAM schema does not say `contract: true`, or a
313
- * 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.
314
356
  */
315
- const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifact | null): void => {
357
+ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifact | null, platformResources: 'refuse' | 'allow'): void => {
316
358
  const declared = schema?.contract === true
317
359
  if (contract === null && declared) {
318
360
  throw new Error('cloudflare: the IAM schema says `contract: true`, but the checkout has no `fabrika.contract.ts`')
319
361
  }
320
- if (contract !== null && !declared) {
362
+ if (contract !== null && !declared && (schema !== null || platformResources === 'allow')) {
321
363
  throw new Error('cloudflare: this deployment serves a contract, so its IAM schema is `schemaFromContract(artifact)` (`contract: true`)')
322
364
  }
323
365
  }
@@ -327,7 +369,7 @@ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifa
327
369
  * application Worker the config returns, never taken from the checkout. A config that returns a proxy is refused.
328
370
  * `ops` adds Control's ops row to the table.
329
371
  */
330
- const platformProxied = (authored: Worker, served: ServedContract, run: CloudflareDeployRun, ops: boolean): Worker => {
372
+ const platformProxied = (authored: Worker, served: ServedContract, run: ApplicationTarget, ops: boolean): Worker => {
331
373
  if (authored.options.bindings?.['APP'] !== undefined) {
332
374
  throw new Error(
333
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`,
@@ -351,7 +393,7 @@ const platformProxied = (authored: Worker, served: ServedContract, run: Cloudfla
351
393
  }
352
394
 
353
395
  /** The origin of the environment's Operations ingest, which the proxy's `connect-src` admits, as the framework's does. */
354
- const operationsOrigin = (run: CloudflareDeployRun): { readonly operationsOrigin?: string } => {
396
+ const operationsOrigin = (run: ApplicationTarget): { readonly operationsOrigin?: string } => {
355
397
  if (run.operationsOrigin !== undefined) return { operationsOrigin: run.operationsOrigin }
356
398
  // A job from an older Control names no origin; derive it from the DSN until no release in the window omits it.
357
399
  const dsn = managedValue(run.managedEnvironment, 'FABRIKA_OPERATIONS_DSN')
@@ -378,7 +420,7 @@ const replaceApplicationWorker = (worker: Worker, replacement: Worker): Worker =
378
420
  return new Worker({
379
421
  ...worker.options,
380
422
  bindings: {
381
- ...(worker.options.bindings ?? {}),
423
+ ...worker.options.bindings,
382
424
  APP: replaceApplicationWorker(child, replacement),
383
425
  },
384
426
  })
@@ -553,7 +595,8 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
553
595
  return
554
596
  }
555
597
  const application = `${run.env}-${applicationWorker(worker).options.name}`
556
- for (const generated of configs) {
598
+ let applicationDir: string | undefined
599
+ for (const generated of deployOrder(configs)) {
557
600
  const generatedDir = dirname(resolve(dir, generated.path))
558
601
  const isApplication = generated.config.name === application
559
602
  // The checkout's build has written the mounts' directories; the walk below checks the staged copy.
@@ -561,9 +604,11 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
561
604
  // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
562
605
  if (env.platformResources === 'refuse') await assertLiteralAssets(generated, generatedDir)
563
606
  await wranglerDeploy(env, generatedDir, isApplication ? env.managedSecrets : {})
564
- // A platform component's own secrets carry framework names (IAM's mail transport), so only an application's are swept.
565
- if (isApplication && env.platformResources === 'refuse') await deleteStaleSecrets(env, generatedDir)
607
+ if (isApplication) applicationDir = generatedDir
566
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)
567
612
  return
568
613
  }
569
614
  case 'reconcile-schema': {
@@ -674,6 +719,8 @@ export interface CloudflareDeployRun {
674
719
  readonly approved?: RunnerApprovedAccess
675
720
  /** Every Cloudflare deployment of the installation in Control's registry; a name of another application is refused. */
676
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
677
724
  readonly dryRun: boolean
678
725
  readonly signal: AbortSignal
679
726
  readonly log: (line: string) => void
@@ -709,10 +756,15 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
709
756
  if (platformResources === 'refuse' && served === null) {
710
757
  throw new Error('cloudflare: the checkout has no `fabrika.contract.ts`; Fabrika deploys an application only with a contract')
711
758
  }
712
- 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)
713
765
  // Read once, before `resources()` runs the checkout's code again: nothing below reads the config's schema.
714
766
  const schema = configSchema(loaded.config)
715
- assertContractSchema(schema, contract)
767
+ assertContractSchema(schema, contract, platformResources)
716
768
  const authored = runnerWorkerGraph(loaded.config.resources({ env: run.env, domain: run.domain }))
717
769
  // Only a release Control named pins the entry or serves ops; a local deploy names none and keeps its authored `main`.
718
770
  const release = run.approved?.framework
@@ -727,7 +779,8 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
727
779
  // An older release's entry exports no object, and a Control older than the runner names no release (ADR-0062).
728
780
  const objectRuntime = run.approved === undefined || (run.approved.framework !== undefined && runsInObject(run.approved.framework))
729
781
  const entry = release !== undefined && pinsGeneratedEntry(release) ? resolve(loaded.cwd, GENERATED_ENTRY_FILE) : null
730
- 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
731
784
  const managed = withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served))
732
785
  const identified = platformResources === 'refuse' ? withIamIdentity(managed.worker, appEnvironmentId(run.appId, run.env)) : managed.worker
733
786
  const connected = withConnectorBindings(identified, connectors)
@@ -776,3 +829,86 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
776
829
  const result = await runSteps(buildPlan(loaded.config, worker, env.entryBuild !== null), run, (step) => runStep(step, env))
777
830
  return { appId: run.appId, env: run.env, ...result }
778
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
  }
package/src/spa-assets.ts CHANGED
@@ -5,8 +5,9 @@
5
5
 
6
6
  import { CLOUDFLARE_ASSETS_BINDING } from '@fabrika/app/build'
7
7
  import type { ContractArtifact } from '@fabrika/auth-core'
8
+ import ignore, { type Ignore } from 'ignore'
8
9
  import type { Stats } from 'node:fs'
9
- import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises'
10
+ import { copyFile, lstat, mkdir, readdir, readFile, rm } from 'node:fs/promises'
10
11
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
11
12
 
12
13
  /** Where the deploy stages the mounts' files, beside the generated `wrangler.jsonc` of the application Worker. */
@@ -21,6 +22,12 @@ export const SPA_ASSETS = { directory: SPA_ASSETS_DIRECTORY, binding: CLOUDFLARE
21
22
  */
22
23
  const ASSET_CONFIG_PATHS: ReadonlySet<string> = new Set(['/_headers', '/_redirects', '/.assetsignore'])
23
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
+
24
31
  /** A ceiling on the staging walk, as on the check of a published directory. */
25
32
  const MAX_ASSET_ENTRIES = 50_000
26
33
 
@@ -74,6 +81,21 @@ const linkOnPath = async (base: string, relativePath: string): Promise<string |
74
81
  return null
75
82
  }
76
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
+
77
99
  const isWithin = (root: string, path: string): boolean => {
78
100
  const between = relative(root, path)
79
101
  return between === '' || (!between.startsWith('..') && !isAbsolute(between))
@@ -83,7 +105,8 @@ const isWithin = (root: string, path: string): boolean => {
83
105
  * Copy each mount's build directory under `root` into `target` at its prefix, after removing whatever `target` held. A
84
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
85
107
  * served (the platform build uploads it to Operations), so it is left out too, and so is Workers Assets' own
86
- * configuration at the root (`ASSET_CONFIG_PATHS`). A mount whose directory is missing, a symbolic link anywhere on
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
87
110
  * its path or in its tree, or anything but a regular file or a directory is refused: the staged tree is uploaded
88
111
  * publicly, and a link would publish its target. `target` is `SPA_ASSETS_DIRECTORY` under `base`, with no link on the
89
112
  * way either. Returns how many files it staged.
@@ -122,6 +145,7 @@ export const stageSpaAssets = async (mounts: readonly AssetMount[], root: string
122
145
  if (!stats.isDirectory()) {
123
146
  throw refuse(stats.isSymbolicLink() ? 'is a symbolic link; the deploy would publish its target' : 'is not a directory')
124
147
  }
148
+ const ignored = await mountIgnore(source, refuse)
125
149
  const longer = mounts.filter((other) => other.prefix.length > mount.prefix.length).map((other) => other.prefix)
126
150
  const walk = async (prefix: string): Promise<void> => {
127
151
  for (const name of (await readdir(join(source, prefix))).sort()) {
@@ -129,8 +153,10 @@ export const stageSpaAssets = async (mounts: readonly AssetMount[], root: string
129
153
  if (entries > MAX_ASSET_ENTRIES) throw refuse(`holds more than ${MAX_ASSET_ENTRIES} entries with the other mounts`)
130
154
  const file = prefix === '' ? name : `${prefix}/${name}`
131
155
  const path = requestPath(mount.prefix, file)
132
- if (longer.some((other) => isUnder(path, other)) || ASSET_CONFIG_PATHS.has(path)) continue
156
+ if (VCS_NAMES.has(name) || longer.some((other) => isUnder(path, other)) || ASSET_CONFIG_PATHS.has(path)) continue
133
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
134
160
  if (entry.isSymbolicLink()) throw refuse(`contains \`${file}\`, a symbolic link; the deploy would publish its target`)
135
161
  if (entry.isDirectory()) {
136
162
  await walk(file)
@@ -1,17 +1,39 @@
1
1
  import { type AppConfigBase, type ProviderAuthoredApp } from '@fabrika/provider-contract';
2
- import type { Worker } from 'oblaka-iac';
2
+ import { Worker } from 'oblaka-iac';
3
3
  /** Inputs used to materialize one environment's Cloudflare resource graph. */
4
4
  export interface ResourceContext {
5
5
  readonly env: string;
6
6
  readonly domain?: string;
7
7
  }
8
+ /** What an author may set on the application Worker `defineApp` builds; everything else is fixed by the platform. */
9
+ export interface ApplicationWorkerOptions {
10
+ /** The application's own bindings, beside `IAM`, which is always the platform's. */
11
+ readonly bindings?: Worker['options']['bindings'];
12
+ readonly compatibility_date?: string;
13
+ readonly compatibility_flags?: Worker['options']['compatibility_flags'];
14
+ }
15
+ /** A Cloudflare app config as `fabrika.config.ts` writes it. */
16
+ export type CloudflareAppConfigInput = AppConfigBase & ({
17
+ /**
18
+ * The application Worker, for a config that composes its own. The deployer builds the proxy Worker in front of it
19
+ * from the contract (ADR-0048); never return one.
20
+ */
21
+ readonly resources: (ctx: ResourceContext) => Worker;
22
+ readonly worker?: never;
23
+ } | {
24
+ readonly resources?: never;
25
+ /** Without `resources`, `defineApp` builds the application Worker from these and the platform's fixed values. */
26
+ readonly worker?: ApplicationWorkerOptions;
27
+ });
8
28
  /** A Cloudflare app config loaded from `fabrika.config.ts` inside the runner checkout. */
9
- export interface CloudflareAppConfigInput extends AppConfigBase {
10
- /** The application Worker. The deployer builds the proxy Worker in front of it from the contract (ADR-0048); never return one. */
29
+ export interface CloudflareAppConfig extends AppConfigBase, ProviderAuthoredApp<'cloudflare'> {
30
+ /** The application Worker. The deployer builds the proxy Worker in front of it from the contract (ADR-0048). */
11
31
  readonly resources: (ctx: ResourceContext) => Worker;
12
32
  }
13
- export type CloudflareAppConfig = CloudflareAppConfigInput & ProviderAuthoredApp<'cloudflare'>;
14
- /** Preserve literal inference while validating the provider's required app id. */
33
+ /**
34
+ * Validate the app id and fill in the application Worker when the config composes none. The result always carries
35
+ * `resources`, because a runner narrows a loaded config with `isCloudflareAppConfig`, which requires it.
36
+ */
15
37
  export declare function defineApp(config: CloudflareAppConfigInput): CloudflareAppConfig;
16
38
  /** Narrow an imported module default without trusting code from the checkout. */
17
39
  export declare const isCloudflareAppConfig: (value: unknown) => value is CloudflareAppConfig;
@@ -34,11 +34,14 @@ export interface DeploymentBounds {
34
34
  /** What the platform gives a contract application's Worker (ADR-0065), or null outside one. */
35
35
  readonly application: ApplicationRuntime | null;
36
36
  }
37
- /** The Durable Object, files bucket and minute tick of a contract application's Worker; the application authors none of them. */
37
+ /** The Durable Object, files bucket and cron trigger of a contract application's Worker; the application authors none of them. */
38
38
  export interface ApplicationRuntime {
39
39
  /** The remote name of the environment's files bucket. */
40
40
  readonly filesBucket: string;
41
- /** The cron triggers the Worker carries: the minute tick when the contract has a job or a file kind, else an empty list. */
41
+ /**
42
+ * The cron triggers the Worker carries when the contract has a job or a file kind, else an empty list: the hourly repair
43
+ * tick of a release that serves alarms, otherwise the minute tick.
44
+ */
42
45
  readonly crons: readonly string[];
43
46
  /**
44
47
  * The absolute path of the entry the deploy regenerates, which the Worker's `main` must name (`pinsGeneratedEntry`), or
@@ -1,4 +1,4 @@
1
- import { type AppEnvironment } from '@fabrika/auth-core';
1
+ import { type AppEnvironment, type ApplicationObjects } from '@fabrika/auth-core';
2
2
  import type { CloudflareAppConfig } from './authoring';
3
3
  import { type CloudflareDeployResult, type PlatformIamTarget } from './provider';
4
4
  import { type RunnerApprovedAccess } from './runner-protocol';
@@ -14,6 +14,11 @@ export declare const parseReturnOrigins: (raw: string | undefined) => readonly s
14
14
  * empty; anything malformed fails the deploy, and the proxy manifest's own parser judges each origin.
15
15
  */
16
16
  export declare const parseCrossOrigins: (raw: string | undefined) => readonly string[] | undefined;
17
+ /**
18
+ * Decode `FABRIKA_RUNNER_APPLICATION_OBJECTS`, the pointer Control recorded, as the runner writes it. Undefined when
19
+ * absent, and the deployer writes its defaults; anything malformed fails the deploy rather than move ordinary traffic.
20
+ */
21
+ export declare const parseApplicationObjectsEnvironment: (raw: string | undefined) => ApplicationObjects | undefined;
17
22
  /**
18
23
  * Decode `FABRIKA_INSTALLATION_APPS`, the Cloudflare deployments Control registered, as the runner writes it.
19
24
  * Undefined when absent; anything malformed fails the deploy rather than dropping the refusal it feeds.
@@ -5,14 +5,23 @@ import type { ProviderManagedEnvironment } from '@fabrika/provider-contract';
5
5
  * workerd resets an object whose transaction runs about 30 s (docs/reference/cloudflare-platform.md).
6
6
  */
7
7
  export declare const CLOUDFLARE_MAX_HANDLER_MS = 25000;
8
+ /** What the release a caller runs a contract as decides about it; each caller reads them off that release. */
9
+ export interface CloudflareContractGates {
10
+ /** The release caps a job at one segment (`capsJobSegments`). */
11
+ readonly capsSegments: boolean;
12
+ /** The release runs `ctx.sql` on the object's SQLite (`servesRawSql`). */
13
+ readonly servesSql: boolean;
14
+ }
8
15
  /**
9
16
  * Refuse what a contract declares that an application on Cloudflare cannot run yet (ADR-0065): a file kind that scans
10
- * its uploads, raw SQL (`ctx.sql`), and a handler allowed to outlive the object's transaction limit.
17
+ * its uploads, a handler allowed to outlive the object's transaction limit, and, by the release it runs as, a job longer
18
+ * than one segment and raw SQL (`ctx.sql`).
11
19
  */
12
- export declare const assertCloudflareContract: (contract: ContractArtifact) => void;
20
+ export declare const assertCloudflareContract: (contract: ContractArtifact, { capsSegments, servesSql }: CloudflareContractGates) => void;
13
21
  /**
14
- * The object runs due jobs and the file sweep of file kinds, a framework job, on the Worker's minute tick (ADR-0065 §5).
15
- * Legacy `files` collections do not count: the object schedules no sweep of theirs.
22
+ * The object runs due jobs and the file sweep of file kinds, a framework job, from the Worker's cron trigger: the minute
23
+ * tick, or from `servesAlarms` its alarm with an hourly repair tick (ADR-0065 §5). Legacy `files` collections do not
24
+ * count: the object schedules no sweep of theirs.
16
25
  */
17
26
  export declare const needsMinuteTick: (contract: ContractArtifact) => boolean;
18
27
  /**
@@ -32,6 +41,38 @@ export declare const runsInObject: (release: string) => boolean;
32
41
  export declare const pinsGeneratedEntry: (release: string) => boolean;
33
42
  /** Whether an environment on release `release` gets the ops row, the ops key digests and the object variables. */
34
43
  export declare const servesOps: (release: string) => boolean;
44
+ /**
45
+ * Whether framework release `release` is at or above the exact version `since` in semver's precedence, prerelease
46
+ * included; a release that is not a semver version never is (ADR-0062).
47
+ */
48
+ export declare const releaseFrom: (release: string, since: string) => boolean;
49
+ /**
50
+ * The release a gate reads for an approved access: the application's pin, never the reader's `checker`, which is this
51
+ * platform's patch of the pin's minor and so passes a `releaseFrom` gate a prerelease pin does not. An access approved before Control recorded the pin is read as the oldest release of its
52
+ * reader's minor (`<major>.<minor>.0-0`): every `releaseAtLeast` gate answers as for that minor, and every `releaseFrom`
53
+ * gate of a prerelease or a patch fails closed, as for an older application, until a deploy reads its pin.
54
+ */
55
+ export declare const applicationRelease: (access: {
56
+ readonly checker: string;
57
+ readonly framework?: string;
58
+ }) => string;
59
+ /**
60
+ * Whether the object of release `release` holds the maintenance barrier and serves Control's data operations: the
61
+ * backups, the migration phase and the side restore (ADR-0069 §3, ADR-0070).
62
+ */
63
+ export declare const servesDataOperations: (release: string) => boolean;
64
+ /**
65
+ * Whether the Worker of release `release` gets the hourly repair tick instead of the minute tick: an older object runs
66
+ * its jobs only from the minute tick and has no alarm.
67
+ */
68
+ export declare const servesAlarms: (release: string) => boolean;
69
+ /**
70
+ * Whether the Cloudflare deploy of release `release` refuses a job whose `timeoutMs` exceeds one segment
71
+ * (`CLOUDFLARE_MAX_JOB_SEGMENT_MS`). An older release deploys as it did (ADR-0062).
72
+ */
73
+ export declare const capsJobSegments: (release: string) => boolean;
74
+ /** Whether an application on release `release` may declare `sql` on Cloudflare. */
75
+ export declare const servesRawSql: (release: string) => boolean;
35
76
  /**
36
77
  * Refuse what a stateless Worker of an older release cannot run: a job, a webhook, a public procedure, installation
37
78
  * mail and token purposes all need the object's database or a Worker secret it never reads.