@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
@@ -0,0 +1,235 @@
1
+ import { CLOUDFLARE_MAX_JOB_SEGMENT_MS } from '@fabrika/app/contract'
2
+ import {
3
+ type ContractArtifact,
4
+ FABRIKA_TOKEN_KEYS,
5
+ isEmailTransportVariable,
6
+ isPlatformTransportVariable,
7
+ isWorkloadKeyVariable,
8
+ managedValue,
9
+ } from '@fabrika/auth-core'
10
+ import type { ProviderManagedEnvironment } from '@fabrika/provider-contract'
11
+
12
+ // Imported by `./control` (the `./runner` entry), so it stays clear of `oblaka-iac`.
13
+
14
+ /**
15
+ * The longest a procedure's or a webhook's handler may run on Cloudflare. It runs inside the object's transaction, and
16
+ * workerd resets an object whose transaction runs about 30 s (docs/reference/cloudflare-platform.md).
17
+ */
18
+ export const CLOUDFLARE_MAX_HANDLER_MS = 25_000
19
+
20
+ /** What the release a caller runs a contract as decides about it; each caller reads them off that release. */
21
+ export interface CloudflareContractGates {
22
+ /** The release caps a job at one segment (`capsJobSegments`). */
23
+ readonly capsSegments: boolean
24
+ /** The release runs `ctx.sql` on the object's SQLite (`servesRawSql`). */
25
+ readonly servesSql: boolean
26
+ }
27
+
28
+ /**
29
+ * Refuse what a contract declares that an application on Cloudflare cannot run yet (ADR-0065): a file kind that scans
30
+ * its uploads, a handler allowed to outlive the object's transaction limit, and, by the release it runs as, a job longer
31
+ * than one segment and raw SQL (`ctx.sql`).
32
+ */
33
+ export const assertCloudflareContract = (contract: ContractArtifact, { capsSegments, servesSql }: CloudflareContractGates): void => {
34
+ const handlers: [string, number][] = [
35
+ ...Object.entries(contract.procedures ?? {}).map(([id, procedure]): [string, number] => [`procedure \`${id}\``, procedure.timeoutMs]),
36
+ ...Object.entries(contract.mounts).flatMap(([name, mount]): [string, number][] =>
37
+ mount.kind === 'webhook' ? [[`webhook \`${name}\``, mount.timeoutMs]] : []
38
+ ),
39
+ ]
40
+ for (const [subject, timeoutMs] of handlers) {
41
+ if (timeoutMs > CLOUDFLARE_MAX_HANDLER_MS) {
42
+ throw new Error(
43
+ `cloudflare: ${subject} runs up to ${timeoutMs} ms, and a handler on Cloudflare runs at most ${CLOUDFLARE_MAX_HANDLER_MS} ms: it holds its Durable Object's transaction`,
44
+ )
45
+ }
46
+ }
47
+ if (capsSegments) {
48
+ for (const [name, job] of Object.entries(contract.jobs)) {
49
+ if (job.timeoutMs > CLOUDFLARE_MAX_JOB_SEGMENT_MS) {
50
+ throw new Error(
51
+ `cloudflare: job \`${name}\` runs up to ${job.timeoutMs} ms, and a job segment on Cloudflare runs at most ${CLOUDFLARE_MAX_JOB_SEGMENT_MS} ms: claim a bounded batch per run and let the next run take the rest; a Workflow for one longer run is planned (backlog 230)`,
52
+ )
53
+ }
54
+ }
55
+ }
56
+ for (const [name, kind] of Object.entries(contract.fileKinds ?? {})) {
57
+ if (kind.scan === true) {
58
+ throw new Error(`cloudflare: file kind \`${name}\` scans its uploads (\`scan: true\`), and no scanner runs on Cloudflare yet`)
59
+ }
60
+ }
61
+ for (const [name, collection] of Object.entries(contract.files)) {
62
+ if (collection.scan === true) {
63
+ throw new Error(`cloudflare: file collection \`${name}\` scans its uploads (\`scan: true\`), and no scanner runs on Cloudflare yet`)
64
+ }
65
+ }
66
+ if (!servesSql) {
67
+ for (const [site, reach] of Object.entries(contract.declared ?? {})) {
68
+ if (reach.sql !== null) {
69
+ throw new Error(
70
+ `cloudflare: \`${site}\` declares raw SQL (\`ctx.sql\`), which an application on Cloudflare runs from framework ${RAW_SQL_SINCE} on; upgrade its framework`,
71
+ )
72
+ }
73
+ }
74
+ }
75
+ }
76
+
77
+ /**
78
+ * The object runs due jobs and the file sweep of file kinds, a framework job, from the Worker's cron trigger: the minute
79
+ * tick, or from `servesAlarms` its alarm with an hourly repair tick (ADR-0065 §5). Legacy `files` collections do not
80
+ * count: the object schedules no sweep of theirs.
81
+ */
82
+ export const needsMinuteTick = (contract: ContractArtifact): boolean =>
83
+ Object.keys(contract.jobs).length > 0 || Object.keys(contract.fileKinds ?? {}).length > 0
84
+
85
+ /**
86
+ * Whether framework release `release` is at least `since`. A prerelease counts as its `major.minor`; a release that
87
+ * does not start with `<major>.<minor>.` is never at least anything (ADR-0062).
88
+ */
89
+ export const releaseAtLeast = (release: string, since: { readonly major: number; readonly minor: number }): boolean => {
90
+ const match = /^(\d+)\.(\d+)\./.exec(release)
91
+ if (match === null) return false
92
+ const major = Number(match[1])
93
+ return major > since.major || (major === since.major && Number(match[2]) >= since.minor)
94
+ }
95
+
96
+ /** The first framework minor whose Cloudflare entry exports the application's Durable Object (ADR-0065). */
97
+ const OBJECT_RUNTIME_SINCE = { major: 0, minor: 9 }
98
+
99
+ /**
100
+ * Whether an application on framework release `release` runs in its Durable Object. An older release's entry is a
101
+ * stateless Worker, which the platform keeps deploying in its old shape (ADR-0062).
102
+ */
103
+ export const runsInObject = (release: string): boolean => releaseAtLeast(release, OBJECT_RUNTIME_SINCE)
104
+
105
+ /** The first framework minor whose Cloudflare deploy pins the generated entry. */
106
+ const PINNED_ENTRY_SINCE = { major: 0, minor: 9 }
107
+
108
+ /** Whether the Cloudflare deploy of release `release` accepts only the generated entry and regenerates it. */
109
+ export const pinsGeneratedEntry = (release: string): boolean => releaseAtLeast(release, PINNED_ENTRY_SINCE)
110
+
111
+ /** The first framework minor whose application object serves Control's ops row (ADR-0069). */
112
+ const SERVES_OPS_SINCE = { major: 0, minor: 9 }
113
+
114
+ /** Whether an environment on release `release` gets the ops row, the ops key digests and the object variables. */
115
+ export const servesOps = (release: string): boolean => releaseAtLeast(release, SERVES_OPS_SINCE)
116
+
117
+ /** A release as semver orders it: the numeric core, then the prerelease identifiers (none sorts above any). */
118
+ interface ReleaseVersion {
119
+ readonly core: readonly number[]
120
+ readonly prerelease: readonly string[]
121
+ }
122
+
123
+ const parseReleaseVersion = (release: string): ReleaseVersion | null => {
124
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(release)
125
+ if (match === null) return null
126
+ return { core: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: match[4] === undefined ? [] : match[4].split('.') }
127
+ }
128
+
129
+ /** Semver's order of two prerelease identifiers: numerically when both are numeric, a numeric one first, else by ASCII. */
130
+ const compareIdentifiers = (a: string, b: string): number => {
131
+ const numericA = /^\d+$/.test(a)
132
+ const numericB = /^\d+$/.test(b)
133
+ if (numericA && numericB) return Number(a) - Number(b)
134
+ if (numericA !== numericB) return numericA ? -1 : 1
135
+ return a < b ? -1 : a > b ? 1 : 0
136
+ }
137
+
138
+ const compareReleases = (a: ReleaseVersion, b: ReleaseVersion): number => {
139
+ for (const [index, part] of a.core.entries()) {
140
+ const other = b.core[index] ?? 0
141
+ if (part !== other) return part - other
142
+ }
143
+ if (a.prerelease.length === 0 || b.prerelease.length === 0) return b.prerelease.length - a.prerelease.length
144
+ for (const [index, identifier] of a.prerelease.entries()) {
145
+ const other = b.prerelease[index]
146
+ if (other === undefined) return 1
147
+ const order = compareIdentifiers(identifier, other)
148
+ if (order !== 0) return order
149
+ }
150
+ return a.prerelease.length - b.prerelease.length
151
+ }
152
+
153
+ /**
154
+ * Whether framework release `release` is at or above the exact version `since` in semver's precedence, prerelease
155
+ * included; a release that is not a semver version never is (ADR-0062).
156
+ */
157
+ export const releaseFrom = (release: string, since: string): boolean => {
158
+ const floor = parseReleaseVersion(since)
159
+ if (floor === null) throw new Error(`releaseFrom: \`${since}\` is not a semver version`)
160
+ const version = parseReleaseVersion(release)
161
+ return version !== null && compareReleases(version, floor) >= 0
162
+ }
163
+
164
+ /**
165
+ * The release a gate reads for an approved access: the application's pin, never the reader's `checker`, which is this
166
+ * 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
167
+ * reader's minor (`<major>.<minor>.0-0`): every `releaseAtLeast` gate answers as for that minor, and every `releaseFrom`
168
+ * gate of a prerelease or a patch fails closed, as for an older application, until a deploy reads its pin.
169
+ */
170
+ export const applicationRelease = (access: { readonly checker: string; readonly framework?: string }): string => {
171
+ if (access.framework !== undefined) return access.framework
172
+ const minor = /^(\d+)\.(\d+)\./.exec(access.checker)
173
+ return minor === null ? access.checker : `${minor[1]}.${minor[2]}.0-0`
174
+ }
175
+
176
+ /**
177
+ * The first framework release whose application object holds the maintenance barrier (`state`, `migrate`) and serves
178
+ * the data operations, runs its jobs from its alarm, and whose deploy caps a job at one segment. The 0.9.0 prereleases
179
+ * published before it (`dev.0`–`dev.4`, `cloudflare.1`–`cloudflare.2`) run in the object without any of that and answer
180
+ * `state` and `migrate` 501, so these gates compare the whole version where `releaseAtLeast` counts a prerelease as
181
+ * its minor. A prerelease of another channel sorts by its name: every `cloudflare.<n>` keeps the older behaviour.
182
+ */
183
+ const OBJECT_OPERATIONS_SINCE = '0.9.0-dev.5'
184
+
185
+ /**
186
+ * Whether the object of release `release` holds the maintenance barrier and serves Control's data operations: the
187
+ * backups, the migration phase and the side restore (ADR-0069 §3, ADR-0070).
188
+ */
189
+ export const servesDataOperations = (release: string): boolean => releaseFrom(release, OBJECT_OPERATIONS_SINCE)
190
+
191
+ /**
192
+ * Whether the Worker of release `release` gets the hourly repair tick instead of the minute tick: an older object runs
193
+ * its jobs only from the minute tick and has no alarm.
194
+ */
195
+ export const servesAlarms = (release: string): boolean => releaseFrom(release, OBJECT_OPERATIONS_SINCE)
196
+
197
+ /**
198
+ * Whether the Cloudflare deploy of release `release` refuses a job whose `timeoutMs` exceeds one segment
199
+ * (`CLOUDFLARE_MAX_JOB_SEGMENT_MS`). An older release deploys as it did (ADR-0062).
200
+ */
201
+ export const capsJobSegments = (release: string): boolean => releaseFrom(release, OBJECT_OPERATIONS_SINCE)
202
+
203
+ /**
204
+ * The first framework release whose object runs `ctx.sql` on its SQLite (ADR-0065 decision 7). An older one refuses a
205
+ * site that declares `sql` at boot, so the deploy refuses it first.
206
+ */
207
+ const RAW_SQL_SINCE = '0.9.0-dev.5'
208
+
209
+ /** Whether an application on release `release` may declare `sql` on Cloudflare. */
210
+ export const servesRawSql = (release: string): boolean => releaseFrom(release, RAW_SQL_SINCE)
211
+
212
+ /**
213
+ * Refuse what a stateless Worker of an older release cannot run: a job, a webhook, a public procedure, installation
214
+ * mail and token purposes all need the object's database or a Worker secret it never reads.
215
+ */
216
+ export const assertStatelessEnvironment = (managed: ProviderManagedEnvironment, release: string): void => {
217
+ const names = Object.keys(managed)
218
+ const workloadKey = names.find(isWorkloadKeyVariable)
219
+ if (workloadKey !== undefined) {
220
+ throw new Error(
221
+ `cloudflare: the contract declares a job, a webhook or a public procedure (${workloadKey}), which an application on framework ${release} cannot run on Cloudflare; upgrade its framework`,
222
+ )
223
+ }
224
+ const mailVariable = names.find((name) => isEmailTransportVariable(name) || isPlatformTransportVariable(name))
225
+ if (mailVariable !== undefined) {
226
+ throw new Error(
227
+ `cloudflare: the contract declares a job that sends mail through the installation (${mailVariable}), which an application on framework ${release} cannot run on Cloudflare; upgrade its framework`,
228
+ )
229
+ }
230
+ if (managedValue(managed, FABRIKA_TOKEN_KEYS) !== null) {
231
+ throw new Error(
232
+ `cloudflare: the contract declares token purposes, which an application on framework ${release} cannot sign on Cloudflare; upgrade its framework`,
233
+ )
234
+ }
235
+ }
package/src/control.ts CHANGED
@@ -1,14 +1,4 @@
1
- import { ReconcileSchemaError } from '@fabrika/auth'
2
- import {
3
- type AppEnvironment,
4
- appEnvironmentId,
5
- type AppSchema,
6
- FABRIKA_TOKEN_KEYS,
7
- isEmailTransportVariable,
8
- isPlatformTransportVariable,
9
- isWorkloadKeyVariable,
10
- parseAppEnvironmentId,
11
- } from '@fabrika/auth-core'
1
+ import { type AppEnvironment, appEnvironmentId, type ApplicationObjects, FABRIKA_PROXY_SECRET, parseAppEnvironmentId } from '@fabrika/auth-core'
12
2
  import type {
13
3
  ControlProvider,
14
4
  JsonValue,
@@ -24,17 +14,25 @@ import type {
24
14
  ProviderSourceResolution,
25
15
  ProviderSourceResolutionInput,
26
16
  ProviderTerminalOutcome,
27
- SchemaReconciler,
28
17
  } from '@fabrika/provider-contract'
29
18
  import { abortableWait, decodeEnvelope, isLeaseLoss, ProviderInvocationAbort } from '@fabrika/provider-contract'
30
- import { isCrossOrigin, MAX_CROSS_ORIGINS } from '@fabrika/proxy-core/headers'
19
+ import { isCrossOrigin, isPolicyOrigin, MAX_CROSS_ORIGINS } from '@fabrika/proxy-core/headers'
31
20
  import { isProxyHost } from '@fabrika/proxy-core/manifest'
32
21
  import { z } from 'zod'
33
22
  import { cloudflareArtifactCodec } from './codec'
34
- import { type RunnerApprovedAccess, runnerApprovedAccessSchema, type RunnerIamReconcile } from './runner-protocol'
23
+ import {
24
+ applicationRelease,
25
+ assertCloudflareContract,
26
+ assertStatelessEnvironment,
27
+ capsJobSegments,
28
+ runsInObject,
29
+ servesDataOperations,
30
+ servesOps,
31
+ servesRawSql,
32
+ } from './contract-support'
35
33
  // `./runner` is this module: keep every import here clear of `oblaka-iac`, which the runner packages
36
34
  // cannot typecheck (they do not relax the two strict flags the raw TS needs).
37
- import { defaultReconcileSchema } from './schema'
35
+ import { applicationObjectsSchema, type RunnerApprovedAccess, runnerApprovedAccessSchema, type RunnerIamReconcile } from './runner-protocol'
38
36
 
39
37
  export * from './runner-protocol'
40
38
 
@@ -71,12 +69,14 @@ export interface CloudflareRunnerJob {
71
69
  readonly domain?: string
72
70
  /** The environment's cross-origin list from Control's registry (ADR-0022); the proxy Worker's manifest entry lists it. */
73
71
  readonly crossOrigins?: readonly string[]
74
- /** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0022). */
75
- readonly returnOrigins?: readonly string[]
72
+ /** The origin of the environment's Operations ingest, from Control; the proxy Worker's `connect-src` admits it. */
73
+ readonly operationsOrigin?: string
76
74
  /** `<app>@<env>` of every Cloudflare deployment in Control's registry; the deploy refuses another application's names. */
77
75
  readonly installationApps?: readonly string[]
78
76
  /** What the deployed proxy enforces and the application starts as; every run but a dry one carries it. */
79
77
  readonly approvedAccess?: RunnerApprovedAccess
78
+ /** The serving object and the listed objects Control records (ADR-0070 §9); absent, the deployer's defaults. */
79
+ readonly applicationObjects?: ApplicationObjects
80
80
  readonly dryRun?: boolean
81
81
  /**
82
82
  * Shared secret the runner verifies before it touches D1 or the container; the binding alone proves
@@ -161,9 +161,10 @@ export const cloudflareRunnerJobSchema = z.object({
161
161
  stateNamespace: z.string().min(1).optional(),
162
162
  domain: z.string().refine((value) => isProxyHost(value.toLowerCase())).optional(),
163
163
  crossOrigins: z.array(z.string().refine(isCrossOrigin)).max(MAX_CROSS_ORIGINS).optional(),
164
- returnOrigins: z.array(z.string().min(1)).optional(),
164
+ operationsOrigin: z.string().refine((origin) => isPolicyOrigin(origin, ['https:', 'http:'])).optional(),
165
165
  installationApps: z.array(z.string().refine((id) => !hasUnsafeChars(id) && parseAppEnvironmentId(id) !== null)).optional(),
166
166
  approvedAccess: runnerApprovedAccessSchema.optional(),
167
+ applicationObjects: applicationObjectsSchema.optional(),
167
168
  dryRun: z.boolean().optional(),
168
169
  secrets: stringRecordSchema.optional(),
169
170
  vars: stringRecordSchema.optional(),
@@ -206,13 +207,9 @@ export type CloudflareRunRecovery = CloudflareRunOutcome | { readonly state: 'ru
206
207
  export interface CloudflareControlOptions {
207
208
  readonly accountId: string
208
209
  readonly apiToken: string
209
- readonly propustkaUrl?: string
210
- readonly propustkaProvisioningKey?: string
211
210
  readonly runnerKey: string
212
211
  /** Every Cloudflare deployment in Control's registry, sent with each job so another application's names are refused. */
213
212
  installationApps?(signal: AbortSignal): Promise<readonly AppEnvironment[]>
214
- /** Overridable for tests; production reconciles over HTTPS with the control plane's own admin key. */
215
- readonly reconcileSchema?: SchemaReconciler
216
213
  resolveSource(input: ProviderSourceResolutionInput): Promise<ProviderSourceResolution>
217
214
  prepareClone(source: ProviderSource, signal: AbortSignal, sourceBinding?: ProviderSourceBinding): Promise<CloudflareCloneSource>
218
215
  startRun(job: CloudflareRunnerJob): Promise<CloudflareRunOutcome>
@@ -282,7 +279,12 @@ const awaitWithSignal = async <T>(signal: AbortSignal, invoke: () => Promise<T>)
282
279
  const runnerApprovedAccess = (environment: ProviderEnvironment): RunnerApprovedAccess | undefined =>
283
280
  environment.access === undefined
284
281
  ? undefined
285
- : { kind: 'contract', contract: environment.access.contract, contractDigest: environment.access.contractDigest }
282
+ : {
283
+ kind: 'contract',
284
+ contract: environment.access.contract,
285
+ contractDigest: environment.access.contractDigest,
286
+ framework: applicationRelease(environment.access),
287
+ }
286
288
 
287
289
  const buildJob = async (options: CloudflareControlOptions, input: ProviderDeployInput): Promise<CloudflareRunnerJob> => {
288
290
  input.signal.throwIfAborted()
@@ -295,25 +297,16 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
295
297
  throw new Error('Cloudflare deploy requires a canonical 40-character commit SHA')
296
298
  }
297
299
  const approvedAccess = runnerApprovedAccess(input.environment)
298
- if (!input.dryRun && approvedAccess === undefined) {
299
- throw new Error('Cloudflare deploy requires the access Control approved for this environment')
300
- }
301
- // A job, a webhook and a public procedure need `@fabrika/db` on Postgres, which a Worker has not; their keys would only
302
- // sit in a config.
303
- const workloadKey = Object.keys(input.managedEnvironment).find(isWorkloadKeyVariable)
304
- if (workloadKey !== undefined) {
305
- throw new Error(`cloudflare: the contract declares a job, a webhook or a public procedure (${workloadKey}); they run on Zerops only`)
306
- }
307
- // A dry run hands no workload key, and a mail credential must not land in a plain Worker var either way.
308
- const mailVariable = Object.keys(input.managedEnvironment).find((name) => isEmailTransportVariable(name) || isPlatformTransportVariable(name))
309
- if (mailVariable !== undefined) {
310
- throw new Error(`cloudflare: the contract declares a job that sends mail through the installation (${mailVariable}); jobs run on Zerops only`)
311
- }
312
- // A Worker's vars are plain text in its config, so the signing keys of the application's tokens never go there.
313
- const tokenKeys = input.managedEnvironment[FABRIKA_TOKEN_KEYS]
314
- if (tokenKeys !== undefined && tokenKeys !== null) {
315
- throw new Error('cloudflare: the contract declares token purposes, whose keys a Worker would hold as plain vars; signed tokens run on Zerops only')
300
+ const release = input.environment.access === undefined ? undefined : applicationRelease(input.environment.access)
301
+ // The deployer refuses it again from the contract it serves; this fails before the clone.
302
+ if (approvedAccess !== undefined) {
303
+ assertCloudflareContract(approvedAccess.contract, {
304
+ capsSegments: release !== undefined && capsJobSegments(release),
305
+ servesSql: release !== undefined && servesRawSql(release),
306
+ })
316
307
  }
308
+ const stateless = release !== undefined && !runsInObject(release)
309
+ if (stateless) assertStatelessEnvironment(input.managedEnvironment, release)
317
310
  const source = await awaitWithSignal(input.signal, () => options.prepareClone(input.app.source, input.signal, input.sourceBinding))
318
311
  const listInstallationApps = options.installationApps
319
312
  const installationApps = listInstallationApps === undefined
@@ -322,8 +315,9 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
322
315
  appEnvironmentId(deployment.app, deployment.env)
323
316
  )
324
317
  const managedEnvironment: Record<string, string> = {}
325
- for (const [name, value] of Object.entries(input.managedEnvironment)) {
326
- if (value !== null) managedEnvironment[name] = value
318
+ for (const [name, { value }] of Object.entries(input.managedEnvironment)) {
319
+ // An older release's Worker would demand the hop secret from a proxy Worker that never sends it.
320
+ if (value !== null && !(stateless && name === FABRIKA_PROXY_SECRET)) managedEnvironment[name] = value
327
321
  }
328
322
  return {
329
323
  runId: input.runId,
@@ -342,9 +336,10 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
342
336
  ...(input.environment.crossOrigins === undefined || input.environment.crossOrigins.length === 0
343
337
  ? {}
344
338
  : { crossOrigins: input.environment.crossOrigins }),
345
- ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
339
+ ...(input.environment.operationsOrigin === undefined ? {} : { operationsOrigin: input.environment.operationsOrigin }),
346
340
  ...(installationApps === undefined ? {} : { installationApps }),
347
341
  ...(approvedAccess === undefined ? {} : { approvedAccess }),
342
+ ...(input.applicationObjects === undefined ? {} : { applicationObjects: input.applicationObjects }),
348
343
  ...(input.dryRun ? { dryRun: true } : {}),
349
344
  ...(Object.keys(input.secrets).length === 0 ? {} : { secrets: input.secrets }),
350
345
  ...(Object.keys(input.vars).length === 0 ? {} : { vars: input.vars }),
@@ -353,85 +348,43 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
353
348
  }
354
349
  }
355
350
 
356
- /** The app a terminal outcome belongs to, and where IAM may hand it a session. */
357
- interface IamReconcileTarget {
358
- readonly appId: string
359
- readonly env: string
360
- readonly returnOrigins?: readonly string[]
361
- /** Control's approved contract (ADR-0050): a contract application's IAM schema comes from it, never from the runner. */
362
- readonly access?: ProviderApprovedAccess
363
- readonly signal: AbortSignal
364
- }
365
-
366
- /** The executor's report itself is unusable; retrying cannot make it valid. */
367
- class InvalidIamReport extends Error {}
368
-
369
- /** Apply a schema with the control plane's own IAM key. */
370
- const applySchema = async (options: CloudflareControlOptions, target: IamReconcileTarget, schema: AppSchema): Promise<void> => {
371
- if (options.propustkaUrl === undefined) return
372
- // Return origins ride this call because `apps.setReturnOrigins` 404s for an app IAM has never heard
373
- // of, and the schema reconcile is what registers it. Separate call, same moment.
374
- const returnOrigins = target.returnOrigins !== undefined && target.returnOrigins.length > 0 ? target.returnOrigins : undefined
375
- await (options.reconcileSchema ?? defaultReconcileSchema)({
376
- url: options.propustkaUrl,
377
- app: appEnvironmentId(target.appId, target.env),
378
- schema,
379
- ...(returnOrigins === undefined ? {} : { returnOrigins }),
380
- ...(options.propustkaProvisioningKey === undefined ? {} : { adminKey: options.propustkaProvisioningKey }),
381
- signal: target.signal,
382
- })
383
- }
384
-
385
351
  /**
386
- * Settle a terminal outcome: apply the IAM schema Control approved, if any, before Control marks the run terminal. Both
387
- * the awaited deploy and a post-restart reconcile come through here under Control's lease. IAM replaces the app's whole
388
- * vocabulary, so applying the same schema again after a lost lease is harmless. `retryUnavailableIam` keeps the run in
389
- * flight when IAM was unreachable or answered 5xx/408/429, so the next reconcile retries; an invalid report or any
390
- * other IAM refusal fails the run.
352
+ * Judge a terminal outcome's report before Control settles it. The runner may report the schema it compiled; Control
353
+ * writes the approved one itself (ADR-0011), so a report is only evidence: a dry run that reports access, or a report
354
+ * where Control approved none, fails the run.
391
355
  */
392
356
  const settleOutcome = async (
393
- options: CloudflareControlOptions,
394
- target: IamReconcileTarget,
357
+ access: ProviderApprovedAccess | undefined,
395
358
  outcome: CloudflareRunOutcome,
396
359
  log: (line: string) => Promise<void>,
397
- retryUnavailableIam: boolean,
398
- ): Promise<ProviderTerminalOutcome | { readonly state: 'running' }> => {
360
+ ): Promise<ProviderTerminalOutcome> => {
399
361
  const terminal: ProviderTerminalOutcome = {
400
362
  state: outcome.state,
401
363
  ...(outcome.exitCode === undefined ? {} : { exitCode: outcome.exitCode }),
402
364
  ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }),
403
365
  }
366
+ if (outcome.iamReconcile === undefined) return terminal
404
367
  const failed: ProviderTerminalOutcome = { state: 'failed', ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }) }
405
- const reported = outcome.iamReconcile !== undefined
406
368
  if (outcome.dryRun === true) {
407
- if (!reported) return terminal
408
369
  await log('reconcile-schema refused: a dry run reported access')
409
370
  return failed
410
371
  }
411
- try {
412
- if (target.access === undefined && reported) {
413
- throw new InvalidIamReport('reported access, but Control approved no access for this environment')
414
- }
415
- // An approved contract reconciles its own schema once the deploy succeeded, whatever the runner reported.
416
- if (target.access !== undefined && outcome.state === 'succeeded') await applySchema(options, target, target.access.schema)
417
- } catch (error) {
418
- target.signal.throwIfAborted()
419
- await log(`reconcile-schema failed: ${error instanceof Error ? error.message : 'unknown error'}`)
420
- if (retryUnavailableIam && isTransientIamFailure(error)) return { state: 'running' }
372
+ if (access === undefined) {
373
+ await log('reconcile-schema failed: reported access, but Control approved no access for this environment')
421
374
  return failed
422
375
  }
423
376
  return terminal
424
377
  }
425
378
 
426
- const isTransientIamFailure = (error: unknown): boolean => {
427
- if (error instanceof InvalidIamReport) return false
428
- if (!(error instanceof ReconcileSchemaError)) return true
429
- return error.status >= 500 || error.status === 408 || error.status === 429
430
- }
431
-
432
379
  /** Build the Cloudflare control capability over its runner and source-resolution ports. */
433
380
  export const createCloudflareControlProvider = (options: CloudflareControlOptions): ControlProvider => ({
434
381
  id: 'cloudflare',
382
+ // The application's Worker forwards each request to its Durable Object with the environment's proxy secret.
383
+ applicationHopSecret: true,
384
+ // The environment's object serves Control's ops requests from the release that gets the composed row.
385
+ opsChannel: (access) => servesOps(applicationRelease(access)),
386
+ // From the release whose object holds the barrier; the 0.9.0 prereleases before it serve only `inspect`.
387
+ dataOperations: (access) => servesOps(applicationRelease(access)) && servesDataOperations(applicationRelease(access)),
435
388
  normalizeRegistration,
436
389
  applicationRoot: (source) => checkoutRelativeDirectory(source.workerDir),
437
390
  source: { binding: 'connection' },
@@ -470,15 +423,7 @@ export const createCloudflareControlProvider = (options: CloudflareControlOption
470
423
  }
471
424
  input.signal.throwIfAborted()
472
425
  if (input.dryRun) return outcome
473
- const target: IamReconcileTarget = {
474
- appId: input.app.id,
475
- env: input.environment.env,
476
- signal: input.signal,
477
- ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
478
- ...(input.environment.access === undefined ? {} : { access: input.environment.access }),
479
- }
480
- const log = async (line: string): Promise<void> => input.events.log(line)
481
- return settleOutcome(options, target, outcome, log, false)
426
+ return settleOutcome(input.environment.access, outcome, async (line) => input.events.log(line))
482
427
  },
483
428
  reconcile: async (input) => {
484
429
  input.signal.throwIfAborted()
@@ -486,19 +431,11 @@ export const createCloudflareControlProvider = (options: CloudflareControlOption
486
431
  if (recoverRun === undefined) return { state: 'running' }
487
432
  const recovery = await awaitWithSignal(input.signal, () => recoverRun(input.runId))
488
433
  if (recovery.state === 'running') return { state: 'running' }
489
- const target: IamReconcileTarget = {
490
- appId: input.environment.appId,
491
- env: input.environment.env,
492
- signal: input.signal,
493
- ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
494
- ...(input.environment.access === undefined ? {} : { access: input.environment.access }),
495
- }
496
434
  const log = async (line: string): Promise<void> => {
497
435
  if (input.log === undefined) console.error(`run ${input.runId}: ${line}`)
498
436
  else await input.log(line)
499
437
  }
500
- const outcome = await settleOutcome(options, target, recovery, log, true)
501
- if (outcome.state === 'running') return outcome
438
+ const outcome = await settleOutcome(input.environment.access, recovery, log)
502
439
  return {
503
440
  state: outcome.state,
504
441
  ...(outcome.exitCode === undefined ? {} : { exitCode: outcome.exitCode }),
@@ -0,0 +1,35 @@
1
+ import type { GeneratedConfig } from 'oblaka-iac'
2
+
3
+ /**
4
+ * The generated configs in the order `wrangler deploy` can take them: a Worker another generated config binds as a
5
+ * service goes first, because wrangler refuses a service binding to a script with no deployment yet (code 10145) —
6
+ * on a first deploy the proxy would otherwise reach the application Worker before it exists. Configs with no such
7
+ * dependency keep oblaka's order. A cycle has no first deploy, so it is refused.
8
+ */
9
+ export const deployOrder = (configs: readonly GeneratedConfig[]): readonly GeneratedConfig[] => {
10
+ const byName = new Map<string, GeneratedConfig>()
11
+ for (const generated of configs) {
12
+ if (generated.config.name !== undefined) byName.set(generated.config.name, generated)
13
+ }
14
+ const dependencies = (generated: GeneratedConfig): GeneratedConfig[] =>
15
+ (generated.config.services ?? []).flatMap((entry) => {
16
+ const target = byName.get(entry.service)
17
+ return target === undefined || target === generated ? [] : [target]
18
+ })
19
+ const ordered: GeneratedConfig[] = []
20
+ const state = new Map<GeneratedConfig, 'visiting' | 'done'>()
21
+ const visit = (generated: GeneratedConfig, path: readonly GeneratedConfig[]): void => {
22
+ const seen = state.get(generated)
23
+ if (seen === 'done') return
24
+ if (seen === 'visiting') {
25
+ const cycle = [...path.slice(path.indexOf(generated)), generated].map((item) => `\`${item.config.name ?? '(unnamed)'}\``)
26
+ throw new Error(`deploy-worker: the generated Workers bind each other as services in a cycle (${cycle.join(' → ')}), so none can deploy first`)
27
+ }
28
+ state.set(generated, 'visiting')
29
+ for (const target of dependencies(generated)) visit(target, [...path, generated])
30
+ state.set(generated, 'done')
31
+ ordered.push(generated)
32
+ }
33
+ for (const generated of configs) visit(generated, [])
34
+ return ordered
35
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  export * from 'oblaka-iac'
2
- export { type CloudflareAppConfig, type CloudflareAppConfigInput, defineApp, isCloudflareAppConfig, type ResourceContext } from './authoring'
2
+ export {
3
+ type ApplicationWorkerOptions,
4
+ type CloudflareAppConfig,
5
+ type CloudflareAppConfigInput,
6
+ defineApp,
7
+ isCloudflareAppConfig,
8
+ type ResourceContext,
9
+ } from './authoring'
3
10
  export { assertGeneratedConfigs, assertGeneration, generateWranglerConfigs } from './bounds'
4
11
  export type { ConfigGeneration, DeploymentBounds, GeneratedResource } from './bounds'
5
12
  export { parseCloudflareArgs, platformComponents } from './cli-args'
@@ -25,7 +32,16 @@ export { cloudflareStoredTargetCodec, createCloudflareControlProvider } from './
25
32
  export type { CloudflareCloneSource, CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget } from './control'
26
33
  export { buildPlan, findMigratableDatabases, PLATFORM_RESOURCE_NAMES } from './plan'
27
34
  export type { CloudflareStep, CloudflareStepKind, MigratableDatabase } from './plan'
28
- export { type CloudflareDeployerOptions, type CloudflareDeployResult, type CloudflareDeployRun, createCloudflareDeployer } from './provider'
29
- export { createCloudflareProxyWorker, IAM_APPLICATION_ENTRYPOINT, iamServiceReference } from './proxy'
35
+ export {
36
+ type CloudflareDeployerOptions,
37
+ type CloudflareDeployResult,
38
+ type CloudflareDeployRun,
39
+ composeLocalApplication,
40
+ createCloudflareDeployer,
41
+ type LocalApplicationOptions,
42
+ type StagedLocalAssets,
43
+ stageLocalAssets,
44
+ } from './provider'
45
+ export { createCloudflareProxyWorker, IAM_APPLICATION_ENTRYPOINT, iamServiceReference, proxyManifestJson } from './proxy'
30
46
  export type { CloudflareProxyWorkerOptions } from './proxy'
31
47
  export { type AppSchemaParse, parseAppSchema } from './schema'