oblaka-iac 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/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Contember Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "oblaka-iac",
3
+ "version": "0.0.1",
4
+ "main": "./src/index.ts",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/contember/oblaka"
10
+ },
11
+ "files": [
12
+ "src/",
13
+ "LICENSE.md"
14
+ ],
15
+ "scripts": {
16
+ "format": "dprint fmt",
17
+ "format:check": "dprint check",
18
+ "lint": "biome check ./src",
19
+ "lint:fix": "biome check --write ./src",
20
+ "typecheck": "tsc --noEmit"
21
+ },
22
+ "devDependencies": {
23
+ "@biomejs/biome": "^2.4.6",
24
+ "@cloudflare/workers-types": "^4.20260307.1",
25
+ "@types/bun": "latest",
26
+ "dprint": "^0.52.0"
27
+ },
28
+ "peerDependencies": {
29
+ "typescript": "^5"
30
+ },
31
+ "dependencies": {
32
+ "@cloudflare/workers-utils": "^0.12.0",
33
+ "jsonc-parser": "^3.3.1"
34
+ }
35
+ }
package/src/client.ts ADDED
@@ -0,0 +1,43 @@
1
+ export class CloudflareClient {
2
+ private baseUrl: string
3
+
4
+ constructor(
5
+ private readonly config: {
6
+ accountId: string
7
+ apiToken: string
8
+ },
9
+ ) {
10
+ this.baseUrl = `https://api.cloudflare.com/client/v4/accounts/${config.accountId}`
11
+ }
12
+
13
+ public async fetch<T>({ url, method, body, headers }: {
14
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE'
15
+ url: string
16
+ body?: any
17
+ headers?: Record<string, string>
18
+ }): Promise<T> {
19
+ if (!this.config.apiToken) {
20
+ throw new Error('API token is not set')
21
+ }
22
+ const response = await fetch(`${this.baseUrl}${url}`, {
23
+ method,
24
+ headers: {
25
+ Authorization: `Bearer ${this.config.apiToken}`,
26
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
27
+ ...headers,
28
+ },
29
+ body: JSON.stringify(body),
30
+ })
31
+
32
+ if (!response.ok) {
33
+ throw new Error(`Failed to fetch ${url}: ${response.statusText} ${await response.text()}`)
34
+ }
35
+
36
+ const res: any = await response.json()
37
+ if (!res.success) {
38
+ console.error('Cloudflare API error:', res)
39
+ throw new Error(`Failed to fetch: ${res.errors?.[0]?.message ?? 'Unknown error'}`)
40
+ }
41
+ return res.result
42
+ }
43
+ }
@@ -0,0 +1,23 @@
1
+ import type { Input } from './input'
2
+ import { ResourceProcessor } from './resource-processor'
3
+
4
+ export class CloudflareConfigureExecutor {
5
+ public static async execute({ input }: {
6
+ input: Input
7
+ }) {
8
+ const executor = new CloudflareConfigureExecutor(input)
9
+ await executor.run()
10
+ }
11
+
12
+ private constructor(
13
+ private readonly input: Input,
14
+ ) {
15
+ }
16
+
17
+ private async run() {
18
+ const resourceProcessor = new ResourceProcessor({
19
+ applyResource: () => Promise.resolve(undefined),
20
+ })
21
+ await resourceProcessor.run({ main: this.input.main, env: this.input.env })
22
+ }
23
+ }
@@ -0,0 +1,124 @@
1
+ import * as fs from 'node:fs/promises'
2
+ import { CloudflareClient } from '../client'
3
+ import { destroyers } from '../resources'
4
+ import { KVStateStorage, type State } from '../state'
5
+ import type { Resource } from '../types'
6
+ import type { Input } from './input'
7
+ import type { ResourceApplier } from './resource-processor'
8
+ import { ResourceProcessor } from './resource-processor'
9
+ import { atomic, registerShutdownHandler } from './utils/pm'
10
+
11
+ export class CloudflareDeployExecutor implements ResourceApplier {
12
+ private remaining: Set<string>
13
+ private totalChanged = 0
14
+
15
+ public static async execute({ input }: {
16
+ input: Input
17
+ }) {
18
+ const cfClient = new CloudflareClient({
19
+ accountId: input.accountId,
20
+ apiToken: input.apiToken,
21
+ })
22
+
23
+ const stateStore = new KVStateStorage(cfClient, input.stateNamespace)
24
+ const stateKey = { env: input.env }
25
+ const state = await stateStore.get(stateKey)
26
+
27
+ const executor = new CloudflareDeployExecutor(input, state, cfClient)
28
+
29
+ const unregisterShutdown = registerShutdownHandler(async () => {
30
+ if (input.dryRun) {
31
+ return
32
+ }
33
+ await stateStore.set(stateKey, state)
34
+ })
35
+
36
+ try {
37
+ await executor.run()
38
+ } finally {
39
+ unregisterShutdown()
40
+ await atomic(async () => {
41
+ if (input.dryRun) {
42
+ return
43
+ }
44
+ await stateStore.set(stateKey, state)
45
+ })
46
+ }
47
+
48
+ if (input.outStatePath) {
49
+ await fs.writeFile(input.outStatePath, JSON.stringify(state, null, '\t'))
50
+ }
51
+ }
52
+
53
+ private constructor(
54
+ private readonly input: Input,
55
+ private readonly state: State,
56
+ private readonly client: CloudflareClient,
57
+ ) {
58
+ this.remaining = new Set(Object.keys(state.resources || {}))
59
+ }
60
+
61
+ private async run() {
62
+ const resourceProcessor = new ResourceProcessor(this)
63
+ await resourceProcessor.run({ main: this.input.main, env: this.input.env })
64
+
65
+ this.log(`Changed ${this.totalChanged} resources`)
66
+
67
+ if (!this.input.destroy && this.remaining.size > 0) {
68
+ this.log('Dangling resources (pass --destroy to delete):')
69
+ for (const idString of this.remaining) {
70
+ this.log(` - ${idString}`)
71
+ }
72
+ } else {
73
+ for (const idString of this.remaining) {
74
+ const [resource, id] = idString.split(':', 2)
75
+ if (!this.input.dryRun) {
76
+ await atomic(async () => {
77
+ await destroyers[resource]?.({
78
+ state: this.state.resources[idString],
79
+ context: {
80
+ env: this.input.env,
81
+ client: this.client,
82
+ },
83
+ })
84
+ delete this.state.resources[idString]
85
+ })
86
+ } else {
87
+ delete this.state.resources[idString]
88
+ }
89
+ this.log(`Destroyed ${resource}:${id}`)
90
+ }
91
+ }
92
+ }
93
+
94
+ private log(message: string) {
95
+ if (this.input.dryRun) {
96
+ console.log(`[DRY RUN] ${message}`)
97
+ } else {
98
+ console.log(message)
99
+ }
100
+ }
101
+
102
+ async applyResource<T>(resource: Resource<T>): Promise<T> {
103
+ return atomic(async () => {
104
+ const id = resource.getId()
105
+ const idString = `${id.resource}:${id.id}`
106
+ const applied = await resource.apply({
107
+ state: this.state?.resources?.[idString],
108
+ dryRun: this.input.dryRun,
109
+ context: {
110
+ env: this.input.env,
111
+ client: this.client,
112
+ },
113
+ })
114
+ const changed = applied !== this.state?.resources?.[idString]
115
+ if (changed) {
116
+ this.log(`Updated ${idString}`)
117
+ this.totalChanged++
118
+ }
119
+ this.state.resources[idString] = applied
120
+ this.remaining.delete(idString)
121
+ return applied
122
+ })
123
+ }
124
+ }
@@ -0,0 +1,26 @@
1
+ import { parseArgs } from './utils/args'
2
+
3
+ const requireString = (value: string | boolean | undefined, name: string): string => {
4
+ if (typeof value === 'string') {
5
+ return value
6
+ }
7
+ throw new Error(`Missing required string argument: ${name}`)
8
+ }
9
+
10
+ export const input = (() => {
11
+ const { named, positional } = parseArgs(process.argv.slice(2))
12
+ return {
13
+ main: requireString(positional[0], 'config entrypoint'),
14
+ env: requireString(named.env || process.env.CLOUDFLARE_ENV || 'local', 'environment'),
15
+ stateNamespace: requireString(named['state-namespace'] || 'cf-state', 'state namespace'),
16
+ configPath: requireString(named.config || 'wrangler.jsonc', 'config path'),
17
+ accountId: requireString(named['account-id'] || process.env.CLOUDFLARE_ACCOUNT_ID || '', 'account id'),
18
+ apiToken: requireString(named['api-token'] || process.env.CLOUDFLARE_API_TOKEN || '', 'api token'),
19
+ dryRun: !!named['dry-run'],
20
+ remote: !!named.remote,
21
+ destroy: !!named.destroy,
22
+ outStatePath: named['out-state'] === true ? 'out-state.json' : named['out-state'],
23
+ }
24
+ })()
25
+
26
+ export type Input = typeof input
@@ -0,0 +1,63 @@
1
+ import * as jsoncParser from 'jsonc-parser'
2
+ import * as fs from 'node:fs/promises'
3
+ import * as path from 'node:path'
4
+ import { Worker } from '../resources'
5
+ import type { Config, DefineFn, Resource } from '../types'
6
+ import { tryReadFile } from './utils/fs'
7
+
8
+ export class ResourceProcessor {
9
+ private workers: Worker[] = []
10
+
11
+ constructor(
12
+ private readonly resourceHandler: ResourceApplier,
13
+ ) {
14
+ }
15
+
16
+ public async run({ main, env }: {
17
+ main: string
18
+ env: string
19
+ }) {
20
+ const defineFn = (await import(path.resolve(main))).default as DefineFn
21
+ const definition = defineFn({ env })
22
+
23
+ if (definition) {
24
+ this.workers.push(definition)
25
+ }
26
+
27
+ while (this.workers.length) {
28
+ await this.processWorker(env)
29
+ }
30
+ }
31
+
32
+ private async processWorker(env: string): Promise<void> {
33
+ const worker = this.workers.shift()
34
+ if (!worker) {
35
+ return
36
+ }
37
+ const configPath = path.join(worker.options.dir, 'wrangler.jsonc')
38
+ const existingConfig = jsoncParser.parse((await tryReadFile(configPath)) || '{}') as Config
39
+ const { bindings, dir, ...workerConfig } = worker?.options ?? {}
40
+
41
+ let config: Config = {
42
+ ...workerConfig,
43
+ migrations: existingConfig.migrations,
44
+ }
45
+
46
+ const selfState = await this.resourceHandler.applyResource(worker)
47
+ config = worker.configureSelf({ config, state: selfState })
48
+
49
+ for (const [bindingName, binding] of Object.entries(worker.options.bindings ?? {})) {
50
+ if (binding instanceof Worker) {
51
+ this.workers.push(binding)
52
+ }
53
+ const state = 'apply' in binding ? await this.resourceHandler.applyResource(binding) : undefined
54
+ config = binding.configureBinding({ config, binding: bindingName, state, env })
55
+ }
56
+
57
+ await fs.writeFile(configPath, `/**\n * File is auto generated DO NOT EDIT\n */\n${JSON.stringify(config, null, '\t')}\n`)
58
+ }
59
+ }
60
+
61
+ export interface ResourceApplier {
62
+ applyResource<T>(resource: Resource<T>): Promise<T | undefined>
63
+ }
@@ -0,0 +1,12 @@
1
+ import { CloudflareConfigureExecutor } from './configure'
2
+ import { CloudflareDeployExecutor } from './deploy'
3
+ import { input } from './input'
4
+ import { registerSignalHandler } from './utils/pm'
5
+
6
+ registerSignalHandler()
7
+
8
+ if (input.remote) {
9
+ await CloudflareDeployExecutor.execute({ input })
10
+ } else {
11
+ await CloudflareConfigureExecutor.execute({ input })
12
+ }
@@ -0,0 +1,20 @@
1
+ export const parseArgs = (args: string[]): { named: { [key: string]: string | true }; positional: string[] } => {
2
+ const named: { [key: string]: string | true } = {}
3
+ const positional: string[] = []
4
+ for (let i = 0; i < args.length; i++) {
5
+ const arg = args[i]
6
+ if (arg.startsWith('--')) {
7
+ const key = arg.slice(2)
8
+ const value = args[i + 1]
9
+ if (value && !value.startsWith('--')) {
10
+ named[key] = value
11
+ i++
12
+ } else {
13
+ named[key] = true
14
+ }
15
+ } else {
16
+ positional.push(arg)
17
+ }
18
+ }
19
+ return { named, positional }
20
+ }
@@ -0,0 +1,12 @@
1
+ import * as fs from 'node:fs/promises'
2
+
3
+ export const tryReadFile = async (path: string) => {
4
+ try {
5
+ return await fs.readFile(path, 'utf-8')
6
+ } catch (error: any) {
7
+ if (error.code === 'ENOENT') {
8
+ return undefined
9
+ }
10
+ throw error
11
+ }
12
+ }
@@ -0,0 +1,47 @@
1
+ let runningAtomic = 0
2
+ let registered = false
3
+ let shouldExit = false
4
+ const shutdownHandlers: (() => Promise<void>)[] = []
5
+
6
+ const shutdown = async () => {
7
+ for (const handler of shutdownHandlers) {
8
+ await handler()
9
+ }
10
+ process.exit(0)
11
+ }
12
+
13
+ export const registerShutdownHandler = (handler: () => Promise<void>) => {
14
+ shutdownHandlers.push(handler)
15
+ return () => {
16
+ shutdownHandlers.splice(shutdownHandlers.indexOf(handler), 1)
17
+ }
18
+ }
19
+
20
+ export const atomic = async <T>(fn: () => Promise<T>) => {
21
+ runningAtomic++
22
+ try {
23
+ return await fn()
24
+ } finally {
25
+ runningAtomic--
26
+ if (shouldExit && runningAtomic === 0) {
27
+ await shutdown()
28
+ }
29
+ }
30
+ }
31
+
32
+ export const registerSignalHandler = () => {
33
+ if (registered) return
34
+ registered = true
35
+
36
+ const handleExit = async () => {
37
+ if (runningAtomic > 0) {
38
+ console.log(`\nReceived exit signal. Waiting for ${runningAtomic} operations to complete...`)
39
+ shouldExit = true
40
+ } else {
41
+ await shutdown()
42
+ }
43
+ }
44
+
45
+ process.on('SIGINT', handleExit)
46
+ process.on('SIGTERM', handleExit)
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { DefineFn } from './types'
2
+
3
+ export * from './resources'
4
+
5
+ export const define = (cb: DefineFn) => {
6
+ return cb
7
+ }
@@ -0,0 +1,45 @@
1
+ import type { BindableResource, Config } from '../types'
2
+
3
+ export interface AnalyticsEngineState {
4
+ name: string
5
+ }
6
+
7
+ /**
8
+ * Cloudflare Analytics Engine binding
9
+ * https://developers.cloudflare.com/analytics/analytics-engine/
10
+ */
11
+ export class AnalyticsEngine implements BindableResource<AnalyticsEngineState> {
12
+ constructor(
13
+ public readonly options: {
14
+ name: string
15
+ },
16
+ ) {}
17
+
18
+ getId() {
19
+ return {
20
+ resource: 'analytics_engine' as const,
21
+ id: this.options.name,
22
+ }
23
+ }
24
+
25
+ configureBinding(args: { config: Config; binding: string; state?: AnalyticsEngineState; env: string }): Config {
26
+ return {
27
+ ...args.config,
28
+ analytics_engine_datasets: [
29
+ ...(args.config.analytics_engine_datasets ?? []),
30
+ {
31
+ binding: args.binding,
32
+ dataset: this.options.name,
33
+ },
34
+ ],
35
+ }
36
+ }
37
+
38
+ async apply(args: { state?: AnalyticsEngineState }): Promise<AnalyticsEngineState> {
39
+ // Analytics Engine datasets are created automatically when first used
40
+ // No API call needed for creation
41
+ return args.state ?? {
42
+ name: this.options.name,
43
+ }
44
+ }
45
+ }
@@ -0,0 +1,10 @@
1
+ import type { Bindable, Config } from '../types'
2
+
3
+ export class Browser implements Bindable {
4
+ configureBinding(args: { config: Config; binding: string; env: string }): Config {
5
+ return {
6
+ ...args.config,
7
+ browser: { binding: args.binding },
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,86 @@
1
+ import type { BindableResource, Config, Context, ResourceDestroyer } from '../types'
2
+ import { getNextMigrationTag } from '../utils/migrations'
3
+
4
+ export interface ContainerState {
5
+ name: string
6
+ }
7
+
8
+ export class Container implements BindableResource<ContainerState> {
9
+ constructor(
10
+ public readonly options: {
11
+ name: string
12
+ className: string
13
+ image: string
14
+ maxInstances: number
15
+ instanceType: 'dev' | 'basic' | 'standard'
16
+ /**
17
+ * The minimum number of seconds to wait before an active container instance becomes eligible for updating during a rollout. At that point, the container will be sent at SIGTERM and still has 15 minutes to shut down before it is forcibly killed and updated. Default is 0.
18
+ */
19
+ rolloutActiveGracePeriod?: number
20
+ /**
21
+ * Build-time variables, equivalent to using --build-arg with docker build. If you want to provide environment variables to your container at runtime, you should use secret bindings or envVars on the Container class.
22
+ */
23
+ imageVars?: Record<string, string>
24
+ },
25
+ ) {}
26
+
27
+ getId() {
28
+ return {
29
+ resource: 'container' as const,
30
+ id: this.options.name,
31
+ }
32
+ }
33
+
34
+ async apply({ context, state }: { context: Context; state?: ContainerState }): Promise<ContainerState> {
35
+ return (
36
+ state ?? {
37
+ name: `${context.env}-${this.options.name}`,
38
+ }
39
+ )
40
+ }
41
+
42
+ configureBinding(args: { config: Config; binding: string; state?: ContainerState; env: string }): Config {
43
+ const hasMigration = args.config?.migrations?.find(it => it.new_sqlite_classes?.includes(this.options.className))
44
+
45
+ return {
46
+ ...args.config,
47
+ migrations: [
48
+ ...(args.config.migrations ?? []),
49
+ ...(hasMigration
50
+ ? []
51
+ : [
52
+ {
53
+ tag: getNextMigrationTag(args.config),
54
+ new_sqlite_classes: [this.options.className],
55
+ },
56
+ ]),
57
+ ],
58
+ containers: [
59
+ ...(args.config.containers ?? []),
60
+ {
61
+ class_name: this.options.className,
62
+ name: args.state?.name ?? this.options.name,
63
+ image: this.options.image,
64
+ instance_type: this.options.instanceType,
65
+ max_instances: this.options.maxInstances,
66
+ rollout_active_grace_period: this.options.rolloutActiveGracePeriod,
67
+ image_vars: this.options.imageVars,
68
+ },
69
+ ],
70
+ durable_objects: {
71
+ ...(args.config.durable_objects ?? {}),
72
+ bindings: [
73
+ ...(args.config.durable_objects?.bindings ?? []),
74
+ {
75
+ name: args.binding,
76
+ class_name: this.options.className,
77
+ },
78
+ ],
79
+ },
80
+ }
81
+ }
82
+ }
83
+
84
+ export const ContainerDestroyer: ResourceDestroyer<ContainerState> = async (args): Promise<void> => {
85
+ // nothing to do
86
+ }
@@ -0,0 +1,71 @@
1
+ import type { BindableResource, Config, Context, ResourceDestroyer } from '../types'
2
+
3
+ export interface D1DatabaseState {
4
+ id: string
5
+ name: string
6
+ }
7
+
8
+ export class D1Database implements BindableResource<D1DatabaseState> {
9
+ constructor(
10
+ public readonly options: {
11
+ name: string
12
+ migrationsDir?: string
13
+ locationHint?: string
14
+ },
15
+ ) {}
16
+
17
+ configureBinding(args: { config: Config; binding: string; state?: D1DatabaseState; env: string }): Config {
18
+ return {
19
+ ...args.config,
20
+ d1_databases: [
21
+ ...args.config?.d1_databases ?? [],
22
+ {
23
+ binding: args.binding,
24
+ database_name: args.state?.name || this.options.name,
25
+ database_id: args.state?.id || this.options.name,
26
+ migrations_dir: this.options.migrationsDir,
27
+ },
28
+ ],
29
+ }
30
+ }
31
+
32
+ getId() {
33
+ return {
34
+ resource: 'd1_database' as const,
35
+ id: this.options.name,
36
+ }
37
+ }
38
+
39
+ async apply(args: { state?: D1DatabaseState; context: Context; dryRun: boolean }): Promise<D1DatabaseState> {
40
+ if (args.state) {
41
+ return args.state
42
+ }
43
+ const remoteName = `${args.context.env}-${this.options.name}`
44
+ if (args.dryRun) {
45
+ return {
46
+ name: remoteName,
47
+ id: 'dry-run-id-' + Math.random().toString(36).substring(2, 11),
48
+ }
49
+ }
50
+
51
+ const result = await args.context.client.fetch<{ uuid: string }>({
52
+ url: `/d1/database`,
53
+ method: 'POST',
54
+ body: {
55
+ name: remoteName,
56
+ primary_location_hint: this.options.locationHint,
57
+ },
58
+ })
59
+ return {
60
+ name: remoteName,
61
+ id: result.uuid,
62
+ }
63
+ }
64
+ }
65
+
66
+ export const D1Destroyer: ResourceDestroyer<D1DatabaseState> = async (args): Promise<void> => {
67
+ await args.context.client.fetch({
68
+ url: `/d1/database/${args.state.id}`,
69
+ method: 'DELETE',
70
+ })
71
+ }