@fabrika/cli 0.4.6 → 0.4.8

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/cli",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,19 +30,19 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "zod": "^3.25.76",
33
- "@fabrika/app": "^0.4.6",
34
- "@fabrika/auth-core": "^0.4.6",
35
- "@fabrika/control-contract": "^0.4.6",
36
- "@fabrika/provider-contract": "^0.4.6",
37
- "@fabrika/db": "^0.4.6",
38
- "@fabrika/platform": "^0.4.6",
39
- "@fabrika/platform-node": "^0.4.6",
40
- "@fabrika/check": "^0.4.6"
33
+ "@fabrika/app": "0.4.8",
34
+ "@fabrika/auth-core": "0.4.8",
35
+ "@fabrika/control-contract": "0.4.8",
36
+ "@fabrika/provider-contract": "0.4.8",
37
+ "@fabrika/db": "0.4.8",
38
+ "@fabrika/platform": "0.4.8",
39
+ "@fabrika/platform-node": "0.4.8",
40
+ "@fabrika/check": "0.4.8"
41
41
  },
42
42
  "peerDependencies": {
43
- "@fabrika/builder": "^0.4.6",
44
- "@fabrika/provider-cloudflare": "^0.4.6",
45
- "@fabrika/provider-zerops": "^0.4.6"
43
+ "@fabrika/builder": "0.4.8",
44
+ "@fabrika/provider-cloudflare": "0.4.8",
45
+ "@fabrika/provider-zerops": "0.4.8"
46
46
  },
47
47
  "peerDependenciesMeta": {
48
48
  "@fabrika/builder": {
package/src/control.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  // Output contract, matching `zops`: stdout carries DATA ONLY, progress and errors go to stderr, and
10
10
  // `--json` prints the procedure's result verbatim so a caller never parses a table.
11
11
 
12
- import { createRpcClient, RpcError } from '@fabrika/app'
12
+ import { createRpcClient, type InferRpcClient, RpcError } from '@fabrika/app'
13
13
  import { type IssueKeyInput, type IssueKeyResult, MAX_KEY_LIFETIME_SECONDS } from '@fabrika/auth-core'
14
14
  import type {
15
15
  AppDto,
@@ -81,6 +81,10 @@ refused before anything is created. \`namespaces get\` lists the hosts a \`zerop
81
81
  serves and which of them are still free; a custom-domain namespace serves the domain you bound to its
82
82
  proxy. A manifest with no proxy target needs no domain.
83
83
 
84
+ \`--public-origin\` is where IAM may return a signed-in person: without one, sign-in to the environment is
85
+ refused. When \`register\` is given none and the namespace lists \`--domain\` among its hosts, it sets
86
+ \`https://<domain>\` and says so on stderr. A custom domain needs the flag.
87
+
84
88
  \`--installation-id\` has three states: omitted resolves the installation from the organization's
85
89
  connected GitHub App, \`none\` registers an anonymous PUBLIC repository source, and a number names one
86
90
  installation outright. With \`none\`, control reads the repository once without a token and refuses one
@@ -88,7 +92,8 @@ GitHub hides: a private repository needs the GitHub App connected in the console
88
92
 
89
93
  Namespace placement options, each defaulting to what the preset would choose:
90
94
 
91
- --project=<name> the provider project the namespace owns
95
+ --project=<name> the provider project the namespace owns; on Zerops the default is
96
+ fabrika-<env>-<namespace id>, beside the installation's fabrika-<env>
92
97
  --core-package=<LIGHT|SERIOUS> defaults to LIGHT on every environment, \`prod\` included (ADR-0038).
93
98
  SERIOUS is a deliberate choice: a project cannot be downgraded again
94
99
  --public-access=<custom-domain|zerops-subdomain>
@@ -214,7 +219,9 @@ const secret = (variable: string, env: Readonly<Record<string, string | undefine
214
219
  }
215
220
 
216
221
  /** The console's client with a bearer instead of a cookie, and no SSO bounce: there is no browser to send. */
217
- const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>) => {
222
+ type ControlClient = InferRpcClient<ControlRpcContract>
223
+
224
+ const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => {
218
225
  const base = origin(flags, 'url', 'FABRIKA_CONTROL_URL', env, 'Control')
219
226
  const key = secret('FABRIKA_CONTROL_KEY', env)
220
227
  return createRpcClient<ControlRpcContract>({
@@ -397,14 +404,38 @@ const registrationRequest = (inputs: RegistrationInputs, provider: string, manif
397
404
  }
398
405
  }
399
406
 
407
+ /**
408
+ * The registration with the public origin sign-in returns to, when `--public-origin` is not given and the namespace
409
+ * lists `--domain` among the hosts it serves. IAM refuses to return to an environment without one. A namespace lists
410
+ * only the hosts its provider publishes, and Zerops publishes each one over HTTPS.
411
+ */
412
+ const withNamespacePublicOrigin = async (body: RegisterAppRequest, client: ControlClient): Promise<RegisterAppRequest> => {
413
+ const { domain, namespaceId } = body
414
+ if (body.publicOrigin !== undefined || domain === undefined || domain === null || namespaceId === undefined || namespaceId === null) {
415
+ return body
416
+ }
417
+ const namespace = await client.namespaces.get({ namespaceId })
418
+ if (!(namespace.hosts ?? []).some((entry) => entry.host === domain)) {
419
+ console.warn(
420
+ `no public origin: namespace ${namespaceId} does not list ${domain}, so sign-in cannot return to ${body.id}/${body.env} `
421
+ + 'until `apps environments put` sets --public-origin',
422
+ )
423
+ return body
424
+ }
425
+ const publicOrigin = `https://${domain}`
426
+ console.warn(`public origin ${publicOrigin}: namespace ${namespaceId} serves ${domain}`)
427
+ return { ...body, publicOrigin }
428
+ }
429
+
400
430
  const runRegister = async (flags: Flags, provider: string | undefined, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
401
431
  if (provider === undefined || provider === '') {
402
432
  throw new Error('--provider=<name> is required: it labels the envelope this registration carries.')
403
433
  }
404
434
  const manifestPath = required(flags, 'manifest')
405
435
  const manifest = await readJsonFile(manifestPath)
406
- const body = registrationRequest(registrationInputs(flags), provider, manifest, manifestPath)
407
- const result = await controlClient(flags, env).register(body)
436
+ const client = controlClient(flags, env)
437
+ const body = await withNamespacePublicOrigin(registrationRequest(registrationInputs(flags), provider, manifest, manifestPath), client)
438
+ const result = await client.register(body)
408
439
  emit(flags, result, () => registrationLine(result))
409
440
  }
410
441
 
@@ -456,7 +487,7 @@ export const registerCompiledManifest = async (
456
487
  }
457
488
  let result: RegisterAppResponse
458
489
  try {
459
- result = await client.register(body)
490
+ result = await client.register(await withNamespacePublicOrigin(body, client))
460
491
  } catch (error) {
461
492
  throw new Error(`Register phase failed after a successful compile; no manifest file was written. ${failureMessage(error, controlKey)}`)
462
493
  }
package/src/db.ts CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  import { CodegenError, generateSchema, SCHEMA_FILE } from '@fabrika/db/codegen'
12
12
  import { FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations'
13
13
  import {
14
+ CONNECTION_CAPACITY_MESSAGE,
15
+ ConnectionCapacityError,
14
16
  createTestProvisioner,
15
17
  DEFAULT_MIGRATION_LOCK_TIMEOUT_MS,
16
18
  DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS,
@@ -19,6 +21,8 @@ import {
19
21
  PostgresMigrationError,
20
22
  postgresMigrationResultMessage,
21
23
  type TestProvisioner,
24
+ TOO_MANY_CONNECTIONS,
25
+ withConnectionCapacity,
22
26
  } from '@fabrika/platform-node'
23
27
  import { SQL } from 'bun'
24
28
  import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
@@ -51,7 +55,10 @@ deletes a generated one the scaffold no longer writes, printing each path, or th
51
55
  one that is missing, edited or stale.
52
56
  \`test-isolation\` is the platform's run of them: with FABRIKA_APP_DATABASE_URL it creates a throwaway provisioner
53
57
  (CREATEROLE, CREATE on the database, nothing of any application) that the tests get instead, ignores the application's
54
- bunfig.toml, and checks the JUnit report against the case names the scaffold wrote.
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.
55
62
  `
56
63
 
57
64
  export interface DbCommandDependencies {
@@ -98,7 +105,7 @@ const reportable = (error: unknown): Error => {
98
105
  const server = serverError(error.cause)
99
106
  return new Error(server === undefined ? error.message : `${error.message}: ${server}`)
100
107
  }
101
- if (error instanceof CodegenError) return error
108
+ if (error instanceof CodegenError || error instanceof ConnectionCapacityError) return error
102
109
  const server = serverError(error)
103
110
  if (server !== undefined) return new Error(server)
104
111
  return new Error('the database connection failed; check FABRIKA_APP_DATABASE_URL (the driver error is withheld: it may contain the URL)')
@@ -200,9 +207,20 @@ const testEnvironment = (source: DbCommandDependencies['source'], url: string):
200
207
  }
201
208
 
202
209
  /**
203
- * Runs exactly the generated tests, with an empty `bunfig.toml` so that no preload, root or ignore pattern of the
204
- * application applies, and fails unless every case the scaffold wrote is reported as passed.
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.
205
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
+
206
224
  /**
207
225
  * Runs exactly the generated tests, with an empty `bunfig.toml` so that no preload, root or ignore pattern of the
208
226
  * application applies, and the platform's preload, which captures Bun's test functions before the application loads.
@@ -224,10 +242,11 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
224
242
  }
225
243
  let provisioner: TestProvisioner
226
244
  try {
227
- provisioner = await createTestProvisioner(url)
245
+ provisioner = await withConnectionCapacity(() => createTestProvisioner(url))
228
246
  } catch (error) {
229
247
  throw reportable(error)
230
248
  }
249
+ if (provisioner.swept.length > 0) deps.write(`dropped the test provisioners earlier runs left behind: ${provisioner.swept.join(', ')}\n`)
231
250
  const scratch = await mkdtemp(join(tmpdir(), 'fabrika-test-isolation-'))
232
251
  try {
233
252
  await writeFile(join(scratch, 'bunfig.toml'), '')
@@ -261,6 +280,11 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
261
280
  if (outcome !== 'passed') failed.push(`${path}: ${name} (${outcome})`)
262
281
  }
263
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
+ }
264
288
  if (code !== 0 || failed.length > 0) {
265
289
  const rerun = verbose ? '' : '; rerun with --verbose locally to see the test output'
266
290
  throw new Error(
@@ -272,7 +296,7 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
272
296
  deps.write(`${total} generated cases passed\n`)
273
297
  } finally {
274
298
  await rm(scratch, { recursive: true, force: true })
275
- await provisioner.drop().catch((error: unknown) => {
299
+ await withConnectionCapacity(() => provisioner.drop()).catch((error: unknown) => {
276
300
  throw reportable(error)
277
301
  })
278
302
  }
package/src/namespace.ts CHANGED
@@ -27,7 +27,8 @@ Options:
27
27
  --preset=<cheap|mid|full> Provider-owned namespace preset.
28
28
  --exclusive-app=<id> App reserved by a full namespace.
29
29
  --project-id=<id> Existing Zerops project id for adoption.
30
- --project-name=<name> Zerops project name (default: namespace id).
30
+ --project-name=<name> Zerops project name (create: default fabrika-<env>-<id>;
31
+ adopt: the existing project's name, default the namespace id).
31
32
  --core-package=<tier> LIGHT or SERIOUS.
32
33
  --public-access=<mode> custom-domain or zerops-subdomain.
33
34
  --postgres-type=<type> Cheap-tier PostgreSQL type.
@@ -204,6 +205,8 @@ export const runZeropsNamespaceCommand = async (
204
205
  version: zeropsNamespaceTargetCodec.version,
205
206
  payload: zeropsNamespaceTargetCodec.encode({
206
207
  ...decoded,
208
+ // An adopted project keeps its own name, so the plan's default for a created one does not apply.
209
+ projectName: args.projectName ?? planned.namespace.id,
207
210
  managed: false,
208
211
  projectId,
209
212
  ready: false,