@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/db.ts
CHANGED
|
@@ -1,64 +1,45 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
type GeneratedTest,
|
|
6
|
-
generatedTests,
|
|
7
|
-
missingEndpointFixtures,
|
|
8
|
-
readApplicationTree,
|
|
9
|
-
scaffoldInputs,
|
|
10
|
-
} from '@fabrika/check'
|
|
11
|
-
import { CodegenError, generateSchema, SCHEMA_FILE } from '@fabrika/db/codegen'
|
|
1
|
+
import { applicationMigrations as sqliteApplicationMigrations } from '@fabrika/app/build'
|
|
2
|
+
import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
|
|
3
|
+
import { CodegenError, type GeneratedModule, generateSchema, leftOutText, SCHEMA_FILE } from '@fabrika/db/codegen'
|
|
4
|
+
import { generateSqliteSchema } from '@fabrika/db/codegen-sqlite'
|
|
12
5
|
import { FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations'
|
|
6
|
+
import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
|
|
13
7
|
import {
|
|
14
|
-
|
|
8
|
+
APPLICATION_MIGRATION_BUNDLE,
|
|
15
9
|
ConnectionCapacityError,
|
|
16
|
-
createTestProvisioner,
|
|
17
10
|
DEFAULT_MIGRATION_LOCK_TIMEOUT_MS,
|
|
18
11
|
DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS,
|
|
19
12
|
definePostgresApplicationMigrations,
|
|
20
13
|
type PostgresApplicationMigrations,
|
|
21
14
|
PostgresMigrationError,
|
|
22
15
|
postgresMigrationResultMessage,
|
|
23
|
-
type TestProvisioner,
|
|
24
|
-
TOO_MANY_CONNECTIONS,
|
|
25
|
-
withConnectionCapacity,
|
|
26
16
|
} from '@fabrika/platform-node'
|
|
27
17
|
import { SQL } from 'bun'
|
|
28
|
-
import { mkdir,
|
|
29
|
-
import { tmpdir } from 'node:os'
|
|
18
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
30
19
|
import { dirname, join } from 'node:path'
|
|
31
|
-
import { fileURLToPath } from 'node:url'
|
|
32
|
-
import { readJunitCases } from './junit'
|
|
33
20
|
|
|
34
21
|
/** The checker's `migration-name` contract (`@fabrika/check`, `db/migrations/`). */
|
|
35
22
|
const MIGRATIONS_DIR = 'db/migrations'
|
|
36
23
|
const SLUG = /^[a-z0-9]+(?:_[a-z0-9]+)*$/
|
|
37
24
|
|
|
38
|
-
export const DB_USAGE = `fabrika db — an application's Postgres
|
|
25
|
+
export const DB_USAGE = `fabrika db — an application's database schema: Postgres, or SQLite on Cloudflare
|
|
39
26
|
|
|
40
27
|
Usage:
|
|
41
28
|
fabrika db new <slug> Write ${MIGRATIONS_DIR}/<UTC YYYYMMDDHHMMSS>_<slug>.sql; the slug is lowercase snake_case.
|
|
42
29
|
fabrika db migrate Apply the framework's tables, then ${MIGRATIONS_DIR}, to the application's schema app_<id>.
|
|
43
|
-
fabrika db codegen [--verify]
|
|
44
|
-
fabrika db test-scaffold Write the generated tests: a policy isolation test per table a store reaches, the endpoint access test.
|
|
45
|
-
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.
|
|
46
31
|
|
|
47
|
-
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
|
|
48
34
|
the environment only. FABRIKA_APP_DATABASE_URL is the provisioning credential: \`migrate\` uses it only to create
|
|
49
35
|
the application's roles (app_<id> owns the schema, run_<id> gets DML on its tables) and fails when it cannot create
|
|
50
36
|
roles. It applies the files as app_<id>, holds a lock derived from the application id, runs each file in one
|
|
51
37
|
transaction with lock_timeout ${DEFAULT_MIGRATION_LOCK_TIMEOUT_MS} ms and statement_timeout ${DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS} ms, and fails when a
|
|
52
38
|
file that already ran has changed: an applied migration is immutable, so a change is a new file.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
(CREATEROLE, CREATE on the database, nothing of any application) that the tests get instead, ignores the application's
|
|
58
|
-
bunfig.toml, and checks the JUnit report against the case names the scaffold wrote. It first drops the provisioners
|
|
59
|
-
that killed runs left behind: expired, and without a session of their own or of a role they created. A database at its
|
|
60
|
-
connection limit (SQLSTATE ${TOO_MANY_CONNECTIONS}) is waited for; one that never frees a slot fails the run saying so,
|
|
61
|
-
never as failed cases.
|
|
39
|
+
|
|
40
|
+
An application whose ${CONFIG_FILE} default-exports @fabrika/provider-cloudflare's defineApp runs on SQLite in its
|
|
41
|
+
Durable Object, which applies the migrations itself when it boots: \`migrate\` refuses, \`codegen\` applies them to an
|
|
42
|
+
in-memory database; neither needs a database URL.
|
|
62
43
|
`
|
|
63
44
|
|
|
64
45
|
export interface DbCommandDependencies {
|
|
@@ -79,6 +60,22 @@ const refuseArguments = (command: string, argv: readonly string[]): void => {
|
|
|
79
60
|
if (argv.length > 0) throw new Error(`db ${command} takes no argument ${argv[0]}\n\n${DB_USAGE}`)
|
|
80
61
|
}
|
|
81
62
|
|
|
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)
|
|
66
|
+
return applicationDialect(new Map(config === undefined ? [] : [[CONFIG_FILE, config]]))
|
|
67
|
+
}
|
|
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
|
+
|
|
82
79
|
const timestamp = (date: Date): string => date.toISOString().replace(/\.\d{3}Z$/, '').replaceAll(/[-:T]/g, '')
|
|
83
80
|
|
|
84
81
|
const newMigration = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
@@ -126,6 +123,11 @@ const applicationMigrations = (appId: string, cwd: string): PostgresApplicationM
|
|
|
126
123
|
|
|
127
124
|
const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
128
125
|
refuseArguments('migrate', argv)
|
|
126
|
+
if ((await dialectAt(deps.cwd)) === 'sqlite') {
|
|
127
|
+
throw new Error(
|
|
128
|
+
'db migrate: an application on Cloudflare migrates its own SQLite database when its Durable Object boots (ADR-0065); there is nothing to run',
|
|
129
|
+
)
|
|
130
|
+
}
|
|
129
131
|
const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
|
|
130
132
|
const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
131
133
|
const files = migrations.read()
|
|
@@ -137,19 +139,33 @@ const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Pr
|
|
|
137
139
|
}
|
|
138
140
|
}
|
|
139
141
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
|
|
142
|
+
/** The schema module of the migrated application schema, read with the provisioning credential. */
|
|
143
|
+
const postgresSchema = async (deps: DbCommandDependencies): Promise<GeneratedModule> => {
|
|
143
144
|
const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
|
|
144
145
|
const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
145
|
-
let source: string
|
|
146
146
|
try {
|
|
147
|
-
// The migrations' manifest: the
|
|
148
|
-
|
|
147
|
+
// The migrations' manifest: the check refuses any database object no migration declares.
|
|
148
|
+
return await generateSchema(url, migrations.schema, migrations.objects())
|
|
149
149
|
} catch (error) {
|
|
150
150
|
throw reportable(error)
|
|
151
151
|
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The schema module of the bundles the Durable Object applies, in its order, run in an in-memory database. */
|
|
155
|
+
const sqliteSchema = async (cwd: string): Promise<GeneratedModule> =>
|
|
156
|
+
generateSqliteSchema([
|
|
157
|
+
{ bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
|
|
158
|
+
{ bundle: APPLICATION_MIGRATION_BUNDLE, migrations: await sqliteApplicationMigrations(cwd) },
|
|
159
|
+
])
|
|
160
|
+
|
|
161
|
+
const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
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)
|
|
152
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`)
|
|
153
169
|
if (verify) {
|
|
154
170
|
const committed = await readFile(path, 'utf8').catch(() => undefined)
|
|
155
171
|
if (committed !== source) throw new Error(`${SCHEMA_FILE} is stale; run fabrika db codegen and commit the result`)
|
|
@@ -161,153 +177,16 @@ const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Pr
|
|
|
161
177
|
deps.write(`${SCHEMA_FILE}\n`)
|
|
162
178
|
}
|
|
163
179
|
|
|
164
|
-
const expectedTests = async (
|
|
165
|
-
cwd: string,
|
|
166
|
-
): Promise<
|
|
167
|
-
{ readonly files: ReadonlyMap<string, string>; readonly tests: ReadonlyMap<string, GeneratedTest>; readonly missing: readonly Finding[] }
|
|
168
|
-
> => {
|
|
169
|
-
const { files } = await readApplicationTree(cwd)
|
|
170
|
-
const inputs = scaffoldInputs(files)
|
|
171
|
-
return { files, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
175
|
-
refuseArguments('test-scaffold', argv)
|
|
176
|
-
const { files, tests, missing } = await expectedTests(deps.cwd)
|
|
177
|
-
for (const [path, text] of files) {
|
|
178
|
-
if (text.startsWith(GENERATED_TEST_HEADER) && !tests.has(path)) {
|
|
179
|
-
await rm(join(deps.cwd, path))
|
|
180
|
-
deps.write(`removed ${path}\n`)
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
for (const [path, { text }] of tests) {
|
|
184
|
-
await mkdir(dirname(join(deps.cwd, path)), { recursive: true })
|
|
185
|
-
await writeFile(join(deps.cwd, path), text)
|
|
186
|
-
deps.write(`${path}\n`)
|
|
187
|
-
}
|
|
188
|
-
if (missing.length > 0) {
|
|
189
|
-
throw new Error(`db test-scaffold: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
|
|
190
|
-
}
|
|
191
|
-
if (tests.size === 0) {
|
|
192
|
-
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')
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/**
|
|
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.
|
|
199
|
-
*/
|
|
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' }
|
|
202
|
-
for (const name of ['PATH', 'HOME', 'TMPDIR']) {
|
|
203
|
-
const value = source[name]
|
|
204
|
-
if (value !== undefined) environment[name] = value
|
|
205
|
-
}
|
|
206
|
-
return environment
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/**
|
|
210
|
-
* The server's own words for a refused connection (SQLSTATE 53300) and the test kit's report of one it gave up on. A
|
|
211
|
-
* run whose tests met one says so instead of counting cases: a case that could not connect proved nothing.
|
|
212
|
-
*/
|
|
213
|
-
const EXHAUSTED_CONNECTIONS = [
|
|
214
|
-
CONNECTION_CAPACITY_MESSAGE,
|
|
215
|
-
'remaining connection slots are reserved',
|
|
216
|
-
'too many clients already',
|
|
217
|
-
'too many connections for role',
|
|
218
|
-
'too many connections for database',
|
|
219
|
-
]
|
|
220
|
-
|
|
221
|
-
/** Whether the tests' output reports a connection the database refused for lack of a free slot. */
|
|
222
|
-
export const reportsExhaustedConnections = (output: string): boolean => EXHAUSTED_CONNECTIONS.some((text) => output.includes(text))
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* Runs exactly the generated tests, with an empty `bunfig.toml` so that no preload, root or ignore pattern of the
|
|
226
|
-
* application applies, and the platform's preload, which captures Bun's test functions before the application loads.
|
|
227
|
-
* Fails unless every case the scaffold wrote is reported as passed with an assertion. The child's output is never
|
|
228
|
-
* printed, because a dependency may write a credential into it; `--verbose`, which the platform never passes, prints it.
|
|
229
|
-
*/
|
|
230
|
-
const testIsolation = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
231
|
-
const verbose = argv.includes('--verbose')
|
|
232
|
-
refuseArguments('test-isolation', argv.filter((arg) => arg !== '--verbose'))
|
|
233
|
-
const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
234
|
-
const { files, tests, missing } = await expectedTests(deps.cwd)
|
|
235
|
-
if (missing.length > 0) throw new Error(`db test-isolation: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
|
|
236
|
-
for (const [path, { text }] of tests) {
|
|
237
|
-
if (files.get(path) !== text) throw new Error(`db test-isolation: ${path} is not the test fabrika db test-scaffold writes; run it`)
|
|
238
|
-
}
|
|
239
|
-
if (tests.size === 0) {
|
|
240
|
-
deps.write('no generated tests\n')
|
|
241
|
-
return
|
|
242
|
-
}
|
|
243
|
-
let provisioner: TestProvisioner
|
|
244
|
-
try {
|
|
245
|
-
provisioner = await withConnectionCapacity(() => createTestProvisioner(url))
|
|
246
|
-
} catch (error) {
|
|
247
|
-
throw reportable(error)
|
|
248
|
-
}
|
|
249
|
-
if (provisioner.swept.length > 0) deps.write(`dropped the test provisioners earlier runs left behind: ${provisioner.swept.join(', ')}\n`)
|
|
250
|
-
const scratch = await mkdtemp(join(tmpdir(), 'fabrika-test-isolation-'))
|
|
251
|
-
try {
|
|
252
|
-
await writeFile(join(scratch, 'bunfig.toml'), '')
|
|
253
|
-
const report = join(scratch, 'junit.xml')
|
|
254
|
-
const child = Bun.spawn(
|
|
255
|
-
[
|
|
256
|
-
process.execPath,
|
|
257
|
-
`--config=${join(scratch, 'bunfig.toml')}`,
|
|
258
|
-
'test',
|
|
259
|
-
`--preload=${fileURLToPath(import.meta.resolve('@fabrika/app/testing/preload'))}`,
|
|
260
|
-
...[...tests.keys()].map((path) => `./${path}`),
|
|
261
|
-
'--reporter=junit',
|
|
262
|
-
`--reporter-outfile=${report}`,
|
|
263
|
-
],
|
|
264
|
-
{ cwd: deps.cwd, env: testEnvironment(deps.source, provisioner.url), stdout: 'pipe', stderr: 'pipe' },
|
|
265
|
-
)
|
|
266
|
-
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
|
|
267
|
-
if (verbose) deps.write(`${stdout}${stderr}\n`)
|
|
268
|
-
const reported = readJunitCases(await readFile(report, 'utf8').catch(() => ''))
|
|
269
|
-
const failed: string[] = []
|
|
270
|
-
let total = 0
|
|
271
|
-
for (const [path, { cases }] of tests) {
|
|
272
|
-
for (const name of cases) {
|
|
273
|
-
total++
|
|
274
|
-
const reportedCase = reported.find((item) => item.file === path && item.name === name)
|
|
275
|
-
const outcome = reportedCase === undefined
|
|
276
|
-
? 'not run'
|
|
277
|
-
: reportedCase.outcome === 'passed' && reportedCase.assertions === 0
|
|
278
|
-
? 'no assertion'
|
|
279
|
-
: reportedCase.outcome
|
|
280
|
-
if (outcome !== 'passed') failed.push(`${path}: ${name} (${outcome})`)
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
if ((code !== 0 || failed.length > 0) && reportsExhaustedConnections(`${stdout}${stderr}`)) {
|
|
284
|
-
throw new Error(
|
|
285
|
-
`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`,
|
|
286
|
-
)
|
|
287
|
-
}
|
|
288
|
-
if (code !== 0 || failed.length > 0) {
|
|
289
|
-
const rerun = verbose ? '' : '; rerun with --verbose locally to see the test output'
|
|
290
|
-
throw new Error(
|
|
291
|
-
`db test-isolation: ${total - failed.length} of ${total} generated cases passed (exit ${code})${rerun}${
|
|
292
|
-
failed.map((line) => `\n- ${line}`).join('')
|
|
293
|
-
}`,
|
|
294
|
-
)
|
|
295
|
-
}
|
|
296
|
-
deps.write(`${total} generated cases passed\n`)
|
|
297
|
-
} finally {
|
|
298
|
-
await rm(scratch, { recursive: true, force: true })
|
|
299
|
-
await withConnectionCapacity(() => provisioner.drop()).catch((error: unknown) => {
|
|
300
|
-
throw reportable(error)
|
|
301
|
-
})
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
180
|
export const runDbCommand = async (command: string | undefined, argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
306
181
|
if (command === 'new') return newMigration(argv, deps)
|
|
307
182
|
if (command === 'migrate') return migrate(argv, deps)
|
|
308
183
|
if (command === 'codegen') return codegen(argv, deps)
|
|
309
|
-
|
|
310
|
-
|
|
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
|
+
}
|
|
311
190
|
throw new Error(`Unknown db command: ${command ?? '(missing)'}\n\n${DB_USAGE}`)
|
|
312
191
|
}
|
|
313
192
|
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { CONTRACT_FILE, type EntryRuntime, writeGeneratedEntry } from '@fabrika/app/build'
|
|
4
4
|
import { authoredAppProvider } from '@fabrika/provider-contract'
|
|
5
|
+
import { type AppCli, appCliFromModule, type NamespaceCli } from '@fabrika/provider-contract/app-cli'
|
|
5
6
|
import { installationCliFromModule, isInstallationCommand, supportsInstallationCommand } from '@fabrika/provider-contract/installation'
|
|
6
7
|
import { dirname, join, relative, resolve } from 'node:path'
|
|
7
8
|
import { CONTROL_USAGE, registerCompiledManifest, runControlCli } from './control.js'
|
|
@@ -25,8 +26,10 @@ Usage:
|
|
|
25
26
|
[--namespace=<id>] [--installation-id=<n|none>] [--url=<origin>] [--json]
|
|
26
27
|
fabrika namespace <plan|create|adopt|reconcile> --provider=zerops [provider options]
|
|
27
28
|
fabrika control <key|apps|namespaces|register|deploy|runs> [options]
|
|
29
|
+
fabrika env <inspect|maintenance|operations|recover|backups|restore> <app> <env> [arguments] [--json]
|
|
30
|
+
fabrika operations <issues|issue|releases|health> [options] [--json]
|
|
28
31
|
fabrika builder <init|next|advance|gate|ensure-daemon|induce|build> [options]
|
|
29
|
-
fabrika db <new|migrate|codegen
|
|
32
|
+
fabrika db <new|migrate|codegen> [options]
|
|
30
33
|
fabrika job run <name>
|
|
31
34
|
fabrika connect <add|pull> <app>/<export>@<version> --consumer=<app> --env=<env> [--url=<control origin>]
|
|
32
35
|
|
|
@@ -49,7 +52,7 @@ A bare \`--trigger-ref\` is a branch (\`deploy/prod\` deploys on a push to \`ref
|
|
|
49
52
|
\`refs/tags/<tag>\` or a glob such as \`refs/tags/v*\`. \`fabrika control --help\` lists every form.
|
|
50
53
|
|
|
51
54
|
\`fabrika db\` manages an application's Postgres schema: migration files, applying them (the template's
|
|
52
|
-
\`run.initCommands\`)
|
|
55
|
+
\`run.initCommands\`) and the generated types. Run \`fabrika db --help\` for its surface.
|
|
53
56
|
|
|
54
57
|
\`fabrika job run <name>\` runs one c.cron job of a contract application: the command each crontab entry runs. Run
|
|
55
58
|
\`fabrika job --help\` for its surface.
|
|
@@ -61,6 +64,12 @@ environment approved, as Control answers it to FABRIKA_CONTROL_KEY. Run \`fabrik
|
|
|
61
64
|
provider-neutral, loads no installation package, and speaks the same typed API the console does. Run
|
|
62
65
|
\`fabrika control --help\` for its surface.
|
|
63
66
|
|
|
67
|
+
\`fabrika env\` shows an application environment's data and backups through the control plane, puts it into
|
|
68
|
+
maintenance, restores its data as of a past time, or recovers a stuck operation. Run \`fabrika env --help\` for its surface.
|
|
69
|
+
|
|
70
|
+
\`fabrika operations\` reads Operations — issues and their events, releases, health — through the console's API, with
|
|
71
|
+
FABRIKA_CONTROL_KEY. It is read-only. Run \`fabrika operations --help\` for its surface.
|
|
72
|
+
|
|
64
73
|
Which platform commands exist, and how WIDE each one is, is the provider's own answer — Zerops'
|
|
65
74
|
\`platform deploy\` owns the whole ordered sequence while Cloudflare's is one step of a scaffolded
|
|
66
75
|
workflow (ADR-0027), and only Zerops offers \`platform install\`, the from-scratch bring-up,
|
|
@@ -152,41 +161,33 @@ const requireInstalled = (specifier: string, command: string): void => {
|
|
|
152
161
|
}
|
|
153
162
|
}
|
|
154
163
|
|
|
164
|
+
/** A provider id names its package, `@fabrika/provider-<id>`; anything else is a module specifier of its own. */
|
|
165
|
+
const PROVIDER_ID = /^[a-z][a-z0-9-]*$/
|
|
166
|
+
|
|
167
|
+
const installationSpecifier = (provider: string): string => PROVIDER_ID.test(provider) ? `@fabrika/provider-${provider}/installation` : provider
|
|
168
|
+
|
|
155
169
|
const installationModule = async (provider: string, command: string): Promise<unknown> => {
|
|
156
|
-
const specifier = provider
|
|
157
|
-
? '@fabrika/provider-cloudflare/installation'
|
|
158
|
-
: provider === 'zerops'
|
|
159
|
-
? '@fabrika/provider-zerops/installation'
|
|
160
|
-
: provider
|
|
170
|
+
const specifier = installationSpecifier(provider)
|
|
161
171
|
requireInstalled(specifier, command)
|
|
162
172
|
return import(specifier)
|
|
163
173
|
}
|
|
164
174
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
const runner = Reflect.get(loaded, exportName)
|
|
172
|
-
if (typeof runner !== 'function') {
|
|
173
|
-
throw new Error(`${packageName} must export \`${exportName}\` as a function`)
|
|
174
|
-
}
|
|
175
|
-
return runner
|
|
175
|
+
/** App and namespace commands take a provider id only: the module's `appCli` must name the same one. */
|
|
176
|
+
const providerAppCli = async (provider: string, command: string): Promise<AppCli> => {
|
|
177
|
+
if (!PROVIDER_ID.test(provider)) throw new Error(`\`${command}\` takes a provider id ([a-z][a-z0-9-]*), not "${provider}"`)
|
|
178
|
+
const specifier = `@fabrika/provider-${provider}/cli`
|
|
179
|
+
requireInstalled(specifier, command)
|
|
180
|
+
return appCliFromModule(await import(specifier), provider, specifier)
|
|
176
181
|
}
|
|
177
182
|
|
|
178
|
-
const
|
|
179
|
-
requireInstalled(packageName, command)
|
|
180
|
-
const loaded: unknown = await import(packageName)
|
|
181
|
-
return appCliRunnerFromModule(loaded, packageName, exportName)
|
|
182
|
-
}
|
|
183
|
+
const unsupported = (provider: string, command: string): Error => new Error(`${provider} app tooling does not support \`${command}\``)
|
|
183
184
|
|
|
184
185
|
const runPlatform = async (parsed: ParsedCommand): Promise<void> => {
|
|
185
186
|
if (!isInstallationCommand(parsed.command)) {
|
|
186
187
|
throw new Error(`Unknown platform command: ${parsed.command ?? '(missing)'}`)
|
|
187
188
|
}
|
|
188
189
|
const provider = requireExplicitProvider(parsed)
|
|
189
|
-
const expectedProvider = provider
|
|
190
|
+
const expectedProvider = PROVIDER_ID.test(provider) ? provider : undefined
|
|
190
191
|
const installation = installationCliFromModule(
|
|
191
192
|
await installationModule(provider, `fabrika platform ${parsed.command} --provider=${provider}`),
|
|
192
193
|
expectedProvider,
|
|
@@ -202,17 +203,12 @@ const runAppRegister = async (parsed: ParsedCommand): Promise<void> => {
|
|
|
202
203
|
const config = configPath(parsed.rest)
|
|
203
204
|
await registerCompiledManifest(parsed.rest, async (env) => {
|
|
204
205
|
const provider = await selectedAppProvider(parsed)
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
requireInstalled('@fabrika/provider-zerops/cli', 'fabrika app register')
|
|
209
|
-
const { buildZeropsManifestText } = await import('@fabrika/provider-zerops/cli')
|
|
210
|
-
return { provider, text: await buildZeropsManifestText({ config, env }) }
|
|
206
|
+
const cli = await providerAppCli(provider, 'fabrika app register')
|
|
207
|
+
if (cli.registrationManifest === undefined) throw unsupported(provider, 'app register')
|
|
208
|
+
return { provider, text: await cli.registrationManifest({ config, env }) }
|
|
211
209
|
})
|
|
212
210
|
}
|
|
213
211
|
|
|
214
|
-
const ENTRY_RUNTIMES: Readonly<Record<string, EntryRuntime>> = { cloudflare: 'cloudflare', zerops: 'bun' }
|
|
215
|
-
|
|
216
212
|
/** A contract application gets its generated entrypoint before the provider builds it. False when it is none. */
|
|
217
213
|
const writeContractEntry = async (argv: readonly string[], runtime: EntryRuntime): Promise<boolean> => {
|
|
218
214
|
const root = dirname(resolve(process.cwd(), configPath(argv)))
|
|
@@ -235,41 +231,37 @@ const runApp = async (parsed: ParsedCommand): Promise<void> => {
|
|
|
235
231
|
return
|
|
236
232
|
}
|
|
237
233
|
const provider = await selectedAppProvider(parsed)
|
|
238
|
-
const
|
|
239
|
-
const
|
|
240
|
-
if (
|
|
241
|
-
|
|
242
|
-
return
|
|
243
|
-
}
|
|
244
|
-
if (parsed.command !== 'deploy') {
|
|
245
|
-
throw new Error(`Cloudflare app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
|
|
246
|
-
}
|
|
247
|
-
const runCloudflareCli = await appCliRunner('@fabrika/provider-cloudflare/cli', 'runCloudflareCli', 'fabrika app deploy')
|
|
248
|
-
await runCloudflareCli(['deploy', ...parsed.rest])
|
|
234
|
+
const command = `app ${parsed.command ?? '(missing)'}`
|
|
235
|
+
const cli = await providerAppCli(provider, `fabrika ${command}`)
|
|
236
|
+
if (parsed.command === 'build' && cli.build !== undefined) {
|
|
237
|
+
await cli.build(parsed.rest, { contract: await writeContractEntry(parsed.rest, cli.entryRuntime) })
|
|
249
238
|
return
|
|
250
239
|
}
|
|
251
|
-
if (
|
|
252
|
-
|
|
253
|
-
throw new Error(`Zerops app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
|
|
254
|
-
}
|
|
255
|
-
const runZeropsCli = await appCliRunner('@fabrika/provider-zerops/cli', 'runZeropsCli', 'fabrika app build')
|
|
256
|
-
await runZeropsCli(['build', ...parsed.rest])
|
|
240
|
+
if (parsed.command === 'deploy' && cli.deploy !== undefined) {
|
|
241
|
+
await cli.deploy(parsed.rest)
|
|
257
242
|
return
|
|
258
243
|
}
|
|
259
|
-
throw
|
|
244
|
+
throw unsupported(provider, command)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const namespaceCli = async (provider: string): Promise<NamespaceCli> => {
|
|
248
|
+
const cli = await providerAppCli(provider, 'fabrika namespace')
|
|
249
|
+
if (cli.namespaces === undefined) throw new Error(`Provider ${provider} does not expose deployment namespaces`)
|
|
250
|
+
return cli.namespaces
|
|
260
251
|
}
|
|
261
252
|
|
|
262
253
|
const runNamespace = async (parsed: ParsedCommand): Promise<void> => {
|
|
263
254
|
const provider = requireExplicitProvider(parsed)
|
|
264
|
-
|
|
265
|
-
throw new Error(`Provider ${provider} does not expose deployment namespaces`)
|
|
266
|
-
}
|
|
255
|
+
const cli = await namespaceCli(provider)
|
|
267
256
|
if (parsed.command === undefined) {
|
|
268
257
|
throw new Error('Namespace command is required')
|
|
269
258
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
259
|
+
const { runNamespaceCommand } = await import('./namespace.js')
|
|
260
|
+
await runNamespaceCommand(cli, parsed.command, parsed.rest, {
|
|
261
|
+
source: process.env,
|
|
262
|
+
fetch: (input, init) => fetch(input, init),
|
|
263
|
+
write: (value) => console.info(value.trimEnd()),
|
|
264
|
+
})
|
|
273
265
|
}
|
|
274
266
|
|
|
275
267
|
export const runCli = async (argv: readonly string[]): Promise<void> => {
|
|
@@ -284,8 +276,21 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
|
|
|
284
276
|
console.info(CONTROL_USAGE)
|
|
285
277
|
return
|
|
286
278
|
}
|
|
279
|
+
if (parsed.help && parsed.area === 'env') {
|
|
280
|
+
const { ENV_USAGE } = await import('./data.js')
|
|
281
|
+
console.info(ENV_USAGE)
|
|
282
|
+
return
|
|
283
|
+
}
|
|
284
|
+
if (parsed.help && parsed.area === 'operations') {
|
|
285
|
+
const { OPERATIONS_USAGE } = await import('./operations.js')
|
|
286
|
+
console.info(OPERATIONS_USAGE)
|
|
287
|
+
return
|
|
288
|
+
}
|
|
287
289
|
if (parsed.help && parsed.area === 'namespace') {
|
|
288
|
-
|
|
290
|
+
if (parsed.provider !== undefined && parsed.provider !== '') {
|
|
291
|
+
console.info((await namespaceCli(parsed.provider)).usage)
|
|
292
|
+
return
|
|
293
|
+
}
|
|
289
294
|
const { NAMESPACE_USAGE } = await import('./namespace.js')
|
|
290
295
|
console.info(NAMESPACE_USAGE)
|
|
291
296
|
return
|
|
@@ -336,6 +341,17 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
|
|
|
336
341
|
await runControlCli(parsed.command, parsed.rest, parsed.provider)
|
|
337
342
|
return
|
|
338
343
|
}
|
|
344
|
+
if (parsed.area === 'env') {
|
|
345
|
+
const { runEnvCli } = await import('./data.js')
|
|
346
|
+
await runEnvCli(parsed.command, parsed.rest)
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
if (parsed.area === 'operations') {
|
|
350
|
+
const { runOperationsCli } = await import('./operations.js')
|
|
351
|
+
const exitCode = await runOperationsCli(parsed.command, parsed.rest)
|
|
352
|
+
if (exitCode !== 0) process.exitCode = exitCode
|
|
353
|
+
return
|
|
354
|
+
}
|
|
339
355
|
if (parsed.area === 'db') {
|
|
340
356
|
const { runDbCli } = await import('./db.js')
|
|
341
357
|
await runDbCli(parsed.command, parsed.rest)
|
package/src/job.ts
CHANGED
|
@@ -16,8 +16,8 @@ come from the environment only and leave the process before ${IMPLEMENTATION_FIL
|
|
|
16
16
|
process started again with the runtime role's credential in place of FABRIKA_APP_DATABASE_URL. A run takes the job's lease
|
|
17
17
|
or does not start. It exits 1 when the job failed, and 0 when it succeeded or a previous run still holds the lease.
|
|
18
18
|
A failure is named by a fixed code (timeout, lease_lost, handler_failed, query_refused, capability_refused,
|
|
19
|
-
driver_failed, crashed, unauthorized, iam_unavailable, boot_failed), never by the
|
|
20
|
-
its catalog reason (query_refused: undeclared_reach).
|
|
19
|
+
framework_fault, unavailable, driver_failed, crashed, unauthorized, iam_unavailable, boot_failed), never by the
|
|
20
|
+
application's error; a framework failure adds its catalog reason (query_refused: undeclared_reach).
|
|
21
21
|
`
|
|
22
22
|
|
|
23
23
|
export interface JobCommandDependencies {
|