@fabrika/cli 0.9.0-dev.4 → 0.9.0-dev.41

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/src/namespace.ts CHANGED
@@ -1,60 +1,18 @@
1
1
  import { createRpcClient } from '@fabrika/app'
2
- import type { AdoptDeploymentNamespaceRequest, ControlRpcContract, CreateDeploymentNamespaceRequest } from '@fabrika/control-contract'
3
- import type { JsonValue, ProviderDeploymentNamespace, ProviderNamespacePlan } from '@fabrika/provider-contract'
4
- import {
5
- createZeropsNamespaceOperator,
6
- decodeZeropsNamespaceProxySource,
7
- parseZeropsCliArgs,
8
- verifyZeropsNamespaceProxySource,
9
- type ZeropsCliArgs,
10
- type ZeropsNamespacePostgres,
11
- zeropsNamespacePostgresSchema,
12
- zeropsNamespaceTargetCodec,
13
- } from '@fabrika/provider-zerops'
2
+ import type { ControlRpcContract } from '@fabrika/control-contract'
3
+ import type { NamespaceCli, NamespaceControl } from '@fabrika/provider-contract/app-cli'
14
4
  import { z } from 'zod'
15
5
  import { namespaceLine, namespacePlanLines } from './control'
16
6
 
17
- export const NAMESPACE_USAGE = `fabrika namespace — Zerops deployment namespaces
7
+ export const NAMESPACE_USAGE = `fabrika namespace — deployment namespaces
18
8
 
19
9
  Usage:
20
- fabrika namespace plan --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> [namespace options]
21
- fabrika namespace create --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> [namespace options] [--control-url=<url>]
22
- fabrika namespace adopt --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> --project-id=<id> [namespace options] [--control-url=<url>]
23
- fabrika namespace reconcile --provider=zerops --id=<id> [--control-url=<url>]
10
+ fabrika namespace <plan|create|adopt|reconcile> --provider=<name> [provider options] [--json]
24
11
 
25
- Options:
26
- --id=<id> Namespace id.
27
- --env=<env> Environment.
28
- --preset=<cheap|mid|full> Provider-owned namespace preset.
29
- --exclusive-app=<id> App reserved by a full namespace.
30
- --project-id=<id> Existing Zerops project id for adoption.
31
- --project-name=<name> Zerops project name (create: default fabrika-<env>-<id>;
32
- adopt: the existing project's name, default the namespace id).
33
- --core-package=<tier> LIGHT or SERIOUS.
34
- --public-access=<mode> custom-domain or zerops-subdomain.
35
- --postgres-type=<type> Cheap-tier PostgreSQL type.
36
- --postgres-profile=<profile> Cheap-tier PostgreSQL profile.
37
- --control-url=<url> Control origin; or FABRIKA_CONTROL_URL.
38
- --json Print the result as JSON instead of rows.
39
- -h, --help Show this help.
40
-
41
- \`plan\` prints one \`<path>\\t<value>\` row per field of the plan, keyed by its path in --json; a multi-line
42
- value such as the proxy's descriptor file is shown by size only. The other commands print one
43
- \`<id>\\t<env>\\t<state>\\t<exclusive app>\` row.
44
-
45
- Mutating namespace commands read the Bearer credential from FABRIKA_CONTROL_TOKEN.
46
- Plan/create/adopt require FABRIKA_ZEROPS_PROXY_SOURCE_JSON:
47
- {"repository":{"owner":"...","name":"..."},"commitSha":"...","descriptor":{"path":"zerops.yaml","contents":"...","sha256":"..."}}
48
- Reconcile uses the persisted namespace source.
12
+ The commands and their options are the provider's: \`fabrika namespace --provider=<name> --help\` prints them.
49
13
  `
50
14
 
51
- export interface ZeropsNamespaceCommand {
52
- readonly args: ZeropsCliArgs
53
- /** The result as JSON; otherwise the rows `fabrika control namespaces` prints. */
54
- readonly json: boolean
55
- }
56
-
57
- export interface ZeropsNamespaceCommandDependencies {
15
+ export interface NamespaceCommandDependencies {
58
16
  readonly source: Readonly<Record<string, string | undefined>>
59
17
  readonly fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>
60
18
  readonly write: (value: string) => void
@@ -67,64 +25,15 @@ const required = (value: string | undefined, label: string): string => {
67
25
  return value.trim()
68
26
  }
69
27
 
70
- const postgres = (args: ZeropsCliArgs): ZeropsNamespacePostgres | undefined => {
71
- const type = args.postgresType
72
- const profile = args.postgresProfile
73
- if (type === undefined && profile === undefined) return undefined
74
- if (type === undefined) {
75
- throw new Error('--postgres-type is required with --postgres-profile')
76
- }
77
- const result = zeropsNamespacePostgresSchema.safeParse({ type, profile })
78
- if (result.success) return result.data
79
- if (result.error.issues[0]?.path[0] === 'type') throw new Error('--postgres-type must be postgresql:ha@18 or postgresql:single@18')
80
- throw new Error(`--postgres-profile ${profile} is not supported by ${type}`)
81
- }
82
-
83
- const planOptions = (args: ZeropsCliArgs): { [key: string]: JsonValue } | undefined => {
84
- const values: { [key: string]: JsonValue } = {}
85
- if (args.projectName !== undefined) values['projectName'] = required(args.projectName, '--project-name')
86
- if (args.corePackage !== undefined) values['corePackage'] = required(args.corePackage, '--core-package')
87
- if (args.publicAccess !== undefined) values['publicAccess'] = required(args.publicAccess, '--public-access')
88
- const database = postgres(args)
89
- if (database !== undefined) {
90
- values['postgres'] = database.profile === undefined ? { type: database.type } : { type: database.type, profile: database.profile }
91
- }
92
- return Object.keys(values).length === 0 ? undefined : values
93
- }
94
-
95
- const namespacePlan = async (
96
- args: ZeropsCliArgs,
97
- source: Readonly<Record<string, string | undefined>>,
98
- ): Promise<ProviderNamespacePlan> => {
99
- // `FABRIKA_ZEROPS_*` because Zerops reserves the bare `ZEROPS_` prefix and refuses to store a custom
100
- // variable using it (`userDataZeropsPrefixForbidden`).
101
- const serialized = required(source['FABRIKA_ZEROPS_PROXY_SOURCE_JSON'], 'FABRIKA_ZEROPS_PROXY_SOURCE_JSON')
102
- let value: unknown
103
- try {
104
- value = JSON.parse(serialized)
105
- } catch {
106
- throw new Error('FABRIKA_ZEROPS_PROXY_SOURCE_JSON must contain valid JSON')
107
- }
108
- const proxySource = decodeZeropsNamespaceProxySource(value)
109
- await verifyZeropsNamespaceProxySource(proxySource)
110
- const operator = createZeropsNamespaceOperator({ proxySource })
111
- const options = planOptions(args)
112
- return operator.plan({
113
- id: required(args.namespaceId, '--id'),
114
- env: required(args.env, '--env'),
115
- preset: required(args.preset, '--preset'),
116
- ...(args.exclusiveAppId === undefined ? {} : { exclusiveAppId: required(args.exclusiveAppId, '--exclusive-app') }),
117
- ...(options === undefined ? {} : { options }),
118
- })
119
- }
120
-
121
28
  const outputJson = (value: unknown): string => `${JSON.stringify(value, null, '\t')}\n`
122
29
 
30
+ const CONTROL_URL_OPTION = '--control-url='
31
+
123
32
  const controlCoordinates = (
124
- args: ZeropsCliArgs,
33
+ controlUrl: string | undefined,
125
34
  source: Readonly<Record<string, string | undefined>>,
126
35
  ): { baseUrl: URL; token: string } => {
127
- const value = required(args.controlUrl ?? source['FABRIKA_CONTROL_URL'], '--control-url or FABRIKA_CONTROL_URL')
36
+ const value = required(controlUrl ?? source['FABRIKA_CONTROL_URL'], '--control-url or FABRIKA_CONTROL_URL')
128
37
  const token = required(source['FABRIKA_CONTROL_TOKEN'], 'FABRIKA_CONTROL_TOKEN')
129
38
  let baseUrl: URL
130
39
  try {
@@ -139,7 +48,7 @@ const controlCoordinates = (
139
48
  }
140
49
 
141
50
  const controlClient = (
142
- deps: ZeropsNamespaceCommandDependencies,
51
+ deps: NamespaceCommandDependencies,
143
52
  coordinates: { baseUrl: URL; token: string },
144
53
  ) =>
145
54
  createRpcClient<ControlRpcContract>({
@@ -158,6 +67,29 @@ const controlClient = (
158
67
  },
159
68
  })
160
69
 
70
+ const namespaceControl = (deps: NamespaceCommandDependencies, controlUrl: string | undefined): NamespaceControl => {
71
+ const client = controlClient(deps, controlCoordinates(controlUrl, deps.source))
72
+ return {
73
+ create: (namespace) =>
74
+ client.namespaces.create({
75
+ id: namespace.id,
76
+ env: namespace.env,
77
+ ...(namespace.exclusiveAppId === undefined ? {} : { exclusiveAppId: namespace.exclusiveAppId }),
78
+ target: namespace.target,
79
+ }),
80
+ adopt: (namespace) =>
81
+ client.namespaces.adopt({
82
+ namespaceId: namespace.id,
83
+ namespace: {
84
+ env: namespace.env,
85
+ ...(namespace.exclusiveAppId === undefined ? {} : { exclusiveAppId: namespace.exclusiveAppId }),
86
+ target: namespace.target,
87
+ },
88
+ }),
89
+ reconcile: (namespaceId) => client.namespaces.reconcile({ namespaceId }),
90
+ }
91
+ }
92
+
161
93
  // Passthrough on purpose: `--json` shows the operator the whole namespace detail, this only checks it is one.
162
94
  const namespaceResponseSchema = z.object({
163
95
  id: z.string(),
@@ -165,85 +97,30 @@ const namespaceResponseSchema = z.object({
165
97
  state: z.enum(['pending', 'provisioning', 'ready', 'failed']),
166
98
  exclusiveAppId: z.string().nullable(),
167
99
  }).passthrough()
168
- const writeNamespace = (command: ZeropsNamespaceCommand, deps: ZeropsNamespaceCommandDependencies, result: unknown): void => {
169
- const parsed = namespaceResponseSchema.safeParse(result)
170
- if (!parsed.success) {
171
- throw new Error('Control API returned an invalid namespace')
172
- }
173
- deps.write(command.json ? outputJson(parsed.data) : `${namespaceLine(parsed.data)}\n`)
174
- }
175
-
176
- const createBody = (namespace: ProviderDeploymentNamespace): CreateDeploymentNamespaceRequest => ({
177
- id: namespace.id,
178
- env: namespace.env,
179
- ...(namespace.exclusiveAppId === undefined ? {} : { exclusiveAppId: namespace.exclusiveAppId }),
180
- target: namespace.target,
181
- })
182
100
 
183
- const adoptBody = (namespace: ProviderDeploymentNamespace): AdoptDeploymentNamespaceRequest => ({
184
- env: namespace.env,
185
- ...(namespace.exclusiveAppId === undefined ? {} : { exclusiveAppId: namespace.exclusiveAppId }),
186
- target: namespace.target,
187
- })
188
-
189
- /** Execute one namespace command. All command inputs are validated before the first fetch. */
190
- export const runZeropsNamespaceCommand = async (
191
- command: ZeropsNamespaceCommand,
192
- deps: ZeropsNamespaceCommandDependencies,
101
+ /**
102
+ * Run one provider's namespace command and print what it answers. `--json` and `--control-url` are this area's own
103
+ * options, so they are taken out before the provider's parser, which refuses unknown options.
104
+ */
105
+ export const runNamespaceCommand = async (
106
+ cli: NamespaceCli,
107
+ subcommand: string,
108
+ argv: readonly string[],
109
+ deps: NamespaceCommandDependencies,
193
110
  ): Promise<void> => {
194
- const { args } = command
195
- const subcommand = required(args.subcommand, 'namespace command')
196
- if (subcommand === 'plan') {
197
- const plan = await namespacePlan(args, deps.source)
198
- deps.write(command.json ? outputJson(plan) : `${namespacePlanLines(plan).join('\n')}\n`)
199
- return
200
- }
201
- if (subcommand === 'reconcile') {
202
- const id = required(args.namespaceId, '--id')
203
- const control = controlCoordinates(args, deps.source)
204
- writeNamespace(command, deps, await controlClient(deps, control).namespaces.reconcile({ namespaceId: id }))
111
+ const json = argv.includes('--json')
112
+ const controlUrl = argv.filter((arg) => arg.startsWith(CONTROL_URL_OPTION)).at(-1)?.slice(CONTROL_URL_OPTION.length)
113
+ const providerArgv = argv.filter((arg) => arg !== '--json' && !arg.startsWith(CONTROL_URL_OPTION))
114
+ // The Control credential stays here: the provider plans with the rest of the environment.
115
+ const { FABRIKA_CONTROL_TOKEN: _token, ...source } = deps.source
116
+ const result = await cli.run(subcommand, providerArgv, { source, control: () => namespaceControl(deps, controlUrl) })
117
+ if ('plan' in result) {
118
+ deps.write(json ? outputJson(result.plan) : `${namespacePlanLines(result.plan).join('\n')}\n`)
205
119
  return
206
120
  }
207
- if (subcommand !== 'create' && subcommand !== 'adopt') {
208
- throw new Error(`Unknown namespace command: ${subcommand}`)
209
- }
210
-
211
- const planned = await namespacePlan(args, deps.source)
212
- const control = controlCoordinates(args, deps.source)
213
- if (subcommand === 'create') {
214
- writeNamespace(command, deps, await controlClient(deps, control).namespaces.create(createBody(planned.namespace)))
215
- return
216
- }
217
-
218
- const projectId = required(args.projectId, '--project-id')
219
- const decoded = zeropsNamespaceTargetCodec.decode(planned.namespace.target.payload)
220
- const namespace: ProviderDeploymentNamespace = {
221
- ...planned.namespace,
222
- target: {
223
- provider: 'zerops',
224
- version: zeropsNamespaceTargetCodec.version,
225
- payload: zeropsNamespaceTargetCodec.encode({
226
- ...decoded,
227
- // An adopted project keeps its own name, so the plan's default for a created one does not apply.
228
- projectName: args.projectName ?? planned.namespace.id,
229
- managed: false,
230
- projectId,
231
- ready: false,
232
- }),
233
- },
121
+ const parsed = namespaceResponseSchema.safeParse(result.namespace)
122
+ if (!parsed.success) {
123
+ throw new Error('Control API returned an invalid namespace')
234
124
  }
235
- writeNamespace(command, deps, await controlClient(deps, control).namespaces.adopt({ namespaceId: namespace.id, namespace: adoptBody(namespace) }))
125
+ deps.write(json ? outputJson(parsed.data) : `${namespaceLine(parsed.data)}\n`)
236
126
  }
237
-
238
- /** `--json` is this area's own flag, so it is taken out before the provider's parser, which refuses unknown options. */
239
- export const parseZeropsNamespaceCommand = (subcommand: string, argv: readonly string[]): ZeropsNamespaceCommand => ({
240
- args: parseZeropsCliArgs(['namespace', subcommand, ...argv.filter((arg) => arg !== '--json')]),
241
- json: argv.includes('--json'),
242
- })
243
-
244
- export const runZeropsNamespaceCli = (subcommand: string, argv: readonly string[]): Promise<void> =>
245
- runZeropsNamespaceCommand(parseZeropsNamespaceCommand(subcommand, argv), {
246
- source: process.env,
247
- fetch: globalThis.fetch,
248
- write: (value) => console.info(value.trimEnd()),
249
- })