@fabrika/provider-cloudflare 0.2.0 → 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/package.json +12 -8
- package/src/cli.ts +7 -8
- package/src/codec.ts +4 -57
- package/src/collaborators.ts +11 -6
- package/src/command.ts +16 -34
- package/src/control.ts +237 -119
- package/src/index.ts +5 -5
- package/src/installation/cloudflare.ts +184 -0
- package/src/installation/envfile.ts +180 -0
- package/src/installation/index.ts +2 -0
- package/src/installation/init.ts +597 -0
- package/src/installation/installation.ts +77 -0
- package/src/installation/scaffold.ts +106 -0
- package/src/installation/templates/README.md +64 -0
- package/src/installation/templates/fabrika.ref +1 -0
- package/src/installation/templates/gitignore +2 -0
- package/src/installation/templates/platform.yml +181 -0
- package/src/plan.ts +21 -31
- package/src/provider.ts +90 -70
- package/src/proxy-worker.ts +1 -1
- package/src/proxy.ts +1 -1
- package/src/runner-protocol.ts +40 -0
- package/src/schema.ts +21 -83
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,34 +8,29 @@ import type {
|
|
|
7
8
|
ProviderRegistration,
|
|
8
9
|
ProviderRegistrationInput,
|
|
9
10
|
ProviderSource,
|
|
11
|
+
ProviderSourceBinding,
|
|
12
|
+
ProviderSourceResolution,
|
|
13
|
+
ProviderSourceResolutionInput,
|
|
10
14
|
ProviderTerminalOutcome,
|
|
11
15
|
SchemaReconciler,
|
|
12
16
|
} from '@fabrika/provider-contract'
|
|
13
|
-
import {
|
|
14
|
-
import
|
|
17
|
+
import { abortableWait, decodeEnvelope, isLeaseLoss, ProviderInvocationAbort } from '@fabrika/provider-contract'
|
|
18
|
+
import { isProxyHost } from '@fabrika/proxy-core/manifest'
|
|
19
|
+
import { z } from 'zod'
|
|
15
20
|
import { cloudflareArtifactCodec } from './codec'
|
|
21
|
+
import { type RunnerIamReconcile, runnerIamReconcileSchema } from './runner-protocol'
|
|
16
22
|
// `./runner` is this module: keep every import here clear of `oblaka-iac`, which the runner packages
|
|
17
23
|
// cannot typecheck (they do not relax the two strict flags the raw TS needs).
|
|
18
24
|
import { defaultReconcileSchema, parseAppSchema } from './schema'
|
|
19
25
|
|
|
26
|
+
export * from './runner-protocol'
|
|
27
|
+
|
|
20
28
|
/** Persisted Cloudflare target data. Installation credentials never enter this envelope. */
|
|
21
29
|
export interface CloudflareStoredTarget {
|
|
22
30
|
readonly stateNamespace?: string
|
|
23
31
|
}
|
|
24
32
|
|
|
25
|
-
const
|
|
26
|
-
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
|
|
27
|
-
throw new Error('Cloudflare target must be an object')
|
|
28
|
-
}
|
|
29
|
-
const value = payload[key]
|
|
30
|
-
if (value === undefined) {
|
|
31
|
-
return undefined
|
|
32
|
-
}
|
|
33
|
-
if (typeof value !== 'string' || value === '') {
|
|
34
|
-
throw new Error(`Cloudflare target ${key} must be a non-empty string when present`)
|
|
35
|
-
}
|
|
36
|
-
return value
|
|
37
|
-
}
|
|
33
|
+
const storedTargetSchema = z.object({ stateNamespace: z.string().min(1).optional() })
|
|
38
34
|
|
|
39
35
|
export const cloudflareStoredTargetCodec: ProviderCodec<CloudflareStoredTarget> = {
|
|
40
36
|
version: 1,
|
|
@@ -45,7 +41,7 @@ export const cloudflareStoredTargetCodec: ProviderCodec<CloudflareStoredTarget>
|
|
|
45
41
|
return { stateNamespace: target.stateNamespace }
|
|
46
42
|
},
|
|
47
43
|
decode: (payload) => {
|
|
48
|
-
const stateNamespace =
|
|
44
|
+
const { stateNamespace } = storedTargetSchema.parse(payload)
|
|
49
45
|
return stateNamespace === undefined ? {} : { stateNamespace }
|
|
50
46
|
},
|
|
51
47
|
}
|
|
@@ -60,7 +56,7 @@ export interface CloudflareRunnerJob {
|
|
|
60
56
|
readonly configPath?: string
|
|
61
57
|
readonly stateNamespace?: string
|
|
62
58
|
readonly domain?: string
|
|
63
|
-
/** Every origin IAM may hand this app a session at, projected by the control plane (ADR-
|
|
59
|
+
/** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0022). */
|
|
64
60
|
readonly returnOrigins?: readonly string[]
|
|
65
61
|
readonly dryRun?: boolean
|
|
66
62
|
/**
|
|
@@ -87,25 +83,10 @@ export interface CloudflareRunnerJob {
|
|
|
87
83
|
}
|
|
88
84
|
}
|
|
89
85
|
|
|
90
|
-
const isStringArray = (value: unknown): boolean => Array.isArray(value) && value.every((entry) => typeof entry === 'string' && entry !== '')
|
|
91
|
-
|
|
92
|
-
const isStringRecord = (value: unknown): boolean =>
|
|
93
|
-
typeof value === 'object'
|
|
94
|
-
&& value !== null
|
|
95
|
-
&& !Array.isArray(value)
|
|
96
|
-
&& Object.values(value).every((entry) => typeof entry === 'string')
|
|
97
|
-
|
|
98
|
-
const isArtifactUpload = (value: unknown): boolean =>
|
|
99
|
-
typeof value === 'object'
|
|
100
|
-
&& value !== null
|
|
101
|
-
&& !Array.isArray(value)
|
|
102
|
-
&& ['url', 'bearer', 'appId', 'environment', 'serviceKey', 'release', 'runId'].every((key) => {
|
|
103
|
-
const field = Reflect.get(value, key)
|
|
104
|
-
return typeof field === 'string' && field !== ''
|
|
105
|
-
})
|
|
106
|
-
|
|
107
86
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
108
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)
|
|
109
90
|
|
|
110
91
|
/** Whitespace or a control character in a value that becomes an argv element or a filesystem path. */
|
|
111
92
|
const hasUnsafeChars = (value: string): boolean =>
|
|
@@ -126,61 +107,52 @@ const isHttpsUrl = (value: string): boolean => {
|
|
|
126
107
|
const isContainedPath = (value: string): boolean =>
|
|
127
108
|
value !== '' && !value.startsWith('/') && !hasUnsafeChars(value) && !value.split('/').includes('..')
|
|
128
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
|
+
|
|
129
116
|
/**
|
|
130
117
|
* Validate the Worker-to-runner JSON boundary by VALUE, not only by type: every field here becomes an
|
|
131
118
|
* argv element, a filesystem path or a hostname inside the deploy container.
|
|
132
119
|
*/
|
|
133
|
-
export const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
)
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
// container carries none. Present means it must be usable; the Worker is what REQUIRES it.
|
|
160
|
-
('runnerKey' in value && value.runnerKey !== undefined && (typeof value.runnerKey !== 'string' || value.runnerKey === ''))
|
|
161
|
-
|| ('workerDir' in value && value.workerDir !== undefined && (typeof value.workerDir !== 'string' || !isContainedPath(value.workerDir)))
|
|
162
|
-
|| ('configPath' in value && value.configPath !== undefined && (typeof value.configPath !== 'string' || !isContainedPath(value.configPath)))
|
|
163
|
-
|| ('stateNamespace' in value && value.stateNamespace !== undefined && (typeof value.stateNamespace !== 'string' || value.stateNamespace === ''))
|
|
164
|
-
|| ('domain' in value && value.domain !== undefined && (typeof value.domain !== 'string' || !isProxyHost(value.domain.toLowerCase())))
|
|
165
|
-
|| ('returnOrigins' in value && value.returnOrigins !== undefined && !isStringArray(value.returnOrigins))
|
|
166
|
-
|| ('dryRun' in value && value.dryRun !== undefined && typeof value.dryRun !== 'boolean')
|
|
167
|
-
|| ('secrets' in value && value.secrets !== undefined && !isStringRecord(value.secrets))
|
|
168
|
-
|| ('vars' in value && value.vars !== undefined && !isStringRecord(value.vars))
|
|
169
|
-
|| ('managedEnvironment' in value && value.managedEnvironment !== undefined && !isStringRecord(value.managedEnvironment))
|
|
170
|
-
|| ('artifactUpload' in value && value.artifactUpload !== undefined && !isArtifactUpload(value.artifactUpload))
|
|
171
|
-
) {
|
|
172
|
-
return false
|
|
173
|
-
}
|
|
174
|
-
return true
|
|
175
|
-
}
|
|
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))
|
|
176
146
|
|
|
177
|
-
export interface
|
|
147
|
+
export interface CloudflareCloneSource {
|
|
178
148
|
readonly repoUrl: string
|
|
179
|
-
readonly ref: string
|
|
180
149
|
}
|
|
181
150
|
|
|
182
151
|
/** A run's terminal outcome plus the IAM reconcile the executor compiled, if the plan reached that step. */
|
|
183
|
-
export type CloudflareRunOutcome = ProviderTerminalOutcome & { readonly iamReconcile?: RunnerIamReconcile }
|
|
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' }
|
|
184
156
|
|
|
185
157
|
export interface CloudflareControlOptions {
|
|
186
158
|
readonly accountId: string
|
|
@@ -190,19 +162,27 @@ export interface CloudflareControlOptions {
|
|
|
190
162
|
readonly runnerKey: string
|
|
191
163
|
/** Overridable for tests; production reconciles over HTTPS with the control plane's own admin key. */
|
|
192
164
|
readonly reconcileSchema?: SchemaReconciler
|
|
193
|
-
resolveSource(
|
|
165
|
+
resolveSource(input: ProviderSourceResolutionInput): Promise<ProviderSourceResolution>
|
|
166
|
+
prepareClone(source: ProviderSource, signal: AbortSignal, sourceBinding?: ProviderSourceBinding): Promise<CloudflareCloneSource>
|
|
194
167
|
startRun(job: CloudflareRunnerJob): Promise<CloudflareRunOutcome>
|
|
195
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>
|
|
196
172
|
}
|
|
197
173
|
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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.
|
|
204
185
|
}
|
|
205
|
-
return codec.decode(envelope.payload)
|
|
206
186
|
}
|
|
207
187
|
|
|
208
188
|
const encodeEnvelope = <T>(codec: ProviderCodec<T>, value: T): ProviderEnvelope => ({
|
|
@@ -211,12 +191,16 @@ const encodeEnvelope = <T>(codec: ProviderCodec<T>, value: T): ProviderEnvelope
|
|
|
211
191
|
payload: codec.encode(value),
|
|
212
192
|
})
|
|
213
193
|
|
|
214
|
-
const
|
|
194
|
+
const assertRegistrationApp = (input: ProviderRegistrationInput): void => {
|
|
215
195
|
if (input.app.id !== input.environment.appId) {
|
|
216
196
|
throw new Error(`Cloudflare environment belongs to app "${input.environment.appId}", expected "${input.app.id}"`)
|
|
217
197
|
}
|
|
218
|
-
|
|
219
|
-
|
|
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)
|
|
220
204
|
return {
|
|
221
205
|
app: input.app,
|
|
222
206
|
environment: {
|
|
@@ -227,10 +211,33 @@ const normalizeRegistration = (input: ProviderRegistrationInput): ProviderRegist
|
|
|
227
211
|
}
|
|
228
212
|
}
|
|
229
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
|
+
|
|
230
231
|
const buildJob = async (options: CloudflareControlOptions, input: ProviderDeployInput): Promise<CloudflareRunnerJob> => {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const
|
|
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))
|
|
234
241
|
const managedEnvironment: Record<string, string> = {}
|
|
235
242
|
for (const [name, value] of Object.entries(input.managedEnvironment)) {
|
|
236
243
|
if (value !== null) managedEnvironment[name] = value
|
|
@@ -238,7 +245,7 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
|
|
|
238
245
|
return {
|
|
239
246
|
runId: input.runId,
|
|
240
247
|
repoUrl: source.repoUrl,
|
|
241
|
-
ref
|
|
248
|
+
ref,
|
|
242
249
|
env: input.environment.env,
|
|
243
250
|
runnerKey: options.runnerKey,
|
|
244
251
|
credentials: {
|
|
@@ -261,66 +268,177 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
|
|
|
261
268
|
/** A megabyte of vocabulary is already absurd; beyond it the control plane refuses to parse at all. */
|
|
262
269
|
const MAX_SCHEMA_JSON_CHARS = 1024 * 1024
|
|
263
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
|
+
|
|
264
281
|
/**
|
|
265
|
-
* Apply the schema the executor compiled, with the control plane's own IAM key. The
|
|
266
|
-
*
|
|
267
|
-
* type-checked, bounded and parsed here before IAM hears about it.
|
|
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.
|
|
268
284
|
*/
|
|
269
285
|
const applyIamReconcile = async (
|
|
270
286
|
options: CloudflareControlOptions,
|
|
271
|
-
|
|
272
|
-
|
|
287
|
+
target: IamReconcileTarget,
|
|
288
|
+
report: RunnerIamReconcile,
|
|
273
289
|
): Promise<void> => {
|
|
274
|
-
|
|
275
|
-
if (
|
|
276
|
-
throw new
|
|
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')
|
|
277
293
|
}
|
|
278
|
-
|
|
279
|
-
|
|
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}"`)
|
|
280
297
|
}
|
|
281
298
|
if (reconcile.schemaJson.length > MAX_SCHEMA_JSON_CHARS) {
|
|
282
|
-
throw new
|
|
299
|
+
throw new InvalidIamReport(`reported an authz schema of ${reconcile.schemaJson.length} characters, over the ${MAX_SCHEMA_JSON_CHARS} limit`)
|
|
283
300
|
}
|
|
284
301
|
let parsed: unknown
|
|
285
302
|
try {
|
|
286
303
|
parsed = JSON.parse(reconcile.schemaJson)
|
|
287
304
|
} catch {
|
|
288
|
-
throw new
|
|
305
|
+
throw new InvalidIamReport('reported an authz schema that is not valid JSON')
|
|
289
306
|
}
|
|
290
307
|
const schema = parseAppSchema(parsed)
|
|
291
308
|
if (!schema.ok) {
|
|
292
|
-
throw new
|
|
309
|
+
throw new InvalidIamReport(`reported a malformed authz schema: ${schema.message}`)
|
|
293
310
|
}
|
|
294
311
|
if (options.propustkaUrl === undefined) return
|
|
295
312
|
// Return origins ride this call because `apps.setReturnOrigins` 404s for an app IAM has never heard
|
|
296
313
|
// of, and the schema reconcile is what registers it. Separate call, same moment.
|
|
297
|
-
const returnOrigins =
|
|
314
|
+
const returnOrigins = target.returnOrigins !== undefined && target.returnOrigins.length > 0 ? target.returnOrigins : undefined
|
|
298
315
|
await (options.reconcileSchema ?? defaultReconcileSchema)({
|
|
299
316
|
url: options.propustkaUrl,
|
|
300
|
-
app:
|
|
317
|
+
app: target.appId,
|
|
301
318
|
schema: schema.schema,
|
|
302
319
|
...(returnOrigins === undefined ? {} : { returnOrigins }),
|
|
303
320
|
...(options.propustkaProvisioningKey === undefined ? {} : { adminKey: options.propustkaProvisioningKey }),
|
|
304
|
-
signal:
|
|
321
|
+
signal: target.signal,
|
|
305
322
|
})
|
|
306
323
|
}
|
|
307
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
|
+
|
|
308
363
|
/** Build the Cloudflare control capability over its runner and source-resolution ports. */
|
|
309
364
|
export const createCloudflareControlProvider = (options: CloudflareControlOptions): ControlProvider => ({
|
|
310
365
|
id: 'cloudflare',
|
|
311
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
|
+
},
|
|
312
373
|
deploy: async (input) => {
|
|
374
|
+
const job = await buildJob(options, input)
|
|
313
375
|
await input.events.externalId(input.runId)
|
|
314
|
-
|
|
315
|
-
const
|
|
316
|
-
|
|
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
|
|
317
391
|
try {
|
|
318
|
-
await
|
|
392
|
+
outcome = await Promise.race([options.startRun(job), interrupted.promise])
|
|
319
393
|
} catch (error) {
|
|
320
|
-
input.
|
|
321
|
-
|
|
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)
|
|
322
442
|
}
|
|
323
|
-
return outcome
|
|
324
443
|
},
|
|
325
|
-
cancel: (input) => options.cancelRun(input.runId),
|
|
326
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
|
|
5
|
+
export { type CloudflareArtifact, cloudflareArtifact, cloudflareArtifactCodec } from './codec'
|
|
6
6
|
export {
|
|
7
7
|
type CloudflareCollaborators,
|
|
8
8
|
type CloudflareConfigLoader,
|
|
@@ -18,11 +18,11 @@ export {
|
|
|
18
18
|
} from './collaborators'
|
|
19
19
|
export { deployCloudflareConfig, loadCloudflareCommandConfig } from './command'
|
|
20
20
|
export type { CloudflareCommandDeployOptions, LoadedCloudflareCommandConfig } from './command'
|
|
21
|
-
export { cloudflareStoredTargetCodec, createCloudflareControlProvider
|
|
22
|
-
export type { CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget
|
|
21
|
+
export { cloudflareStoredTargetCodec, createCloudflareControlProvider } from './control'
|
|
22
|
+
export type { CloudflareCloneSource, CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget } from './control'
|
|
23
23
|
export { assertAuthoredGraph, buildPlan, findMigratableDatabases, PLATFORM_RESOURCE_NAMES } from './plan'
|
|
24
|
-
export type { AuthoredGraphLimits,
|
|
25
|
-
export {
|
|
24
|
+
export type { AuthoredGraphLimits, CloudflareStep, CloudflareStepKind, MigratableDatabase } from './plan'
|
|
25
|
+
export { type CloudflareDeployerOptions, type CloudflareDeployResult, type CloudflareDeployRun, createCloudflareDeployer } from './provider'
|
|
26
26
|
export { createCloudflareProxyWorker } from './proxy'
|
|
27
27
|
export type { CloudflareProxyWorkerOptions } from './proxy'
|
|
28
28
|
export { type AppSchemaParse, parseAppSchema } from './schema'
|