@fabrika/provider-cloudflare 0.0.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 ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@fabrika/provider-cloudflare",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/contember/fabrika-platform.git",
8
+ "directory": "packages/provider-cloudflare"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "files": [
14
+ "src",
15
+ "!src/**/__tests__/**"
16
+ ],
17
+ "exports": {
18
+ ".": {
19
+ "bun": "./src/index.ts",
20
+ "types": "./src/index.ts",
21
+ "default": "./src/index.ts"
22
+ },
23
+ "./cli": {
24
+ "bun": "./src/cli.ts",
25
+ "types": "./src/cli.ts",
26
+ "default": "./src/cli.ts"
27
+ },
28
+ "./runner": {
29
+ "bun": "./src/control.ts",
30
+ "types": "./src/control.ts",
31
+ "default": "./src/control.ts"
32
+ }
33
+ },
34
+ "scripts": {
35
+ "typecheck": "tsc --noEmit",
36
+ "test": "bun test"
37
+ },
38
+ "dependencies": {
39
+ "@fabrika/auth": "^0.0.1",
40
+ "@fabrika/engine": "^0.0.1",
41
+ "@fabrika/proxy-core": "^0.0.1",
42
+ "@fabrika/proxy-contract": "^0.0.1",
43
+ "@fabrika/provider-contract": "^0.0.1",
44
+ "oblaka-iac": "^0.0.18"
45
+ }
46
+ }
@@ -0,0 +1,34 @@
1
+ import { APP_PROVIDER, type AppConfigBase, isProviderAuthoredApp, type ProviderAuthoredApp } from '@fabrika/provider-contract'
2
+ import type { Worker } from 'oblaka-iac'
3
+
4
+ /** Inputs used to materialize one environment's Cloudflare resource graph. */
5
+ export interface ResourceContext {
6
+ readonly env: string
7
+ readonly domain?: string
8
+ }
9
+
10
+ /** A Cloudflare app config loaded from `fabrika.config.ts` inside the runner checkout. */
11
+ export interface CloudflareAppConfigInput extends AppConfigBase {
12
+ readonly resources: (ctx: ResourceContext) => Worker
13
+ }
14
+
15
+ export type CloudflareAppConfig = CloudflareAppConfigInput & ProviderAuthoredApp<'cloudflare'>
16
+
17
+ /** Preserve literal inference while validating the provider's required app id. */
18
+ export function defineApp(config: CloudflareAppConfigInput): CloudflareAppConfig {
19
+ if (typeof config.id !== 'string' || config.id.trim() === '') {
20
+ throw new Error('defineApp: `id` is required and must be a non-empty string')
21
+ }
22
+ return { ...config, [APP_PROVIDER]: 'cloudflare' }
23
+ }
24
+
25
+ /** Narrow an imported module default without trusting code from the checkout. */
26
+ export const isCloudflareAppConfig = (value: unknown): value is CloudflareAppConfig =>
27
+ isProviderAuthoredApp(value, 'cloudflare')
28
+ && typeof value === 'object'
29
+ && value !== null
30
+ && 'id' in value
31
+ && typeof value.id === 'string'
32
+ && value.id.trim() !== ''
33
+ && 'resources' in value
34
+ && typeof value.resources === 'function'
@@ -0,0 +1,72 @@
1
+ export interface ParsedCloudflareArgs {
2
+ readonly command: string | undefined
3
+ readonly subcommand: string | undefined
4
+ readonly env: string | undefined
5
+ readonly config: string
6
+ readonly runnerConfig: string | undefined
7
+ readonly workerConfig: string | undefined
8
+ readonly managedVarNames: readonly string[]
9
+ readonly dryRun: boolean
10
+ readonly help: boolean
11
+ }
12
+
13
+ export const parseCloudflareArgs = (argv: readonly string[]): ParsedCloudflareArgs => {
14
+ let command: string | undefined
15
+ let subcommand: string | undefined
16
+ let env: string | undefined
17
+ let config = './fabrika.config.ts'
18
+ let runnerConfig: string | undefined
19
+ let workerConfig: string | undefined
20
+ const managedVarNames: string[] = []
21
+ let dryRun = false
22
+ let help = false
23
+
24
+ for (const arg of argv) {
25
+ if (arg === '-h' || arg === '--help') {
26
+ help = true
27
+ } else if (arg === '--dry-run') {
28
+ dryRun = true
29
+ } else if (arg.startsWith('--env=')) {
30
+ env = arg.slice('--env='.length)
31
+ } else if (arg.startsWith('--config=')) {
32
+ config = arg.slice('--config='.length)
33
+ } else if (arg.startsWith('--runner-config=')) {
34
+ runnerConfig = arg.slice('--runner-config='.length)
35
+ } else if (arg.startsWith('--worker-config=')) {
36
+ workerConfig = arg.slice('--worker-config='.length)
37
+ } else if (arg.startsWith('--managed-var=')) {
38
+ const name = arg.slice('--managed-var='.length)
39
+ if (!/^[A-Z][A-Z0-9_]*$/.test(name)) {
40
+ throw new Error('Invalid --managed-var name')
41
+ }
42
+ managedVarNames.push(name)
43
+ } else if (!arg.startsWith('-')) {
44
+ if (command === undefined) {
45
+ command = arg
46
+ } else if (subcommand === undefined) {
47
+ subcommand = arg
48
+ }
49
+ }
50
+ }
51
+
52
+ return { command, subcommand, env, config, runnerConfig, workerConfig, managedVarNames, dryRun, help }
53
+ }
54
+
55
+ export interface PlatformComponent {
56
+ readonly label: string
57
+ readonly configPath: string
58
+ }
59
+
60
+ /** The executor must exist before the control plane binds to it. */
61
+ export const platformComponents = (runnerConfig: string | undefined, workerConfig: string | undefined): readonly PlatformComponent[] => {
62
+ if (runnerConfig === undefined || runnerConfig === '') {
63
+ throw new Error('Missing --runner-config=<path> for `platform deploy`')
64
+ }
65
+ if (workerConfig === undefined || workerConfig === '') {
66
+ throw new Error('Missing --worker-config=<path> for `platform deploy`')
67
+ }
68
+ return [
69
+ { label: 'vozka-runner', configPath: runnerConfig },
70
+ { label: 'vozka', configPath: workerConfig },
71
+ ]
72
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import type { ProviderDeployResult } from '@fabrika/provider-contract'
4
+ import { parseCloudflareArgs } from './cli-args'
5
+ import { deployCloudflareConfig } from './command'
6
+
7
+ const USAGE = `Internal Cloudflare app executor
8
+
9
+ Usage:
10
+ fabrika-cloudflare-executor deploy --env=<env> [--config=<path>] [--managed-var=<name>] [--dry-run]
11
+
12
+ Options:
13
+ --env=<env> Target environment.
14
+ --config=<path> App config path (default: ./fabrika.config.ts).
15
+ --managed-var=<name> Platform-owned environment name; repeatable. Values stay in the environment.
16
+ --dry-run Plan only; do not mutate remote resources.
17
+ -h, --help Show this help.
18
+
19
+ Credentials, declared secrets and declared vars are read only from the environment.
20
+ `
21
+
22
+ const die = (message: string): never => {
23
+ throw new Error(message)
24
+ }
25
+
26
+ const formatDuration = (step: ProviderDeployResult['steps'][number]): string => {
27
+ if (step.startedAt === undefined || step.finishedAt === undefined) {
28
+ return ''
29
+ }
30
+ return ` (${step.finishedAt - step.startedAt}ms)`
31
+ }
32
+
33
+ const ICON: Readonly<Record<string, string>> = {
34
+ pending: '·',
35
+ running: '…',
36
+ succeeded: '✓',
37
+ failed: '✗',
38
+ skipped: '∅',
39
+ }
40
+
41
+ const printResult = (result: ProviderDeployResult): void => {
42
+ console.log(`\n${result.appId} → ${result.env}: ${result.status}`)
43
+ for (const step of result.steps) {
44
+ console.log(` ${ICON[step.status] ?? '?'} ${step.spec.id} — ${step.status}${formatDuration(step)}`)
45
+ if (step.error !== undefined) {
46
+ console.log(` ${step.error}`)
47
+ }
48
+ }
49
+ }
50
+
51
+ const requireSuccessful = (result: ProviderDeployResult): void => {
52
+ printResult(result)
53
+ if (result.status === 'failed') {
54
+ throw new Error('Cloudflare deployment failed')
55
+ }
56
+ }
57
+
58
+ export const runCloudflareCli = async (argv: readonly string[]): Promise<void> => {
59
+ const args = parseCloudflareArgs(argv)
60
+ if (args.help || args.command === undefined) {
61
+ console.log(USAGE)
62
+ return
63
+ }
64
+ if (args.command !== 'deploy') {
65
+ const command = args.subcommand === undefined ? args.command : `${args.command} ${args.subcommand}`
66
+ die(`Unknown command: ${command}\n\n${USAGE}`)
67
+ }
68
+ const env = args.env ?? die(`Missing --env=<env>\n\n${USAGE}`)
69
+ requireSuccessful(
70
+ await deployCloudflareConfig({
71
+ env,
72
+ configPath: args.config,
73
+ dryRun: args.dryRun,
74
+ managedVarNames: args.managedVarNames,
75
+ stateNamespace: process.env['CLOUDFLARE_STATE_NAMESPACE'],
76
+ }),
77
+ )
78
+ }
79
+
80
+ if (import.meta.main) {
81
+ await runCloudflareCli(process.argv.slice(2)).catch((error: unknown) => {
82
+ console.error(`fabrika-cloudflare-executor: ${error instanceof Error ? error.message : 'unknown error'}`)
83
+ process.exit(1)
84
+ })
85
+ }
package/src/codec.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { JsonValue, ProviderCodec } from '@fabrika/provider-contract'
2
+
3
+ /** Ephemeral credentials and handles used by one Cloudflare deploy. */
4
+ export interface CloudflareTarget {
5
+ readonly accountId: string
6
+ readonly apiToken: string
7
+ readonly stateNamespace?: string
8
+ readonly propustkaUrl?: string
9
+ readonly adminKey?: string
10
+ }
11
+
12
+ /** A checkout recipe. The Oblaka graph stays executable code in the referenced config module. */
13
+ export interface CloudflareArtifact {
14
+ readonly configPath: string
15
+ }
16
+
17
+ const objectProperty = (value: JsonValue, property: string): JsonValue => {
18
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
19
+ throw new Error('expected an object')
20
+ }
21
+ const propertyValue = value[property]
22
+ if (propertyValue === undefined) {
23
+ throw new Error(`missing ${property}`)
24
+ }
25
+ return propertyValue
26
+ }
27
+
28
+ const stringProperty = (value: JsonValue, property: string): string => {
29
+ const propertyValue = objectProperty(value, property)
30
+ if (typeof propertyValue !== 'string' || propertyValue === '') {
31
+ throw new Error(`${property} must be a non-empty string`)
32
+ }
33
+ return propertyValue
34
+ }
35
+
36
+ const optionalStringProperty = (value: JsonValue, property: string): string | undefined => {
37
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
38
+ throw new Error('expected an object')
39
+ }
40
+ const propertyValue = value[property]
41
+ if (propertyValue === undefined) {
42
+ return undefined
43
+ }
44
+ if (typeof propertyValue !== 'string' || propertyValue === '') {
45
+ throw new Error(`${property} must be a non-empty string`)
46
+ }
47
+ return propertyValue
48
+ }
49
+
50
+ export const cloudflareTargetCodec: ProviderCodec<CloudflareTarget> = {
51
+ version: 1,
52
+ encode: (target) => ({
53
+ accountId: target.accountId,
54
+ apiToken: target.apiToken,
55
+ ...(target.stateNamespace === undefined ? {} : { stateNamespace: target.stateNamespace }),
56
+ ...(target.propustkaUrl === undefined ? {} : { propustkaUrl: target.propustkaUrl }),
57
+ ...(target.adminKey === undefined ? {} : { adminKey: target.adminKey }),
58
+ }),
59
+ decode: (payload) => ({
60
+ accountId: stringProperty(payload, 'accountId'),
61
+ apiToken: stringProperty(payload, 'apiToken'),
62
+ ...(optionalStringProperty(payload, 'stateNamespace') === undefined
63
+ ? {}
64
+ : { stateNamespace: optionalStringProperty(payload, 'stateNamespace') }),
65
+ ...(optionalStringProperty(payload, 'propustkaUrl') === undefined
66
+ ? {}
67
+ : { propustkaUrl: optionalStringProperty(payload, 'propustkaUrl') }),
68
+ ...(optionalStringProperty(payload, 'adminKey') === undefined ? {} : { adminKey: optionalStringProperty(payload, 'adminKey') }),
69
+ }),
70
+ }
71
+
72
+ export const cloudflareArtifactCodec: ProviderCodec<CloudflareArtifact> = {
73
+ version: 1,
74
+ encode: (artifact) => ({ configPath: artifact.configPath }),
75
+ decode: (payload) => ({ configPath: stringProperty(payload, 'configPath') }),
76
+ }
77
+
78
+ /** Build the default checkout recipe used by the Cloudflare runner. */
79
+ export const cloudflareArtifact = (configPath = 'fabrika.config.ts'): CloudflareArtifact => ({ configPath })
@@ -0,0 +1,104 @@
1
+ import type { SchemaReconciler } from '@fabrika/provider-contract'
2
+ import { resolve } from 'node:path'
3
+ import { type Definition, deploy as oblakaDeploy, type DeployResult as OblakaDeployResult } from 'oblaka-iac'
4
+ import { type CloudflareAppConfig, isCloudflareAppConfig } from './authoring'
5
+ import { defaultReconcileSchema } from './schema'
6
+
7
+ export interface CommandSpec {
8
+ readonly command: string
9
+ readonly args: string[]
10
+ readonly cwd: string
11
+ readonly env?: Record<string, string>
12
+ readonly stdin?: string
13
+ readonly signal?: AbortSignal
14
+ }
15
+
16
+ export interface CommandResult {
17
+ readonly exitCode: number
18
+ readonly stdout: string
19
+ readonly stderr: string
20
+ }
21
+
22
+ export type CommandRunner = (spec: CommandSpec) => Promise<CommandResult>
23
+
24
+ export interface ProvisionInput {
25
+ readonly definition: Definition
26
+ readonly accountId: string
27
+ readonly apiToken: string
28
+ readonly env: string
29
+ readonly cwd: string
30
+ readonly stateNamespace: string
31
+ readonly dryRun: boolean
32
+ }
33
+
34
+ export type OblakaProvisioner = (input: ProvisionInput) => Promise<OblakaDeployResult>
35
+
36
+ export interface LoadedCloudflareConfig {
37
+ readonly config: CloudflareAppConfig
38
+ readonly cwd: string
39
+ }
40
+
41
+ export type CloudflareConfigLoader = (cwd: string, configPath: string) => Promise<LoadedCloudflareConfig>
42
+
43
+ export interface CloudflareCollaborators {
44
+ readonly loadConfig: CloudflareConfigLoader
45
+ readonly runCommand: CommandRunner
46
+ readonly provision: OblakaProvisioner
47
+ readonly reconcileSchema: SchemaReconciler
48
+ }
49
+
50
+ const defaultLoadConfig: CloudflareConfigLoader = async (cwd, configPath) => {
51
+ const absolute = resolve(cwd, configPath)
52
+ const loaded: unknown = await import(absolute)
53
+ if (typeof loaded !== 'object' || loaded === null || !('default' in loaded) || !isCloudflareAppConfig(loaded.default)) {
54
+ throw new Error(`Cloudflare config at ${absolute} must export a valid default defineApp(...) value`)
55
+ }
56
+ return { config: loaded.default, cwd: resolve(absolute, '..') }
57
+ }
58
+
59
+ const defaultRunCommand: CommandRunner = async (spec) => {
60
+ const proc = Bun.spawn([spec.command, ...spec.args], {
61
+ cwd: spec.cwd,
62
+ env: { ...process.env, ...spec.env },
63
+ stdin: spec.stdin === undefined ? 'inherit' : new TextEncoder().encode(spec.stdin),
64
+ stdout: 'pipe',
65
+ stderr: 'pipe',
66
+ })
67
+ const kill = (): void => {
68
+ proc.kill()
69
+ }
70
+ if (spec.signal?.aborted === true) {
71
+ kill()
72
+ }
73
+ spec.signal?.addEventListener('abort', kill, { once: true })
74
+ try {
75
+ const [stdout, stderr, exitCode] = await Promise.all([
76
+ new Response(proc.stdout).text(),
77
+ new Response(proc.stderr).text(),
78
+ proc.exited,
79
+ ])
80
+ return { exitCode, stdout, stderr }
81
+ } finally {
82
+ spec.signal?.removeEventListener('abort', kill)
83
+ }
84
+ }
85
+
86
+ const defaultProvision: OblakaProvisioner = (input) =>
87
+ oblakaDeploy(input.definition, {
88
+ accountId: input.accountId,
89
+ apiToken: input.apiToken,
90
+ env: input.env,
91
+ cwd: input.cwd,
92
+ stateNamespace: input.stateNamespace,
93
+ remote: !input.dryRun,
94
+ dryRun: input.dryRun,
95
+ })
96
+
97
+ export const defaultCloudflareCollaborators: CloudflareCollaborators = {
98
+ loadConfig: defaultLoadConfig,
99
+ runCommand: defaultRunCommand,
100
+ provision: defaultProvision,
101
+ reconcileSchema: defaultReconcileSchema,
102
+ }
103
+
104
+ export type { SchemaReconciler }
package/src/command.ts ADDED
@@ -0,0 +1,108 @@
1
+ import { deploy } from '@fabrika/engine'
2
+ import type { ProviderDeployResult, ProviderRunEvents, RuntimeProviderRun } from '@fabrika/provider-contract'
3
+ import { resolve } from 'node:path'
4
+ import { type CloudflareAppConfig, isCloudflareAppConfig } from './authoring'
5
+ import { cloudflareArtifact } from './codec'
6
+ import { cloudflareProvider } from './provider'
7
+
8
+ const requiredEnvironmentValue = (name: string): string => {
9
+ const value = environmentValue(name)
10
+ if (value === undefined || value === '') {
11
+ throw new Error(`Missing ${name} environment variable`)
12
+ }
13
+ return value
14
+ }
15
+
16
+ const declaredValues = (names: readonly string[] | undefined): Record<string, string> => {
17
+ const values: Record<string, string> = {}
18
+ for (const name of names ?? []) {
19
+ const value = environmentValue(name)
20
+ if (value !== undefined && value !== '') {
21
+ values[name] = value
22
+ }
23
+ }
24
+ return values
25
+ }
26
+
27
+ const environmentValue = (name: string): string | undefined => process.env[name]
28
+
29
+ const requiredValues = (names: readonly string[] | undefined): Record<string, string> => {
30
+ const values: Record<string, string> = {}
31
+ for (const name of names ?? []) {
32
+ values[name] = requiredEnvironmentValue(name)
33
+ }
34
+ return values
35
+ }
36
+
37
+ /**
38
+ * Decode `FABRIKA_IAM_RETURN_ORIGINS`, the comma-separated set the control plane projects into the
39
+ * deploy environment (ADR-0021). Undefined for an absent or empty value, so a deploy with nothing to
40
+ * project leaves IAM's registry alone rather than clearing it. Part of the executor's environment
41
+ * contract, exported for the test that pins it; not part of the package's public surface.
42
+ */
43
+ export const parseReturnOrigins = (raw: string | undefined): readonly string[] | undefined => {
44
+ const origins = (raw ?? '').split(',').map((entry) => entry.trim()).filter((entry) => entry !== '')
45
+ return origins.length === 0 ? undefined : origins
46
+ }
47
+
48
+ export interface LoadedCloudflareCommandConfig {
49
+ readonly config: CloudflareAppConfig
50
+ readonly absolutePath: string
51
+ readonly cwd: string
52
+ }
53
+
54
+ export const loadCloudflareCommandConfig = async (configPath: string, cwd: string): Promise<LoadedCloudflareCommandConfig> => {
55
+ const absolutePath = resolve(cwd, configPath)
56
+ const loaded: unknown = await import(absolutePath)
57
+ if (typeof loaded !== 'object' || loaded === null || !('default' in loaded) || !isCloudflareAppConfig(loaded.default)) {
58
+ throw new Error(`Cloudflare config at ${absolutePath} must export a valid default defineApp(...) value`)
59
+ }
60
+ return { config: loaded.default, absolutePath, cwd: resolve(absolutePath, '..') }
61
+ }
62
+
63
+ export interface CloudflareCommandDeployOptions {
64
+ readonly env: string
65
+ readonly configPath?: string
66
+ readonly cwd?: string
67
+ readonly dryRun?: boolean
68
+ readonly stateNamespace?: string
69
+ readonly managedVarNames?: readonly string[]
70
+ readonly signal?: AbortSignal
71
+ readonly log?: (line: string) => void
72
+ }
73
+
74
+ /** Build an opaque provider run from one config and execute it through the neutral engine. */
75
+ export const deployCloudflareConfig = async (options: CloudflareCommandDeployOptions): Promise<ProviderDeployResult> => {
76
+ const cwd = options.cwd ?? process.cwd()
77
+ const loaded = await loadCloudflareCommandConfig(options.configPath ?? './fabrika.config.ts', cwd)
78
+ const events: ProviderRunEvents = {
79
+ log: options.log ?? ((line) => console.log(line)),
80
+ externalId: async () => {},
81
+ }
82
+ const domain = environmentValue('FABRIKA_CONTROL_DOMAIN')
83
+ const iamUrl = environmentValue('FABRIKA_IAM_URL')
84
+ const iamProvisioningKey = environmentValue('FABRIKA_IAM_PROVISIONING_KEY')
85
+ const returnOrigins = parseReturnOrigins(environmentValue('FABRIKA_IAM_RETURN_ORIGINS'))
86
+ const run: RuntimeProviderRun = {
87
+ appId: loaded.config.id,
88
+ env: options.env,
89
+ ...(domain === undefined ? {} : { domain }),
90
+ ...(returnOrigins === undefined ? {} : { returnOrigins }),
91
+ cwd: loaded.cwd,
92
+ secrets: declaredValues(loaded.config.pipeline?.secrets),
93
+ vars: declaredValues(loaded.config.pipeline?.vars),
94
+ managedEnvironment: requiredValues(options.managedVarNames),
95
+ dryRun: options.dryRun ?? false,
96
+ signal: options.signal ?? new AbortController().signal,
97
+ events,
98
+ target: cloudflareProvider.encodeTarget({
99
+ accountId: requiredEnvironmentValue('CLOUDFLARE_ACCOUNT_ID'),
100
+ apiToken: requiredEnvironmentValue('CLOUDFLARE_API_TOKEN'),
101
+ ...(options.stateNamespace === undefined ? {} : { stateNamespace: options.stateNamespace }),
102
+ ...(iamUrl === undefined ? {} : { propustkaUrl: iamUrl }),
103
+ ...(iamProvisioningKey === undefined ? {} : { adminKey: iamProvisioningKey }),
104
+ }),
105
+ artifact: cloudflareProvider.encodeArtifact(cloudflareArtifact(loaded.absolutePath)),
106
+ }
107
+ return deploy(cloudflareProvider.runtime, run)
108
+ }