@fabrika/cli 0.9.0-dev.5 → 0.9.0-dev.51
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 +16 -13
- package/src/app-dev-seed.ts +2 -6
- package/src/app-dev-ui.ts +155 -24
- package/src/app-dev.ts +65 -24
- package/src/connect.ts +24 -8
- package/src/control-oauth.ts +463 -0
- package/src/control.ts +899 -105
- package/src/credential-origin.ts +54 -0
- package/src/data.ts +61 -24
- package/src/db.ts +35 -212
- package/src/index.ts +21 -5
- package/src/job.ts +2 -2
- package/src/operations.ts +737 -0
- package/types/src/app-dev-seed.d.ts +0 -2
- package/types/src/app-dev-ui.d.ts +22 -8
- package/types/src/connect.d.ts +4 -1
- package/types/src/control-oauth.d.ts +56 -0
- package/types/src/control.d.ts +86 -14
- package/types/src/credential-origin.d.ts +14 -0
- package/types/src/data.d.ts +3 -1
- package/types/src/db.d.ts +1 -3
- package/types/src/job.d.ts +1 -1
- package/types/src/operations.d.ts +23 -0
- package/src/junit.ts +0 -37
- package/types/src/junit.d.ts +0 -10
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The origin check every credential the CLI sends passes before it goes anywhere.
|
|
2
|
+
|
|
3
|
+
/** Plain http may carry a credential to loopback only: 127.0.0.0/8, [::1], and the names RFC 6761 reserves for it, `localhost` and `*.localhost`. */
|
|
4
|
+
const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
|
|
5
|
+
|
|
6
|
+
/** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
|
|
7
|
+
export interface OriginSource {
|
|
8
|
+
readonly label: string
|
|
9
|
+
readonly flag: string
|
|
10
|
+
readonly variable: string
|
|
11
|
+
readonly hint?: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type OriginCheck = { readonly origin: string } | { readonly refusal: 'not_url' | 'scheme' | 'not_origin' }
|
|
15
|
+
|
|
16
|
+
/** `raw`'s origin when it may carry a credential: https, or http to a loopback host, and nothing but scheme, host and port. */
|
|
17
|
+
function checkOrigin(raw: string): OriginCheck {
|
|
18
|
+
let url: URL
|
|
19
|
+
try {
|
|
20
|
+
url = new URL(raw.trim())
|
|
21
|
+
} catch {
|
|
22
|
+
return { refusal: 'not_url' }
|
|
23
|
+
}
|
|
24
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) return { refusal: 'scheme' }
|
|
25
|
+
if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
|
|
26
|
+
return { refusal: 'not_origin' }
|
|
27
|
+
}
|
|
28
|
+
return { origin: url.origin }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The origin of a value another party published (an authorization server), or null when no credential may go there. */
|
|
32
|
+
export const credentialOriginOf = (raw: string): string | null => {
|
|
33
|
+
const checked = checkOrigin(raw)
|
|
34
|
+
return 'origin' in checked ? checked.origin : null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* An origin a credential is sent to, checked before the credential goes anywhere. A refusal never repeats the value,
|
|
39
|
+
* which may hold userinfo.
|
|
40
|
+
*/
|
|
41
|
+
export const credentialOrigin = (raw: string | undefined, source: OriginSource): string => {
|
|
42
|
+
const { label, flag, variable } = source
|
|
43
|
+
if (raw === undefined || raw.trim() === '') {
|
|
44
|
+
throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
|
|
45
|
+
}
|
|
46
|
+
const checked = checkOrigin(raw)
|
|
47
|
+
if ('origin' in checked) return checked.origin
|
|
48
|
+
const reason = {
|
|
49
|
+
not_url: `--${flag} or ${variable} is not a URL`,
|
|
50
|
+
scheme: `--${flag} or ${variable} must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]`,
|
|
51
|
+
not_origin: `--${flag} or ${variable} must be an origin only: no credentials, path, query or fragment`,
|
|
52
|
+
}[checked.refusal]
|
|
53
|
+
throw new Error(source.hint === undefined ? reason : `${reason}. ${source.hint}`)
|
|
54
|
+
}
|
package/src/data.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { RpcError } from '@fabrika/app'
|
|
5
5
|
import {
|
|
6
|
+
OPS_MIGRATION_FAILURES,
|
|
6
7
|
OPS_ROW_COUNT_CAP,
|
|
7
8
|
type OpsContentView,
|
|
8
9
|
type OpsView,
|
|
@@ -10,20 +11,26 @@ import {
|
|
|
10
11
|
parseOpsContentView,
|
|
11
12
|
parseOpsView,
|
|
12
13
|
} from '@fabrika/auth-core'
|
|
13
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
DATA_OPERATION_RESOLUTIONS,
|
|
16
|
+
type DataBackupDto,
|
|
17
|
+
type DataBackupScheduleDto,
|
|
18
|
+
type DataOperationDto,
|
|
19
|
+
startDataOperationInputSchema,
|
|
20
|
+
} from '@fabrika/control-contract'
|
|
14
21
|
import { z } from 'zod'
|
|
15
|
-
import { connectControl, type ControlClient, withoutControlKey } from './control.js'
|
|
22
|
+
import { ApprovalPendingError, connectControl, type ControlClient, directWrite, withoutControlKey } from './control.js'
|
|
16
23
|
|
|
17
24
|
const USAGE = `fabrika env — an application environment's data, through the control plane
|
|
18
25
|
|
|
19
26
|
Usage:
|
|
20
27
|
fabrika env inspect <app> <env> [--content] [--json]
|
|
21
|
-
fabrika env maintenance <app> <env> <open|read-only|closed> [--json]
|
|
28
|
+
fabrika env maintenance <app> <env> <open|read-only|closed> [--wait] [--json]
|
|
22
29
|
fabrika env operations <app> <env> [--json]
|
|
23
|
-
fabrika env recover <app> <env> <operationId> <resume|open> [--json]
|
|
30
|
+
fabrika env recover <app> <env> <operationId> <resume|open|rollback> [--wait] [--json]
|
|
24
31
|
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]
|
|
32
|
+
fabrika env backups schedule <app> <env> [on|off] [--wait] [--json]
|
|
33
|
+
fabrika env restore <app> <env> --at=<time> [--wait] [--json]
|
|
27
34
|
|
|
28
35
|
\`inspect\` prints the environment's data view: the object's maintenance mode and generation, the database size and
|
|
29
36
|
each table's row count (a count at ${OPS_ROW_COUNT_CAP} reads \`${OPS_ROW_COUNT_CAP}+\`: it is capped), the applied migrations,
|
|
@@ -38,8 +45,10 @@ and needs \`data.content.read\` granted globally.
|
|
|
38
45
|
<id> <kind> <state> <step> <target mode> <generation> <error code> <created at>.
|
|
39
46
|
|
|
40
47
|
\`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
|
|
42
|
-
\`
|
|
48
|
+
operation from its recorded step, or \`open\`s the environment. A failed operation can only be opened past, or, for a
|
|
49
|
+
failed migration whose data holds nothing of it (\`rollbackAndOpen\` in \`--json\`), rolled back: \`rollback\` fences
|
|
50
|
+
it in \`inspect\`, deploys the last succeeded commit again as a new run, waits until the failed version is gone and
|
|
51
|
+
opens it. It needs \`data.manage\`.
|
|
43
52
|
|
|
44
53
|
\`backups\` lists the environment's consistent backups, newest first, one row each:
|
|
45
54
|
<id> <object> <state> <created at> <size bytes> <parts> <tables> <rehearsal> <rehearsal code> <error code> <expired>
|
|
@@ -57,6 +66,10 @@ object, ordinary traffic is pointed at the clone, which serves the current data
|
|
|
57
66
|
rewound to that time and kept in \`inspect\`, serving nothing, for inspection. It starts a data operation and prints
|
|
58
67
|
it; \`operations\` follows it. It needs \`data.manage\`.
|
|
59
68
|
|
|
69
|
+
On a protected environment whose \`data\` category waits for a person (ADR-0083), a write by a key or an agent does not
|
|
70
|
+
apply: Control stores it as an approval request, the request's \`<id> <state> <url>\` goes to stdout, and the command
|
|
71
|
+
exits 75. Hand the person the link. \`--wait\` follows the request to its end instead and succeeds only when it executed.
|
|
72
|
+
|
|
60
73
|
A release of the control plane that does not offer a command answers that it is not available; retrying does not
|
|
61
74
|
change that. An environment the caller may not see answers \`not_found\`, as one that does not exist.
|
|
62
75
|
|
|
@@ -66,9 +79,10 @@ The control origin takes either form:
|
|
|
66
79
|
|
|
67
80
|
--url=<origin> FABRIKA_CONTROL_URL
|
|
68
81
|
|
|
69
|
-
The credential is read from the ENVIRONMENT ONLY and has no flag:
|
|
82
|
+
The credential is read from the ENVIRONMENT ONLY and has no flag; one of:
|
|
70
83
|
|
|
71
|
-
FABRIKA_CONTROL_KEY
|
|
84
|
+
FABRIKA_CONTROL_KEY a machine \`px_\` credential for the control app
|
|
85
|
+
FABRIKA_CONTROL_CREDENTIAL_HELPER the helper a \`fabrika control auth device\` grant is stored through
|
|
72
86
|
`
|
|
73
87
|
|
|
74
88
|
type Environment = Readonly<Record<string, string | undefined>>
|
|
@@ -77,6 +91,8 @@ interface EnvArgs {
|
|
|
77
91
|
readonly positional: readonly string[]
|
|
78
92
|
readonly json: boolean
|
|
79
93
|
readonly content: boolean
|
|
94
|
+
/** Follow a write that waits for a person to its end state. */
|
|
95
|
+
readonly wait: boolean
|
|
80
96
|
readonly url: string | undefined
|
|
81
97
|
/** \`''\` when \`--at\` closes the arguments with no time after it. */
|
|
82
98
|
readonly at: string | undefined
|
|
@@ -84,31 +100,33 @@ interface EnvArgs {
|
|
|
84
100
|
|
|
85
101
|
const COMMAND_FORMS: Readonly<Record<string, string>> = {
|
|
86
102
|
inspect: '<app> <env> [--content] [--json]',
|
|
87
|
-
maintenance: '<app> <env> <open|read-only|closed> [--json]',
|
|
103
|
+
maintenance: '<app> <env> <open|read-only|closed> [--wait] [--json]',
|
|
88
104
|
operations: '<app> <env> [--json]',
|
|
89
|
-
recover: '<app> <env> <operationId> <resume|open> [--json]',
|
|
105
|
+
recover: '<app> <env> <operationId> <resume|open|rollback> [--wait] [--json]',
|
|
90
106
|
backups: '<app> <env> [--json]',
|
|
91
|
-
'backups schedule': '<app> <env> [on|off] [--json]',
|
|
92
|
-
restore: '<app> <env> --at=<time> [--json]',
|
|
107
|
+
'backups schedule': '<app> <env> [on|off] [--wait] [--json]',
|
|
108
|
+
restore: '<app> <env> --at=<time> [--wait] [--json]',
|
|
93
109
|
}
|
|
94
110
|
|
|
95
111
|
const parseEnvArgs = (argv: readonly string[]): EnvArgs => {
|
|
96
112
|
const positional: string[] = []
|
|
97
113
|
let json = false
|
|
98
114
|
let content = false
|
|
115
|
+
let wait = false
|
|
99
116
|
let url: string | undefined
|
|
100
117
|
let at: string | undefined
|
|
101
118
|
for (let index = 0; index < argv.length; index++) {
|
|
102
119
|
const arg = argv[index] ?? ''
|
|
103
120
|
if (arg === '--json') json = true
|
|
104
121
|
else if (arg === '--content') content = true
|
|
122
|
+
else if (arg === '--wait') wait = true
|
|
105
123
|
else if (arg.startsWith('--url=')) url = arg.slice('--url='.length)
|
|
106
124
|
else if (arg.startsWith('--at=')) at = arg.slice('--at='.length)
|
|
107
125
|
else if (arg === '--at') at = argv[++index] ?? ''
|
|
108
126
|
else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`)
|
|
109
127
|
else positional.push(arg)
|
|
110
128
|
}
|
|
111
|
-
return { positional, json, content, url, at }
|
|
129
|
+
return { positional, json, content, wait, url, at }
|
|
112
130
|
}
|
|
113
131
|
|
|
114
132
|
/** The positional words of `command`, exactly `count` of them. */
|
|
@@ -157,9 +175,19 @@ const dataOperationSchema: z.ZodType<DataOperationDto, z.ZodTypeDef, unknown> =
|
|
|
157
175
|
updatedAt: z.number().int().nonnegative(),
|
|
158
176
|
finishedAt: z.number().int().nonnegative().nullable(),
|
|
159
177
|
recoversOperationId: z.string().uuid().nullable(),
|
|
160
|
-
resolution: z.enum(
|
|
178
|
+
resolution: z.enum(DATA_OPERATION_RESOLUTIONS).nullable(),
|
|
161
179
|
// Absent from a Control before the migration phase.
|
|
162
180
|
runId: z.string().uuid().nullable().default(null),
|
|
181
|
+
// Absent from a Control before the migrating deploy without a read-only window.
|
|
182
|
+
recordsBookmark: z.boolean().default(false),
|
|
183
|
+
migrationFailure: z.enum(OPS_MIGRATION_FAILURES).nullable().default(null),
|
|
184
|
+
revertRunId: z.string().uuid().nullable().default(null),
|
|
185
|
+
candidateRecovered: z.boolean().default(false),
|
|
186
|
+
// Absent from a Control before the in-place rewind.
|
|
187
|
+
rewound: z.boolean().default(false),
|
|
188
|
+
rewindRefusal: z.string().regex(ERROR_CODE).nullable().default(null),
|
|
189
|
+
// Absent from a Control before the roll back and open recovery.
|
|
190
|
+
rollbackAndOpen: z.boolean().default(false),
|
|
163
191
|
})
|
|
164
192
|
|
|
165
193
|
interface Target {
|
|
@@ -232,7 +260,6 @@ const parseSchedule = (value: unknown, target: Target): DataBackupScheduleDto =>
|
|
|
232
260
|
}
|
|
233
261
|
|
|
234
262
|
const MAINTENANCE_MODES = ['open', 'read-only', 'closed'] as const
|
|
235
|
-
const RESOLUTIONS = ['resume', 'open'] as const
|
|
236
263
|
const SCHEDULE_SWITCHES = ['on', 'off'] as const
|
|
237
264
|
|
|
238
265
|
const oneOf = <T extends string>(value: string, allowed: readonly T[]): T | undefined => allowed.find((candidate) => candidate === value)
|
|
@@ -272,7 +299,7 @@ const scheduleLines = (schedule: DataBackupScheduleDto): string =>
|
|
|
272
299
|
[`daily\t${schedule.daily ? 'on' : 'off'}`, `updatedAt\t${schedule.updatedAt === null ? '-' : isoSeconds(schedule.updatedAt)}`].join('\n')
|
|
273
300
|
|
|
274
301
|
/** 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, '')
|
|
302
|
+
export const printable = (text: string): string => text.replace(/[^\P{Cc}\t\n]/gu, '')
|
|
276
303
|
|
|
277
304
|
const viewLines = (view: OpsView | OpsContentView): string[] => [
|
|
278
305
|
`release\t${view.release}`,
|
|
@@ -332,7 +359,9 @@ const runMaintenance = async (args: EnvArgs, env: Environment): Promise<void> =>
|
|
|
332
359
|
const [appId = '', environment = '', requested = ''] = words('maintenance', args, 3)
|
|
333
360
|
const mode = oneOf(requested, MAINTENANCE_MODES)
|
|
334
361
|
if (mode === undefined) throw new Error(`The mode is one of ${MAINTENANCE_MODES.join(', ')}, not "${requested}"`)
|
|
335
|
-
const
|
|
362
|
+
const client = controlClient(args, env)
|
|
363
|
+
const result = await directWrite(client, args, () => client.data.start({ appId, env: environment, kind: 'maintenance', mode }))
|
|
364
|
+
if (result === null) return
|
|
336
365
|
emitOperation(args, parseOperation(result, { appId, env: environment }))
|
|
337
366
|
}
|
|
338
367
|
|
|
@@ -349,9 +378,11 @@ const runOperations = async (args: EnvArgs, env: Environment): Promise<void> =>
|
|
|
349
378
|
|
|
350
379
|
const runRecover = async (args: EnvArgs, env: Environment): Promise<void> => {
|
|
351
380
|
const [appId = '', environment = '', operationId = '', requested = ''] = words('recover', args, 4)
|
|
352
|
-
const resolution = oneOf(requested,
|
|
353
|
-
if (resolution === undefined) throw new Error(`The resolution is resume or
|
|
354
|
-
const
|
|
381
|
+
const resolution = oneOf(requested, DATA_OPERATION_RESOLUTIONS)
|
|
382
|
+
if (resolution === undefined) throw new Error(`The resolution is resume, open or rollback, not "${requested}"`)
|
|
383
|
+
const client = controlClient(args, env)
|
|
384
|
+
const result = await directWrite(client, args, () => client.data.recover({ appId, env: environment, operationId, resolution }))
|
|
385
|
+
if (result === null) return
|
|
355
386
|
emitOperation(args, parseOperation(result, { appId, env: environment }))
|
|
356
387
|
}
|
|
357
388
|
|
|
@@ -382,7 +413,9 @@ const runBackupSchedule = async (args: EnvArgs, env: Environment): Promise<void>
|
|
|
382
413
|
}
|
|
383
414
|
const daily = oneOf(requested, SCHEDULE_SWITCHES)
|
|
384
415
|
if (daily === undefined) throw new Error(`The schedule is on or off, not "${requested}"`)
|
|
385
|
-
const
|
|
416
|
+
const result = await directWrite(client, args, () => client.data.backups.setSchedule({ ...target, daily: daily === 'on' }))
|
|
417
|
+
if (result === null) return
|
|
418
|
+
const schedule = parseSchedule(result, target)
|
|
386
419
|
if (!schedule.daily) note('the backup before a migration still runs')
|
|
387
420
|
emit(args, schedule, () => scheduleLines(schedule))
|
|
388
421
|
}
|
|
@@ -393,7 +426,9 @@ const runRestore = async (args: EnvArgs, env: Environment): Promise<void> => {
|
|
|
393
426
|
// The contract's own rule for `at`, checked before anything is sent; whether it lies in the past is Control's to decide.
|
|
394
427
|
const input = startDataOperationInputSchema.safeParse({ appId, env: environment, kind: 'restore', at: args.at })
|
|
395
428
|
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
|
|
429
|
+
const client = controlClient(args, env)
|
|
430
|
+
const result = await directWrite(client, args, () => client.data.start(input.data))
|
|
431
|
+
if (result === null) return
|
|
397
432
|
emitOperation(args, parseOperation(result, { appId, env: environment }))
|
|
398
433
|
}
|
|
399
434
|
|
|
@@ -435,8 +470,10 @@ export const runEnvCli = async (command: string | undefined, argv: readonly stri
|
|
|
435
470
|
const args = parseEnvArgs(argv)
|
|
436
471
|
if (args.content && command !== 'inspect') throw new Error('--content applies to `env inspect` only')
|
|
437
472
|
if (args.at !== undefined && command !== 'restore') throw new Error('--at applies to `env restore` only')
|
|
473
|
+
if (args.wait && (command === 'inspect' || command === 'operations')) throw new Error('--wait applies to a write only')
|
|
438
474
|
await run(args, env)
|
|
439
475
|
} catch (error) {
|
|
476
|
+
if (error instanceof ApprovalPendingError) throw new ApprovalPendingError(printable(error.message))
|
|
440
477
|
throw new Error(printable(withoutControlKey(diagnostic(command, error), env)))
|
|
441
478
|
}
|
|
442
479
|
}
|
package/src/db.ts
CHANGED
|
@@ -1,42 +1,22 @@
|
|
|
1
1
|
import { applicationMigrations as sqliteApplicationMigrations } from '@fabrika/app/build'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
applicationDialect,
|
|
5
|
-
CONFIG_FILE,
|
|
6
|
-
type Finding,
|
|
7
|
-
formatFinding,
|
|
8
|
-
GENERATED_TEST_HEADER,
|
|
9
|
-
type GeneratedTest,
|
|
10
|
-
generatedTests,
|
|
11
|
-
missingEndpointFixtures,
|
|
12
|
-
readApplicationTree,
|
|
13
|
-
scaffoldInputs,
|
|
14
|
-
} from '@fabrika/check'
|
|
15
|
-
import { CodegenError, generateSchema, SCHEMA_FILE } from '@fabrika/db/codegen'
|
|
2
|
+
import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
|
|
3
|
+
import { CodegenError, type GeneratedModule, generateSchema, leftOutText, SCHEMA_FILE } from '@fabrika/db/codegen'
|
|
16
4
|
import { generateSqliteSchema } from '@fabrika/db/codegen-sqlite'
|
|
17
5
|
import { FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations'
|
|
18
6
|
import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
|
|
19
7
|
import {
|
|
20
8
|
APPLICATION_MIGRATION_BUNDLE,
|
|
21
|
-
CONNECTION_CAPACITY_MESSAGE,
|
|
22
9
|
ConnectionCapacityError,
|
|
23
|
-
createTestProvisioner,
|
|
24
10
|
DEFAULT_MIGRATION_LOCK_TIMEOUT_MS,
|
|
25
11
|
DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS,
|
|
26
12
|
definePostgresApplicationMigrations,
|
|
27
13
|
type PostgresApplicationMigrations,
|
|
28
14
|
PostgresMigrationError,
|
|
29
15
|
postgresMigrationResultMessage,
|
|
30
|
-
type TestProvisioner,
|
|
31
|
-
TOO_MANY_CONNECTIONS,
|
|
32
|
-
withConnectionCapacity,
|
|
33
16
|
} from '@fabrika/platform-node'
|
|
34
17
|
import { SQL } from 'bun'
|
|
35
|
-
import { mkdir,
|
|
36
|
-
import { tmpdir } from 'node:os'
|
|
18
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
37
19
|
import { dirname, join } from 'node:path'
|
|
38
|
-
import { fileURLToPath } from 'node:url'
|
|
39
|
-
import { readJunitCases } from './junit'
|
|
40
20
|
|
|
41
21
|
/** The checker's `migration-name` contract (`@fabrika/check`, `db/migrations/`). */
|
|
42
22
|
const MIGRATIONS_DIR = 'db/migrations'
|
|
@@ -47,29 +27,19 @@ export const DB_USAGE = `fabrika db — an application's database schema: Postgr
|
|
|
47
27
|
Usage:
|
|
48
28
|
fabrika db new <slug> Write ${MIGRATIONS_DIR}/<UTC YYYYMMDDHHMMSS>_<slug>.sql; the slug is lowercase snake_case.
|
|
49
29
|
fabrika db migrate Apply the framework's tables, then ${MIGRATIONS_DIR}, to the application's schema app_<id>.
|
|
50
|
-
fabrika db codegen [--verify]
|
|
51
|
-
fabrika db test-scaffold Write the generated tests: a policy isolation test per table a store reaches, the endpoint access test.
|
|
52
|
-
fabrika db test-isolation [--verbose] Run the generated tests on a throwaway schema; fail unless every case the scaffold wrote passed.
|
|
30
|
+
fabrika db codegen [--verify] [--config=<path>] Write ${SCHEMA_FILE} from the migrated schema; --verify only fails when it is stale.
|
|
53
31
|
|
|
54
|
-
Run from the application root. \`
|
|
32
|
+
Run from the application root. \`--config\` names the application's config, ${CONFIG_FILE} by default, as \`fabrika app
|
|
33
|
+
build\` takes it: its provider decides the dialect. \`migrate\` and \`codegen\` read FABRIKA_APP_ID and FABRIKA_APP_DATABASE_URL from
|
|
55
34
|
the environment only. FABRIKA_APP_DATABASE_URL is the provisioning credential: \`migrate\` uses it only to create
|
|
56
35
|
the application's roles (app_<id> owns the schema, run_<id> gets DML on its tables) and fails when it cannot create
|
|
57
36
|
roles. It applies the files as app_<id>, holds a lock derived from the application id, runs each file in one
|
|
58
37
|
transaction with lock_timeout ${DEFAULT_MIGRATION_LOCK_TIMEOUT_MS} ms and statement_timeout ${DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS} ms, and fails when a
|
|
59
38
|
file that already ran has changed: an applied migration is immutable, so a change is a new file.
|
|
60
|
-
\`test-scaffold\` reads fabrika.contract.ts and src/db/tables.ts as the checker does, rewrites every generated test and
|
|
61
|
-
deletes a generated one the scaffold no longer writes, printing each path, or that it wrote none; @fabrika/check refuses
|
|
62
|
-
one that is missing, edited or stale.
|
|
63
|
-
\`test-isolation\` is the platform's run of them: with FABRIKA_APP_DATABASE_URL it creates a throwaway provisioner
|
|
64
|
-
(CREATEROLE, CREATE on the database, nothing of any application) that the tests get instead, ignores the application's
|
|
65
|
-
bunfig.toml, and checks the JUnit report against the case names the scaffold wrote. It first drops the provisioners
|
|
66
|
-
that killed runs left behind: expired, and without a session of their own or of a role they created. A database at its
|
|
67
|
-
connection limit (SQLSTATE ${TOO_MANY_CONNECTIONS}) is waited for; one that never frees a slot fails the run saying so,
|
|
68
|
-
never as failed cases.
|
|
69
39
|
|
|
70
40
|
An application whose ${CONFIG_FILE} default-exports @fabrika/provider-cloudflare's defineApp runs on SQLite in its
|
|
71
41
|
Durable Object, which applies the migrations itself when it boots: \`migrate\` refuses, \`codegen\` applies them to an
|
|
72
|
-
in-memory database
|
|
42
|
+
in-memory database; neither needs a database URL.
|
|
73
43
|
`
|
|
74
44
|
|
|
75
45
|
export interface DbCommandDependencies {
|
|
@@ -90,12 +60,22 @@ const refuseArguments = (command: string, argv: readonly string[]): void => {
|
|
|
90
60
|
if (argv.length > 0) throw new Error(`db ${command} takes no argument ${argv[0]}\n\n${DB_USAGE}`)
|
|
91
61
|
}
|
|
92
62
|
|
|
93
|
-
/** The dialect
|
|
94
|
-
const dialectAt = async (cwd: string): Promise<ApplicationDialect> => {
|
|
95
|
-
const config = await readFile(join(cwd,
|
|
63
|
+
/** The dialect the config at `configPath` names, read as the checker reads `fabrika.config.ts`; Postgres without a config. */
|
|
64
|
+
const dialectAt = async (cwd: string, configPath: string = CONFIG_FILE): Promise<ApplicationDialect> => {
|
|
65
|
+
const config = await readFile(join(cwd, configPath), 'utf8').catch(() => undefined)
|
|
96
66
|
return applicationDialect(new Map(config === undefined ? [] : [[CONFIG_FILE, config]]))
|
|
97
67
|
}
|
|
98
68
|
|
|
69
|
+
const CONFIG_OPTION = '--config='
|
|
70
|
+
|
|
71
|
+
/** `--config=<path>`, relative to the application root, and the arguments besides it. */
|
|
72
|
+
const configOption = (argv: readonly string[]): { readonly config: string; readonly rest: readonly string[] } => {
|
|
73
|
+
const named = argv.filter((arg) => arg.startsWith(CONFIG_OPTION))
|
|
74
|
+
const config = named.at(-1)?.slice(CONFIG_OPTION.length)
|
|
75
|
+
if (named.length > 1 || config === '') throw new Error(`db: --config names one config file\n\n${DB_USAGE}`)
|
|
76
|
+
return { config: config ?? CONFIG_FILE, rest: argv.filter((arg) => !arg.startsWith(CONFIG_OPTION)) }
|
|
77
|
+
}
|
|
78
|
+
|
|
99
79
|
const timestamp = (date: Date): string => date.toISOString().replace(/\.\d{3}Z$/, '').replaceAll(/[-:T]/g, '')
|
|
100
80
|
|
|
101
81
|
const newMigration = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
@@ -160,11 +140,11 @@ const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Pr
|
|
|
160
140
|
}
|
|
161
141
|
|
|
162
142
|
/** The schema module of the migrated application schema, read with the provisioning credential. */
|
|
163
|
-
const postgresSchema = async (deps: DbCommandDependencies): Promise<
|
|
143
|
+
const postgresSchema = async (deps: DbCommandDependencies): Promise<GeneratedModule> => {
|
|
164
144
|
const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
|
|
165
145
|
const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
166
146
|
try {
|
|
167
|
-
// The migrations' manifest: the
|
|
147
|
+
// The migrations' manifest: the check refuses any database object no migration declares.
|
|
168
148
|
return await generateSchema(url, migrations.schema, migrations.objects())
|
|
169
149
|
} catch (error) {
|
|
170
150
|
throw reportable(error)
|
|
@@ -172,17 +152,20 @@ const postgresSchema = async (deps: DbCommandDependencies): Promise<string> => {
|
|
|
172
152
|
}
|
|
173
153
|
|
|
174
154
|
/** 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<
|
|
155
|
+
const sqliteSchema = async (cwd: string): Promise<GeneratedModule> =>
|
|
176
156
|
generateSqliteSchema([
|
|
177
157
|
{ bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
|
|
178
158
|
{ bundle: APPLICATION_MIGRATION_BUNDLE, migrations: await sqliteApplicationMigrations(cwd) },
|
|
179
159
|
])
|
|
180
160
|
|
|
181
161
|
const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
162
|
+
const { config, rest } = configOption(argv)
|
|
163
|
+
const verify = rest.includes('--verify')
|
|
164
|
+
refuseArguments('codegen', rest.filter((arg) => arg !== '--verify'))
|
|
165
|
+
const { source, leftOut } = (await dialectAt(deps.cwd, config)) === 'sqlite' ? await sqliteSchema(deps.cwd) : await postgresSchema(deps)
|
|
185
166
|
const path = join(deps.cwd, SCHEMA_FILE)
|
|
167
|
+
// Named on every run, --verify's too, so a column the module leaves out is never silent.
|
|
168
|
+
for (const column of leftOut) deps.write(`${leftOutText(`${column.table}.${column.column}`, column.type, column.of)}\n`)
|
|
186
169
|
if (verify) {
|
|
187
170
|
const committed = await readFile(path, 'utf8').catch(() => undefined)
|
|
188
171
|
if (committed !== source) throw new Error(`${SCHEMA_FILE} is stale; run fabrika db codegen and commit the result`)
|
|
@@ -194,176 +177,16 @@ const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Pr
|
|
|
194
177
|
deps.write(`${SCHEMA_FILE}\n`)
|
|
195
178
|
}
|
|
196
179
|
|
|
197
|
-
const expectedTests = async (
|
|
198
|
-
cwd: string,
|
|
199
|
-
): Promise<
|
|
200
|
-
{ readonly files: ReadonlyMap<string, string>; readonly tests: ReadonlyMap<string, GeneratedTest>; readonly missing: readonly Finding[] }
|
|
201
|
-
> => {
|
|
202
|
-
const { files } = await readApplicationTree(cwd)
|
|
203
|
-
const inputs = scaffoldInputs(files)
|
|
204
|
-
return {
|
|
205
|
-
files,
|
|
206
|
-
tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures, inputs.dialect),
|
|
207
|
-
missing: missingEndpointFixtures(inputs),
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
212
|
-
refuseArguments('test-scaffold', argv)
|
|
213
|
-
const { files, tests, missing } = await expectedTests(deps.cwd)
|
|
214
|
-
for (const [path, text] of files) {
|
|
215
|
-
if (text.startsWith(GENERATED_TEST_HEADER) && !tests.has(path)) {
|
|
216
|
-
await rm(join(deps.cwd, path))
|
|
217
|
-
deps.write(`removed ${path}\n`)
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
for (const [path, { text }] of tests) {
|
|
221
|
-
await mkdir(dirname(join(deps.cwd, path)), { recursive: true })
|
|
222
|
-
await writeFile(join(deps.cwd, path), text)
|
|
223
|
-
deps.write(`${path}\n`)
|
|
224
|
-
}
|
|
225
|
-
if (missing.length > 0) {
|
|
226
|
-
throw new Error(`db test-scaffold: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
|
|
227
|
-
}
|
|
228
|
-
if (tests.size === 0) {
|
|
229
|
-
deps.write('no generated tests: they start with the first table a store reaches, and the application has none; write the first test yourself\n')
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/**
|
|
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.
|
|
237
|
-
*/
|
|
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' }
|
|
240
|
-
for (const name of ['PATH', 'HOME', 'TMPDIR']) {
|
|
241
|
-
const value = source[name]
|
|
242
|
-
if (value !== undefined) environment[name] = value
|
|
243
|
-
}
|
|
244
|
-
return environment
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* The server's own words for a refused connection (SQLSTATE 53300) and the test kit's report of one it gave up on. A
|
|
249
|
-
* run whose tests met one says so instead of counting cases: a case that could not connect proved nothing.
|
|
250
|
-
*/
|
|
251
|
-
const EXHAUSTED_CONNECTIONS = [
|
|
252
|
-
CONNECTION_CAPACITY_MESSAGE,
|
|
253
|
-
'remaining connection slots are reserved',
|
|
254
|
-
'too many clients already',
|
|
255
|
-
'too many connections for role',
|
|
256
|
-
'too many connections for database',
|
|
257
|
-
]
|
|
258
|
-
|
|
259
|
-
/** Whether the tests' output reports a connection the database refused for lack of a free slot. */
|
|
260
|
-
export const reportsExhaustedConnections = (output: string): boolean => EXHAUSTED_CONNECTIONS.some((text) => output.includes(text))
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* Runs exactly the generated tests, with an empty `bunfig.toml` so that no preload, root or ignore pattern of the
|
|
264
|
-
* application applies, and the platform's preload, which captures Bun's test functions before the application loads.
|
|
265
|
-
* Fails unless every case the scaffold wrote is reported as passed with an assertion. The child's output is never
|
|
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.
|
|
268
|
-
*/
|
|
269
|
-
const testIsolation = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
270
|
-
const verbose = argv.includes('--verbose')
|
|
271
|
-
refuseArguments('test-isolation', argv.filter((arg) => arg !== '--verbose'))
|
|
272
|
-
const sqlite = (await dialectAt(deps.cwd)) === 'sqlite'
|
|
273
|
-
const url = sqlite ? undefined : required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
274
|
-
const { files, tests, missing } = await expectedTests(deps.cwd)
|
|
275
|
-
if (missing.length > 0) throw new Error(`db test-isolation: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
|
|
276
|
-
for (const [path, { text }] of tests) {
|
|
277
|
-
if (files.get(path) !== text) throw new Error(`db test-isolation: ${path} is not the test fabrika db test-scaffold writes; run it`)
|
|
278
|
-
}
|
|
279
|
-
if (tests.size === 0) {
|
|
280
|
-
deps.write('no generated tests\n')
|
|
281
|
-
return
|
|
282
|
-
}
|
|
283
|
-
if (url === undefined) {
|
|
284
|
-
await runGeneratedTests(tests, verbose, testEnvironment(deps.source, undefined), deps)
|
|
285
|
-
return
|
|
286
|
-
}
|
|
287
|
-
let provisioner: TestProvisioner
|
|
288
|
-
try {
|
|
289
|
-
provisioner = await withConnectionCapacity(() => createTestProvisioner(url))
|
|
290
|
-
} catch (error) {
|
|
291
|
-
throw reportable(error)
|
|
292
|
-
}
|
|
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> => {
|
|
309
|
-
const scratch = await mkdtemp(join(tmpdir(), 'fabrika-test-isolation-'))
|
|
310
|
-
try {
|
|
311
|
-
await writeFile(join(scratch, 'bunfig.toml'), '')
|
|
312
|
-
const report = join(scratch, 'junit.xml')
|
|
313
|
-
const child = Bun.spawn(
|
|
314
|
-
[
|
|
315
|
-
process.execPath,
|
|
316
|
-
`--config=${join(scratch, 'bunfig.toml')}`,
|
|
317
|
-
'test',
|
|
318
|
-
`--preload=${fileURLToPath(import.meta.resolve('@fabrika/app/testing/preload'))}`,
|
|
319
|
-
...[...tests.keys()].map((path) => `./${path}`),
|
|
320
|
-
'--reporter=junit',
|
|
321
|
-
`--reporter-outfile=${report}`,
|
|
322
|
-
],
|
|
323
|
-
{ cwd: deps.cwd, env, stdout: 'pipe', stderr: 'pipe' },
|
|
324
|
-
)
|
|
325
|
-
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
|
|
326
|
-
if (verbose) deps.write(`${stdout}${stderr}\n`)
|
|
327
|
-
const reported = readJunitCases(await readFile(report, 'utf8').catch(() => ''))
|
|
328
|
-
const failed: string[] = []
|
|
329
|
-
let total = 0
|
|
330
|
-
for (const [path, { cases }] of tests) {
|
|
331
|
-
for (const name of cases) {
|
|
332
|
-
total++
|
|
333
|
-
const reportedCase = reported.find((item) => item.file === path && item.name === name)
|
|
334
|
-
const outcome = reportedCase === undefined
|
|
335
|
-
? 'not run'
|
|
336
|
-
: reportedCase.outcome === 'passed' && reportedCase.assertions === 0
|
|
337
|
-
? 'no assertion'
|
|
338
|
-
: reportedCase.outcome
|
|
339
|
-
if (outcome !== 'passed') failed.push(`${path}: ${name} (${outcome})`)
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
if ((code !== 0 || failed.length > 0) && reportsExhaustedConnections(`${stdout}${stderr}`)) {
|
|
343
|
-
throw new Error(
|
|
344
|
-
`db test-isolation: ${CONNECTION_CAPACITY_MESSAGE} for the generated tests (SQLSTATE ${TOO_MANY_CONNECTIONS}), so they reached no verdict; other processes hold the database's connections: free them or give the database more, then run it again`,
|
|
345
|
-
)
|
|
346
|
-
}
|
|
347
|
-
if (code !== 0 || failed.length > 0) {
|
|
348
|
-
const rerun = verbose ? '' : '; rerun with --verbose locally to see the test output'
|
|
349
|
-
throw new Error(
|
|
350
|
-
`db test-isolation: ${total - failed.length} of ${total} generated cases passed (exit ${code})${rerun}${
|
|
351
|
-
failed.map((line) => `\n- ${line}`).join('')
|
|
352
|
-
}`,
|
|
353
|
-
)
|
|
354
|
-
}
|
|
355
|
-
deps.write(`${total} generated cases passed\n`)
|
|
356
|
-
} finally {
|
|
357
|
-
await rm(scratch, { recursive: true, force: true })
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
|
|
361
180
|
export const runDbCommand = async (command: string | undefined, argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
362
181
|
if (command === 'new') return newMigration(argv, deps)
|
|
363
182
|
if (command === 'migrate') return migrate(argv, deps)
|
|
364
183
|
if (command === 'codegen') return codegen(argv, deps)
|
|
365
|
-
|
|
366
|
-
|
|
184
|
+
// A platform release up to 0.9.0-dev.18 still runs this init command against the application's own CLI, and its
|
|
185
|
+
// reader admits a newer prerelease of the same version (ADR-0062): the command stays, and runs nothing.
|
|
186
|
+
if (command === 'test-isolation') {
|
|
187
|
+
deps.write('db test-isolation: nothing to run; this release generates no tests\n')
|
|
188
|
+
return
|
|
189
|
+
}
|
|
367
190
|
throw new Error(`Unknown db command: ${command ?? '(missing)'}\n\n${DB_USAGE}`)
|
|
368
191
|
}
|
|
369
192
|
|