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

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,445 @@
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; one of:
70
+
71
+ FABRIKA_CONTROL_KEY a machine \`px_\` credential for the control app
72
+ FABRIKA_CONTROL_CREDENTIAL_HELPER the helper a \`fabrika control auth device\` grant is stored through
73
+ `
74
+
75
+ type Environment = Readonly<Record<string, string | undefined>>
76
+
77
+ interface EnvArgs {
78
+ readonly positional: readonly string[]
79
+ readonly json: boolean
80
+ readonly content: boolean
81
+ readonly url: string | undefined
82
+ /** \`''\` when \`--at\` closes the arguments with no time after it. */
83
+ readonly at: string | undefined
84
+ }
85
+
86
+ const COMMAND_FORMS: Readonly<Record<string, string>> = {
87
+ inspect: '<app> <env> [--content] [--json]',
88
+ maintenance: '<app> <env> <open|read-only|closed> [--json]',
89
+ operations: '<app> <env> [--json]',
90
+ recover: '<app> <env> <operationId> <resume|open> [--json]',
91
+ backups: '<app> <env> [--json]',
92
+ 'backups schedule': '<app> <env> [on|off] [--json]',
93
+ restore: '<app> <env> --at=<time> [--json]',
94
+ }
95
+
96
+ const parseEnvArgs = (argv: readonly string[]): EnvArgs => {
97
+ const positional: string[] = []
98
+ let json = false
99
+ let content = false
100
+ let url: string | undefined
101
+ let at: string | undefined
102
+ for (let index = 0; index < argv.length; index++) {
103
+ const arg = argv[index] ?? ''
104
+ if (arg === '--json') json = true
105
+ else if (arg === '--content') content = true
106
+ else if (arg.startsWith('--url=')) url = arg.slice('--url='.length)
107
+ else if (arg.startsWith('--at=')) at = arg.slice('--at='.length)
108
+ else if (arg === '--at') at = argv[++index] ?? ''
109
+ else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`)
110
+ else positional.push(arg)
111
+ }
112
+ return { positional, json, content, url, at }
113
+ }
114
+
115
+ /** The positional words of `command`, exactly `count` of them. */
116
+ const words = (command: string, args: EnvArgs, count: number): readonly string[] => {
117
+ if (args.positional.length !== count || args.positional.some((word) => word.trim() === '')) throw usage(command)
118
+ return args.positional
119
+ }
120
+
121
+ const usage = (command: string): Error => new Error(`Usage: fabrika env ${command} ${COMMAND_FORMS[command] ?? ''}`)
122
+
123
+ const controlClient = (args: EnvArgs, env: Environment): ControlClient => connectControl(args.url, env)
124
+
125
+ /** Control's own rule for an operation's or a backup's error code (`db/data-operations.ts`, `db/backups.ts`). */
126
+ const ERROR_CODE = /^[a-z][a-z0-9_]{0,63}$/
127
+
128
+ /** The known fields of an operation, validated; a field a newer Control adds is dropped, never printed. */
129
+ const dataOperationSchema: z.ZodType<DataOperationDto, z.ZodTypeDef, unknown> = z.object({
130
+ id: z.string().uuid(),
131
+ appId: z.string(),
132
+ env: z.string(),
133
+ kind: z.enum(['maintenance', 'backup', 'migrate', 'recovery', 'restore']),
134
+ step: z.enum([
135
+ 'reconcile',
136
+ 'restrict',
137
+ 'backup',
138
+ 'verify',
139
+ 'deploy',
140
+ 'migrate',
141
+ 'resume',
142
+ 'open',
143
+ 'list',
144
+ 'import',
145
+ 'promote',
146
+ 'point',
147
+ 'serve',
148
+ 'rewind',
149
+ 'check',
150
+ 'revert',
151
+ ]),
152
+ targetMode: z.enum(['open', 'read-only', 'closed', 'inspect']),
153
+ generation: z.number().int().nonnegative(),
154
+ state: z.enum(['running', 'succeeded', 'failed']),
155
+ errorCode: z.string().regex(ERROR_CODE).nullable(),
156
+ actor: z.string(),
157
+ createdAt: z.number().int().nonnegative(),
158
+ updatedAt: z.number().int().nonnegative(),
159
+ finishedAt: z.number().int().nonnegative().nullable(),
160
+ recoversOperationId: z.string().uuid().nullable(),
161
+ resolution: z.enum(['resume', 'open']).nullable(),
162
+ // Absent from a Control before the migration phase.
163
+ runId: z.string().uuid().nullable().default(null),
164
+ })
165
+
166
+ interface Target {
167
+ readonly appId: string
168
+ readonly env: string
169
+ }
170
+
171
+ /** An answer about the environment asked about, and of no other. */
172
+ const ofTarget = (answer: Target, target: Target): boolean => answer.appId === target.appId && answer.env === target.env
173
+
174
+ const parseOperation = (value: unknown, target: Target): DataOperationDto => {
175
+ const parsed = dataOperationSchema.safeParse(value)
176
+ if (!parsed.success || !ofTarget(parsed.data, target)) throw new Error('Control returned an unreadable data operation')
177
+ return parsed.data
178
+ }
179
+
180
+ const dataOperationPageSchema = z.object({ items: z.array(dataOperationSchema), nextCursor: z.string().uuid().nullable() })
181
+
182
+ const parseOperationPage = (value: unknown, target: Target): { items: DataOperationDto[]; nextCursor: string | null } => {
183
+ const parsed = dataOperationPageSchema.safeParse(value)
184
+ if (!parsed.success || !parsed.data.items.every((operation) => ofTarget(operation, target))) {
185
+ throw new Error('Control returned an unreadable list of data operations')
186
+ }
187
+ return parsed.data
188
+ }
189
+
190
+ /** The known fields of a backup, validated as an operation's are. */
191
+ const dataBackupSchema: z.ZodType<DataBackupDto> = z.object({
192
+ id: z.string().uuid(),
193
+ appId: z.string(),
194
+ env: z.string(),
195
+ operationId: z.string().uuid(),
196
+ object: z.string().refine((name) => parseApplicationObjectName(name) !== null),
197
+ dumpId: z.string().uuid(),
198
+ preMigration: z.boolean(),
199
+ state: z.enum(['running', 'succeeded', 'failed']),
200
+ errorCode: z.string().regex(ERROR_CODE).nullable(),
201
+ createdAt: z.number().int().nonnegative(),
202
+ finishedAt: z.number().int().nonnegative().nullable(),
203
+ bookmark: z.string().nullable(),
204
+ sizeBytes: z.number().int().nonnegative().nullable(),
205
+ parts: z.number().int().nonnegative().nullable(),
206
+ tables: z.number().int().nonnegative().nullable(),
207
+ rehearsal: z.enum(['pending', 'passed', 'failed']),
208
+ rehearsalCode: z.string().regex(ERROR_CODE).nullable(),
209
+ expired: z.boolean(),
210
+ })
211
+
212
+ const dataBackupPageSchema = z.object({ items: z.array(dataBackupSchema), nextCursor: z.string().uuid().nullable() })
213
+
214
+ const parseBackupPage = (value: unknown, target: Target): { items: DataBackupDto[]; nextCursor: string | null } => {
215
+ const parsed = dataBackupPageSchema.safeParse(value)
216
+ if (!parsed.success || !parsed.data.items.every((backup) => ofTarget(backup, target))) {
217
+ throw new Error('Control returned an unreadable list of backups')
218
+ }
219
+ return parsed.data
220
+ }
221
+
222
+ const dataBackupScheduleSchema: z.ZodType<DataBackupScheduleDto> = z.object({
223
+ appId: z.string(),
224
+ env: z.string(),
225
+ daily: z.boolean(),
226
+ updatedAt: z.number().int().nonnegative().nullable(),
227
+ })
228
+
229
+ const parseSchedule = (value: unknown, target: Target): DataBackupScheduleDto => {
230
+ const parsed = dataBackupScheduleSchema.safeParse(value)
231
+ if (!parsed.success || !ofTarget(parsed.data, target)) throw new Error('Control returned an unreadable backup schedule')
232
+ return parsed.data
233
+ }
234
+
235
+ const MAINTENANCE_MODES = ['open', 'read-only', 'closed'] as const
236
+ const RESOLUTIONS = ['resume', 'open'] as const
237
+ const SCHEDULE_SWITCHES = ['on', 'off'] as const
238
+
239
+ const oneOf = <T extends string>(value: string, allowed: readonly T[]): T | undefined => allowed.find((candidate) => candidate === value)
240
+
241
+ /** Control's timestamps are Unix seconds. */
242
+ const isoSeconds = (seconds: number): string => new Date(seconds * 1000).toISOString()
243
+
244
+ const operationLine = (operation: DataOperationDto): string =>
245
+ [
246
+ operation.id,
247
+ operation.kind,
248
+ operation.state,
249
+ operation.step,
250
+ operation.targetMode,
251
+ String(operation.generation),
252
+ operation.errorCode ?? '-',
253
+ isoSeconds(operation.createdAt),
254
+ ].join('\t')
255
+
256
+ const backupLine = (backup: DataBackupDto): string =>
257
+ [
258
+ backup.id,
259
+ backup.object,
260
+ backup.state,
261
+ isoSeconds(backup.createdAt),
262
+ backup.sizeBytes === null ? '-' : String(backup.sizeBytes),
263
+ backup.parts === null ? '-' : String(backup.parts),
264
+ backup.tables === null ? '-' : String(backup.tables),
265
+ backup.rehearsal,
266
+ backup.rehearsalCode ?? '-',
267
+ backup.errorCode ?? '-',
268
+ backup.expired ? 'expired' : '-',
269
+ backup.preMigration ? 'pre-migration' : '-',
270
+ ].join('\t')
271
+
272
+ const scheduleLines = (schedule: DataBackupScheduleDto): string =>
273
+ [`daily\t${schedule.daily ? 'on' : 'off'}`, `updatedAt\t${schedule.updatedAt === null ? '-' : isoSeconds(schedule.updatedAt)}`].join('\n')
274
+
275
+ /** Every control character but tab and line feed: an answer must not drive the operator's terminal. */
276
+ export const printable = (text: string): string => text.replace(/[^\P{Cc}\t\n]/gu, '')
277
+
278
+ const viewLines = (view: OpsView | OpsContentView): string[] => [
279
+ `release\t${view.release}`,
280
+ `mode\t${view.maintenance.mode}`,
281
+ `generation\t${view.maintenance.generation ?? '-'}`,
282
+ `published\t${view.maintenance.published ? 'yes' : 'no'}`,
283
+ `databaseBytes\t${view.database.sizeBytes}`,
284
+ ...view.database.tables.map((table) => `table\t${table.name}\t${table.rows >= OPS_ROW_COUNT_CAP ? `${OPS_ROW_COUNT_CAP}+` : table.rows}`),
285
+ ...view.migrations.map((migration) => `migration\t${migration.bundle}\t${migration.name}\t${migration.appliedAt}`),
286
+ `alarm\t${view.scheduler.alarm ?? '-'}`,
287
+ ...view.jobs.map((job) =>
288
+ `job\t${job.job}\t${job.lastStatus ?? '-'}\t${job.lastStartedAt ?? '-'}\t${job.lastFinishedAt ?? '-'}\t${job.lastDurationMs ?? '-'}`
289
+ ),
290
+ ...view.files.map((file) => `file\t${file.kind}\t${file.status}\t${file.count}`),
291
+ ...view.webhooks.map((webhook) => `webhook\t${webhook.webhook}\t${webhook.state}\t${webhook.count}`),
292
+ `bootFailure\t${view.bootFailure?.at ?? '-'}`,
293
+ ]
294
+
295
+ const contentLines = (view: OpsContentView): string[] => {
296
+ const failure = view.bootFailure
297
+ if (failure === null) return viewLines(view)
298
+ return [...viewLines(view), '', failure.message, ...(failure.stack === null ? [] : [failure.stack])]
299
+ }
300
+
301
+ /** Human output and every note pass `printable`; `--json` escapes what JSON must. */
302
+ const emit = (args: EnvArgs, result: unknown, render: () => string): void => {
303
+ console.info(args.json ? JSON.stringify(result, null, 2) : printable(render()))
304
+ }
305
+
306
+ const note = (text: string): void => {
307
+ console.warn(printable(text))
308
+ }
309
+
310
+ /** An operation is an answer whatever its state; stderr names what follows it. */
311
+ const emitOperation = (args: EnvArgs, operation: DataOperationDto): void => {
312
+ const coordinates = `${operation.appId} ${operation.env}`
313
+ if (operation.state === 'running') note(`follow it: fabrika env operations ${coordinates}`)
314
+ if (operation.state === 'failed') note(`open the environment past it: fabrika env recover ${coordinates} ${operation.id} open`)
315
+ emit(args, operation, () => operationLine(operation))
316
+ }
317
+
318
+ const runInspect = async (args: EnvArgs, env: Environment): Promise<void> => {
319
+ const [appId = '', environment = ''] = words('inspect', args, 2)
320
+ const client = controlClient(args, env)
321
+ if (args.content) {
322
+ const view = parseOpsContentView(await client.data.content({ appId, env: environment }))
323
+ if (view === null) throw new Error('Control returned an unreadable data view')
324
+ emit(args, view, () => contentLines(view).join('\n'))
325
+ return
326
+ }
327
+ const view = parseOpsView(await client.data.view({ appId, env: environment }))
328
+ if (view === null) throw new Error('Control returned an unreadable data view')
329
+ emit(args, view, () => viewLines(view).join('\n'))
330
+ }
331
+
332
+ const runMaintenance = async (args: EnvArgs, env: Environment): Promise<void> => {
333
+ const [appId = '', environment = '', requested = ''] = words('maintenance', args, 3)
334
+ const mode = oneOf(requested, MAINTENANCE_MODES)
335
+ if (mode === undefined) throw new Error(`The mode is one of ${MAINTENANCE_MODES.join(', ')}, not "${requested}"`)
336
+ const result = await controlClient(args, env).data.start({ appId, env: environment, kind: 'maintenance', mode })
337
+ emitOperation(args, parseOperation(result, { appId, env: environment }))
338
+ }
339
+
340
+ const runOperations = async (args: EnvArgs, env: Environment): Promise<void> => {
341
+ const [appId = '', environment = ''] = words('operations', args, 2)
342
+ const page = parseOperationPage(await controlClient(args, env).data.operations.list({ appId, env: environment }), { appId, env: environment })
343
+ if (page.nextCursor !== null) note(`showing the newest ${page.items.length} operations; older ones exist`)
344
+ if (!args.json && page.items.length === 0) {
345
+ note(`${appId} ${environment} has no data operations`)
346
+ return
347
+ }
348
+ emit(args, page, () => page.items.map(operationLine).join('\n'))
349
+ }
350
+
351
+ const runRecover = async (args: EnvArgs, env: Environment): Promise<void> => {
352
+ const [appId = '', environment = '', operationId = '', requested = ''] = words('recover', args, 4)
353
+ const resolution = oneOf(requested, RESOLUTIONS)
354
+ if (resolution === undefined) throw new Error(`The resolution is resume or open, not "${requested}"`)
355
+ const result = await controlClient(args, env).data.recover({ appId, env: environment, operationId, resolution })
356
+ emitOperation(args, parseOperation(result, { appId, env: environment }))
357
+ }
358
+
359
+ const runBackups = async (args: EnvArgs, env: Environment): Promise<void> => {
360
+ if (args.positional[0] === 'schedule' && args.positional.length > 2) {
361
+ await runBackupSchedule(args, env)
362
+ return
363
+ }
364
+ const [appId = '', environment = ''] = words('backups', args, 2)
365
+ const page = parseBackupPage(await controlClient(args, env).data.backups.list({ appId, env: environment }), { appId, env: environment })
366
+ if (page.nextCursor !== null) note(`showing the newest ${page.items.length} backups; older ones exist`)
367
+ if (!args.json && page.items.length === 0) {
368
+ note(`${appId} ${environment} has no backups`)
369
+ return
370
+ }
371
+ emit(args, page, () => page.items.map(backupLine).join('\n'))
372
+ }
373
+
374
+ const runBackupSchedule = async (args: EnvArgs, env: Environment): Promise<void> => {
375
+ const [, appId = '', environment = '', requested] = args.positional
376
+ if (args.positional.length > 4 || appId.trim() === '' || environment.trim() === '') throw usage('backups schedule')
377
+ const client = controlClient(args, env)
378
+ const target = { appId, env: environment }
379
+ if (requested === undefined) {
380
+ const schedule = parseSchedule(await client.data.backups.schedule(target), target)
381
+ emit(args, schedule, () => scheduleLines(schedule))
382
+ return
383
+ }
384
+ const daily = oneOf(requested, SCHEDULE_SWITCHES)
385
+ if (daily === undefined) throw new Error(`The schedule is on or off, not "${requested}"`)
386
+ const schedule = parseSchedule(await client.data.backups.setSchedule({ ...target, daily: daily === 'on' }), target)
387
+ if (!schedule.daily) note('the backup before a migration still runs')
388
+ emit(args, schedule, () => scheduleLines(schedule))
389
+ }
390
+
391
+ const runRestore = async (args: EnvArgs, env: Environment): Promise<void> => {
392
+ const [appId = '', environment = ''] = words('restore', args, 2)
393
+ if (args.at === undefined || args.at === '') throw usage('restore')
394
+ // The contract's own rule for `at`, checked before anything is sent; whether it lies in the past is Control's to decide.
395
+ const input = startDataOperationInputSchema.safeParse({ appId, env: environment, kind: 'restore', at: args.at })
396
+ 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}"`)
397
+ const result = await controlClient(args, env).data.start(input.data)
398
+ emitOperation(args, parseOperation(result, { appId, env: environment }))
399
+ }
400
+
401
+ const commandRun = (command: string): ((args: EnvArgs, env: Environment) => Promise<void>) | undefined => {
402
+ switch (command) {
403
+ case 'inspect':
404
+ return runInspect
405
+ case 'maintenance':
406
+ return runMaintenance
407
+ case 'operations':
408
+ return runOperations
409
+ case 'recover':
410
+ return runRecover
411
+ case 'backups':
412
+ return runBackups
413
+ case 'restore':
414
+ return runRestore
415
+ default:
416
+ return undefined
417
+ }
418
+ }
419
+
420
+ const diagnostic = (command: string, error: unknown): string => {
421
+ if (!(error instanceof RpcError)) return error instanceof Error ? error.message : String(error)
422
+ // Not offered by this release: a definite answer, unlike an outage, so nothing suggests trying again.
423
+ if (error.httpStatus === 501) return `\`env ${command}\` is not available in this release of the control plane; retrying will not change that`
424
+ // A refusal is an answer, not a transport fault: its type tells "Control said no" from "Control was unreachable".
425
+ return `${error.type}: ${error.message}`
426
+ }
427
+
428
+ export const runEnvCli = async (command: string | undefined, argv: readonly string[], env: Environment = process.env): Promise<void> => {
429
+ if (command === undefined) {
430
+ console.info(USAGE)
431
+ return
432
+ }
433
+ try {
434
+ const run = commandRun(command)
435
+ if (run === undefined) throw new Error(`Unknown env command: ${command}\n\n${USAGE}`)
436
+ const args = parseEnvArgs(argv)
437
+ if (args.content && command !== 'inspect') throw new Error('--content applies to `env inspect` only')
438
+ if (args.at !== undefined && command !== 'restore') throw new Error('--at applies to `env restore` only')
439
+ await run(args, env)
440
+ } catch (error) {
441
+ throw new Error(printable(withoutControlKey(diagnostic(command, error), env)))
442
+ }
443
+ }
444
+
445
+ export { USAGE as ENV_USAGE }