@fabrika/cli 0.9.0-dev.10 → 0.9.0-dev.12
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.ts +3 -2
- package/src/control.ts +76 -62
- package/src/data.ts +1 -1
- package/src/db.ts +1 -1
- package/src/index.ts +15 -0
- package/src/operations.ts +722 -0
- package/types/src/app-dev-seed.d.ts +0 -2
- package/types/src/control.d.ts +24 -8
- package/types/src/data.d.ts +2 -0
- package/types/src/operations.d.ts +20 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/cli",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,24 +26,25 @@
|
|
|
26
26
|
}
|
|
27
27
|
},
|
|
28
28
|
"scripts": {
|
|
29
|
-
"typecheck": "
|
|
29
|
+
"typecheck": "tsrs --build tsconfig.test.json",
|
|
30
30
|
"test": "bun test"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"zod": "^3.25.76",
|
|
34
|
-
"@fabrika/app": "0.9.0-dev.
|
|
35
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
36
|
-
"@fabrika/control-contract": "0.9.0-dev.
|
|
37
|
-
"@fabrika/
|
|
38
|
-
"@fabrika/
|
|
39
|
-
"@fabrika/
|
|
40
|
-
"@fabrika/platform
|
|
41
|
-
"@fabrika/
|
|
34
|
+
"@fabrika/app": "0.9.0-dev.12",
|
|
35
|
+
"@fabrika/auth-core": "0.9.0-dev.12",
|
|
36
|
+
"@fabrika/control-contract": "0.9.0-dev.12",
|
|
37
|
+
"@fabrika/operations-contract": "0.9.0-dev.12",
|
|
38
|
+
"@fabrika/provider-contract": "0.9.0-dev.12",
|
|
39
|
+
"@fabrika/db": "0.9.0-dev.12",
|
|
40
|
+
"@fabrika/platform": "0.9.0-dev.12",
|
|
41
|
+
"@fabrika/platform-node": "0.9.0-dev.12",
|
|
42
|
+
"@fabrika/check": "0.9.0-dev.12"
|
|
42
43
|
},
|
|
43
44
|
"peerDependencies": {
|
|
44
|
-
"@fabrika/builder": "0.9.0-dev.
|
|
45
|
-
"@fabrika/provider-cloudflare": "0.9.0-dev.
|
|
46
|
-
"@fabrika/provider-zerops": "0.9.0-dev.
|
|
45
|
+
"@fabrika/builder": "0.9.0-dev.12",
|
|
46
|
+
"@fabrika/provider-cloudflare": "0.9.0-dev.12",
|
|
47
|
+
"@fabrika/provider-zerops": "0.9.0-dev.12"
|
|
47
48
|
},
|
|
48
49
|
"peerDependenciesMeta": {
|
|
49
50
|
"@fabrika/builder": {
|
package/src/app-dev-seed.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import type { AnyContract } from '@fabrika/app/contract'
|
|
5
5
|
import type { DevKit, PersonTestCaller } from '@fabrika/app/testing'
|
|
6
|
+
import { sameOriginTarget } from '@fabrika/auth-core'
|
|
6
7
|
import { existsSync } from 'node:fs'
|
|
7
8
|
import { isAbsolute, join } from 'node:path'
|
|
8
9
|
import { pathToFileURL } from 'node:url'
|
|
@@ -53,11 +54,6 @@ const SeedResult = z.strictObject({
|
|
|
53
54
|
scopes: z.record(z.string(), z.array(z.strictObject({ value: Text(MAX_SCOPE_VALUE), label: Text(MAX_NAME) })).max(MAX_ENTRIES)).optional(),
|
|
54
55
|
}).optional()
|
|
55
56
|
|
|
56
|
-
/** A path of this origin; a link the application issued is one (`/s/#px_…`). */
|
|
57
|
-
export function isLocalPath(path: string): boolean {
|
|
58
|
-
return path.startsWith('/') && !path.startsWith('//') && !path.startsWith('/\\')
|
|
59
|
-
}
|
|
60
|
-
|
|
61
57
|
/** The seed module's path: `--seed`, relative to the root, or `dev/seed.ts` when it exists; `null` for none. */
|
|
62
58
|
export function seedPath(root: string, given: string | null): string | null {
|
|
63
59
|
if (given !== null) {
|
|
@@ -102,7 +98,7 @@ export function parseSeeded<C extends AnyContract>(dev: DevKit<C>, answer: unkno
|
|
|
102
98
|
return { name: persona.name, description: persona.description ?? null, caller }
|
|
103
99
|
})
|
|
104
100
|
const links = (result.links ?? []).map((link, index): SeedLink => {
|
|
105
|
-
if (
|
|
101
|
+
if (sameOriginTarget(dev.kit.origin, link.url) === null) {
|
|
106
102
|
throw new SeedProblem(`app dev: link ${index + 1} of the seed is not a path of the application, as ctx.links answers it`)
|
|
107
103
|
}
|
|
108
104
|
return { title: link.title, description: link.description ?? null, url: link.url }
|
package/src/app-dev.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { implementationAt } from '@fabrika/app/bun'
|
|
|
10
10
|
import type { AnyContract } from '@fabrika/app/contract'
|
|
11
11
|
import { BootError, type ContractImplementation } from '@fabrika/app/implement'
|
|
12
12
|
import { DEV_OUTBOX_ORIGIN, type DevKit, devKit, type DevOutside, type LabelledTestCaller, type TestCaller } from '@fabrika/app/testing'
|
|
13
|
+
import { sameOriginTarget } from '@fabrika/auth-core'
|
|
13
14
|
import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
|
|
14
15
|
import { SqliteMigrationError } from '@fabrika/db/sqlite-migrate'
|
|
15
16
|
import { TEST_POSTGRES_URL, type TestDatabase, testDatabase } from '@fabrika/db/testing'
|
|
@@ -19,7 +20,7 @@ import { existsSync, readFileSync } from 'node:fs'
|
|
|
19
20
|
import { join } from 'node:path'
|
|
20
21
|
import { z } from 'zod/v4'
|
|
21
22
|
import { DEV_ENV_FILE, DevEnvProblem, type DevOutbox, devOutbox, mailHeadOf, readDevEnv, shownBody } from './app-dev-outside'
|
|
22
|
-
import { DEFAULT_SEED, importSeed,
|
|
23
|
+
import { DEFAULT_SEED, importSeed, NOTHING_SEEDED, parseSeeded, type Seeded, seedPath, SeedProblem } from './app-dev-seed'
|
|
23
24
|
import {
|
|
24
25
|
type Badge,
|
|
25
26
|
type CurrentView,
|
|
@@ -294,7 +295,7 @@ async function serveDevKit(
|
|
|
294
295
|
const toolbar = toolbarScript(STATE_PATH)
|
|
295
296
|
|
|
296
297
|
/** A path of this origin to go on to; anything else is the first SPA. */
|
|
297
|
-
const nextOf = (next: string | null): string => (next !== null &&
|
|
298
|
+
const nextOf = (next: string | null): string => (next !== null && sameOriginTarget(kit.origin, next) !== null ? next : firstSpa)
|
|
298
299
|
|
|
299
300
|
/** The caller a role choice names, made once and kept, so its membership changes last; `null` when it is no grant. */
|
|
300
301
|
const roleCaller = (role: string, value: string | null): LabelledTestCaller | null => {
|
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, type InferRpcClient, RpcError } from '@fabrika/app'
|
|
12
|
+
import { createRpcClient, type InferRpcClient, RpcError, type RpcFetch } from '@fabrika/app'
|
|
13
13
|
import { type IssueKeyInput, type IssueKeyResult, MAX_KEY_LIFETIME_SECONDS } from '@fabrika/auth-core'
|
|
14
14
|
import { APP_ENV_KINDS } from '@fabrika/control-contract'
|
|
15
15
|
import type {
|
|
@@ -60,7 +60,7 @@ Usage:
|
|
|
60
60
|
[--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]
|
|
61
61
|
[--cross-origin=<origin> ...] [--kind=standard|dev]
|
|
62
62
|
fabrika control apps variables list --app=<id>
|
|
63
|
-
fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>]
|
|
63
|
+
fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret]
|
|
64
64
|
fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]
|
|
65
65
|
fabrika control apps secrets list --app=<id>
|
|
66
66
|
fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)
|
|
@@ -91,7 +91,9 @@ refused before anything is created. \`namespaces get\` lists the hosts a \`zerop
|
|
|
91
91
|
serves and which of them are still free; a custom-domain namespace serves the domain you bound to its
|
|
92
92
|
proxy. A manifest with no proxy target needs no domain.
|
|
93
93
|
|
|
94
|
-
A variable's value is stored and printed in clear
|
|
94
|
+
A variable's value is stored and printed in clear, so \`apps variables put\` refuses one that looks like a
|
|
95
|
+
credential (by its name, such as \`*_TOKEN\` or \`*_PASSWORD\`, or by its value) and names \`apps secrets put\` instead.
|
|
96
|
+
\`--not-secret\` stores it anyway, for a value you have checked is not one. A secret's value is write-only: \`apps secrets put\`
|
|
95
97
|
reads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and
|
|
96
98
|
one trailing newline is dropped. No command prints it back; \`apps secrets list\` shows names, scope and
|
|
97
99
|
storage only. Generate one in the pipe:
|
|
@@ -118,7 +120,8 @@ GitHub hides: a private repository needs the GitHub App connected in the console
|
|
|
118
120
|
on \`deploy\`. A bare name is a branch: \`--trigger-ref=deploy/prod\` is stored as \`refs/heads/deploy/prod\`.
|
|
119
121
|
A full ref is kept as given: \`refs/heads/<branch>\`, \`refs/tags/<tag>\`, or a \`*\` glob such as
|
|
120
122
|
\`refs/tags/v*\`, which deploys every matching tag. A tag always needs the \`refs/tags/\` form. Each
|
|
121
|
-
environment of an app needs its own trigger ref.
|
|
123
|
+
environment of an app needs its own trigger ref. Branches named \`fabrika/…\` are reserved for MCP
|
|
124
|
+
workspaces and are never a trigger ref.
|
|
122
125
|
|
|
123
126
|
Namespace placement options, each defaulting to what the preset would choose:
|
|
124
127
|
|
|
@@ -186,18 +189,23 @@ interface Flags {
|
|
|
186
189
|
/** Every value of every option, in order; `values` keeps the last. Only a repeatable option reads it. */
|
|
187
190
|
readonly repeated: ReadonlyMap<string, readonly string[]>
|
|
188
191
|
readonly json: boolean
|
|
192
|
+
/** `--not-secret`: `apps variables put` stores a value that looks like a credential. */
|
|
193
|
+
readonly notSecret: boolean
|
|
189
194
|
readonly positional: readonly string[]
|
|
190
195
|
}
|
|
191
196
|
|
|
192
|
-
/** Split `--key=value` options from positional words; `--json` is the one flag every verb shares. */
|
|
197
|
+
/** Split `--key=value` options from positional words; `--json` is the one flag every verb shares, `--not-secret` the other bare one. */
|
|
193
198
|
export const parseControlFlags = (argv: readonly string[]): Flags => {
|
|
194
199
|
const values = new Map<string, string>()
|
|
195
200
|
const repeated = new Map<string, string[]>()
|
|
196
201
|
const positional: string[] = []
|
|
197
202
|
let json = false
|
|
203
|
+
let notSecret = false
|
|
198
204
|
for (const arg of argv) {
|
|
199
205
|
if (arg === '--json') {
|
|
200
206
|
json = true
|
|
207
|
+
} else if (arg === '--not-secret') {
|
|
208
|
+
notSecret = true
|
|
201
209
|
} else if (arg.startsWith('--')) {
|
|
202
210
|
const eq = arg.indexOf('=')
|
|
203
211
|
if (eq === -1) {
|
|
@@ -211,7 +219,7 @@ export const parseControlFlags = (argv: readonly string[]): Flags => {
|
|
|
211
219
|
positional.push(arg)
|
|
212
220
|
}
|
|
213
221
|
}
|
|
214
|
-
return { values, repeated, json, positional }
|
|
222
|
+
return { values, repeated, json, notSecret, positional }
|
|
215
223
|
}
|
|
216
224
|
|
|
217
225
|
const required = (flags: Flags, name: string): string => {
|
|
@@ -249,26 +257,6 @@ const positiveInteger = (raw: string, name: string): number => {
|
|
|
249
257
|
return parsed
|
|
250
258
|
}
|
|
251
259
|
|
|
252
|
-
/**
|
|
253
|
-
* An origin from the flag, else the environment. Trailing slashes are dropped so paths concatenate.
|
|
254
|
-
*
|
|
255
|
-
* `label` names WHICH origin is missing: `key issue` reaches IAM, not the control plane, and a message
|
|
256
|
-
* that says "Control origin" while asking for `--iam-url` sends the operator to the wrong variable.
|
|
257
|
-
*/
|
|
258
|
-
const origin = (
|
|
259
|
-
flags: Flags,
|
|
260
|
-
flag: string,
|
|
261
|
-
variable: string,
|
|
262
|
-
env: Readonly<Record<string, string | undefined>>,
|
|
263
|
-
label: string,
|
|
264
|
-
): string => {
|
|
265
|
-
const value = flags.values.get(flag) ?? env[variable]
|
|
266
|
-
if (value === undefined || value.trim() === '') {
|
|
267
|
-
throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
|
|
268
|
-
}
|
|
269
|
-
return value.trim().replace(/\/+$/, '')
|
|
270
|
-
}
|
|
271
|
-
|
|
272
260
|
const secret = (variable: string, env: Readonly<Record<string, string | undefined>>): string => {
|
|
273
261
|
const value = env[variable]
|
|
274
262
|
if (value === undefined || value.trim() === '') {
|
|
@@ -283,25 +271,45 @@ export type ControlClient = InferRpcClient<ControlRpcContract>
|
|
|
283
271
|
/** Plain http may carry the key to loopback only: 127.0.0.0/8, [::1], and the names RFC 6761 reserves for it, `localhost` and `*.localhost`. */
|
|
284
272
|
const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
|
|
285
273
|
|
|
274
|
+
/** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
|
|
275
|
+
interface OriginSource {
|
|
276
|
+
readonly label: string
|
|
277
|
+
readonly flag: string
|
|
278
|
+
readonly variable: string
|
|
279
|
+
readonly hint?: string
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const CONTROL_ORIGIN: OriginSource = { label: 'Control', flag: 'url', variable: 'FABRIKA_CONTROL_URL' }
|
|
283
|
+
|
|
284
|
+
const IAM_ORIGIN: OriginSource = {
|
|
285
|
+
label: 'IAM',
|
|
286
|
+
flag: 'iam-url',
|
|
287
|
+
variable: 'FABRIKA_IAM_RPC_URL',
|
|
288
|
+
hint: "It is IAM's PUBLIC https origin (control's FABRIKA_IAM_ISSUER): a private hostname such as `http://iam:3000` answers only "
|
|
289
|
+
+ "inside the provider's project, never from this machine.",
|
|
290
|
+
}
|
|
291
|
+
|
|
286
292
|
/**
|
|
287
|
-
*
|
|
288
|
-
* and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
|
|
293
|
+
* An origin a credential is sent to, checked before the credential goes anywhere: https, or http to a loopback host for
|
|
294
|
+
* local development, and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
|
|
289
295
|
*/
|
|
290
|
-
export const
|
|
296
|
+
export const credentialOrigin = (raw: string | undefined, source: OriginSource): string => {
|
|
297
|
+
const { label, flag, variable } = source
|
|
291
298
|
if (raw === undefined || raw.trim() === '') {
|
|
292
|
-
throw new Error(
|
|
299
|
+
throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
|
|
293
300
|
}
|
|
301
|
+
const refuse = (reason: string): Error => new Error(source.hint === undefined ? reason : `${reason}. ${source.hint}`)
|
|
294
302
|
let url: URL
|
|
295
303
|
try {
|
|
296
304
|
url = new URL(raw.trim())
|
|
297
305
|
} catch {
|
|
298
|
-
throw
|
|
306
|
+
throw refuse(`--${flag} or ${variable} is not a URL`)
|
|
299
307
|
}
|
|
300
308
|
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) {
|
|
301
|
-
throw
|
|
309
|
+
throw refuse(`--${flag} or ${variable} must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]`)
|
|
302
310
|
}
|
|
303
311
|
if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
|
|
304
|
-
throw
|
|
312
|
+
throw refuse(`--${flag} or ${variable} must be an origin only: no credentials, path, query or fragment`)
|
|
305
313
|
}
|
|
306
314
|
return url.origin
|
|
307
315
|
}
|
|
@@ -337,22 +345,38 @@ const withoutEchoedKey = async (response: Response, key: string): Promise<Respon
|
|
|
337
345
|
return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
|
|
338
346
|
}
|
|
339
347
|
|
|
348
|
+
/** Control's origin and the fetch that carries FABRIKA_CONTROL_KEY to it. */
|
|
349
|
+
export interface ControlTransport {
|
|
350
|
+
readonly origin: string
|
|
351
|
+
readonly fetch: RpcFetch
|
|
352
|
+
}
|
|
353
|
+
|
|
340
354
|
/**
|
|
341
|
-
* The
|
|
342
|
-
*
|
|
355
|
+
* The origin from `url` or FABRIKA_CONTROL_URL, the key from FABRIKA_CONTROL_KEY in the environment only, no redirect
|
|
356
|
+
* followed. Every client of the console's origin is built on it.
|
|
343
357
|
*/
|
|
344
|
-
export const
|
|
345
|
-
|
|
358
|
+
export const controlTransport = (
|
|
359
|
+
url: string | undefined,
|
|
360
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
361
|
+
send: RpcFetch = fetch,
|
|
362
|
+
): ControlTransport => {
|
|
363
|
+
const origin = credentialOrigin(url ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
|
|
346
364
|
const key = secret('FABRIKA_CONTROL_KEY', env)
|
|
347
|
-
return
|
|
348
|
-
|
|
365
|
+
return {
|
|
366
|
+
origin,
|
|
349
367
|
fetch: async (input, init) => {
|
|
350
368
|
const headers = new Headers(init?.headers)
|
|
351
369
|
headers.set('authorization', `Bearer ${key}`)
|
|
352
370
|
// A redirect would carry the bearer to wherever it points.
|
|
353
|
-
return await withoutEchoedKey(await
|
|
371
|
+
return await withoutEchoedKey(await send(input, { ...init, headers, redirect: 'manual' }), key)
|
|
354
372
|
},
|
|
355
|
-
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The one client of Control that `fabrika control`, `fabrika env` and `fabrika operations` share. */
|
|
377
|
+
export const connectControl = (url: string | undefined, env: Readonly<Record<string, string | undefined>>): ControlClient => {
|
|
378
|
+
const transport = controlTransport(url, env)
|
|
379
|
+
return createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch })
|
|
356
380
|
}
|
|
357
381
|
|
|
358
382
|
const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => connectControl(flags.values.get('url'), env)
|
|
@@ -403,32 +427,16 @@ const appLine = (app: AppDto): string => `${app.id}\t${app.repoUrl}\t${app.defau
|
|
|
403
427
|
|
|
404
428
|
const runLine = (run: RunDto): string => `${run.id}\t${run.appId}\t${run.env}\t${run.status}\t${run.ref}`
|
|
405
429
|
|
|
406
|
-
/** How the IAM origin was supplied, for a message that must not echo the value itself. */
|
|
407
|
-
const IAM_ORIGIN_SOURCE = '--iam-url / FABRIKA_IAM_RPC_URL'
|
|
408
|
-
|
|
409
430
|
/**
|
|
410
431
|
* The one `key issue` failure whose cause is almost always the address itself.
|
|
411
432
|
*
|
|
412
|
-
* `fetch` rejects only when the request never completed, so this reports what could not be reached and
|
|
413
|
-
*
|
|
414
|
-
* value, and `new URL().origin` drops it. A value that does not parse is not echoed at all — the
|
|
415
|
-
* variable is named instead. The cause object may quote anything, so only its short error code is.
|
|
433
|
+
* `fetch` rejects only when the request never completed, so this reports what could not be reached and the mistake that
|
|
434
|
+
* produces it. The cause object may quote anything, so only its short error code is.
|
|
416
435
|
*/
|
|
417
|
-
const unreachableIam = (
|
|
436
|
+
const unreachableIam = (origin: string, cause: unknown): string => {
|
|
418
437
|
const code = typeof cause === 'object' && cause !== null ? Reflect.get(cause, 'code') : undefined
|
|
419
438
|
const reason = typeof code === 'string' && code !== '' && code.length <= 40 ? code : 'the connection failed'
|
|
420
|
-
|
|
421
|
-
try {
|
|
422
|
-
parsed = new URL(base).origin
|
|
423
|
-
} catch {
|
|
424
|
-
parsed = undefined
|
|
425
|
-
}
|
|
426
|
-
if (parsed === undefined || parsed === 'null' || code === 'ERR_INVALID_URL') {
|
|
427
|
-
return `${IAM_ORIGIN_SOURCE} is not a URL — it needs the \`https://\` scheme and IAM's PUBLIC host, `
|
|
428
|
-
+ 'shaped `https://<iam-host>`.'
|
|
429
|
-
}
|
|
430
|
-
return `IAM could not be reached at ${parsed} (${reason}). ${IAM_ORIGIN_SOURCE} must be IAM's PUBLIC origin: `
|
|
431
|
-
+ "a private hostname such as `http://iam:3000` answers only inside the provider's project, never from this machine."
|
|
439
|
+
return `IAM could not be reached at ${origin} (${reason}). ${IAM_ORIGIN.hint}`
|
|
432
440
|
}
|
|
433
441
|
|
|
434
442
|
const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
@@ -448,14 +456,19 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
|
|
|
448
456
|
label: required(flags, 'label'),
|
|
449
457
|
expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
|
|
450
458
|
}
|
|
451
|
-
const base =
|
|
459
|
+
const base = credentialOrigin(flags.values.get('iam-url') ?? env['FABRIKA_IAM_RPC_URL'], IAM_ORIGIN)
|
|
452
460
|
const response = await fetch(`${base}/rpc/issueKey`, {
|
|
453
461
|
method: 'POST',
|
|
454
462
|
headers: { authorization: `Bearer ${secret('FABRIKA_IAM_RPC_KEY', env)}`, 'content-type': 'application/json' },
|
|
455
463
|
body: JSON.stringify(body),
|
|
464
|
+
// A followed 307/308 would re-send the provisioning key to wherever it points.
|
|
465
|
+
redirect: 'manual',
|
|
456
466
|
}).catch((cause: unknown) => {
|
|
457
467
|
throw new Error(unreachableIam(base, cause))
|
|
458
468
|
})
|
|
469
|
+
if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {
|
|
470
|
+
throw new Error(`IAM answered with a redirect (HTTP ${response.status}), which is not followed. ${IAM_ORIGIN.hint}`)
|
|
471
|
+
}
|
|
459
472
|
if (!response.ok) {
|
|
460
473
|
// The body can quote what came off the wire, so report the status and nothing else.
|
|
461
474
|
throw new Error(`IAM refused the issue request: HTTP ${response.status}`)
|
|
@@ -706,6 +719,7 @@ const runVariables = async (verb: string | undefined, flags: Flags, env: Readonl
|
|
|
706
719
|
name: required(flags, 'name'),
|
|
707
720
|
value: required(flags, 'value'),
|
|
708
721
|
...(scope === undefined ? {} : { env: scope }),
|
|
722
|
+
...(flags.notSecret ? { notSecret: true } : {}),
|
|
709
723
|
}
|
|
710
724
|
const result = await client.apps.variables.put({ appId, variable })
|
|
711
725
|
emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\t${result.value}`)
|
package/src/data.ts
CHANGED
|
@@ -272,7 +272,7 @@ const scheduleLines = (schedule: DataBackupScheduleDto): string =>
|
|
|
272
272
|
[`daily\t${schedule.daily ? 'on' : 'off'}`, `updatedAt\t${schedule.updatedAt === null ? '-' : isoSeconds(schedule.updatedAt)}`].join('\n')
|
|
273
273
|
|
|
274
274
|
/** 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, '')
|
|
275
|
+
export const printable = (text: string): string => text.replace(/[^\P{Cc}\t\n]/gu, '')
|
|
276
276
|
|
|
277
277
|
const viewLines = (view: OpsView | OpsContentView): string[] => [
|
|
278
278
|
`release\t${view.release}`,
|
package/src/db.ts
CHANGED
|
@@ -184,7 +184,7 @@ const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Pr
|
|
|
184
184
|
const { source, leftOut } = (await dialectAt(deps.cwd)) === 'sqlite' ? await sqliteSchema(deps.cwd) : await postgresSchema(deps)
|
|
185
185
|
const path = join(deps.cwd, SCHEMA_FILE)
|
|
186
186
|
// Named on every run, --verify's too, so a column the module leaves out is never silent.
|
|
187
|
-
for (const column of leftOut) deps.write(`${leftOutText(`${column.table}.${column.column}`, column.type)}\n`)
|
|
187
|
+
for (const column of leftOut) deps.write(`${leftOutText(`${column.table}.${column.column}`, column.type, column.of)}\n`)
|
|
188
188
|
if (verify) {
|
|
189
189
|
const committed = await readFile(path, 'utf8').catch(() => undefined)
|
|
190
190
|
if (committed !== source) throw new Error(`${SCHEMA_FILE} is stale; run fabrika db codegen and commit the result`)
|
package/src/index.ts
CHANGED
|
@@ -27,6 +27,7 @@ Usage:
|
|
|
27
27
|
fabrika namespace <plan|create|adopt|reconcile> --provider=zerops [provider options]
|
|
28
28
|
fabrika control <key|apps|namespaces|register|deploy|runs> [options]
|
|
29
29
|
fabrika env <inspect|maintenance|operations|recover|backups|restore> <app> <env> [arguments] [--json]
|
|
30
|
+
fabrika operations <issues|issue|releases|health> [options] [--json]
|
|
30
31
|
fabrika builder <init|next|advance|gate|ensure-daemon|induce|build> [options]
|
|
31
32
|
fabrika db <new|migrate|codegen|test-scaffold|test-isolation> [options]
|
|
32
33
|
fabrika job run <name>
|
|
@@ -66,6 +67,9 @@ provider-neutral, loads no installation package, and speaks the same typed API t
|
|
|
66
67
|
\`fabrika env\` shows an application environment's data and backups through the control plane, puts it into
|
|
67
68
|
maintenance, restores its data as of a past time, or recovers a stuck operation. Run \`fabrika env --help\` for its surface.
|
|
68
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
|
+
|
|
69
73
|
Which platform commands exist, and how WIDE each one is, is the provider's own answer — Zerops'
|
|
70
74
|
\`platform deploy\` owns the whole ordered sequence while Cloudflare's is one step of a scaffolded
|
|
71
75
|
workflow (ADR-0027), and only Zerops offers \`platform install\`, the from-scratch bring-up,
|
|
@@ -277,6 +281,11 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
|
|
|
277
281
|
console.info(ENV_USAGE)
|
|
278
282
|
return
|
|
279
283
|
}
|
|
284
|
+
if (parsed.help && parsed.area === 'operations') {
|
|
285
|
+
const { OPERATIONS_USAGE } = await import('./operations.js')
|
|
286
|
+
console.info(OPERATIONS_USAGE)
|
|
287
|
+
return
|
|
288
|
+
}
|
|
280
289
|
if (parsed.help && parsed.area === 'namespace') {
|
|
281
290
|
if (parsed.provider !== undefined && parsed.provider !== '') {
|
|
282
291
|
console.info((await namespaceCli(parsed.provider)).usage)
|
|
@@ -337,6 +346,12 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
|
|
|
337
346
|
await runEnvCli(parsed.command, parsed.rest)
|
|
338
347
|
return
|
|
339
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
|
+
}
|
|
340
355
|
if (parsed.area === 'db') {
|
|
341
356
|
const { runDbCli } = await import('./db.js')
|
|
342
357
|
await runDbCli(parsed.command, parsed.rest)
|
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
// The `fabrika operations` command area: Operations' issues, releases and health, read through the console's
|
|
2
|
+
// `/operations/api/rpc`, the typed RPC the console's Operations pages call. It is read-only: every command is a read
|
|
3
|
+
// procedure of `OperationsRpcContract`, and the area reaches no write.
|
|
4
|
+
|
|
5
|
+
import { createRpcClient, type InferRpcClient, RpcError, type RpcFetch } from '@fabrika/app'
|
|
6
|
+
import type { ConsoleAccessDto, ControlRpcContract } from '@fabrika/control-contract'
|
|
7
|
+
import { OPERATIONS_ACTIONS } from '@fabrika/operations-contract/access'
|
|
8
|
+
import type { ActivityItem, DisplayFrame, EventBreadcrumb, EventDetail, EventException } from '@fabrika/operations-contract/operator'
|
|
9
|
+
import type {
|
|
10
|
+
OperationsEventDetailResponseDto,
|
|
11
|
+
OperationsHealthCheckDto,
|
|
12
|
+
OperationsHealthResponseDto,
|
|
13
|
+
OperationsIssueDetailResponseDto,
|
|
14
|
+
OperationsIssueListResponseDto,
|
|
15
|
+
OperationsIssueOccurrenceDto,
|
|
16
|
+
OperationsIssueSummaryDto,
|
|
17
|
+
OperationsReleaseListResponseDto,
|
|
18
|
+
OperationsReleaseSummaryDto,
|
|
19
|
+
OperationsSourceHealthDto,
|
|
20
|
+
OperationsSourceListResponseDto,
|
|
21
|
+
OperationsSourceSummaryDto,
|
|
22
|
+
} from '@fabrika/operations-contract/operator-api'
|
|
23
|
+
import type { OperationsIssueQuery, OperationsReleaseQuery, OperationsRpcContract } from '@fabrika/operations-contract/rpc'
|
|
24
|
+
import { z } from 'zod'
|
|
25
|
+
import { controlTransport, withoutControlKey } from './control.js'
|
|
26
|
+
import { printable } from './data.js'
|
|
27
|
+
|
|
28
|
+
const USAGE = `fabrika operations — read Operations (errors, releases, health) from the command line
|
|
29
|
+
|
|
30
|
+
Usage:
|
|
31
|
+
fabrika operations issues [--app=<id>] [--env=<env>] [--service=<key>] [--status=<open|resolved|ignored>]
|
|
32
|
+
[--level=<fatal|error|warning|info>] [--since=<24h|7d|30d|all>] [--search=<text>]
|
|
33
|
+
[--sort=<recent|new|frequency>] [--limit=<1-100>] [--cursor=<cursor>] [--json]
|
|
34
|
+
fabrika operations issue <issueId> [--event=<occurrenceId>] [--json]
|
|
35
|
+
fabrika operations releases [--app=<id>] [--env=<env>] [--service=<key>] [--limit=<1-100>] [--cursor=<cursor>] [--json]
|
|
36
|
+
fabrika operations health [--app=<id>] [--env=<env>] [--service=<key>] [--json]
|
|
37
|
+
|
|
38
|
+
Every command is read-only. It reads what the console's Operations pages show, through the same API, with the
|
|
39
|
+
key's rights: a source (one service of an application environment) the key may not read is not listed, and an
|
|
40
|
+
issue of one answers \`not_found\`.
|
|
41
|
+
|
|
42
|
+
\`issues\` lists issues, the most recently seen first (\`--sort\` changes that), one row each:
|
|
43
|
+
<id> <status> <level> <events> <last seen> <app> <env> <service> <title>.
|
|
44
|
+
stderr carries the selection's counts by status (whatever \`--status\` says) and, when more issues match, the
|
|
45
|
+
\`--cursor\` that reads the next page with the same options.
|
|
46
|
+
|
|
47
|
+
\`issue\` prints one issue: its fields, its activity, its recent events (\`occurrence\` rows), and the latest
|
|
48
|
+
event in full: request, user, tags, each exception with its stack frames, and the breadcrumbs. \`--event\` shows
|
|
49
|
+
the event of another occurrence instead. The raw event is in \`--json\` only.
|
|
50
|
+
|
|
51
|
+
\`releases\` lists releases, newest first, one row each:
|
|
52
|
+
<id> <state> <artifacts> <release> <commit> <created at> <finished at> <new issues> <regressions> <app> <env> <service>.
|
|
53
|
+
|
|
54
|
+
\`health\` prints each source's telemetry health and its HTTP checks:
|
|
55
|
+
source <app> <env> <service> <telemetry state>
|
|
56
|
+
check <app> <env> <service> <path> <state> <observed at> <latency ms> <detail code> <consecutive failures>
|
|
57
|
+
|
|
58
|
+
\`--app\`, \`--env\` and \`--service\` select sources. On \`issues\` and \`releases\` they must select exactly one;
|
|
59
|
+
when they match several, the error lists them. Without them every source the key may read is included.
|
|
60
|
+
|
|
61
|
+
Issue titles, exception messages, breadcrumbs, tags and the raw event are text the application's users and code
|
|
62
|
+
wrote. They are printed as data with control characters removed; \`--json\` escapes them, C1 controls included,
|
|
63
|
+
as JSON strings.
|
|
64
|
+
|
|
65
|
+
stdout carries data only; notes and errors go to stderr. Times are ISO 8601 UTC, except a breadcrumb time the event
|
|
66
|
+
wrote as text. \`--json\` prints the parsed answer: of the procedure, or for \`issue\` \`{ issue, event }\`, the
|
|
67
|
+
issue and the event shown (\`null\` when none is stored).
|
|
68
|
+
|
|
69
|
+
Exit codes:
|
|
70
|
+
0 the answer was printed (an empty list included)
|
|
71
|
+
1 the call failed: Control or Operations unreachable, a server error, an unreadable answer, or a procedure this
|
|
72
|
+
installation's release does not offer
|
|
73
|
+
2 usage: an unknown command or option, a bad value, or a selection that matches several sources
|
|
74
|
+
3 the key: FABRIKA_CONTROL_KEY is missing, was refused, or does not hold \`operations.read\`
|
|
75
|
+
4 not found: no such issue, event or source, or one the key may not read
|
|
76
|
+
|
|
77
|
+
The console origin takes either form:
|
|
78
|
+
|
|
79
|
+
--url=<origin> FABRIKA_CONTROL_URL
|
|
80
|
+
|
|
81
|
+
The credential is read from the ENVIRONMENT ONLY and has no flag:
|
|
82
|
+
|
|
83
|
+
FABRIKA_CONTROL_KEY required a \`px_\` key of the console app holding \`operations.read\`
|
|
84
|
+
|
|
85
|
+
Mint a key narrowed to \`operations.read\` alone, with a short expiry: docs/reference/operations-errors.md,
|
|
86
|
+
"Reading Operations from the command line".
|
|
87
|
+
`
|
|
88
|
+
|
|
89
|
+
export const OPERATIONS_EXIT = { ok: 0, failed: 1, usage: 2, credential: 3, notFound: 4 } as const
|
|
90
|
+
|
|
91
|
+
type ExitCode = (typeof OPERATIONS_EXIT)[keyof typeof OPERATIONS_EXIT]
|
|
92
|
+
|
|
93
|
+
class OperationsCliError extends Error {
|
|
94
|
+
constructor(readonly exitCode: ExitCode, message: string) {
|
|
95
|
+
super(message)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
type Environment = Readonly<Record<string, string | undefined>>
|
|
100
|
+
|
|
101
|
+
/** What the area reads and writes: the environment, the network, stdout and stderr. */
|
|
102
|
+
export interface OperationsIo {
|
|
103
|
+
readonly env: Environment
|
|
104
|
+
readonly fetch: RpcFetch
|
|
105
|
+
readonly out: (text: string) => void
|
|
106
|
+
readonly err: (text: string) => void
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const processIo = (): OperationsIo => ({
|
|
110
|
+
env: process.env,
|
|
111
|
+
fetch: (input, init) => fetch(input, init),
|
|
112
|
+
out: (text) => console.info(text),
|
|
113
|
+
err: (text) => console.warn(text),
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
// ── Arguments ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
const COMMAND_OPTIONS: Readonly<Record<string, readonly string[]>> = {
|
|
119
|
+
issues: ['app', 'env', 'service', 'status', 'level', 'since', 'search', 'sort', 'limit', 'cursor'],
|
|
120
|
+
issue: ['event'],
|
|
121
|
+
releases: ['app', 'env', 'service', 'limit', 'cursor'],
|
|
122
|
+
health: ['app', 'env', 'service'],
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface Args {
|
|
126
|
+
readonly positional: readonly string[]
|
|
127
|
+
readonly options: ReadonlyMap<string, string>
|
|
128
|
+
readonly json: boolean
|
|
129
|
+
readonly url: string | undefined
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const usageError = (message: string): OperationsCliError => new OperationsCliError(OPERATIONS_EXIT.usage, message)
|
|
133
|
+
|
|
134
|
+
const parseArgs = (command: string, argv: readonly string[]): Args => {
|
|
135
|
+
const allowed = COMMAND_OPTIONS[command] ?? []
|
|
136
|
+
const positional: string[] = []
|
|
137
|
+
const options = new Map<string, string>()
|
|
138
|
+
let json = false
|
|
139
|
+
let url: string | undefined
|
|
140
|
+
for (const arg of argv) {
|
|
141
|
+
if (arg === '--json') {
|
|
142
|
+
json = true
|
|
143
|
+
continue
|
|
144
|
+
}
|
|
145
|
+
if (!arg.startsWith('-')) {
|
|
146
|
+
positional.push(arg)
|
|
147
|
+
continue
|
|
148
|
+
}
|
|
149
|
+
const eq = arg.indexOf('=')
|
|
150
|
+
const name = eq === -1 ? arg.replace(/^-+/, '') : arg.slice(2, eq)
|
|
151
|
+
if (!arg.startsWith('--') || (name !== 'url' && !allowed.includes(name))) {
|
|
152
|
+
throw usageError(`Unknown option for \`operations ${command}\`: ${arg}`)
|
|
153
|
+
}
|
|
154
|
+
if (eq === -1 || arg.slice(eq + 1) === '') throw usageError(`Option --${name} needs a value: --${name}=<value>`)
|
|
155
|
+
if (name === 'url') url = arg.slice(eq + 1)
|
|
156
|
+
else options.set(name, arg.slice(eq + 1))
|
|
157
|
+
}
|
|
158
|
+
return { positional, options, json, url }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const oneOf = <T extends string>(args: Args, name: string, allowed: readonly T[]): T | undefined => {
|
|
162
|
+
const value = args.options.get(name)
|
|
163
|
+
if (value === undefined) return undefined
|
|
164
|
+
const match = allowed.find((candidate) => candidate === value)
|
|
165
|
+
if (match === undefined) throw usageError(`--${name} is one of ${allowed.join(', ')}, not "${value}"`)
|
|
166
|
+
return match
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const pageLimit = (args: Args): number | undefined => {
|
|
170
|
+
const value = args.options.get('limit')
|
|
171
|
+
if (value === undefined) return undefined
|
|
172
|
+
const limit = Number(value)
|
|
173
|
+
if (!/^\d+$/.test(value) || limit < 1 || limit > 100) throw usageError(`--limit is a whole number from 1 to 100, not "${value}"`)
|
|
174
|
+
return limit
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
interface SourceFilter {
|
|
178
|
+
readonly app: string | undefined
|
|
179
|
+
readonly env: string | undefined
|
|
180
|
+
readonly service: string | undefined
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const sourceFilter = (args: Args): SourceFilter => ({
|
|
184
|
+
app: args.options.get('app'),
|
|
185
|
+
env: args.options.get('env'),
|
|
186
|
+
service: args.options.get('service'),
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
const filters = (filter: SourceFilter): boolean => filter.app !== undefined || filter.env !== undefined || filter.service !== undefined
|
|
190
|
+
|
|
191
|
+
const selects = (filter: SourceFilter, source: OperationsSourceSummaryDto): boolean =>
|
|
192
|
+
(filter.app === undefined || source.appId === filter.app)
|
|
193
|
+
&& (filter.env === undefined || source.environment === filter.env)
|
|
194
|
+
&& (filter.service === undefined || source.serviceKey === filter.service)
|
|
195
|
+
|
|
196
|
+
const filterLabel = (filter: SourceFilter): string =>
|
|
197
|
+
[
|
|
198
|
+
filter.app === undefined ? null : `--app=${filter.app}`,
|
|
199
|
+
filter.env === undefined ? null : `--env=${filter.env}`,
|
|
200
|
+
filter.service === undefined
|
|
201
|
+
? null
|
|
202
|
+
: `--service=${filter.service}`,
|
|
203
|
+
]
|
|
204
|
+
.filter((part) => part !== null)
|
|
205
|
+
.join(' ')
|
|
206
|
+
|
|
207
|
+
const noPositional = (command: string, args: Args): void => {
|
|
208
|
+
if (args.positional.length > 0) throw usageError(`\`operations ${command}\` takes no argument: ${args.positional.join(' ')}`)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ── Answers, parsed where they enter ──────────────────────────────────────────────────────────────────────────────
|
|
212
|
+
// Each schema projects the DTO's known fields: a field a newer Operations adds is dropped, never printed.
|
|
213
|
+
|
|
214
|
+
const unreadable = (what: string): OperationsCliError => new OperationsCliError(OPERATIONS_EXIT.failed, `Operations returned an unreadable ${what}`)
|
|
215
|
+
|
|
216
|
+
const parse = <T>(schema: z.ZodType<T, z.ZodTypeDef, unknown>, value: unknown, what: string): T => {
|
|
217
|
+
const parsed = schema.safeParse(value)
|
|
218
|
+
if (!parsed.success) throw unreadable(what)
|
|
219
|
+
return parsed.data
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const time = z.number().finite()
|
|
223
|
+
const issueStatus = z.enum(['open', 'resolved', 'ignored'])
|
|
224
|
+
|
|
225
|
+
const sourceSchema: z.ZodType<OperationsSourceSummaryDto, z.ZodTypeDef, unknown> = z.object({
|
|
226
|
+
id: z.string(),
|
|
227
|
+
appId: z.string(),
|
|
228
|
+
environment: z.string(),
|
|
229
|
+
serviceKey: z.string(),
|
|
230
|
+
displayName: z.string(),
|
|
231
|
+
publicOrigin: z.string().nullable(),
|
|
232
|
+
enabled: z.boolean(),
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
const sourceListSchema: z.ZodType<OperationsSourceListResponseDto, z.ZodTypeDef, unknown> = z.object({ items: z.array(sourceSchema) })
|
|
236
|
+
|
|
237
|
+
const issueSummaryFields = {
|
|
238
|
+
id: z.string(),
|
|
239
|
+
source: sourceSchema,
|
|
240
|
+
title: z.string(),
|
|
241
|
+
culprit: z.string().nullable(),
|
|
242
|
+
level: z.string(),
|
|
243
|
+
status: issueStatus,
|
|
244
|
+
assignedTo: z.object({ id: z.string(), label: z.string().nullable() }).nullable(),
|
|
245
|
+
regressedAt: time.nullable(),
|
|
246
|
+
firstSeen: time,
|
|
247
|
+
lastSeen: time,
|
|
248
|
+
count: z.number().int().nonnegative(),
|
|
249
|
+
trend: z.array(z.number()),
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const issueSummarySchema: z.ZodType<OperationsIssueSummaryDto, z.ZodTypeDef, unknown> = z.object(issueSummaryFields)
|
|
253
|
+
|
|
254
|
+
const issueListSchema: z.ZodType<OperationsIssueListResponseDto, z.ZodTypeDef, unknown> = z.object({
|
|
255
|
+
items: z.array(issueSummarySchema),
|
|
256
|
+
nextCursor: z.string().nullable(),
|
|
257
|
+
summary: z.object({
|
|
258
|
+
total: z.number().int().nonnegative(),
|
|
259
|
+
open: z.number().int().nonnegative(),
|
|
260
|
+
resolved: z.number().int().nonnegative(),
|
|
261
|
+
ignored: z.number().int().nonnegative(),
|
|
262
|
+
}),
|
|
263
|
+
})
|
|
264
|
+
|
|
265
|
+
const occurrenceSchema: z.ZodType<OperationsIssueOccurrenceDto, z.ZodTypeDef, unknown> = z.object({
|
|
266
|
+
id: z.string(),
|
|
267
|
+
eventId: z.string(),
|
|
268
|
+
receivedAt: time,
|
|
269
|
+
release: z.string().nullable(),
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
const activitySchema: z.ZodType<ActivityItem, z.ZodTypeDef, unknown> = z.object({
|
|
273
|
+
id: z.string(),
|
|
274
|
+
kind: z.enum(['comment', 'status', 'assigned', 'regressed', 'snoozed', 'unsnoozed', 'merged']),
|
|
275
|
+
actorLabel: z.string().nullable(),
|
|
276
|
+
data: z.record(z.unknown()).nullable(),
|
|
277
|
+
at: time,
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
const issueDetailSchema: z.ZodType<OperationsIssueDetailResponseDto, z.ZodTypeDef, unknown> = z.object({
|
|
281
|
+
issue: z.object({
|
|
282
|
+
...issueSummaryFields,
|
|
283
|
+
snoozeUntil: time.nullable(),
|
|
284
|
+
snoozeUntilCount: z.number().nullable(),
|
|
285
|
+
resolvedInRelease: z.object({ id: z.string(), name: z.string() }).nullable(),
|
|
286
|
+
mergedIntoIssueId: z.string().nullable(),
|
|
287
|
+
activity: z.array(activitySchema),
|
|
288
|
+
latestOccurrence: occurrenceSchema.nullable(),
|
|
289
|
+
occurrences: z.array(occurrenceSchema),
|
|
290
|
+
occurrencesNextCursor: z.string().nullable(),
|
|
291
|
+
}),
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
const frameSchema: z.ZodType<DisplayFrame, z.ZodTypeDef, unknown> = z.object({
|
|
295
|
+
file: z.string(),
|
|
296
|
+
function: z.string().nullable(),
|
|
297
|
+
line: z.number().nullable(),
|
|
298
|
+
column: z.number().nullable(),
|
|
299
|
+
inApp: z.boolean(),
|
|
300
|
+
resolved: z.boolean(),
|
|
301
|
+
source: z.object({ lines: z.array(z.string()), errorIndex: z.number(), startLine: z.number() }).optional(),
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
const exceptionSchema: z.ZodType<EventException, z.ZodTypeDef, unknown> = z.object({
|
|
305
|
+
type: z.string().nullable(),
|
|
306
|
+
value: z.string().nullable(),
|
|
307
|
+
handled: z.boolean().nullable(),
|
|
308
|
+
frames: z.array(frameSchema),
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
const breadcrumbSchema: z.ZodType<EventBreadcrumb, z.ZodTypeDef, unknown> = z.object({
|
|
312
|
+
timestamp: z.union([z.number(), z.string()]).optional(),
|
|
313
|
+
type: z.string().optional(),
|
|
314
|
+
category: z.string().optional(),
|
|
315
|
+
level: z.string().optional(),
|
|
316
|
+
message: z.string().optional(),
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
const eventDetailSchema: z.ZodType<EventDetail, z.ZodTypeDef, unknown> = z.object({
|
|
320
|
+
eventId: z.string().nullable(),
|
|
321
|
+
platform: z.string().nullable(),
|
|
322
|
+
release: z.string().nullable(),
|
|
323
|
+
environment: z.string().nullable(),
|
|
324
|
+
tags: z.array(z.object({ key: z.string(), value: z.string() })),
|
|
325
|
+
request: z.object({ url: z.string().nullable(), method: z.string().nullable() }).nullable(),
|
|
326
|
+
user: z.object({ id: z.string().nullable(), email: z.string().nullable(), username: z.string().nullable() }).nullable(),
|
|
327
|
+
breadcrumbs: z.array(breadcrumbSchema),
|
|
328
|
+
runtime: z.string().nullable(),
|
|
329
|
+
os: z.string().nullable(),
|
|
330
|
+
serverName: z.string().nullable(),
|
|
331
|
+
traceId: z.string().nullable(),
|
|
332
|
+
exceptions: z.array(exceptionSchema),
|
|
333
|
+
rawEvent: z.string(),
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
const eventSchema: z.ZodType<OperationsEventDetailResponseDto, z.ZodTypeDef, unknown> = z.object({
|
|
337
|
+
occurrenceId: z.string(),
|
|
338
|
+
receivedAt: time,
|
|
339
|
+
detail: eventDetailSchema,
|
|
340
|
+
})
|
|
341
|
+
|
|
342
|
+
const releaseSchema: z.ZodType<OperationsReleaseSummaryDto, z.ZodTypeDef, unknown> = z.object({
|
|
343
|
+
id: z.string(),
|
|
344
|
+
source: sourceSchema,
|
|
345
|
+
runId: z.string(),
|
|
346
|
+
commitSha: z.string(),
|
|
347
|
+
state: z.string(),
|
|
348
|
+
artifactState: z.enum(['pending', 'complete', 'incomplete', 'not_applicable']),
|
|
349
|
+
releaseName: z.string(),
|
|
350
|
+
createdAt: time,
|
|
351
|
+
finishedAt: time.nullable(),
|
|
352
|
+
newIssueCount: z.number().int().nonnegative(),
|
|
353
|
+
regressionCount: z.number().int().nonnegative(),
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
const releaseListSchema: z.ZodType<OperationsReleaseListResponseDto, z.ZodTypeDef, unknown> = z.object({
|
|
357
|
+
items: z.array(releaseSchema),
|
|
358
|
+
nextCursor: z.string().nullable(),
|
|
359
|
+
})
|
|
360
|
+
|
|
361
|
+
const healthState = z.enum(['healthy', 'degraded', 'failed', 'stale', 'unavailable'])
|
|
362
|
+
|
|
363
|
+
const healthCheckSchema: z.ZodType<OperationsHealthCheckDto, z.ZodTypeDef, unknown> = z.object({
|
|
364
|
+
id: z.string(),
|
|
365
|
+
sourceId: z.string(),
|
|
366
|
+
path: z.string(),
|
|
367
|
+
enabled: z.boolean(),
|
|
368
|
+
intervalMs: z.number(),
|
|
369
|
+
timeoutMs: z.number(),
|
|
370
|
+
expectedStatus: z.number(),
|
|
371
|
+
failureThreshold: z.number(),
|
|
372
|
+
recoveryThreshold: z.number(),
|
|
373
|
+
staleAfterMs: z.number(),
|
|
374
|
+
current: z.object({
|
|
375
|
+
state: z.enum(['healthy', 'degraded', 'failed', 'stale']),
|
|
376
|
+
observedAt: time,
|
|
377
|
+
latencyMs: z.number().nullable(),
|
|
378
|
+
detailCode: z.string(),
|
|
379
|
+
consecutiveFailures: z.number().int().nonnegative(),
|
|
380
|
+
consecutiveSuccesses: z.number().int().nonnegative(),
|
|
381
|
+
}).nullable(),
|
|
382
|
+
history: z.array(z.object({
|
|
383
|
+
id: z.string(),
|
|
384
|
+
state: healthState,
|
|
385
|
+
observedAt: time,
|
|
386
|
+
latencyMs: z.number().nullable(),
|
|
387
|
+
detailCode: z.string().nullable(),
|
|
388
|
+
successful: z.boolean(),
|
|
389
|
+
statusCode: z.number().nullable(),
|
|
390
|
+
})),
|
|
391
|
+
})
|
|
392
|
+
|
|
393
|
+
const sourceHealthSchema: z.ZodType<OperationsSourceHealthDto, z.ZodTypeDef, unknown> = z.object({
|
|
394
|
+
source: sourceSchema,
|
|
395
|
+
httpChecks: z.array(healthCheckSchema),
|
|
396
|
+
telemetryState: healthState,
|
|
397
|
+
})
|
|
398
|
+
|
|
399
|
+
const healthSchema: z.ZodType<OperationsHealthResponseDto, z.ZodTypeDef, unknown> = z.object({ sources: z.array(sourceHealthSchema) })
|
|
400
|
+
|
|
401
|
+
const consoleAccessSchema: z.ZodType<ConsoleAccessDto, z.ZodTypeDef, unknown> = z.object({
|
|
402
|
+
principal: z.object({ id: z.string(), label: z.string() }).nullable(),
|
|
403
|
+
global: z.array(z.string()),
|
|
404
|
+
scopes: z.array(z.object({ type: z.string(), value: z.string(), actions: z.array(z.string()) })),
|
|
405
|
+
})
|
|
406
|
+
|
|
407
|
+
// ── Output ────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
408
|
+
|
|
409
|
+
/** Operations' times are Unix milliseconds. */
|
|
410
|
+
const iso = (milliseconds: number): string => new Date(milliseconds).toISOString()
|
|
411
|
+
|
|
412
|
+
const isoOrDash = (milliseconds: number | null): string => milliseconds === null ? '-' : iso(milliseconds)
|
|
413
|
+
|
|
414
|
+
/** One cell of a row: untrusted text loses its control characters, and a tab or line break would split the row. */
|
|
415
|
+
const cell = (value: string | number | boolean | null | undefined): string => {
|
|
416
|
+
if (value === null || value === undefined || value === '') return '-'
|
|
417
|
+
return printable(String(value)).replace(/[\t\n]+/g, ' ')
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const row = (...cells: readonly (string | number | boolean | null | undefined)[]): string => cells.map(cell).join('\t')
|
|
421
|
+
|
|
422
|
+
const sourceCells = (source: OperationsSourceSummaryDto): string[] => [source.appId, source.environment, source.serviceKey]
|
|
423
|
+
|
|
424
|
+
const issueRow = (issue: OperationsIssueSummaryDto): string =>
|
|
425
|
+
row(issue.id, issue.status, issue.level, issue.count, iso(issue.lastSeen), ...sourceCells(issue.source), issue.title)
|
|
426
|
+
|
|
427
|
+
const releaseRow = (release: OperationsReleaseSummaryDto): string =>
|
|
428
|
+
row(
|
|
429
|
+
release.id,
|
|
430
|
+
release.state,
|
|
431
|
+
release.artifactState,
|
|
432
|
+
release.releaseName,
|
|
433
|
+
release.commitSha,
|
|
434
|
+
iso(release.createdAt),
|
|
435
|
+
isoOrDash(release.finishedAt),
|
|
436
|
+
release.newIssueCount,
|
|
437
|
+
release.regressionCount,
|
|
438
|
+
...sourceCells(release.source),
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
const checkState = (check: OperationsHealthCheckDto): string => !check.enabled ? 'disabled' : check.current?.state ?? 'pending'
|
|
442
|
+
|
|
443
|
+
const healthLines = (health: OperationsSourceHealthDto): string[] => [
|
|
444
|
+
row('source', ...sourceCells(health.source), health.telemetryState),
|
|
445
|
+
...health.httpChecks.map((check) =>
|
|
446
|
+
row(
|
|
447
|
+
'check',
|
|
448
|
+
...sourceCells(health.source),
|
|
449
|
+
check.path,
|
|
450
|
+
checkState(check),
|
|
451
|
+
isoOrDash(check.current?.observedAt ?? null),
|
|
452
|
+
check.current?.latencyMs,
|
|
453
|
+
check.current?.detailCode,
|
|
454
|
+
check.current?.consecutiveFailures ?? 0,
|
|
455
|
+
)
|
|
456
|
+
),
|
|
457
|
+
]
|
|
458
|
+
|
|
459
|
+
/** Sentry gives a breadcrumb's time as Unix seconds, or as text the event wrote, which prints as given. */
|
|
460
|
+
const breadcrumbTime = (crumb: EventBreadcrumb): string | undefined =>
|
|
461
|
+
typeof crumb.timestamp === 'number' && Number.isFinite(crumb.timestamp) ? iso(crumb.timestamp * 1000) : crumb.timestamp?.toString()
|
|
462
|
+
|
|
463
|
+
const frameLocation = (frame: DisplayFrame): string => [frame.file, frame.line, frame.column].filter((part) => part !== null).join(':')
|
|
464
|
+
|
|
465
|
+
const eventLines = (event: OperationsEventDetailResponseDto): string[] => {
|
|
466
|
+
const detail = event.detail
|
|
467
|
+
return [
|
|
468
|
+
row('event', event.occurrenceId, iso(event.receivedAt), detail.eventId),
|
|
469
|
+
row('release', detail.release),
|
|
470
|
+
row('environment', detail.environment),
|
|
471
|
+
row('platform', detail.platform),
|
|
472
|
+
row('runtime', detail.runtime),
|
|
473
|
+
row('os', detail.os),
|
|
474
|
+
row('server', detail.serverName),
|
|
475
|
+
row('trace', detail.traceId),
|
|
476
|
+
...(detail.request === null ? [] : [row('request', detail.request.method, detail.request.url)]),
|
|
477
|
+
...(detail.user === null ? [] : [row('user', detail.user.id, detail.user.username, detail.user.email)]),
|
|
478
|
+
...detail.tags.map((tag) => row('tag', tag.key, tag.value)),
|
|
479
|
+
...detail.exceptions.flatMap((exception) => [
|
|
480
|
+
row('exception', exception.type, exception.handled === null ? null : exception.handled ? 'handled' : 'unhandled', exception.value),
|
|
481
|
+
...exception.frames.map((frame) => row('frame', frameLocation(frame), frame.function, frame.inApp ? 'app' : 'library')),
|
|
482
|
+
]),
|
|
483
|
+
...detail.breadcrumbs.map((crumb) => row('breadcrumb', breadcrumbTime(crumb), crumb.level, crumb.category ?? crumb.type, crumb.message)),
|
|
484
|
+
]
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const issueLines = (detail: OperationsIssueDetailResponseDto, event: OperationsEventDetailResponseDto | null): string[] => {
|
|
488
|
+
const issue = detail.issue
|
|
489
|
+
return [
|
|
490
|
+
row('id', issue.id),
|
|
491
|
+
row('title', issue.title),
|
|
492
|
+
row('culprit', issue.culprit),
|
|
493
|
+
row('status', issue.status),
|
|
494
|
+
row('level', issue.level),
|
|
495
|
+
row('source', ...sourceCells(issue.source)),
|
|
496
|
+
row('events', issue.count),
|
|
497
|
+
row('firstSeen', iso(issue.firstSeen)),
|
|
498
|
+
row('lastSeen', iso(issue.lastSeen)),
|
|
499
|
+
row('regressedAt', isoOrDash(issue.regressedAt)),
|
|
500
|
+
row('assignedTo', issue.assignedTo?.label ?? issue.assignedTo?.id),
|
|
501
|
+
row('snoozeUntil', isoOrDash(issue.snoozeUntil)),
|
|
502
|
+
row('snoozeUntilCount', issue.snoozeUntilCount),
|
|
503
|
+
row('resolvedInRelease', issue.resolvedInRelease?.name),
|
|
504
|
+
row('mergedInto', issue.mergedIntoIssueId),
|
|
505
|
+
...issue.activity.map((item) => row('activity', iso(item.at), item.kind, item.actorLabel, item.data === null ? null : JSON.stringify(item.data))),
|
|
506
|
+
...issue.occurrences.map((occurrence) => row('occurrence', occurrence.id, iso(occurrence.receivedAt), occurrence.eventId, occurrence.release)),
|
|
507
|
+
...(event === null ? [] : eventLines(event)),
|
|
508
|
+
]
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// ── Calls ─────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
512
|
+
|
|
513
|
+
interface Clients {
|
|
514
|
+
readonly operations: InferRpcClient<OperationsRpcContract>
|
|
515
|
+
readonly control: InferRpcClient<ControlRpcContract>
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const connect = (args: Args, io: OperationsIo): Clients => {
|
|
519
|
+
const key = io.env['FABRIKA_CONTROL_KEY']
|
|
520
|
+
if (key === undefined || key.trim() === '') {
|
|
521
|
+
throw new OperationsCliError(OPERATIONS_EXIT.credential, 'FABRIKA_CONTROL_KEY is required (environment only — it has no flag).')
|
|
522
|
+
}
|
|
523
|
+
let transport: ReturnType<typeof controlTransport>
|
|
524
|
+
try {
|
|
525
|
+
transport = controlTransport(args.url, io.env, io.fetch)
|
|
526
|
+
} catch (error) {
|
|
527
|
+
throw usageError(error instanceof Error ? error.message : String(error))
|
|
528
|
+
}
|
|
529
|
+
return {
|
|
530
|
+
operations: createRpcClient<OperationsRpcContract>({ baseUrl: `${transport.origin}/operations/api/rpc`, fetch: transport.fetch }),
|
|
531
|
+
control: createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch }),
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Operations answers a key without `operations.read` with empty lists, as it answers a key scoped elsewhere. The
|
|
537
|
+
* console's own navigation asks Control which actions the caller holds; so does this, to tell the two apart.
|
|
538
|
+
*/
|
|
539
|
+
const requireRead = async (clients: Clients): Promise<void> => {
|
|
540
|
+
const access = parse(consoleAccessSchema, await clients.control.consoleAccess(), 'console access')
|
|
541
|
+
const read = OPERATIONS_ACTIONS.READ
|
|
542
|
+
if (access.global.includes(read) || access.scopes.some((scope) => scope.actions.includes(read))) return
|
|
543
|
+
throw new OperationsCliError(
|
|
544
|
+
OPERATIONS_EXIT.credential,
|
|
545
|
+
`FABRIKA_CONTROL_KEY does not hold ${read} in any scope. Use a key of the console app narrowed to ${read}; see \`fabrika operations --help\`.`,
|
|
546
|
+
)
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** The one source `filter` selects, or none when it selects nothing in particular. */
|
|
550
|
+
const selectedSource = async (clients: Clients, filter: SourceFilter): Promise<OperationsSourceSummaryDto | undefined> => {
|
|
551
|
+
if (!filters(filter)) return undefined
|
|
552
|
+
const sources = parse(sourceListSchema, await clients.operations.sources(), 'source list').items.filter((source) => selects(filter, source))
|
|
553
|
+
const [only, ...others] = sources
|
|
554
|
+
if (only === undefined) {
|
|
555
|
+
throw new OperationsCliError(OPERATIONS_EXIT.notFound, `No Operations source matches ${filterLabel(filter)}, or the key may not read it`)
|
|
556
|
+
}
|
|
557
|
+
if (others.length > 0) {
|
|
558
|
+
const listed = sources.map((source) => ` ${row(...sourceCells(source))}`).join('\n')
|
|
559
|
+
throw usageError(`${filterLabel(filter)} matches ${sources.length} sources; add --env or --service to pick one:\n${listed}`)
|
|
560
|
+
}
|
|
561
|
+
return only
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* JSON whose text cannot drive a terminal: `JSON.stringify` escapes C0 controls only, so DEL, the C1 controls (U+009B
|
|
566
|
+
* opens a sequence like ESC [) and the line separators are escaped too. They can occur only inside strings.
|
|
567
|
+
*/
|
|
568
|
+
const escapedJson = (value: unknown): string =>
|
|
569
|
+
JSON.stringify(value, null, 2).replace(/[\u007f-\u009f\u2028\u2029]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)
|
|
570
|
+
|
|
571
|
+
const emit = (args: Args, io: OperationsIo, result: unknown, lines: () => readonly string[]): void => {
|
|
572
|
+
if (args.json) {
|
|
573
|
+
io.out(escapedJson(result))
|
|
574
|
+
return
|
|
575
|
+
}
|
|
576
|
+
const text = lines()
|
|
577
|
+
if (text.length > 0) io.out(text.join('\n'))
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const note = (io: OperationsIo, text: string): void => io.err(printable(text))
|
|
581
|
+
|
|
582
|
+
const runIssues = async (args: Args, io: OperationsIo): Promise<void> => {
|
|
583
|
+
noPositional('issues', args)
|
|
584
|
+
const status = oneOf(args, 'status', ['open', 'resolved', 'ignored'] as const)
|
|
585
|
+
const level = oneOf(args, 'level', ['fatal', 'error', 'warning', 'info'] as const)
|
|
586
|
+
const window = oneOf(args, 'since', ['24h', '7d', '30d', 'all'] as const)
|
|
587
|
+
const sort = oneOf(args, 'sort', ['recent', 'new', 'frequency'] as const)
|
|
588
|
+
const limit = pageLimit(args)
|
|
589
|
+
const search = args.options.get('search')
|
|
590
|
+
const cursor = args.options.get('cursor')
|
|
591
|
+
const clients = connect(args, io)
|
|
592
|
+
await requireRead(clients)
|
|
593
|
+
const source = await selectedSource(clients, sourceFilter(args))
|
|
594
|
+
const query: OperationsIssueQuery = {
|
|
595
|
+
...(source === undefined ? {} : { sourceId: source.id }),
|
|
596
|
+
...(status === undefined ? {} : { status }),
|
|
597
|
+
...(level === undefined ? {} : { level }),
|
|
598
|
+
...(window === undefined ? {} : { window }),
|
|
599
|
+
...(search === undefined ? {} : { query: search }),
|
|
600
|
+
...(sort === undefined ? {} : { sort }),
|
|
601
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
602
|
+
...(limit === undefined ? {} : { limit }),
|
|
603
|
+
}
|
|
604
|
+
const page = parse(issueListSchema, await clients.operations.issues(query), 'issue list')
|
|
605
|
+
const { summary } = page
|
|
606
|
+
note(io, `${summary.total} issues in this selection, any status: ${summary.open} open, ${summary.resolved} resolved, ${summary.ignored} ignored`)
|
|
607
|
+
if (page.nextCursor !== null) note(io, `more issues match; the next page: the same options and --cursor=${page.nextCursor}`)
|
|
608
|
+
emit(args, io, page, () => page.items.map(issueRow))
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const runIssue = async (args: Args, io: OperationsIo): Promise<void> => {
|
|
612
|
+
const [issueId, ...extra] = args.positional
|
|
613
|
+
if (issueId === undefined || issueId.trim() === '' || extra.length > 0) {
|
|
614
|
+
throw usageError('Usage: fabrika operations issue <issueId> [--event=<occurrenceId>] [--json]')
|
|
615
|
+
}
|
|
616
|
+
const occurrenceId = args.options.get('event')
|
|
617
|
+
const clients = connect(args, io)
|
|
618
|
+
await requireRead(clients)
|
|
619
|
+
const detail = parse(issueDetailSchema, await clients.operations.issue({ issueId }), 'issue')
|
|
620
|
+
let event: OperationsEventDetailResponseDto | null = null
|
|
621
|
+
if (occurrenceId !== undefined) {
|
|
622
|
+
event = parse(eventSchema, await clients.operations.event({ issueId, occurrenceId }), 'event')
|
|
623
|
+
} else if (detail.issue.latestOccurrence !== null) {
|
|
624
|
+
try {
|
|
625
|
+
event = parse(eventSchema, await clients.operations.latestEvent({ issueId }), 'event')
|
|
626
|
+
} catch (error) {
|
|
627
|
+
// The issue was readable a moment ago, so a missing latest event is a payload no longer stored.
|
|
628
|
+
if (!(error instanceof RpcError) || error.httpStatus !== 404) throw error
|
|
629
|
+
note(io, 'the latest event is no longer stored')
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (detail.issue.occurrencesNextCursor !== null) {
|
|
633
|
+
note(io, `showing the ${detail.issue.occurrences.length} most recent events of ${detail.issue.count}`)
|
|
634
|
+
}
|
|
635
|
+
emit(args, io, { ...detail, event }, () => issueLines(detail, event))
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const runReleases = async (args: Args, io: OperationsIo): Promise<void> => {
|
|
639
|
+
noPositional('releases', args)
|
|
640
|
+
const limit = pageLimit(args)
|
|
641
|
+
const cursor = args.options.get('cursor')
|
|
642
|
+
const clients = connect(args, io)
|
|
643
|
+
await requireRead(clients)
|
|
644
|
+
const source = await selectedSource(clients, sourceFilter(args))
|
|
645
|
+
const query: OperationsReleaseQuery = {
|
|
646
|
+
...(source === undefined ? {} : { sourceId: source.id }),
|
|
647
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
648
|
+
...(limit === undefined ? {} : { limit }),
|
|
649
|
+
}
|
|
650
|
+
const page = parse(releaseListSchema, await clients.operations.releases(query), 'release list')
|
|
651
|
+
if (page.items.length === 0) note(io, 'no releases')
|
|
652
|
+
if (page.nextCursor !== null) note(io, `more releases exist; the next page: the same options and --cursor=${page.nextCursor}`)
|
|
653
|
+
emit(args, io, page, () => page.items.map(releaseRow))
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const runHealth = async (args: Args, io: OperationsIo): Promise<void> => {
|
|
657
|
+
noPositional('health', args)
|
|
658
|
+
const filter = sourceFilter(args)
|
|
659
|
+
const clients = connect(args, io)
|
|
660
|
+
await requireRead(clients)
|
|
661
|
+
const health = parse(healthSchema, await clients.operations.health(), 'health answer')
|
|
662
|
+
const sources = health.sources.filter((entry) => selects(filter, entry.source))
|
|
663
|
+
if (sources.length === 0) {
|
|
664
|
+
if (filters(filter)) {
|
|
665
|
+
throw new OperationsCliError(OPERATIONS_EXIT.notFound, `No Operations source matches ${filterLabel(filter)}, or the key may not read it`)
|
|
666
|
+
}
|
|
667
|
+
note(io, 'no Operations source is visible to this key')
|
|
668
|
+
}
|
|
669
|
+
emit(args, io, { sources }, () => sources.flatMap(healthLines))
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const COMMANDS: Readonly<Record<string, (args: Args, io: OperationsIo) => Promise<void>>> = {
|
|
673
|
+
issues: runIssues,
|
|
674
|
+
issue: runIssue,
|
|
675
|
+
releases: runReleases,
|
|
676
|
+
health: runHealth,
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** An RPC refusal mapped to its exit code; the type and message are the server's, cleaned before they print. */
|
|
680
|
+
const rpcFailure = (error: RpcError): OperationsCliError => {
|
|
681
|
+
const said = `${error.type}: ${error.message}`
|
|
682
|
+
// Not offered by this installation's release: a definite answer, not a missing record.
|
|
683
|
+
if (error.type === 'method_not_found') {
|
|
684
|
+
return new OperationsCliError(
|
|
685
|
+
OPERATIONS_EXIT.failed,
|
|
686
|
+
`This installation's release does not offer the call; retrying will not change that — ${said}`,
|
|
687
|
+
)
|
|
688
|
+
}
|
|
689
|
+
if (error.httpStatus === 401) {
|
|
690
|
+
return new OperationsCliError(OPERATIONS_EXIT.credential, `The console refused FABRIKA_CONTROL_KEY (unknown, expired or revoked) — ${said}`)
|
|
691
|
+
}
|
|
692
|
+
if (error.httpStatus === 403) return new OperationsCliError(OPERATIONS_EXIT.credential, `FABRIKA_CONTROL_KEY may not make this call — ${said}`)
|
|
693
|
+
if (error.httpStatus === 404 || error.type === 'not_found') {
|
|
694
|
+
return new OperationsCliError(OPERATIONS_EXIT.notFound, `Not found, or the key may not read it — ${said}`)
|
|
695
|
+
}
|
|
696
|
+
if (error.httpStatus === 400) return usageError(said)
|
|
697
|
+
return new OperationsCliError(OPERATIONS_EXIT.failed, said)
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Runs one command and returns its exit code; every diagnostic goes to stderr with the key cut out. */
|
|
701
|
+
export const runOperationsCli = async (command: string | undefined, argv: readonly string[], io: OperationsIo = processIo()): Promise<number> => {
|
|
702
|
+
if (command === undefined) {
|
|
703
|
+
io.out(USAGE)
|
|
704
|
+
return OPERATIONS_EXIT.ok
|
|
705
|
+
}
|
|
706
|
+
try {
|
|
707
|
+
const run = COMMANDS[command]
|
|
708
|
+
if (run === undefined) throw usageError(`Unknown operations command: ${command}\n\n${USAGE}`)
|
|
709
|
+
await run(parseArgs(command, argv), io)
|
|
710
|
+
return OPERATIONS_EXIT.ok
|
|
711
|
+
} catch (error) {
|
|
712
|
+
const failure = error instanceof OperationsCliError
|
|
713
|
+
? error
|
|
714
|
+
: error instanceof RpcError
|
|
715
|
+
? rpcFailure(error)
|
|
716
|
+
: new OperationsCliError(OPERATIONS_EXIT.failed, error instanceof Error ? error.message : String(error))
|
|
717
|
+
io.err(`fabrika: ${printable(withoutControlKey(failure.message, io.env))}`)
|
|
718
|
+
return failure.exitCode
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
export { USAGE as OPERATIONS_USAGE }
|
|
@@ -27,8 +27,6 @@ export declare const NOTHING_SEEDED: Seeded;
|
|
|
27
27
|
export declare class SeedProblem extends Error {
|
|
28
28
|
readonly name = "SeedProblem";
|
|
29
29
|
}
|
|
30
|
-
/** A path of this origin; a link the application issued is one (`/s/#px_…`). */
|
|
31
|
-
export declare function isLocalPath(path: string): boolean;
|
|
32
30
|
/** The seed module's path: `--seed`, relative to the root, or `dev/seed.ts` when it exists; `null` for none. */
|
|
33
31
|
export declare function seedPath(root: string, given: string | null): string | null;
|
|
34
32
|
/** The seed's default export, a function of the kit and the dev outbox. */
|
package/types/src/control.d.ts
CHANGED
|
@@ -1,28 +1,44 @@
|
|
|
1
|
-
import { type InferRpcClient } from '@fabrika/app';
|
|
1
|
+
import { type InferRpcClient, type RpcFetch } from '@fabrika/app';
|
|
2
2
|
import type { AppEnvDto, ControlRpcContract, DeploymentNamespaceDto, PlanDeploymentNamespaceResponse } from '@fabrika/control-contract';
|
|
3
|
-
declare const USAGE = "fabrika control \u2014 operate the Delivery control plane\n\nUsage:\n fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]\n fabrika control apps list\n fabrika control apps get --app=<id>\n fabrika control apps environments list --app=<id>\n fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]\n [--cross-origin=<origin> ...] [--kind=standard|dev]\n fabrika control apps variables list --app=<id>\n fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>]\n fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]\n fabrika control apps secrets list --app=<id>\n fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)\n fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>]\n fabrika control register --provider=<name> --app=<id> --repo=<url> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>]\n [--namespace=<id>] [--installation-id=<n|none>] [--cross-origin=<origin> ...]\n fabrika control namespaces list\n fabrika control namespaces get --namespace=<id>\n fabrika control namespaces plan --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces create --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces reconcile --namespace=<id>\n fabrika control namespaces update --namespace=<id> --proxy-source=current\n fabrika control namespaces remove --namespace=<id>\n fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>\n fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]\n fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]\n fabrika control runs get --run=<id>\n fabrika control runs log --run=<id>\n\n`register` CREATES an app and refuses a second one with the same id. Re-registering a changed\nmanifest \u2014 a new `zerops.yaml`, a new import document \u2014 is `apps environments put`, which replaces\none environment's envelopes and leaves the app row alone.\n\nA manifest that publishes the app through the namespace proxy is routed by HOST, so `--domain` is\nREQUIRED for it \u2014 on `register` and on `apps environments put` alike \u2014 and a registration without one is\nrefused before anything is created. `namespaces get` lists the hosts a `zerops-subdomain` namespace\nserves and which of them are still free; a custom-domain namespace serves the domain you bound to its\nproxy. A manifest with no proxy target needs no domain.\n\nA variable's value is stored and printed in clear. A secret's value is write-only: `apps secrets put`\nreads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and\none trailing newline is dropped. No command prints it back; `apps secrets list` shows names, scope and\nstorage only. Generate one in the pipe:\n\n openssl rand -base64 32 | fabrika control apps secrets put --app=<id> --name=<name>\n\n`--public-origin` is where IAM may return a signed-in person: without one, sign-in to the environment is\nrefused. When `register` is given none and the namespace lists `--domain` among its hosts, it sets\n`https://<domain>` and says so on stderr. A custom domain needs the flag.\n\n`--cross-origin` names an origin whose pages may call the environment's cross-origin endpoints (ADR-0022), and\nrepeats: the flags given are the environment's whole list. Each is an exact origin with a literal host\n(`https://app.example.com`; `http://` only for a local one), never the environment's own domain, at most 16.\n`apps environments put` without the flag keeps the stored list, and a lone empty `--cross-origin=` clears it.\nOn Zerops the change reaches the namespace proxy at once; on Cloudflare the next deploy of the environment\napplies it.\n\n`--installation-id` has three states: omitted resolves the installation from the organization's\nconnected GitHub App, `none` registers an anonymous PUBLIC repository source, and a number names one\ninstallation outright. With `none`, control reads the repository once without a token and refuses one\nGitHub hides: a private repository needs the GitHub App connected in the console first.\n\n`--trigger-ref` is the git ref whose push deploys the environment; without it the environment deploys only\non `deploy`. A bare name is a branch: `--trigger-ref=deploy/prod` is stored as `refs/heads/deploy/prod`.\nA full ref is kept as given: `refs/heads/<branch>`, `refs/tags/<tag>`, or a `*` glob such as\n`refs/tags/v*`, which deploys every matching tag. A tag always needs the `refs/tags/` form. Each\nenvironment of an app needs its own trigger ref.\n\nNamespace placement options, each defaulting to what the preset would choose:\n\n --project=<name> the provider project the namespace owns; on Zerops the default is\n fabrika-<env>-<namespace id>, beside the installation's fabrika-<env>\n --core-package=<LIGHT|SERIOUS> defaults to LIGHT on every environment, `prod` included (ADR-0038).\n SERIOUS is a deliberate choice: a project cannot be downgraded again\n --public-access=<custom-domain|zerops-subdomain>\n --exclusive-app=<id> required by, and only by, the `full` preset\n --postgres-type=<type> the `cheap` preset's shared PostgreSQL; on Zerops postgresql:single@18\n (default) or postgresql:ha@18, which keeps its data through a node loss.\n Fixed once created\n --postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,\n oltp-staging (about $11) or oltp-production (about $72) for HA\n\n`namespaces plan` is a preview and changes nothing. It prints one `<path>\\t<value>` row per field of\nthe plan, keyed by its path in `--json`; a multi-line value such as the proxy's descriptor file is shown\nby size only. `namespaces create` commits that exact plan \u2014 the\nsame two steps the console's form takes \u2014 and returns as soon as the placement is recorded: provisioning\nruns behind the control queue and takes minutes, so the state comes back `pending`. Follow it with\n`namespaces get` or `namespaces list`; nothing needs to stay connected. `namespaces remove` frees the id\nof a placement no application is registered in. It deletes nothing at the provider and prints, on stderr,\nthe provider resources it stopped tracking. `namespaces update --proxy-source=current` re-pins a placement's\nproxy to the source this control plane deploys new placements from \u2014 a placement keeps the one it was created\nwith until you do \u2014 and queues the reconcile that rebuilds the proxy from it; a `failed` placement accepts it.\n\n`namespaces release-claims` frees the resource names one app environment holds in a placement, which an\nenvironment or app delete otherwise refuses over. Delete those resources at the provider first: the release\nreads each one back and refuses, naming it, while any still exists. It prints one released key per line.\n\nEvery command accepts --json, which prints the procedure's result verbatim.\n\nThe control origin is not a credential and takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nCredentials are read from the ENVIRONMENT ONLY and have no flag, so they cannot reach a CI log or a\nprocess listing:\n\n FABRIKA_CONTROL_KEY required a machine `px_` credential for the control app\n\n`key issue` mints that credential and therefore authenticates differently \u2014 it presents the\ninstallation's IAM RPC key as transport authentication and its provisioning key as the ISSUING\ncredential. Every key expires: `--expires-in` is required and at most 2592000 (30 days). Both\ncredentials are read from the environment only:\n\n FABRIKA_IAM_RPC_URL required IAM's PUBLIC origin, or --iam-url\n FABRIKA_IAM_RPC_KEY required the installation's IAM RPC key\n FABRIKA_IAM_PROVISIONING_KEY required the installation's seeded `px_` provisioning key\n FABRIKA_CONTROL_APP_ID optional the control app's IAM id (default `vozka`)\n\nThe PUBLIC origin is the `https://` address the installation answers on \u2014 the one `platform admin`\nand `platform init` print in their closing block, and the value `FABRIKA_IAM_ISSUER` holds on the\ncontrol service. It is NOT the private hostname the services use between themselves: `http://iam:3000`\nresolves inside the provider's project and nowhere else, so from here it only ever fails to connect.\n\nConnecting a GitHub source is NOT here and will not be: App creation is a browser flow whose\nauthorization requires a human principal (ADR-0029). Use Settings \u2192 Source in the console.\n";
|
|
3
|
+
declare const USAGE = "fabrika control \u2014 operate the Delivery control plane\n\nUsage:\n fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]\n fabrika control apps list\n fabrika control apps get --app=<id>\n fabrika control apps environments list --app=<id>\n fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]\n [--cross-origin=<origin> ...] [--kind=standard|dev]\n fabrika control apps variables list --app=<id>\n fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret]\n fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]\n fabrika control apps secrets list --app=<id>\n fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)\n fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>]\n fabrika control register --provider=<name> --app=<id> --repo=<url> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>]\n [--namespace=<id>] [--installation-id=<n|none>] [--cross-origin=<origin> ...]\n fabrika control namespaces list\n fabrika control namespaces get --namespace=<id>\n fabrika control namespaces plan --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces create --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces reconcile --namespace=<id>\n fabrika control namespaces update --namespace=<id> --proxy-source=current\n fabrika control namespaces remove --namespace=<id>\n fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>\n fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]\n fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]\n fabrika control runs get --run=<id>\n fabrika control runs log --run=<id>\n\n`register` CREATES an app and refuses a second one with the same id. Re-registering a changed\nmanifest \u2014 a new `zerops.yaml`, a new import document \u2014 is `apps environments put`, which replaces\none environment's envelopes and leaves the app row alone.\n\nA manifest that publishes the app through the namespace proxy is routed by HOST, so `--domain` is\nREQUIRED for it \u2014 on `register` and on `apps environments put` alike \u2014 and a registration without one is\nrefused before anything is created. `namespaces get` lists the hosts a `zerops-subdomain` namespace\nserves and which of them are still free; a custom-domain namespace serves the domain you bound to its\nproxy. A manifest with no proxy target needs no domain.\n\nA variable's value is stored and printed in clear, so `apps variables put` refuses one that looks like a\ncredential (by its name, such as `*_TOKEN` or `*_PASSWORD`, or by its value) and names `apps secrets put` instead.\n`--not-secret` stores it anyway, for a value you have checked is not one. A secret's value is write-only: `apps secrets put`\nreads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and\none trailing newline is dropped. No command prints it back; `apps secrets list` shows names, scope and\nstorage only. Generate one in the pipe:\n\n openssl rand -base64 32 | fabrika control apps secrets put --app=<id> --name=<name>\n\n`--public-origin` is where IAM may return a signed-in person: without one, sign-in to the environment is\nrefused. When `register` is given none and the namespace lists `--domain` among its hosts, it sets\n`https://<domain>` and says so on stderr. A custom domain needs the flag.\n\n`--cross-origin` names an origin whose pages may call the environment's cross-origin endpoints (ADR-0022), and\nrepeats: the flags given are the environment's whole list. Each is an exact origin with a literal host\n(`https://app.example.com`; `http://` only for a local one), never the environment's own domain, at most 16.\n`apps environments put` without the flag keeps the stored list, and a lone empty `--cross-origin=` clears it.\nOn Zerops the change reaches the namespace proxy at once; on Cloudflare the next deploy of the environment\napplies it.\n\n`--installation-id` has three states: omitted resolves the installation from the organization's\nconnected GitHub App, `none` registers an anonymous PUBLIC repository source, and a number names one\ninstallation outright. With `none`, control reads the repository once without a token and refuses one\nGitHub hides: a private repository needs the GitHub App connected in the console first.\n\n`--trigger-ref` is the git ref whose push deploys the environment; without it the environment deploys only\non `deploy`. A bare name is a branch: `--trigger-ref=deploy/prod` is stored as `refs/heads/deploy/prod`.\nA full ref is kept as given: `refs/heads/<branch>`, `refs/tags/<tag>`, or a `*` glob such as\n`refs/tags/v*`, which deploys every matching tag. A tag always needs the `refs/tags/` form. Each\nenvironment of an app needs its own trigger ref. Branches named `fabrika/\u2026` are reserved for MCP\nworkspaces and are never a trigger ref.\n\nNamespace placement options, each defaulting to what the preset would choose:\n\n --project=<name> the provider project the namespace owns; on Zerops the default is\n fabrika-<env>-<namespace id>, beside the installation's fabrika-<env>\n --core-package=<LIGHT|SERIOUS> defaults to LIGHT on every environment, `prod` included (ADR-0038).\n SERIOUS is a deliberate choice: a project cannot be downgraded again\n --public-access=<custom-domain|zerops-subdomain>\n --exclusive-app=<id> required by, and only by, the `full` preset\n --postgres-type=<type> the `cheap` preset's shared PostgreSQL; on Zerops postgresql:single@18\n (default) or postgresql:ha@18, which keeps its data through a node loss.\n Fixed once created\n --postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,\n oltp-staging (about $11) or oltp-production (about $72) for HA\n\n`namespaces plan` is a preview and changes nothing. It prints one `<path>\\t<value>` row per field of\nthe plan, keyed by its path in `--json`; a multi-line value such as the proxy's descriptor file is shown\nby size only. `namespaces create` commits that exact plan \u2014 the\nsame two steps the console's form takes \u2014 and returns as soon as the placement is recorded: provisioning\nruns behind the control queue and takes minutes, so the state comes back `pending`. Follow it with\n`namespaces get` or `namespaces list`; nothing needs to stay connected. `namespaces remove` frees the id\nof a placement no application is registered in. It deletes nothing at the provider and prints, on stderr,\nthe provider resources it stopped tracking. `namespaces update --proxy-source=current` re-pins a placement's\nproxy to the source this control plane deploys new placements from \u2014 a placement keeps the one it was created\nwith until you do \u2014 and queues the reconcile that rebuilds the proxy from it; a `failed` placement accepts it.\n\n`namespaces release-claims` frees the resource names one app environment holds in a placement, which an\nenvironment or app delete otherwise refuses over. Delete those resources at the provider first: the release\nreads each one back and refuses, naming it, while any still exists. It prints one released key per line.\n\nEvery command accepts --json, which prints the procedure's result verbatim.\n\nThe control origin is not a credential and takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nCredentials are read from the ENVIRONMENT ONLY and have no flag, so they cannot reach a CI log or a\nprocess listing:\n\n FABRIKA_CONTROL_KEY required a machine `px_` credential for the control app\n\n`key issue` mints that credential and therefore authenticates differently \u2014 it presents the\ninstallation's IAM RPC key as transport authentication and its provisioning key as the ISSUING\ncredential. Every key expires: `--expires-in` is required and at most 2592000 (30 days). Both\ncredentials are read from the environment only:\n\n FABRIKA_IAM_RPC_URL required IAM's PUBLIC origin, or --iam-url\n FABRIKA_IAM_RPC_KEY required the installation's IAM RPC key\n FABRIKA_IAM_PROVISIONING_KEY required the installation's seeded `px_` provisioning key\n FABRIKA_CONTROL_APP_ID optional the control app's IAM id (default `vozka`)\n\nThe PUBLIC origin is the `https://` address the installation answers on \u2014 the one `platform admin`\nand `platform init` print in their closing block, and the value `FABRIKA_IAM_ISSUER` holds on the\ncontrol service. It is NOT the private hostname the services use between themselves: `http://iam:3000`\nresolves inside the provider's project and nowhere else, so from here it only ever fails to connect.\n\nConnecting a GitHub source is NOT here and will not be: App creation is a browser flow whose\nauthorization requires a human principal (ADR-0029). Use Settings \u2192 Source in the console.\n";
|
|
4
4
|
interface Flags {
|
|
5
5
|
readonly values: ReadonlyMap<string, string>;
|
|
6
6
|
/** Every value of every option, in order; `values` keeps the last. Only a repeatable option reads it. */
|
|
7
7
|
readonly repeated: ReadonlyMap<string, readonly string[]>;
|
|
8
8
|
readonly json: boolean;
|
|
9
|
+
/** `--not-secret`: `apps variables put` stores a value that looks like a credential. */
|
|
10
|
+
readonly notSecret: boolean;
|
|
9
11
|
readonly positional: readonly string[];
|
|
10
12
|
}
|
|
11
|
-
/** Split `--key=value` options from positional words; `--json` is the one flag every verb shares. */
|
|
13
|
+
/** Split `--key=value` options from positional words; `--json` is the one flag every verb shares, `--not-secret` the other bare one. */
|
|
12
14
|
export declare const parseControlFlags: (argv: readonly string[]) => Flags;
|
|
13
15
|
/** The console's client with a bearer instead of a cookie, and no SSO bounce: there is no browser to send. */
|
|
14
16
|
export type ControlClient = InferRpcClient<ControlRpcContract>;
|
|
17
|
+
/** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
|
|
18
|
+
interface OriginSource {
|
|
19
|
+
readonly label: string;
|
|
20
|
+
readonly flag: string;
|
|
21
|
+
readonly variable: string;
|
|
22
|
+
readonly hint?: string;
|
|
23
|
+
}
|
|
15
24
|
/**
|
|
16
|
-
*
|
|
17
|
-
* and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
|
|
25
|
+
* An origin a credential is sent to, checked before the credential goes anywhere: https, or http to a loopback host for
|
|
26
|
+
* local development, and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
|
|
18
27
|
*/
|
|
19
|
-
export declare const
|
|
28
|
+
export declare const credentialOrigin: (raw: string | undefined, source: OriginSource) => string;
|
|
20
29
|
/** `text` with the control key cut out: every diagnostic of an area that holds the key passes through it. */
|
|
21
30
|
export declare const withoutControlKey: (text: string, env: Readonly<Record<string, string | undefined>>) => string;
|
|
31
|
+
/** Control's origin and the fetch that carries FABRIKA_CONTROL_KEY to it. */
|
|
32
|
+
export interface ControlTransport {
|
|
33
|
+
readonly origin: string;
|
|
34
|
+
readonly fetch: RpcFetch;
|
|
35
|
+
}
|
|
22
36
|
/**
|
|
23
|
-
* The
|
|
24
|
-
*
|
|
37
|
+
* The origin from `url` or FABRIKA_CONTROL_URL, the key from FABRIKA_CONTROL_KEY in the environment only, no redirect
|
|
38
|
+
* followed. Every client of the console's origin is built on it.
|
|
25
39
|
*/
|
|
40
|
+
export declare const controlTransport: (url: string | undefined, env: Readonly<Record<string, string | undefined>>, send?: RpcFetch) => ControlTransport;
|
|
41
|
+
/** The one client of Control that `fabrika control`, `fabrika env` and `fabrika operations` share. */
|
|
26
42
|
export declare const connectControl: (url: string | undefined, env: Readonly<Record<string, string | undefined>>) => ControlClient;
|
|
27
43
|
/** The exact text `app build` would write, and the provider whose envelope carries it. */
|
|
28
44
|
export interface CompiledManifest {
|
package/types/src/data.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
declare const USAGE = "fabrika env \u2014 an application environment's data, through the control plane\n\nUsage:\n fabrika env inspect <app> <env> [--content] [--json]\n fabrika env maintenance <app> <env> <open|read-only|closed> [--json]\n fabrika env operations <app> <env> [--json]\n fabrika env recover <app> <env> <operationId> <resume|open> [--json]\n fabrika env backups <app> <env> [--json]\n fabrika env backups schedule <app> <env> [on|off] [--json]\n fabrika env restore <app> <env> --at=<time> [--json]\n\n`inspect` prints the environment's data view: the object's maintenance mode and generation, the database size and\neach table's row count (a count at 100000 reads `100000+`: it is capped), the applied migrations,\nthe scheduler's alarm, each job's last run, file and webhook counts, and when the application last failed to boot.\nIt needs `data.read`. `--content` adds the boot failure's message and stack, which are the application's own text,\nand needs `data.content.read` granted globally.\n\n`maintenance` puts the environment into a mode: `read-only` refuses writes, `closed` refuses every request, and\n`open` serves again. It starts a data operation and prints it; `operations` follows it. It needs `data.manage`.\n\n`operations` lists the environment's data operations, newest first, one row each:\n<id> <kind> <state> <step> <target mode> <generation> <error code> <created at>.\n\n`recover` fences an environment whose operation is stuck in `closed` at a fresh generation, then `resume`s that\noperation from its recorded step, or `open`s the environment. A failed operation can only be opened past. It needs\n`data.manage`.\n\n`backups` lists the environment's consistent backups, newest first, one row each:\n<id> <object> <state> <created at> <size bytes> <parts> <tables> <rehearsal> <rehearsal code> <error code> <expired>\n<pre-migration>.\nA backup counts as `succeeded` only once its rehearsal, an import into a scratch object, passed. One older than 30\ndays is `expired` and never offered for a restore. The last column is `pre-migration` for the backup a migration\ntakes before its deploy, and `-` for any other, such as a daily backup or a restore's. It needs `data.read`.\n\n`backups schedule` prints whether the environment takes a daily backup; `on` or `off` sets it, which needs\n`data.manage`. Turning it off stops the daily backup only: the backup before a migration still runs.\n\n`restore` brings back the environment's data as it was at `--at`, an ISO 8601 time with an offset in the past. It\nis a side restore: the serving object is frozen read-only and backed up, the backup is imported into a new clone\nobject, ordinary traffic is pointed at the clone, which serves the current data from then on, and the original is\nrewound to that time and kept in `inspect`, serving nothing, for inspection. It starts a data operation and prints\nit; `operations` follows it. It needs `data.manage`.\n\nA release of the control plane that does not offer a command answers that it is not available; retrying does not\nchange that. An environment the caller may not see answers `not_found`, as one that does not exist.\n\nstdout carries data only; progress and follow-up commands go to stderr. `--json` prints the result as JSON.\n\nThe control origin takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nThe credential is read from the ENVIRONMENT ONLY and has no flag:\n\n FABRIKA_CONTROL_KEY required a machine `px_` credential for the control app\n";
|
|
2
2
|
type Environment = Readonly<Record<string, string | undefined>>;
|
|
3
|
+
/** Every control character but tab and line feed: an answer must not drive the operator's terminal. */
|
|
4
|
+
export declare const printable: (text: string) => string;
|
|
3
5
|
export declare const runEnvCli: (command: string | undefined, argv: readonly string[], env?: Environment) => Promise<void>;
|
|
4
6
|
export { USAGE as ENV_USAGE };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type RpcFetch } from '@fabrika/app';
|
|
2
|
+
declare const USAGE = "fabrika operations \u2014 read Operations (errors, releases, health) from the command line\n\nUsage:\n fabrika operations issues [--app=<id>] [--env=<env>] [--service=<key>] [--status=<open|resolved|ignored>]\n [--level=<fatal|error|warning|info>] [--since=<24h|7d|30d|all>] [--search=<text>]\n [--sort=<recent|new|frequency>] [--limit=<1-100>] [--cursor=<cursor>] [--json]\n fabrika operations issue <issueId> [--event=<occurrenceId>] [--json]\n fabrika operations releases [--app=<id>] [--env=<env>] [--service=<key>] [--limit=<1-100>] [--cursor=<cursor>] [--json]\n fabrika operations health [--app=<id>] [--env=<env>] [--service=<key>] [--json]\n\nEvery command is read-only. It reads what the console's Operations pages show, through the same API, with the\nkey's rights: a source (one service of an application environment) the key may not read is not listed, and an\nissue of one answers `not_found`.\n\n`issues` lists issues, the most recently seen first (`--sort` changes that), one row each:\n<id> <status> <level> <events> <last seen> <app> <env> <service> <title>.\nstderr carries the selection's counts by status (whatever `--status` says) and, when more issues match, the\n`--cursor` that reads the next page with the same options.\n\n`issue` prints one issue: its fields, its activity, its recent events (`occurrence` rows), and the latest\nevent in full: request, user, tags, each exception with its stack frames, and the breadcrumbs. `--event` shows\nthe event of another occurrence instead. The raw event is in `--json` only.\n\n`releases` lists releases, newest first, one row each:\n<id> <state> <artifacts> <release> <commit> <created at> <finished at> <new issues> <regressions> <app> <env> <service>.\n\n`health` prints each source's telemetry health and its HTTP checks:\nsource <app> <env> <service> <telemetry state>\ncheck <app> <env> <service> <path> <state> <observed at> <latency ms> <detail code> <consecutive failures>\n\n`--app`, `--env` and `--service` select sources. On `issues` and `releases` they must select exactly one;\nwhen they match several, the error lists them. Without them every source the key may read is included.\n\nIssue titles, exception messages, breadcrumbs, tags and the raw event are text the application's users and code\nwrote. They are printed as data with control characters removed; `--json` escapes them, C1 controls included,\nas JSON strings.\n\nstdout carries data only; notes and errors go to stderr. Times are ISO 8601 UTC, except a breadcrumb time the event\nwrote as text. `--json` prints the parsed answer: of the procedure, or for `issue` `{ issue, event }`, the\nissue and the event shown (`null` when none is stored).\n\nExit codes:\n 0 the answer was printed (an empty list included)\n 1 the call failed: Control or Operations unreachable, a server error, an unreadable answer, or a procedure this\n installation's release does not offer\n 2 usage: an unknown command or option, a bad value, or a selection that matches several sources\n 3 the key: FABRIKA_CONTROL_KEY is missing, was refused, or does not hold `operations.read`\n 4 not found: no such issue, event or source, or one the key may not read\n\nThe console origin takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nThe credential is read from the ENVIRONMENT ONLY and has no flag:\n\n FABRIKA_CONTROL_KEY required a `px_` key of the console app holding `operations.read`\n\nMint a key narrowed to `operations.read` alone, with a short expiry: docs/reference/operations-errors.md,\n\"Reading Operations from the command line\".\n";
|
|
3
|
+
export declare const OPERATIONS_EXIT: {
|
|
4
|
+
readonly ok: 0;
|
|
5
|
+
readonly failed: 1;
|
|
6
|
+
readonly usage: 2;
|
|
7
|
+
readonly credential: 3;
|
|
8
|
+
readonly notFound: 4;
|
|
9
|
+
};
|
|
10
|
+
type Environment = Readonly<Record<string, string | undefined>>;
|
|
11
|
+
/** What the area reads and writes: the environment, the network, stdout and stderr. */
|
|
12
|
+
export interface OperationsIo {
|
|
13
|
+
readonly env: Environment;
|
|
14
|
+
readonly fetch: RpcFetch;
|
|
15
|
+
readonly out: (text: string) => void;
|
|
16
|
+
readonly err: (text: string) => void;
|
|
17
|
+
}
|
|
18
|
+
/** Runs one command and returns its exit code; every diagnostic goes to stderr with the key cut out. */
|
|
19
|
+
export declare const runOperationsCli: (command: string | undefined, argv: readonly string[], io?: OperationsIo) => Promise<number>;
|
|
20
|
+
export { USAGE as OPERATIONS_USAGE };
|