@fabrika/provider-cloudflare 0.0.26 → 0.3.1

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/control.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ReconcileSchemaError } from '@fabrika/auth'
1
2
  import type {
2
3
  ControlProvider,
3
4
  JsonValue,
@@ -7,28 +8,29 @@ import type {
7
8
  ProviderRegistration,
8
9
  ProviderRegistrationInput,
9
10
  ProviderSource,
11
+ ProviderSourceBinding,
12
+ ProviderSourceResolution,
13
+ ProviderSourceResolutionInput,
10
14
  ProviderTerminalOutcome,
15
+ SchemaReconciler,
11
16
  } from '@fabrika/provider-contract'
17
+ import { abortableWait, decodeEnvelope, isLeaseLoss, ProviderInvocationAbort } from '@fabrika/provider-contract'
18
+ import { isProxyHost } from '@fabrika/proxy-core/manifest'
19
+ import { z } from 'zod'
12
20
  import { cloudflareArtifactCodec } from './codec'
21
+ import { type RunnerIamReconcile, runnerIamReconcileSchema } from './runner-protocol'
22
+ // `./runner` is this module: keep every import here clear of `oblaka-iac`, which the runner packages
23
+ // cannot typecheck (they do not relax the two strict flags the raw TS needs).
24
+ import { defaultReconcileSchema, parseAppSchema } from './schema'
25
+
26
+ export * from './runner-protocol'
13
27
 
14
28
  /** Persisted Cloudflare target data. Installation credentials never enter this envelope. */
15
29
  export interface CloudflareStoredTarget {
16
30
  readonly stateNamespace?: string
17
31
  }
18
32
 
19
- const optionalString = (payload: ProviderEnvelope['payload'], key: string): string | undefined => {
20
- if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
21
- throw new Error('Cloudflare target must be an object')
22
- }
23
- const value = payload[key]
24
- if (value === undefined) {
25
- return undefined
26
- }
27
- if (typeof value !== 'string' || value === '') {
28
- throw new Error(`Cloudflare target ${key} must be a non-empty string when present`)
29
- }
30
- return value
31
- }
33
+ const storedTargetSchema = z.object({ stateNamespace: z.string().min(1).optional() })
32
34
 
33
35
  export const cloudflareStoredTargetCodec: ProviderCodec<CloudflareStoredTarget> = {
34
36
  version: 1,
@@ -39,7 +41,7 @@ export const cloudflareStoredTargetCodec: ProviderCodec<CloudflareStoredTarget>
39
41
  return { stateNamespace: target.stateNamespace }
40
42
  },
41
43
  decode: (payload) => {
42
- const stateNamespace = optionalString(payload, 'stateNamespace')
44
+ const { stateNamespace } = storedTargetSchema.parse(payload)
43
45
  return stateNamespace === undefined ? {} : { stateNamespace }
44
46
  },
45
47
  }
@@ -54,14 +56,18 @@ export interface CloudflareRunnerJob {
54
56
  readonly configPath?: string
55
57
  readonly stateNamespace?: string
56
58
  readonly domain?: string
57
- /** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0021). */
59
+ /** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0022). */
58
60
  readonly returnOrigins?: readonly string[]
59
61
  readonly dryRun?: boolean
62
+ /**
63
+ * Shared secret the runner verifies before it touches D1 or the container; the binding alone proves
64
+ * nothing. Optional in the type because the wire boundary may omit it — the Worker refuses it there.
65
+ */
66
+ readonly runnerKey?: string
67
+ /** Exactly the Cloudflare account credential. IAM's admin key stays in the control plane (ADR-0022). */
60
68
  readonly credentials: {
61
69
  readonly CLOUDFLARE_ACCOUNT_ID: string
62
70
  readonly CLOUDFLARE_API_TOKEN: string
63
- readonly FABRIKA_IAM_ISSUER?: string
64
- readonly FABRIKA_IAM_PROVISIONING_KEY?: string
65
71
  }
66
72
  readonly secrets?: Readonly<Record<string, string>>
67
73
  readonly vars?: Readonly<Record<string, string>>
@@ -77,90 +83,106 @@ export interface CloudflareRunnerJob {
77
83
  }
78
84
  }
79
85
 
80
- const isStringArray = (value: unknown): boolean => Array.isArray(value) && value.every((entry) => typeof entry === 'string' && entry !== '')
81
-
82
- const isStringRecord = (value: unknown): boolean =>
83
- typeof value === 'object'
84
- && value !== null
85
- && !Array.isArray(value)
86
- && Object.values(value).every((entry) => typeof entry === 'string')
87
-
88
- const isArtifactUpload = (value: unknown): boolean =>
89
- typeof value === 'object'
90
- && value !== null
91
- && !Array.isArray(value)
92
- && ['url', 'bearer', 'appId', 'environment', 'serviceKey', 'release', 'runId'].every((key) => {
93
- const field = Reflect.get(value, key)
94
- return typeof field === 'string' && field !== ''
86
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
87
+ const ENV_NAME = /^[a-z0-9-]+$/
88
+ const COMMIT_SHA = /^[0-9a-f]{40}$/
89
+ const isCanonicalCommit = (value: string): boolean => value.length === 40 && COMMIT_SHA.test(value)
90
+
91
+ /** Whitespace or a control character in a value that becomes an argv element or a filesystem path. */
92
+ const hasUnsafeChars = (value: string): boolean =>
93
+ /\s/.test(value) || [...value].some((char) => {
94
+ const code = char.codePointAt(0) ?? 0
95
+ return code < 0x20 || code === 0x7f
95
96
  })
96
97
 
97
- /** Minimal structural validation for the Worker-to-runner JSON boundary. */
98
- export const isCloudflareRunnerJob = (value: unknown): value is CloudflareRunnerJob => {
99
- if (
100
- typeof value !== 'object'
101
- || value === null
102
- || !('runId' in value && typeof value.runId === 'string')
103
- || !('repoUrl' in value && typeof value.repoUrl === 'string')
104
- || !('ref' in value && typeof value.ref === 'string')
105
- || !('env' in value && typeof value.env === 'string')
106
- || !('credentials' in value && typeof value.credentials === 'object' && value.credentials !== null)
107
- ) {
108
- return false
109
- }
110
- const credentials = value.credentials
111
- const requiredCredentials = 'CLOUDFLARE_ACCOUNT_ID' in credentials
112
- && typeof credentials.CLOUDFLARE_ACCOUNT_ID === 'string'
113
- && credentials.CLOUDFLARE_ACCOUNT_ID !== ''
114
- && 'CLOUDFLARE_API_TOKEN' in credentials
115
- && typeof credentials.CLOUDFLARE_API_TOKEN === 'string'
116
- && credentials.CLOUDFLARE_API_TOKEN !== ''
117
- if (!requiredCredentials) {
118
- return false
119
- }
120
- if (
121
- ('FABRIKA_IAM_ISSUER' in credentials && credentials.FABRIKA_IAM_ISSUER !== undefined && typeof credentials.FABRIKA_IAM_ISSUER !== 'string')
122
- || ('FABRIKA_IAM_PROVISIONING_KEY' in credentials
123
- && credentials.FABRIKA_IAM_PROVISIONING_KEY !== undefined
124
- && typeof credentials.FABRIKA_IAM_PROVISIONING_KEY !== 'string')
125
- || ('workerDir' in value && value.workerDir !== undefined && typeof value.workerDir !== 'string')
126
- || ('configPath' in value && value.configPath !== undefined && typeof value.configPath !== 'string')
127
- || ('stateNamespace' in value && value.stateNamespace !== undefined && typeof value.stateNamespace !== 'string')
128
- || ('domain' in value && value.domain !== undefined && typeof value.domain !== 'string')
129
- || ('returnOrigins' in value && value.returnOrigins !== undefined && !isStringArray(value.returnOrigins))
130
- || ('dryRun' in value && value.dryRun !== undefined && typeof value.dryRun !== 'boolean')
131
- || ('secrets' in value && value.secrets !== undefined && !isStringRecord(value.secrets))
132
- || ('vars' in value && value.vars !== undefined && !isStringRecord(value.vars))
133
- || ('managedEnvironment' in value && value.managedEnvironment !== undefined && !isStringRecord(value.managedEnvironment))
134
- || ('artifactUpload' in value && value.artifactUpload !== undefined && !isArtifactUpload(value.artifactUpload))
135
- ) {
98
+ const isHttpsUrl = (value: string): boolean => {
99
+ try {
100
+ return new URL(value).protocol === 'https:'
101
+ } catch {
136
102
  return false
137
103
  }
138
- return true
139
104
  }
140
105
 
141
- export interface ResolvedCloudflareSource {
106
+ /** A path that stays inside the checkout: relative, and with no `..` segment to climb out of it. */
107
+ const isContainedPath = (value: string): boolean =>
108
+ value !== '' && !value.startsWith('/') && !hasUnsafeChars(value) && !value.split('/').includes('..')
109
+
110
+ // Entries preserve own environment names such as `__proto__`, which Zod's record parser drops.
111
+ const stringRecordSchema = z.preprocess(
112
+ (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? Object.entries(value) : undefined,
113
+ z.array(z.tuple([z.string(), z.string()])).transform((entries) => Object.fromEntries(entries)),
114
+ )
115
+
116
+ /**
117
+ * Validate the Worker-to-runner JSON boundary by VALUE, not only by type: every field here becomes an
118
+ * argv element, a filesystem path or a hostname inside the deploy container.
119
+ */
120
+ export const cloudflareRunnerJobSchema = z.object({
121
+ runId: z.string().regex(UUID),
122
+ repoUrl: z.string().refine((value) => !hasUnsafeChars(value) && isHttpsUrl(value)),
123
+ ref: z.string().min(1).refine((value) => !value.startsWith('-') && !hasUnsafeChars(value)),
124
+ env: z.string().regex(ENV_NAME),
125
+ credentials: z.object({ CLOUDFLARE_ACCOUNT_ID: z.string().min(1), CLOUDFLARE_API_TOKEN: z.string().min(1) }).strict(),
126
+ runnerKey: z.string().min(1).optional(),
127
+ workerDir: z.string().refine(isContainedPath).optional(),
128
+ configPath: z.string().refine(isContainedPath).optional(),
129
+ stateNamespace: z.string().min(1).optional(),
130
+ domain: z.string().refine((value) => isProxyHost(value.toLowerCase())).optional(),
131
+ returnOrigins: z.array(z.string().min(1)).optional(),
132
+ dryRun: z.boolean().optional(),
133
+ secrets: stringRecordSchema.optional(),
134
+ vars: stringRecordSchema.optional(),
135
+ managedEnvironment: stringRecordSchema.optional(),
136
+ artifactUpload: z.object({
137
+ url: z.string().min(1),
138
+ bearer: z.string().min(1),
139
+ appId: z.string().min(1),
140
+ environment: z.string().min(1),
141
+ serviceKey: z.string().min(1),
142
+ release: z.string().min(1),
143
+ runId: z.string().min(1),
144
+ }).optional(),
145
+ }).refine((job) => job.dryRun === true || isCanonicalCommit(job.ref))
146
+
147
+ export interface CloudflareCloneSource {
142
148
  readonly repoUrl: string
143
- readonly ref: string
144
149
  }
145
150
 
151
+ /** A run's terminal outcome plus the IAM reconcile the executor compiled, if the plan reached that step. */
152
+ export type CloudflareRunOutcome = ProviderTerminalOutcome & { readonly iamReconcile?: RunnerIamReconcile; readonly dryRun?: boolean }
153
+
154
+ /** What the runner reports for a run after a control-plane restart: its persisted outcome, or still in flight. */
155
+ export type CloudflareRunRecovery = CloudflareRunOutcome | { readonly state: 'running' }
156
+
146
157
  export interface CloudflareControlOptions {
147
158
  readonly accountId: string
148
159
  readonly apiToken: string
149
160
  readonly propustkaUrl?: string
150
161
  readonly propustkaProvisioningKey?: string
151
- resolveSource(source: ProviderSource, signal: AbortSignal): Promise<ResolvedCloudflareSource>
152
- startRun(job: CloudflareRunnerJob): Promise<ProviderTerminalOutcome>
162
+ readonly runnerKey: string
163
+ /** Overridable for tests; production reconciles over HTTPS with the control plane's own admin key. */
164
+ readonly reconcileSchema?: SchemaReconciler
165
+ resolveSource(input: ProviderSourceResolutionInput): Promise<ProviderSourceResolution>
166
+ prepareClone(source: ProviderSource, signal: AbortSignal, sourceBinding?: ProviderSourceBinding): Promise<CloudflareCloneSource>
167
+ startRun(job: CloudflareRunnerJob): Promise<CloudflareRunOutcome>
153
168
  cancelRun(runId: string): Promise<void>
169
+ recoverRun?(runId: string): Promise<CloudflareRunRecovery>
170
+ /** Overridable for tests; the wait between two reads of Control's step boundary. */
171
+ readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>
154
172
  }
155
173
 
156
- const decodeEnvelope = <T>(kind: string, envelope: ProviderEnvelope, codec: ProviderCodec<T>): T => {
157
- if (envelope.provider !== 'cloudflare') {
158
- throw new Error(`${kind} belongs to provider "${envelope.provider}", expected "cloudflare"`)
159
- }
160
- if (envelope.version !== codec.version) {
161
- throw new Error(`${kind} schema version ${envelope.version} is not supported by provider "cloudflare"`)
174
+ const BOUNDARY_INTERVAL_MS = 10_000
175
+
176
+ /** Read Control's step boundary while the runner works; a rejection that matters aborts the run signal. */
177
+ const readBoundaries = async (events: ProviderDeployInput['events'], sleep: CloudflareControlOptions['sleep'], stop: AbortSignal): Promise<void> => {
178
+ try {
179
+ for (;;) {
180
+ await (sleep ?? abortableWait)(BOUNDARY_INTERVAL_MS, stop)
181
+ await events.boundary().catch(() => {})
182
+ }
183
+ } catch {
184
+ // `stop` aborted: the runner answered.
162
185
  }
163
- return codec.decode(envelope.payload)
164
186
  }
165
187
 
166
188
  const encodeEnvelope = <T>(codec: ProviderCodec<T>, value: T): ProviderEnvelope => ({
@@ -169,12 +191,16 @@ const encodeEnvelope = <T>(codec: ProviderCodec<T>, value: T): ProviderEnvelope
169
191
  payload: codec.encode(value),
170
192
  })
171
193
 
172
- const normalizeRegistration = (input: ProviderRegistrationInput): ProviderRegistration => {
194
+ const assertRegistrationApp = (input: ProviderRegistrationInput): void => {
173
195
  if (input.app.id !== input.environment.appId) {
174
196
  throw new Error(`Cloudflare environment belongs to app "${input.environment.appId}", expected "${input.app.id}"`)
175
197
  }
176
- const target = decodeEnvelope('target', input.environment.target, cloudflareStoredTargetCodec)
177
- const artifact = decodeEnvelope('artifact', input.environment.artifact, cloudflareArtifactCodec)
198
+ }
199
+
200
+ const normalizeRegistration = (input: ProviderRegistrationInput): ProviderRegistration => {
201
+ assertRegistrationApp(input)
202
+ const target = decodeEnvelope('target', 'cloudflare', input.environment.target, cloudflareStoredTargetCodec)
203
+ const artifact = decodeEnvelope('artifact', 'cloudflare', input.environment.artifact, cloudflareArtifactCodec)
178
204
  return {
179
205
  app: input.app,
180
206
  environment: {
@@ -185,10 +211,33 @@ const normalizeRegistration = (input: ProviderRegistrationInput): ProviderRegist
185
211
  }
186
212
  }
187
213
 
214
+ const awaitWithSignal = async <T>(signal: AbortSignal, invoke: () => Promise<T>): Promise<T> => {
215
+ signal.throwIfAborted()
216
+ const interrupted = Promise.withResolvers<never>()
217
+ const abort = (): void => interrupted.reject(signal.reason)
218
+ signal.addEventListener('abort', abort, { once: true })
219
+ try {
220
+ const result = await Promise.race([invoke(), interrupted.promise])
221
+ signal.throwIfAborted()
222
+ return result
223
+ } catch (error) {
224
+ signal.throwIfAborted()
225
+ throw error
226
+ } finally {
227
+ signal.removeEventListener('abort', abort)
228
+ }
229
+ }
230
+
188
231
  const buildJob = async (options: CloudflareControlOptions, input: ProviderDeployInput): Promise<CloudflareRunnerJob> => {
189
- const source = await options.resolveSource(input.app.source, input.signal)
190
- const storedTarget = decodeEnvelope('target', input.environment.target, cloudflareStoredTargetCodec)
191
- const artifact = decodeEnvelope('artifact', input.environment.artifact, cloudflareArtifactCodec)
232
+ input.signal.throwIfAborted()
233
+ assertRegistrationApp(input)
234
+ const storedTarget = decodeEnvelope('target', 'cloudflare', input.environment.target, cloudflareStoredTargetCodec)
235
+ const artifact = decodeEnvelope('artifact', 'cloudflare', input.environment.artifact, cloudflareArtifactCodec)
236
+ const ref = input.app.source.ref
237
+ if (!input.dryRun && !isCanonicalCommit(ref)) {
238
+ throw new Error('Cloudflare deploy requires a canonical 40-character commit SHA')
239
+ }
240
+ const source = await awaitWithSignal(input.signal, () => options.prepareClone(input.app.source, input.signal, input.sourceBinding))
192
241
  const managedEnvironment: Record<string, string> = {}
193
242
  for (const [name, value] of Object.entries(input.managedEnvironment)) {
194
243
  if (value !== null) managedEnvironment[name] = value
@@ -196,15 +245,12 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
196
245
  return {
197
246
  runId: input.runId,
198
247
  repoUrl: source.repoUrl,
199
- ref: source.ref,
248
+ ref,
200
249
  env: input.environment.env,
250
+ runnerKey: options.runnerKey,
201
251
  credentials: {
202
252
  CLOUDFLARE_ACCOUNT_ID: options.accountId,
203
253
  CLOUDFLARE_API_TOKEN: options.apiToken,
204
- ...(options.propustkaUrl === undefined ? {} : { FABRIKA_IAM_ISSUER: options.propustkaUrl }),
205
- ...(options.propustkaProvisioningKey === undefined
206
- ? {}
207
- : { FABRIKA_IAM_PROVISIONING_KEY: options.propustkaProvisioningKey }),
208
254
  },
209
255
  ...(input.app.source.workerDir === undefined ? {} : { workerDir: input.app.source.workerDir }),
210
256
  configPath: artifact.configPath,
@@ -219,13 +265,180 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
219
265
  }
220
266
  }
221
267
 
268
+ /** A megabyte of vocabulary is already absurd; beyond it the control plane refuses to parse at all. */
269
+ const MAX_SCHEMA_JSON_CHARS = 1024 * 1024
270
+
271
+ /** The app a terminal outcome belongs to, and where IAM may hand it a session. */
272
+ interface IamReconcileTarget {
273
+ readonly appId: string
274
+ readonly returnOrigins?: readonly string[]
275
+ readonly signal: AbortSignal
276
+ }
277
+
278
+ /** The executor's report itself is unusable; retrying cannot make it valid. */
279
+ class InvalidIamReport extends Error {}
280
+
281
+ /**
282
+ * Apply the schema the executor compiled, with the control plane's own IAM key. The control port may
283
+ * have implementations other than the runner relay, so validate and bound its report before IAM hears it.
284
+ */
285
+ const applyIamReconcile = async (
286
+ options: CloudflareControlOptions,
287
+ target: IamReconcileTarget,
288
+ report: RunnerIamReconcile,
289
+ ): Promise<void> => {
290
+ const parsedReport = runnerIamReconcileSchema.safeParse(report)
291
+ if (!parsedReport.success) {
292
+ throw new InvalidIamReport('reported an authz schema whose app id or body is not a string')
293
+ }
294
+ const reconcile = parsedReport.data
295
+ if (reconcile.app !== target.appId) {
296
+ throw new InvalidIamReport(`reported an authz schema for app "${reconcile.app}", expected "${target.appId}"`)
297
+ }
298
+ if (reconcile.schemaJson.length > MAX_SCHEMA_JSON_CHARS) {
299
+ throw new InvalidIamReport(`reported an authz schema of ${reconcile.schemaJson.length} characters, over the ${MAX_SCHEMA_JSON_CHARS} limit`)
300
+ }
301
+ let parsed: unknown
302
+ try {
303
+ parsed = JSON.parse(reconcile.schemaJson)
304
+ } catch {
305
+ throw new InvalidIamReport('reported an authz schema that is not valid JSON')
306
+ }
307
+ const schema = parseAppSchema(parsed)
308
+ if (!schema.ok) {
309
+ throw new InvalidIamReport(`reported a malformed authz schema: ${schema.message}`)
310
+ }
311
+ if (options.propustkaUrl === undefined) return
312
+ // Return origins ride this call because `apps.setReturnOrigins` 404s for an app IAM has never heard
313
+ // of, and the schema reconcile is what registers it. Separate call, same moment.
314
+ const returnOrigins = target.returnOrigins !== undefined && target.returnOrigins.length > 0 ? target.returnOrigins : undefined
315
+ await (options.reconcileSchema ?? defaultReconcileSchema)({
316
+ url: options.propustkaUrl,
317
+ app: target.appId,
318
+ schema: schema.schema,
319
+ ...(returnOrigins === undefined ? {} : { returnOrigins }),
320
+ ...(options.propustkaProvisioningKey === undefined ? {} : { adminKey: options.propustkaProvisioningKey }),
321
+ signal: target.signal,
322
+ })
323
+ }
324
+
325
+ /**
326
+ * Settle a terminal outcome: apply its IAM reconcile, if any, before Control marks the run terminal. Both
327
+ * the awaited deploy and a post-restart reconcile come through here under Control's lease. IAM replaces
328
+ * the app's whole vocabulary, so applying the same schema again after a lost lease is harmless.
329
+ * `retryUnavailableIam` keeps the run in flight when IAM was unreachable or answered 5xx/408/429, so the
330
+ * next reconcile retries; an invalid report or any other IAM refusal fails the run.
331
+ */
332
+ const settleOutcome = async (
333
+ options: CloudflareControlOptions,
334
+ target: IamReconcileTarget,
335
+ outcome: CloudflareRunOutcome,
336
+ log: (line: string) => Promise<void>,
337
+ retryUnavailableIam: boolean,
338
+ ): Promise<ProviderTerminalOutcome | { readonly state: 'running' }> => {
339
+ const failed: ProviderTerminalOutcome = { state: 'failed', ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }) }
340
+ const reconcile = outcome.iamReconcile
341
+ if (reconcile === undefined) return outcome
342
+ if (outcome.dryRun === true) {
343
+ await log('reconcile-schema refused: a dry run reported an authz schema')
344
+ return failed
345
+ }
346
+ try {
347
+ await applyIamReconcile(options, target, reconcile)
348
+ } catch (error) {
349
+ target.signal.throwIfAborted()
350
+ await log(`reconcile-schema failed: ${error instanceof Error ? error.message : 'unknown error'}`)
351
+ if (retryUnavailableIam && isTransientIamFailure(error)) return { state: 'running' }
352
+ return failed
353
+ }
354
+ return outcome
355
+ }
356
+
357
+ const isTransientIamFailure = (error: unknown): boolean => {
358
+ if (error instanceof InvalidIamReport) return false
359
+ if (!(error instanceof ReconcileSchemaError)) return true
360
+ return error.status >= 500 || error.status === 408 || error.status === 429
361
+ }
362
+
222
363
  /** Build the Cloudflare control capability over its runner and source-resolution ports. */
223
364
  export const createCloudflareControlProvider = (options: CloudflareControlOptions): ControlProvider => ({
224
365
  id: 'cloudflare',
225
366
  normalizeRegistration,
367
+ source: { binding: 'connection' },
368
+ resolveSource: async (input) => {
369
+ input.signal.throwIfAborted()
370
+ const registration = normalizeRegistration(input)
371
+ return awaitWithSignal(input.signal, () => options.resolveSource({ ...input, ...registration }))
372
+ },
226
373
  deploy: async (input) => {
374
+ const job = await buildJob(options, input)
227
375
  await input.events.externalId(input.runId)
228
- return options.startRun(await buildJob(options, input))
376
+ input.signal.throwIfAborted()
377
+ const interrupted = Promise.withResolvers<never>()
378
+ const abort = (): void => {
379
+ const reason: unknown = input.signal.reason
380
+ if (reason instanceof ProviderInvocationAbort && reason.kind === 'cancel_requested') {
381
+ // A boundary that finds the lease lost forbids the cancel (ADR-0044).
382
+ void input.events.boundary().catch((error: unknown) => error).then((crossed) => isLeaseLoss(crossed) ? undefined : options.cancelRun(input.runId))
383
+ .catch(() => {})
384
+ }
385
+ interrupted.reject(reason)
386
+ }
387
+ input.signal.addEventListener('abort', abort, { once: true })
388
+ const stopBoundaries = new AbortController()
389
+ const boundaries = readBoundaries(input.events, options.sleep, stopBoundaries.signal)
390
+ let outcome: CloudflareRunOutcome
391
+ try {
392
+ outcome = await Promise.race([options.startRun(job), interrupted.promise])
393
+ } catch (error) {
394
+ input.signal.throwIfAborted()
395
+ throw error
396
+ } finally {
397
+ input.signal.removeEventListener('abort', abort)
398
+ stopBoundaries.abort()
399
+ await boundaries
400
+ }
401
+ input.signal.throwIfAborted()
402
+ if (input.dryRun) return outcome
403
+ const target = { appId: input.app.id, signal: input.signal, ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }) }
404
+ const log = async (line: string): Promise<void> => input.events.log(line)
405
+ return settleOutcome(options, target, outcome, log, false)
406
+ },
407
+ reconcile: async (input) => {
408
+ input.signal.throwIfAborted()
409
+ const recoverRun = options.recoverRun
410
+ if (recoverRun === undefined) return { state: 'running' }
411
+ const recovery = await awaitWithSignal(input.signal, () => recoverRun(input.runId))
412
+ if (recovery.state === 'running') return { state: 'running' }
413
+ const target = {
414
+ appId: input.environment.appId,
415
+ signal: input.signal,
416
+ ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
417
+ }
418
+ const log = async (line: string): Promise<void> => {
419
+ if (input.log === undefined) console.error(`run ${input.runId}: ${line}`)
420
+ else await input.log(line)
421
+ }
422
+ const outcome = await settleOutcome(options, target, recovery, log, true)
423
+ if (outcome.state === 'running') return outcome
424
+ return {
425
+ state: outcome.state,
426
+ ...(outcome.exitCode === undefined ? {} : { exitCode: outcome.exitCode }),
427
+ ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }),
428
+ ...(recovery.dryRun === true ? { dryRun: true } : {}),
429
+ }
430
+ },
431
+ cancel: async (input) => {
432
+ input.signal.throwIfAborted()
433
+ const interrupted = Promise.withResolvers<never>()
434
+ const abort = (): void => interrupted.reject(input.signal.reason)
435
+ input.signal.addEventListener('abort', abort, { once: true })
436
+ try {
437
+ await Promise.race([options.cancelRun(input.runId), interrupted.promise])
438
+ input.signal.throwIfAborted()
439
+ return { state: 'settled' }
440
+ } finally {
441
+ input.signal.removeEventListener('abort', abort)
442
+ }
229
443
  },
230
- cancel: (input) => options.cancelRun(input.runId),
231
444
  })
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@ export * from 'oblaka-iac'
2
2
  export { type CloudflareAppConfig, type CloudflareAppConfigInput, defineApp, isCloudflareAppConfig, type ResourceContext } from './authoring'
3
3
  export { parseCloudflareArgs, platformComponents } from './cli-args'
4
4
  export type { ParsedCloudflareArgs, PlatformComponent } from './cli-args'
5
- export { type CloudflareArtifact, cloudflareArtifact, cloudflareArtifactCodec, type CloudflareTarget, cloudflareTargetCodec } from './codec'
5
+ export { type CloudflareArtifact, cloudflareArtifact, cloudflareArtifactCodec } from './codec'
6
6
  export {
7
7
  type CloudflareCollaborators,
8
8
  type CloudflareConfigLoader,
@@ -12,15 +12,17 @@ export {
12
12
  defaultCloudflareCollaborators,
13
13
  type LoadedCloudflareConfig,
14
14
  type OblakaProvisioner,
15
+ type OutcomeWriter,
15
16
  type ProvisionInput,
16
17
  type SchemaReconciler,
17
18
  } from './collaborators'
18
19
  export { deployCloudflareConfig, loadCloudflareCommandConfig } from './command'
19
20
  export type { CloudflareCommandDeployOptions, LoadedCloudflareCommandConfig } from './command'
20
- export { cloudflareStoredTargetCodec, createCloudflareControlProvider, isCloudflareRunnerJob } from './control'
21
- export type { CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget, ResolvedCloudflareSource } from './control'
22
- export { buildPlan, findMigratableDatabases } from './plan'
23
- export type { CloudflareJobSpec, CloudflarePlan, CloudflarePlanInput, CloudflareStepKind, MigratableDatabase } from './plan'
24
- export { cloudflareProvider, createCloudflareProvider } from './provider'
21
+ export { cloudflareStoredTargetCodec, createCloudflareControlProvider } from './control'
22
+ export type { CloudflareCloneSource, CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget } from './control'
23
+ export { assertAuthoredGraph, buildPlan, findMigratableDatabases, PLATFORM_RESOURCE_NAMES } from './plan'
24
+ export type { AuthoredGraphLimits, CloudflareStep, CloudflareStepKind, MigratableDatabase } from './plan'
25
+ export { type CloudflareDeployerOptions, type CloudflareDeployResult, type CloudflareDeployRun, createCloudflareDeployer } from './provider'
25
26
  export { createCloudflareProxyWorker } from './proxy'
26
27
  export type { CloudflareProxyWorkerOptions } from './proxy'
28
+ export { type AppSchemaParse, parseAppSchema } from './schema'