@fabrika/provider-contract 0.9.0-dev.2 → 0.9.0-dev.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/provider-contract",
3
- "version": "0.9.0-dev.2",
3
+ "version": "0.9.0-dev.20",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,13 +25,24 @@
25
25
  "bun": "./src/installation.ts",
26
26
  "types": "./types/src/installation.d.ts",
27
27
  "default": "./src/installation.ts"
28
+ },
29
+ "./app-cli": {
30
+ "bun": "./src/app-cli.ts",
31
+ "types": "./types/src/app-cli.d.ts",
32
+ "default": "./src/app-cli.ts"
33
+ },
34
+ "./conformance": {
35
+ "bun": "./src/conformance.ts",
36
+ "types": "./types/src/conformance.d.ts",
37
+ "default": "./src/conformance.ts"
28
38
  }
29
39
  },
30
40
  "scripts": {
31
- "typecheck": "tsc --noEmit",
41
+ "typecheck": "tsrs --build tsconfig.test.json",
32
42
  "test": "bun test"
33
43
  },
34
44
  "dependencies": {
35
- "@fabrika/auth-core": "0.9.0-dev.2"
45
+ "@fabrika/auth-core": "0.9.0-dev.20",
46
+ "@fabrika/proxy-core": "0.9.0-dev.20"
36
47
  }
37
48
  }
package/src/app-cli.ts ADDED
@@ -0,0 +1,81 @@
1
+ // What a provider's `/cli` module offers the `fabrika` command for an application: `app build`, `app deploy`,
2
+ // `app register` and `fabrika namespace`. The command loads the module by the provider's id and never branches on it.
3
+
4
+ import type { ProviderDeploymentNamespace, ProviderNamespacePlan } from './control'
5
+
6
+ /** The runtime a contract application's generated entry is written for (`@fabrika/app/build`'s `EntryRuntime`). */
7
+ export type AppEntryRuntime = 'bun' | 'cloudflare'
8
+
9
+ /** What a namespace command asks of Control. The `fabrika` command holds the Control origin, the credential and the transport. */
10
+ export interface NamespaceControl {
11
+ create(namespace: ProviderDeploymentNamespace): Promise<unknown>
12
+ adopt(namespace: ProviderDeploymentNamespace): Promise<unknown>
13
+ reconcile(namespaceId: string): Promise<unknown>
14
+ }
15
+
16
+ /** A plan, or the namespace Control answered with; the `fabrika` command validates and prints either. */
17
+ export type NamespaceCommandResult = { readonly plan: ProviderNamespacePlan } | { readonly namespace: unknown }
18
+
19
+ export interface NamespaceCommandContext {
20
+ readonly source: Readonly<Record<string, string | undefined>>
21
+ /** Reads the Control origin and credential, and throws when either is missing: call it after every other input is checked. */
22
+ control(): NamespaceControl
23
+ }
24
+
25
+ export interface NamespaceCli {
26
+ readonly usage: string
27
+ /** `argv` is the command's own arguments, without the router's `--provider` and `--json`. */
28
+ run(subcommand: string, argv: readonly string[], context: NamespaceCommandContext): Promise<NamespaceCommandResult>
29
+ }
30
+
31
+ export interface AppCli {
32
+ readonly provider: string
33
+ readonly entryRuntime: AppEntryRuntime
34
+ /** `fabrika app build`, after the command wrote a contract application's entry; `contract` says whether it did. */
35
+ build?(argv: readonly string[], context: { readonly contract: boolean }): Promise<void>
36
+ deploy?(argv: readonly string[]): Promise<void>
37
+ /** The text `fabrika app register` hands Control: the application's manifest for one environment. */
38
+ registrationManifest?(options: { readonly config: string; readonly env: string }): Promise<string>
39
+ readonly namespaces?: NamespaceCli
40
+ }
41
+
42
+ export interface AppCliModule {
43
+ readonly appCli: AppCli
44
+ }
45
+
46
+ const optionalFunction = (value: object, key: string): boolean => {
47
+ const member: unknown = Reflect.get(value, key)
48
+ return member === undefined || typeof member === 'function'
49
+ }
50
+
51
+ const isNamespaceCli = (value: unknown): value is NamespaceCli =>
52
+ typeof value === 'object'
53
+ && value !== null
54
+ && 'usage' in value
55
+ && typeof value.usage === 'string'
56
+ && 'run' in value
57
+ && typeof value.run === 'function'
58
+
59
+ export const isAppCli = (value: unknown): value is AppCli =>
60
+ typeof value === 'object'
61
+ && value !== null
62
+ && 'provider' in value
63
+ && typeof value.provider === 'string'
64
+ && value.provider.trim() !== ''
65
+ && 'entryRuntime' in value
66
+ && (value.entryRuntime === 'bun' || value.entryRuntime === 'cloudflare')
67
+ && optionalFunction(value, 'build')
68
+ && optionalFunction(value, 'deploy')
69
+ && optionalFunction(value, 'registrationManifest')
70
+ && (!('namespaces' in value) || value.namespaces === undefined || isNamespaceCli(value.namespaces))
71
+
72
+ /** `specifier` names the module in the error, so an operator knows which package to upgrade. */
73
+ export const appCliFromModule = (value: unknown, expectedProvider: string, specifier: string): AppCli => {
74
+ if (typeof value !== 'object' || value === null || !('appCli' in value) || !isAppCli(value.appCli)) {
75
+ throw new Error(`${specifier} must export a valid \`appCli\`; a provider release older than this CLI has none`)
76
+ }
77
+ if (value.appCli.provider !== expectedProvider) {
78
+ throw new Error(`${specifier} provides "${value.appCli.provider}", expected "${expectedProvider}"`)
79
+ }
80
+ return value.appCli
81
+ }
@@ -0,0 +1,221 @@
1
+ // The cases every `ControlProvider` passes, whatever cloud it deploys to. A provider's own test file calls
2
+ // `describeControlProviderConformance` once with a harness over its fake cloud: the harness builds the provider and a
3
+ // deploy its cloud accepts, and reports what the cloud was asked to change and to stop.
4
+
5
+ import { describe, expect, test } from 'bun:test'
6
+ import {
7
+ type ControlProvider,
8
+ type ProviderDeployInput,
9
+ type ProviderDeployOutcome,
10
+ ProviderInvocationAbort,
11
+ type ProviderRunEvents,
12
+ } from './control'
13
+ import type { JsonValue } from './json'
14
+
15
+ /** What the suite hands a fake cloud: `accepted` is called once the cloud has taken the deploy's operation. */
16
+ export interface ConformanceCloudHooks {
17
+ accepted(): void
18
+ }
19
+
20
+ /** One provider over one fresh fake cloud. */
21
+ export interface ConformanceCloud {
22
+ readonly provider: ControlProvider
23
+ /** A deploy the fake cloud accepts and lets succeed. Each case sets `dryRun`, `signal` and `events` itself. */
24
+ readonly input: Omit<ProviderDeployInput, 'dryRun' | 'signal' | 'events'>
25
+ /** The credentials the provider holds itself (a cloud token, a signed URL); no event may carry one. */
26
+ readonly credentials: readonly string[]
27
+ /** Every request that changed the cloud: a write, a created resource, started work. A preview the cloud runs is none. */
28
+ mutations(): readonly string[]
29
+ /** Every request to stop or remove the deploy's work: a cancelled build or job, a deleted version. */
30
+ stops(): readonly string[]
31
+ }
32
+
33
+ export interface ControlProviderConformanceHarness {
34
+ /** Called once per case, and once per event in the lease-loss sweep. */
35
+ create(hooks: ConformanceCloudHooks): ConformanceCloud
36
+ }
37
+
38
+ /** A secret the suite adds to every deploy; no event may carry it. */
39
+ const SECRET_NAME = 'CONFORMANCE_SECRET'
40
+ const SECRET_VALUE = 'conformance-secret-value-7f3a9c'
41
+
42
+ /** What a deploy reported through its events, as Control would have persisted it. */
43
+ interface Recorded {
44
+ readonly logs: string[]
45
+ readonly externalIds: Array<{ readonly id: string; readonly state?: JsonValue }>
46
+ readonly checkpoints: JsonValue[]
47
+ /** Events that hold the lease: `boundary`, `externalId` and `checkpoint`, in order. */
48
+ events: number
49
+ /** A state Control could not store as given; collected, because a provider may swallow what an event throws. */
50
+ readonly violations: string[]
51
+ }
52
+
53
+ interface Invocation {
54
+ readonly input: ProviderDeployInput
55
+ readonly recorded: Recorded
56
+ /** Lose the lease as Control does: the signal aborts, and every later event rejects with the same reason. */
57
+ loseLease(): void
58
+ readonly signal: AbortSignal
59
+ }
60
+
61
+ const LEASE_LOST = new ProviderInvocationAbort('lease_lost')
62
+
63
+ /** `lostAt`: the lease goes at this event (1-based), which rejects like every one after it. */
64
+ function invocation(cloud: ConformanceCloud, dryRun: boolean, options: { readonly lostAt?: number } = {}): Invocation {
65
+ const controller = new AbortController()
66
+ const recorded: Recorded = { logs: [], externalIds: [], checkpoints: [], events: 0, violations: [] }
67
+ const loseLease = (): void => {
68
+ if (!controller.signal.aborted) controller.abort(LEASE_LOST)
69
+ }
70
+ const held = async (): Promise<void> => {
71
+ recorded.events += 1
72
+ if (recorded.events === options.lostAt) loseLease()
73
+ if (controller.signal.aborted) throw controller.signal.reason
74
+ }
75
+ const stored = (kind: string, state: JsonValue): JsonValue => {
76
+ const parsed: JsonValue = JSON.parse(JSON.stringify(state))
77
+ if (!Bun.deepEquals(parsed, state, true)) recorded.violations.push(`${kind} state is not JSON as given`)
78
+ return parsed
79
+ }
80
+ const events: ProviderRunEvents = {
81
+ log: (line) => {
82
+ recorded.logs.push(line)
83
+ },
84
+ externalId: async (id, state) => {
85
+ await held()
86
+ recorded.externalIds.push(state === undefined ? { id } : { id, state: stored('externalId', state) })
87
+ },
88
+ checkpoint: async (state) => {
89
+ await held()
90
+ recorded.checkpoints.push(stored('checkpoint', state))
91
+ },
92
+ boundary: held,
93
+ }
94
+ const input: ProviderDeployInput = {
95
+ ...cloud.input,
96
+ secrets: { ...cloud.input.secrets, [SECRET_NAME]: SECRET_VALUE },
97
+ dryRun,
98
+ signal: controller.signal,
99
+ events,
100
+ }
101
+ return { input, recorded, loseLease, signal: controller.signal }
102
+ }
103
+
104
+ /**
105
+ * The deploy's outcome, or the reason it rejected with. A step a provider stops waiting for may still run, so the
106
+ * cloud is read only after the tasks already queued have run.
107
+ */
108
+ async function settle(provider: ControlProvider, input: ProviderDeployInput): Promise<ProviderDeployOutcome | { readonly rejected: unknown }> {
109
+ let outcome: ProviderDeployOutcome | { readonly rejected: unknown }
110
+ try {
111
+ outcome = await provider.deploy(input)
112
+ } catch (error) {
113
+ outcome = { rejected: error }
114
+ }
115
+ await new Promise((resolve) => setTimeout(resolve, 0))
116
+ return outcome
117
+ }
118
+
119
+ /** No event carried a credential: the deploy's secrets, its credential managed entries, the upload bearer, the provider's own. */
120
+ function expectCredentialFree(cloud: ConformanceCloud, run: Invocation): void {
121
+ const { input } = run
122
+ const managed = Object.values(input.managedEnvironment).flatMap((entry) => entry.credential && entry.value !== null ? [entry.value] : [])
123
+ const bearer = input.artifactUpload === undefined ? [] : [input.artifactUpload.bearer]
124
+ const reported = JSON.stringify({ logs: run.recorded.logs, externalIds: run.recorded.externalIds, checkpoints: run.recorded.checkpoints })
125
+ for (const credential of [...Object.values(input.secrets), ...managed, ...bearer, ...cloud.credentials]) {
126
+ expect(reported).not.toContain(credential)
127
+ }
128
+ expect(run.recorded.violations).toEqual([])
129
+ }
130
+
131
+ export function describeControlProviderConformance(name: string, harness: ControlProviderConformanceHarness): void {
132
+ const quiet = (): ConformanceCloud => harness.create({ accepted: () => {} })
133
+
134
+ describe(`${name} conforms to ControlProvider`, () => {
135
+ test('a deploy succeeds, and nothing it reports carries a credential', async () => {
136
+ const cloud = quiet()
137
+ const run = invocation(cloud, false)
138
+ expect(await settle(cloud.provider, run.input)).toMatchObject({ state: 'succeeded' })
139
+ expect(cloud.mutations().length).toBeGreaterThan(0)
140
+ expect(cloud.stops()).toEqual([])
141
+ expectCredentialFree(cloud, run)
142
+ })
143
+
144
+ test('a dry run succeeds, changes nothing in the cloud, and reports no credential', async () => {
145
+ const cloud = quiet()
146
+ const run = invocation(cloud, true)
147
+ expect(await settle(cloud.provider, run.input)).toMatchObject({ state: 'succeeded' })
148
+ expect(cloud.mutations()).toEqual([])
149
+ expect(cloud.stops()).toEqual([])
150
+ expectCredentialFree(cloud, run)
151
+ })
152
+
153
+ test('an invocation whose lease is gone at its first event changes nothing in the cloud', async () => {
154
+ const cloud = quiet()
155
+ const run = invocation(cloud, false, { lostAt: 1 })
156
+ expect(await settle(cloud.provider, run.input)).not.toMatchObject({ state: 'succeeded' })
157
+ expect(cloud.mutations()).toEqual([])
158
+ expect(cloud.stops()).toEqual([])
159
+ })
160
+
161
+ test('a lease lost at any event of a deploy stops nothing, and the deploy claims no success', async () => {
162
+ const cloud = quiet()
163
+ const complete = invocation(cloud, false)
164
+ await settle(cloud.provider, complete.input)
165
+ expect(complete.recorded.events).toBeGreaterThan(0)
166
+ for (let lostAt = 1; lostAt <= complete.recorded.events; lostAt += 1) {
167
+ const lost = quiet()
168
+ const run = invocation(lost, false, { lostAt })
169
+ const outcome = await settle(lost.provider, run.input)
170
+ // The cloud may still finish the work; this invocation may not claim it, and may not stop it.
171
+ expect({ lostAt, outcome }).not.toMatchObject({ outcome: { state: 'succeeded' } })
172
+ expect({ lostAt, stops: lost.stops() }).toEqual({ lostAt, stops: [] })
173
+ expectCredentialFree(lost, run)
174
+ }
175
+ })
176
+
177
+ test('a lease lost once the cloud accepted the deploy stops nothing, in the deploy, a reconcile or a cancel', async () => {
178
+ let run: Invocation | undefined
179
+ let accepted = false
180
+ const cloud = harness.create({
181
+ accepted: () => {
182
+ accepted = true
183
+ run?.loseLease()
184
+ },
185
+ })
186
+ run = invocation(cloud, false)
187
+ const outcome = await settle(cloud.provider, run.input)
188
+ expect(accepted).toBe(true)
189
+ expect(outcome).not.toMatchObject({ state: 'succeeded' })
190
+ expect(cloud.stops()).toEqual([])
191
+
192
+ // Control reconciles and cancels a run by what its last owner recorded.
193
+ const recordedId = run.recorded.externalIds[0]
194
+ if (recordedId === undefined) throw new Error('the deploy recorded no external id before its operation was accepted')
195
+ const providerState = run.recorded.checkpoints.at(-1) ?? recordedId.state
196
+ const reference = {
197
+ runId: run.input.runId,
198
+ externalId: recordedId.id,
199
+ environment: run.input.environment,
200
+ signal: run.signal,
201
+ ...(providerState === undefined ? {} : { providerState }),
202
+ }
203
+ const mutations = cloud.mutations().length
204
+ await cloud.provider.reconcile?.(reference).catch(() => {})
205
+ await cloud.provider.cancel?.(reference).catch(() => {})
206
+ await new Promise((resolve) => setTimeout(resolve, 0))
207
+ expect(cloud.stops()).toEqual([])
208
+ expect(cloud.mutations()).toHaveLength(mutations)
209
+ })
210
+
211
+ test('a registration normalizes to itself, and its envelopes survive JSON', () => {
212
+ const cloud = quiet()
213
+ const normalize = cloud.provider.normalizeRegistration
214
+ if (normalize === undefined) return
215
+ const once = normalize({ app: cloud.input.app, environment: cloud.input.environment })
216
+ expect(normalize(once)).toEqual(once)
217
+ expect(JSON.parse(JSON.stringify(once.environment.target))).toEqual(once.environment.target)
218
+ expect(JSON.parse(JSON.stringify(once.environment.artifact))).toEqual(once.environment.artifact)
219
+ })
220
+ })
221
+ }