@fabrika/cli 0.9.0-dev.4 → 0.9.0-dev.6

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/data.ts ADDED
@@ -0,0 +1,444 @@
1
+ // The `fabrika env` command area: an application environment's data as Control serves it (ADR-0069). Every command is
2
+ // one `data.*` procedure of `ControlRpcContract`, reached through the client `fabrika control` uses (`connectControl`).
3
+
4
+ import { RpcError } from '@fabrika/app'
5
+ import {
6
+ OPS_ROW_COUNT_CAP,
7
+ type OpsContentView,
8
+ type OpsView,
9
+ parseApplicationObjectName,
10
+ parseOpsContentView,
11
+ parseOpsView,
12
+ } from '@fabrika/auth-core'
13
+ import { type DataBackupDto, type DataBackupScheduleDto, type DataOperationDto, startDataOperationInputSchema } from '@fabrika/control-contract'
14
+ import { z } from 'zod'
15
+ import { connectControl, type ControlClient, withoutControlKey } from './control.js'
16
+
17
+ const USAGE = `fabrika env — an application environment's data, through the control plane
18
+
19
+ Usage:
20
+ fabrika env inspect <app> <env> [--content] [--json]
21
+ fabrika env maintenance <app> <env> <open|read-only|closed> [--json]
22
+ fabrika env operations <app> <env> [--json]
23
+ fabrika env recover <app> <env> <operationId> <resume|open> [--json]
24
+ fabrika env backups <app> <env> [--json]
25
+ fabrika env backups schedule <app> <env> [on|off] [--json]
26
+ fabrika env restore <app> <env> --at=<time> [--json]
27
+
28
+ \`inspect\` prints the environment's data view: the object's maintenance mode and generation, the database size and
29
+ each table's row count (a count at ${OPS_ROW_COUNT_CAP} reads \`${OPS_ROW_COUNT_CAP}+\`: it is capped), the applied migrations,
30
+ the scheduler's alarm, each job's last run, file and webhook counts, and when the application last failed to boot.
31
+ It needs \`data.read\`. \`--content\` adds the boot failure's message and stack, which are the application's own text,
32
+ and needs \`data.content.read\` granted globally.
33
+
34
+ \`maintenance\` puts the environment into a mode: \`read-only\` refuses writes, \`closed\` refuses every request, and
35
+ \`open\` serves again. It starts a data operation and prints it; \`operations\` follows it. It needs \`data.manage\`.
36
+
37
+ \`operations\` lists the environment's data operations, newest first, one row each:
38
+ <id> <kind> <state> <step> <target mode> <generation> <error code> <created at>.
39
+
40
+ \`recover\` fences an environment whose operation is stuck in \`closed\` at a fresh generation, then \`resume\`s that
41
+ operation from its recorded step, or \`open\`s the environment. A failed operation can only be opened past. It needs
42
+ \`data.manage\`.
43
+
44
+ \`backups\` lists the environment's consistent backups, newest first, one row each:
45
+ <id> <object> <state> <created at> <size bytes> <parts> <tables> <rehearsal> <rehearsal code> <error code> <expired>
46
+ <pre-migration>.
47
+ A backup counts as \`succeeded\` only once its rehearsal, an import into a scratch object, passed. One older than 30
48
+ days is \`expired\` and never offered for a restore. The last column is \`pre-migration\` for the backup a migration
49
+ takes before its deploy, and \`-\` for any other, such as a daily backup or a restore's. It needs \`data.read\`.
50
+
51
+ \`backups schedule\` prints whether the environment takes a daily backup; \`on\` or \`off\` sets it, which needs
52
+ \`data.manage\`. Turning it off stops the daily backup only: the backup before a migration still runs.
53
+
54
+ \`restore\` brings back the environment's data as it was at \`--at\`, an ISO 8601 time with an offset in the past. It
55
+ is a side restore: the serving object is frozen read-only and backed up, the backup is imported into a new clone
56
+ object, ordinary traffic is pointed at the clone, which serves the current data from then on, and the original is
57
+ rewound to that time and kept in \`inspect\`, serving nothing, for inspection. It starts a data operation and prints
58
+ it; \`operations\` follows it. It needs \`data.manage\`.
59
+
60
+ A release of the control plane that does not offer a command answers that it is not available; retrying does not
61
+ change that. An environment the caller may not see answers \`not_found\`, as one that does not exist.
62
+
63
+ stdout carries data only; progress and follow-up commands go to stderr. \`--json\` prints the result as JSON.
64
+
65
+ The control origin takes either form:
66
+
67
+ --url=<origin> FABRIKA_CONTROL_URL
68
+
69
+ The credential is read from the ENVIRONMENT ONLY and has no flag:
70
+
71
+ FABRIKA_CONTROL_KEY required a machine \`px_\` credential for the control app
72
+ `
73
+
74
+ type Environment = Readonly<Record<string, string | undefined>>
75
+
76
+ interface EnvArgs {
77
+ readonly positional: readonly string[]
78
+ readonly json: boolean
79
+ readonly content: boolean
80
+ readonly url: string | undefined
81
+ /** \`''\` when \`--at\` closes the arguments with no time after it. */
82
+ readonly at: string | undefined
83
+ }
84
+
85
+ const COMMAND_FORMS: Readonly<Record<string, string>> = {
86
+ inspect: '<app> <env> [--content] [--json]',
87
+ maintenance: '<app> <env> <open|read-only|closed> [--json]',
88
+ operations: '<app> <env> [--json]',
89
+ recover: '<app> <env> <operationId> <resume|open> [--json]',
90
+ backups: '<app> <env> [--json]',
91
+ 'backups schedule': '<app> <env> [on|off] [--json]',
92
+ restore: '<app> <env> --at=<time> [--json]',
93
+ }
94
+
95
+ const parseEnvArgs = (argv: readonly string[]): EnvArgs => {
96
+ const positional: string[] = []
97
+ let json = false
98
+ let content = false
99
+ let url: string | undefined
100
+ let at: string | undefined
101
+ for (let index = 0; index < argv.length; index++) {
102
+ const arg = argv[index] ?? ''
103
+ if (arg === '--json') json = true
104
+ else if (arg === '--content') content = true
105
+ else if (arg.startsWith('--url=')) url = arg.slice('--url='.length)
106
+ else if (arg.startsWith('--at=')) at = arg.slice('--at='.length)
107
+ else if (arg === '--at') at = argv[++index] ?? ''
108
+ else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`)
109
+ else positional.push(arg)
110
+ }
111
+ return { positional, json, content, url, at }
112
+ }
113
+
114
+ /** The positional words of `command`, exactly `count` of them. */
115
+ const words = (command: string, args: EnvArgs, count: number): readonly string[] => {
116
+ if (args.positional.length !== count || args.positional.some((word) => word.trim() === '')) throw usage(command)
117
+ return args.positional
118
+ }
119
+
120
+ const usage = (command: string): Error => new Error(`Usage: fabrika env ${command} ${COMMAND_FORMS[command] ?? ''}`)
121
+
122
+ const controlClient = (args: EnvArgs, env: Environment): ControlClient => connectControl(args.url, env)
123
+
124
+ /** Control's own rule for an operation's or a backup's error code (`db/data-operations.ts`, `db/backups.ts`). */
125
+ const ERROR_CODE = /^[a-z][a-z0-9_]{0,63}$/
126
+
127
+ /** The known fields of an operation, validated; a field a newer Control adds is dropped, never printed. */
128
+ const dataOperationSchema: z.ZodType<DataOperationDto, z.ZodTypeDef, unknown> = z.object({
129
+ id: z.string().uuid(),
130
+ appId: z.string(),
131
+ env: z.string(),
132
+ kind: z.enum(['maintenance', 'backup', 'migrate', 'recovery', 'restore']),
133
+ step: z.enum([
134
+ 'reconcile',
135
+ 'restrict',
136
+ 'backup',
137
+ 'verify',
138
+ 'deploy',
139
+ 'migrate',
140
+ 'resume',
141
+ 'open',
142
+ 'list',
143
+ 'import',
144
+ 'promote',
145
+ 'point',
146
+ 'serve',
147
+ 'rewind',
148
+ 'check',
149
+ 'revert',
150
+ ]),
151
+ targetMode: z.enum(['open', 'read-only', 'closed', 'inspect']),
152
+ generation: z.number().int().nonnegative(),
153
+ state: z.enum(['running', 'succeeded', 'failed']),
154
+ errorCode: z.string().regex(ERROR_CODE).nullable(),
155
+ actor: z.string(),
156
+ createdAt: z.number().int().nonnegative(),
157
+ updatedAt: z.number().int().nonnegative(),
158
+ finishedAt: z.number().int().nonnegative().nullable(),
159
+ recoversOperationId: z.string().uuid().nullable(),
160
+ resolution: z.enum(['resume', 'open']).nullable(),
161
+ // Absent from a Control before the migration phase.
162
+ runId: z.string().uuid().nullable().default(null),
163
+ })
164
+
165
+ interface Target {
166
+ readonly appId: string
167
+ readonly env: string
168
+ }
169
+
170
+ /** An answer about the environment asked about, and of no other. */
171
+ const ofTarget = (answer: Target, target: Target): boolean => answer.appId === target.appId && answer.env === target.env
172
+
173
+ const parseOperation = (value: unknown, target: Target): DataOperationDto => {
174
+ const parsed = dataOperationSchema.safeParse(value)
175
+ if (!parsed.success || !ofTarget(parsed.data, target)) throw new Error('Control returned an unreadable data operation')
176
+ return parsed.data
177
+ }
178
+
179
+ const dataOperationPageSchema = z.object({ items: z.array(dataOperationSchema), nextCursor: z.string().uuid().nullable() })
180
+
181
+ const parseOperationPage = (value: unknown, target: Target): { items: DataOperationDto[]; nextCursor: string | null } => {
182
+ const parsed = dataOperationPageSchema.safeParse(value)
183
+ if (!parsed.success || !parsed.data.items.every((operation) => ofTarget(operation, target))) {
184
+ throw new Error('Control returned an unreadable list of data operations')
185
+ }
186
+ return parsed.data
187
+ }
188
+
189
+ /** The known fields of a backup, validated as an operation's are. */
190
+ const dataBackupSchema: z.ZodType<DataBackupDto> = z.object({
191
+ id: z.string().uuid(),
192
+ appId: z.string(),
193
+ env: z.string(),
194
+ operationId: z.string().uuid(),
195
+ object: z.string().refine((name) => parseApplicationObjectName(name) !== null),
196
+ dumpId: z.string().uuid(),
197
+ preMigration: z.boolean(),
198
+ state: z.enum(['running', 'succeeded', 'failed']),
199
+ errorCode: z.string().regex(ERROR_CODE).nullable(),
200
+ createdAt: z.number().int().nonnegative(),
201
+ finishedAt: z.number().int().nonnegative().nullable(),
202
+ bookmark: z.string().nullable(),
203
+ sizeBytes: z.number().int().nonnegative().nullable(),
204
+ parts: z.number().int().nonnegative().nullable(),
205
+ tables: z.number().int().nonnegative().nullable(),
206
+ rehearsal: z.enum(['pending', 'passed', 'failed']),
207
+ rehearsalCode: z.string().regex(ERROR_CODE).nullable(),
208
+ expired: z.boolean(),
209
+ })
210
+
211
+ const dataBackupPageSchema = z.object({ items: z.array(dataBackupSchema), nextCursor: z.string().uuid().nullable() })
212
+
213
+ const parseBackupPage = (value: unknown, target: Target): { items: DataBackupDto[]; nextCursor: string | null } => {
214
+ const parsed = dataBackupPageSchema.safeParse(value)
215
+ if (!parsed.success || !parsed.data.items.every((backup) => ofTarget(backup, target))) {
216
+ throw new Error('Control returned an unreadable list of backups')
217
+ }
218
+ return parsed.data
219
+ }
220
+
221
+ const dataBackupScheduleSchema: z.ZodType<DataBackupScheduleDto> = z.object({
222
+ appId: z.string(),
223
+ env: z.string(),
224
+ daily: z.boolean(),
225
+ updatedAt: z.number().int().nonnegative().nullable(),
226
+ })
227
+
228
+ const parseSchedule = (value: unknown, target: Target): DataBackupScheduleDto => {
229
+ const parsed = dataBackupScheduleSchema.safeParse(value)
230
+ if (!parsed.success || !ofTarget(parsed.data, target)) throw new Error('Control returned an unreadable backup schedule')
231
+ return parsed.data
232
+ }
233
+
234
+ const MAINTENANCE_MODES = ['open', 'read-only', 'closed'] as const
235
+ const RESOLUTIONS = ['resume', 'open'] as const
236
+ const SCHEDULE_SWITCHES = ['on', 'off'] as const
237
+
238
+ const oneOf = <T extends string>(value: string, allowed: readonly T[]): T | undefined => allowed.find((candidate) => candidate === value)
239
+
240
+ /** Control's timestamps are Unix seconds. */
241
+ const isoSeconds = (seconds: number): string => new Date(seconds * 1000).toISOString()
242
+
243
+ const operationLine = (operation: DataOperationDto): string =>
244
+ [
245
+ operation.id,
246
+ operation.kind,
247
+ operation.state,
248
+ operation.step,
249
+ operation.targetMode,
250
+ String(operation.generation),
251
+ operation.errorCode ?? '-',
252
+ isoSeconds(operation.createdAt),
253
+ ].join('\t')
254
+
255
+ const backupLine = (backup: DataBackupDto): string =>
256
+ [
257
+ backup.id,
258
+ backup.object,
259
+ backup.state,
260
+ isoSeconds(backup.createdAt),
261
+ backup.sizeBytes === null ? '-' : String(backup.sizeBytes),
262
+ backup.parts === null ? '-' : String(backup.parts),
263
+ backup.tables === null ? '-' : String(backup.tables),
264
+ backup.rehearsal,
265
+ backup.rehearsalCode ?? '-',
266
+ backup.errorCode ?? '-',
267
+ backup.expired ? 'expired' : '-',
268
+ backup.preMigration ? 'pre-migration' : '-',
269
+ ].join('\t')
270
+
271
+ const scheduleLines = (schedule: DataBackupScheduleDto): string =>
272
+ [`daily\t${schedule.daily ? 'on' : 'off'}`, `updatedAt\t${schedule.updatedAt === null ? '-' : isoSeconds(schedule.updatedAt)}`].join('\n')
273
+
274
+ /** Every control character but tab and line feed: an answer must not drive the operator's terminal. */
275
+ const printable = (text: string): string => text.replace(/[^\P{Cc}\t\n]/gu, '')
276
+
277
+ const viewLines = (view: OpsView | OpsContentView): string[] => [
278
+ `release\t${view.release}`,
279
+ `mode\t${view.maintenance.mode}`,
280
+ `generation\t${view.maintenance.generation ?? '-'}`,
281
+ `published\t${view.maintenance.published ? 'yes' : 'no'}`,
282
+ `databaseBytes\t${view.database.sizeBytes}`,
283
+ ...view.database.tables.map((table) => `table\t${table.name}\t${table.rows >= OPS_ROW_COUNT_CAP ? `${OPS_ROW_COUNT_CAP}+` : table.rows}`),
284
+ ...view.migrations.map((migration) => `migration\t${migration.bundle}\t${migration.name}\t${migration.appliedAt}`),
285
+ `alarm\t${view.scheduler.alarm ?? '-'}`,
286
+ ...view.jobs.map((job) =>
287
+ `job\t${job.job}\t${job.lastStatus ?? '-'}\t${job.lastStartedAt ?? '-'}\t${job.lastFinishedAt ?? '-'}\t${job.lastDurationMs ?? '-'}`
288
+ ),
289
+ ...view.files.map((file) => `file\t${file.kind}\t${file.status}\t${file.count}`),
290
+ ...view.webhooks.map((webhook) => `webhook\t${webhook.webhook}\t${webhook.state}\t${webhook.count}`),
291
+ `bootFailure\t${view.bootFailure?.at ?? '-'}`,
292
+ ]
293
+
294
+ const contentLines = (view: OpsContentView): string[] => {
295
+ const failure = view.bootFailure
296
+ if (failure === null) return viewLines(view)
297
+ return [...viewLines(view), '', failure.message, ...(failure.stack === null ? [] : [failure.stack])]
298
+ }
299
+
300
+ /** Human output and every note pass `printable`; `--json` escapes what JSON must. */
301
+ const emit = (args: EnvArgs, result: unknown, render: () => string): void => {
302
+ console.info(args.json ? JSON.stringify(result, null, 2) : printable(render()))
303
+ }
304
+
305
+ const note = (text: string): void => {
306
+ console.warn(printable(text))
307
+ }
308
+
309
+ /** An operation is an answer whatever its state; stderr names what follows it. */
310
+ const emitOperation = (args: EnvArgs, operation: DataOperationDto): void => {
311
+ const coordinates = `${operation.appId} ${operation.env}`
312
+ if (operation.state === 'running') note(`follow it: fabrika env operations ${coordinates}`)
313
+ if (operation.state === 'failed') note(`open the environment past it: fabrika env recover ${coordinates} ${operation.id} open`)
314
+ emit(args, operation, () => operationLine(operation))
315
+ }
316
+
317
+ const runInspect = async (args: EnvArgs, env: Environment): Promise<void> => {
318
+ const [appId = '', environment = ''] = words('inspect', args, 2)
319
+ const client = controlClient(args, env)
320
+ if (args.content) {
321
+ const view = parseOpsContentView(await client.data.content({ appId, env: environment }))
322
+ if (view === null) throw new Error('Control returned an unreadable data view')
323
+ emit(args, view, () => contentLines(view).join('\n'))
324
+ return
325
+ }
326
+ const view = parseOpsView(await client.data.view({ appId, env: environment }))
327
+ if (view === null) throw new Error('Control returned an unreadable data view')
328
+ emit(args, view, () => viewLines(view).join('\n'))
329
+ }
330
+
331
+ const runMaintenance = async (args: EnvArgs, env: Environment): Promise<void> => {
332
+ const [appId = '', environment = '', requested = ''] = words('maintenance', args, 3)
333
+ const mode = oneOf(requested, MAINTENANCE_MODES)
334
+ if (mode === undefined) throw new Error(`The mode is one of ${MAINTENANCE_MODES.join(', ')}, not "${requested}"`)
335
+ const result = await controlClient(args, env).data.start({ appId, env: environment, kind: 'maintenance', mode })
336
+ emitOperation(args, parseOperation(result, { appId, env: environment }))
337
+ }
338
+
339
+ const runOperations = async (args: EnvArgs, env: Environment): Promise<void> => {
340
+ const [appId = '', environment = ''] = words('operations', args, 2)
341
+ const page = parseOperationPage(await controlClient(args, env).data.operations.list({ appId, env: environment }), { appId, env: environment })
342
+ if (page.nextCursor !== null) note(`showing the newest ${page.items.length} operations; older ones exist`)
343
+ if (!args.json && page.items.length === 0) {
344
+ note(`${appId} ${environment} has no data operations`)
345
+ return
346
+ }
347
+ emit(args, page, () => page.items.map(operationLine).join('\n'))
348
+ }
349
+
350
+ const runRecover = async (args: EnvArgs, env: Environment): Promise<void> => {
351
+ const [appId = '', environment = '', operationId = '', requested = ''] = words('recover', args, 4)
352
+ const resolution = oneOf(requested, RESOLUTIONS)
353
+ if (resolution === undefined) throw new Error(`The resolution is resume or open, not "${requested}"`)
354
+ const result = await controlClient(args, env).data.recover({ appId, env: environment, operationId, resolution })
355
+ emitOperation(args, parseOperation(result, { appId, env: environment }))
356
+ }
357
+
358
+ const runBackups = async (args: EnvArgs, env: Environment): Promise<void> => {
359
+ if (args.positional[0] === 'schedule' && args.positional.length > 2) {
360
+ await runBackupSchedule(args, env)
361
+ return
362
+ }
363
+ const [appId = '', environment = ''] = words('backups', args, 2)
364
+ const page = parseBackupPage(await controlClient(args, env).data.backups.list({ appId, env: environment }), { appId, env: environment })
365
+ if (page.nextCursor !== null) note(`showing the newest ${page.items.length} backups; older ones exist`)
366
+ if (!args.json && page.items.length === 0) {
367
+ note(`${appId} ${environment} has no backups`)
368
+ return
369
+ }
370
+ emit(args, page, () => page.items.map(backupLine).join('\n'))
371
+ }
372
+
373
+ const runBackupSchedule = async (args: EnvArgs, env: Environment): Promise<void> => {
374
+ const [, appId = '', environment = '', requested] = args.positional
375
+ if (args.positional.length > 4 || appId.trim() === '' || environment.trim() === '') throw usage('backups schedule')
376
+ const client = controlClient(args, env)
377
+ const target = { appId, env: environment }
378
+ if (requested === undefined) {
379
+ const schedule = parseSchedule(await client.data.backups.schedule(target), target)
380
+ emit(args, schedule, () => scheduleLines(schedule))
381
+ return
382
+ }
383
+ const daily = oneOf(requested, SCHEDULE_SWITCHES)
384
+ if (daily === undefined) throw new Error(`The schedule is on or off, not "${requested}"`)
385
+ const schedule = parseSchedule(await client.data.backups.setSchedule({ ...target, daily: daily === 'on' }), target)
386
+ if (!schedule.daily) note('the backup before a migration still runs')
387
+ emit(args, schedule, () => scheduleLines(schedule))
388
+ }
389
+
390
+ const runRestore = async (args: EnvArgs, env: Environment): Promise<void> => {
391
+ const [appId = '', environment = ''] = words('restore', args, 2)
392
+ if (args.at === undefined || args.at === '') throw usage('restore')
393
+ // The contract's own rule for `at`, checked before anything is sent; whether it lies in the past is Control's to decide.
394
+ const input = startDataOperationInputSchema.safeParse({ appId, env: environment, kind: 'restore', at: args.at })
395
+ if (!input.success) throw new Error(`The time is ISO 8601 with an offset, such as 2026-10-24T12:00:00.000Z, not "${args.at}"`)
396
+ const result = await controlClient(args, env).data.start(input.data)
397
+ emitOperation(args, parseOperation(result, { appId, env: environment }))
398
+ }
399
+
400
+ const commandRun = (command: string): ((args: EnvArgs, env: Environment) => Promise<void>) | undefined => {
401
+ switch (command) {
402
+ case 'inspect':
403
+ return runInspect
404
+ case 'maintenance':
405
+ return runMaintenance
406
+ case 'operations':
407
+ return runOperations
408
+ case 'recover':
409
+ return runRecover
410
+ case 'backups':
411
+ return runBackups
412
+ case 'restore':
413
+ return runRestore
414
+ default:
415
+ return undefined
416
+ }
417
+ }
418
+
419
+ const diagnostic = (command: string, error: unknown): string => {
420
+ if (!(error instanceof RpcError)) return error instanceof Error ? error.message : String(error)
421
+ // Not offered by this release: a definite answer, unlike an outage, so nothing suggests trying again.
422
+ if (error.httpStatus === 501) return `\`env ${command}\` is not available in this release of the control plane; retrying will not change that`
423
+ // A refusal is an answer, not a transport fault: its type tells "Control said no" from "Control was unreachable".
424
+ return `${error.type}: ${error.message}`
425
+ }
426
+
427
+ export const runEnvCli = async (command: string | undefined, argv: readonly string[], env: Environment = process.env): Promise<void> => {
428
+ if (command === undefined) {
429
+ console.info(USAGE)
430
+ return
431
+ }
432
+ try {
433
+ const run = commandRun(command)
434
+ if (run === undefined) throw new Error(`Unknown env command: ${command}\n\n${USAGE}`)
435
+ const args = parseEnvArgs(argv)
436
+ if (args.content && command !== 'inspect') throw new Error('--content applies to `env inspect` only')
437
+ if (args.at !== undefined && command !== 'restore') throw new Error('--at applies to `env restore` only')
438
+ await run(args, env)
439
+ } catch (error) {
440
+ throw new Error(printable(withoutControlKey(diagnostic(command, error), env)))
441
+ }
442
+ }
443
+
444
+ export { USAGE as ENV_USAGE }
package/src/db.ts CHANGED
@@ -1,4 +1,8 @@
1
+ import { applicationMigrations as sqliteApplicationMigrations } from '@fabrika/app/build'
1
2
  import {
3
+ type ApplicationDialect,
4
+ applicationDialect,
5
+ CONFIG_FILE,
2
6
  type Finding,
3
7
  formatFinding,
4
8
  GENERATED_TEST_HEADER,
@@ -9,8 +13,11 @@ import {
9
13
  scaffoldInputs,
10
14
  } from '@fabrika/check'
11
15
  import { CodegenError, generateSchema, SCHEMA_FILE } from '@fabrika/db/codegen'
16
+ import { generateSqliteSchema } from '@fabrika/db/codegen-sqlite'
12
17
  import { FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations'
18
+ import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
13
19
  import {
20
+ APPLICATION_MIGRATION_BUNDLE,
14
21
  CONNECTION_CAPACITY_MESSAGE,
15
22
  ConnectionCapacityError,
16
23
  createTestProvisioner,
@@ -35,7 +42,7 @@ import { readJunitCases } from './junit'
35
42
  const MIGRATIONS_DIR = 'db/migrations'
36
43
  const SLUG = /^[a-z0-9]+(?:_[a-z0-9]+)*$/
37
44
 
38
- export const DB_USAGE = `fabrika db — an application's Postgres schema
45
+ export const DB_USAGE = `fabrika db — an application's database schema: Postgres, or SQLite on Cloudflare
39
46
 
40
47
  Usage:
41
48
  fabrika db new <slug> Write ${MIGRATIONS_DIR}/<UTC YYYYMMDDHHMMSS>_<slug>.sql; the slug is lowercase snake_case.
@@ -59,6 +66,10 @@ bunfig.toml, and checks the JUnit report against the case names the scaffold wro
59
66
  that killed runs left behind: expired, and without a session of their own or of a role they created. A database at its
60
67
  connection limit (SQLSTATE ${TOO_MANY_CONNECTIONS}) is waited for; one that never frees a slot fails the run saying so,
61
68
  never as failed cases.
69
+
70
+ An application whose ${CONFIG_FILE} default-exports @fabrika/provider-cloudflare's defineApp runs on SQLite in its
71
+ Durable Object, which applies the migrations itself when it boots: \`migrate\` refuses, \`codegen\` applies them to an
72
+ in-memory database, and the generated tests run on @fabrika/db/testing-sqlite; none of them needs a database URL.
62
73
  `
63
74
 
64
75
  export interface DbCommandDependencies {
@@ -79,6 +90,12 @@ const refuseArguments = (command: string, argv: readonly string[]): void => {
79
90
  if (argv.length > 0) throw new Error(`db ${command} takes no argument ${argv[0]}\n\n${DB_USAGE}`)
80
91
  }
81
92
 
93
+ /** The dialect `fabrika.config.ts` names, read as the checker reads it; Postgres without a config. */
94
+ const dialectAt = async (cwd: string): Promise<ApplicationDialect> => {
95
+ const config = await readFile(join(cwd, CONFIG_FILE), 'utf8').catch(() => undefined)
96
+ return applicationDialect(new Map(config === undefined ? [] : [[CONFIG_FILE, config]]))
97
+ }
98
+
82
99
  const timestamp = (date: Date): string => date.toISOString().replace(/\.\d{3}Z$/, '').replaceAll(/[-:T]/g, '')
83
100
 
84
101
  const newMigration = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
@@ -126,6 +143,11 @@ const applicationMigrations = (appId: string, cwd: string): PostgresApplicationM
126
143
 
127
144
  const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
128
145
  refuseArguments('migrate', argv)
146
+ if ((await dialectAt(deps.cwd)) === 'sqlite') {
147
+ throw new Error(
148
+ 'db migrate: an application on Cloudflare migrates its own SQLite database when its Durable Object boots (ADR-0065); there is nothing to run',
149
+ )
150
+ }
129
151
  const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
130
152
  const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
131
153
  const files = migrations.read()
@@ -137,18 +159,29 @@ const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Pr
137
159
  }
138
160
  }
139
161
 
140
- const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
141
- const verify = argv.includes('--verify')
142
- refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
162
+ /** The schema module of the migrated application schema, read with the provisioning credential. */
163
+ const postgresSchema = async (deps: DbCommandDependencies): Promise<string> => {
143
164
  const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
144
165
  const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
145
- let source: string
146
166
  try {
147
167
  // The migrations' manifest: the start check refuses any database object no migration declares.
148
- source = await generateSchema(url, migrations.schema, migrations.objects())
168
+ return await generateSchema(url, migrations.schema, migrations.objects())
149
169
  } catch (error) {
150
170
  throw reportable(error)
151
171
  }
172
+ }
173
+
174
+ /** The schema module of the bundles the Durable Object applies, in its order, run in an in-memory database. */
175
+ const sqliteSchema = async (cwd: string): Promise<string> =>
176
+ generateSqliteSchema([
177
+ { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
178
+ { bundle: APPLICATION_MIGRATION_BUNDLE, migrations: await sqliteApplicationMigrations(cwd) },
179
+ ])
180
+
181
+ const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
182
+ const verify = argv.includes('--verify')
183
+ refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
184
+ const source = (await dialectAt(deps.cwd)) === 'sqlite' ? await sqliteSchema(deps.cwd) : await postgresSchema(deps)
152
185
  const path = join(deps.cwd, SCHEMA_FILE)
153
186
  if (verify) {
154
187
  const committed = await readFile(path, 'utf8').catch(() => undefined)
@@ -168,7 +201,11 @@ const expectedTests = async (
168
201
  > => {
169
202
  const { files } = await readApplicationTree(cwd)
170
203
  const inputs = scaffoldInputs(files)
171
- return { files, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
204
+ return {
205
+ files,
206
+ tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures, inputs.dialect),
207
+ missing: missingEndpointFixtures(inputs),
208
+ }
172
209
  }
173
210
 
174
211
  const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
@@ -194,11 +231,12 @@ const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies
194
231
  }
195
232
 
196
233
  /**
197
- * Only what Bun needs to run; the URL arrives as the kit's own variable, and no framework variable is passed on. It is
198
- * a throwaway provisioner's, never FABRIKA_APP_DATABASE_URL: the generated tests load application code.
234
+ * Only what Bun needs to run; on Postgres the URL arrives as the kit's own variable, and no framework variable is passed
235
+ * on. It is a throwaway provisioner's, never FABRIKA_APP_DATABASE_URL: the generated tests load application code. The
236
+ * SQLite kit opens an in-memory database and needs none.
199
237
  */
200
- const testEnvironment = (source: DbCommandDependencies['source'], url: string): Record<string, string> => {
201
- const environment: Record<string, string> = { FABRIKA_TEST_POSTGRES_URL: url, FABRIKA_TEST_POSTGRES_REQUIRED: '1' }
238
+ const testEnvironment = (source: DbCommandDependencies['source'], url: string | undefined): Record<string, string> => {
239
+ const environment: Record<string, string> = url === undefined ? {} : { FABRIKA_TEST_POSTGRES_URL: url, FABRIKA_TEST_POSTGRES_REQUIRED: '1' }
202
240
  for (const name of ['PATH', 'HOME', 'TMPDIR']) {
203
241
  const value = source[name]
204
242
  if (value !== undefined) environment[name] = value
@@ -226,11 +264,13 @@ export const reportsExhaustedConnections = (output: string): boolean => EXHAUSTE
226
264
  * application applies, and the platform's preload, which captures Bun's test functions before the application loads.
227
265
  * Fails unless every case the scaffold wrote is reported as passed with an assertion. The child's output is never
228
266
  * printed, because a dependency may write a credential into it; `--verbose`, which the platform never passes, prints it.
267
+ * On Postgres they run as a throwaway provisioner, dropped afterwards; on SQLite with no database URL at all.
229
268
  */
230
269
  const testIsolation = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
231
270
  const verbose = argv.includes('--verbose')
232
271
  refuseArguments('test-isolation', argv.filter((arg) => arg !== '--verbose'))
233
- const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
272
+ const sqlite = (await dialectAt(deps.cwd)) === 'sqlite'
273
+ const url = sqlite ? undefined : required(deps.source, 'FABRIKA_APP_DATABASE_URL')
234
274
  const { files, tests, missing } = await expectedTests(deps.cwd)
235
275
  if (missing.length > 0) throw new Error(`db test-isolation: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
236
276
  for (const [path, { text }] of tests) {
@@ -240,6 +280,10 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
240
280
  deps.write('no generated tests\n')
241
281
  return
242
282
  }
283
+ if (url === undefined) {
284
+ await runGeneratedTests(tests, verbose, testEnvironment(deps.source, undefined), deps)
285
+ return
286
+ }
243
287
  let provisioner: TestProvisioner
244
288
  try {
245
289
  provisioner = await withConnectionCapacity(() => createTestProvisioner(url))
@@ -247,6 +291,21 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
247
291
  throw reportable(error)
248
292
  }
249
293
  if (provisioner.swept.length > 0) deps.write(`dropped the test provisioners earlier runs left behind: ${provisioner.swept.join(', ')}\n`)
294
+ try {
295
+ await runGeneratedTests(tests, verbose, testEnvironment(deps.source, provisioner.url), deps)
296
+ } finally {
297
+ await withConnectionCapacity(() => provisioner.drop()).catch((error: unknown) => {
298
+ throw reportable(error)
299
+ })
300
+ }
301
+ }
302
+
303
+ const runGeneratedTests = async (
304
+ tests: ReadonlyMap<string, GeneratedTest>,
305
+ verbose: boolean,
306
+ env: Record<string, string>,
307
+ deps: DbCommandDependencies,
308
+ ): Promise<void> => {
250
309
  const scratch = await mkdtemp(join(tmpdir(), 'fabrika-test-isolation-'))
251
310
  try {
252
311
  await writeFile(join(scratch, 'bunfig.toml'), '')
@@ -261,7 +320,7 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
261
320
  '--reporter=junit',
262
321
  `--reporter-outfile=${report}`,
263
322
  ],
264
- { cwd: deps.cwd, env: testEnvironment(deps.source, provisioner.url), stdout: 'pipe', stderr: 'pipe' },
323
+ { cwd: deps.cwd, env, stdout: 'pipe', stderr: 'pipe' },
265
324
  )
266
325
  const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
267
326
  if (verbose) deps.write(`${stdout}${stderr}\n`)
@@ -296,9 +355,6 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
296
355
  deps.write(`${total} generated cases passed\n`)
297
356
  } finally {
298
357
  await rm(scratch, { recursive: true, force: true })
299
- await withConnectionCapacity(() => provisioner.drop()).catch((error: unknown) => {
300
- throw reportable(error)
301
- })
302
358
  }
303
359
  }
304
360