@fabrika/cli 0.9.0-dev.3 → 0.9.0-dev.31
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 +14 -13
- package/src/app-dev-seed.ts +2 -6
- package/src/app-dev-ui.ts +155 -24
- package/src/app-dev.ts +94 -39
- package/src/control.ts +165 -61
- package/src/data.ts +444 -0
- package/src/db.ts +62 -183
- package/src/index.ts +73 -57
- package/src/job.ts +2 -2
- package/src/namespace.ts +55 -178
- package/src/operations.ts +722 -0
- package/types/src/app-dev-seed.d.ts +0 -2
- package/types/src/app-dev-ui.d.ts +22 -8
- package/types/src/app-dev.d.ts +1 -1
- package/types/src/control.d.ts +34 -3
- package/types/src/data.d.ts +6 -0
- package/types/src/db.d.ts +1 -3
- package/types/src/index.d.ts +0 -2
- package/types/src/job.d.ts +1 -1
- package/types/src/namespace.d.ts +8 -13
- package/types/src/operations.d.ts +20 -0
- package/src/junit.ts +0 -37
- package/types/src/junit.d.ts +0 -10
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
|
+
export 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 }
|