@ankhorage/infra 5.1.5 → 5.1.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @ankhorage/infra
2
2
 
3
+ ## 5.1.6
4
+
5
+ ### Patch Changes
6
+
7
+ - 57da4cf: Prove the released Hetzner, k3s, Supabase and R2 composition with independent object-storage ownership and privileged output isolation.
8
+
3
9
  ## 5.1.5
4
10
 
5
11
  ### Patch Changes
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ankhorage/infra",
3
3
  "type": "module",
4
- "version": "5.1.5",
4
+ "version": "5.1.6",
5
5
  "description": "Project-aware infrastructure generation library and executable Ankh provider for Ankhorage.",
6
6
  "homepage": "https://github.com/ankhorage/infra#readme",
7
7
  "bugs": {
@@ -119,7 +119,7 @@
119
119
  "@ankhorage/minikube": "^0.4.2",
120
120
  "@ankhorage/paradox": "^0.1.24",
121
121
  "@ankhorage/r2": "^0.2.0",
122
- "@ankhorage/supabase": "^0.4.9",
122
+ "@ankhorage/supabase": "^0.5.5",
123
123
  "@ankhorage/supabase-vault": "^0.3.1",
124
124
  "@types/bun": "^1.4.1",
125
125
  "@types/node": "^25.6.0",
@@ -0,0 +1,482 @@
1
+ import type { InfraManifest, InfraResult } from '@ankhorage/contracts/infra';
2
+ import {
3
+ createInfraAdapter as createHetznerInfraAdapter,
4
+ type HetznerCloudApi,
5
+ type HetznerCloudObservation,
6
+ type HetznerDesiredCompute,
7
+ type HetznerHostKeyProbe,
8
+ type HetznerProjectIdentity,
9
+ type HetznerResourceId,
10
+ infraAdapterDescriptor as hetznerInfraAdapterDescriptor,
11
+ } from '@ankhorage/hetzner';
12
+ import {
13
+ createInfraAdapter as createK3sInfraAdapter,
14
+ infraAdapterDescriptor as k3sInfraAdapterDescriptor,
15
+ type K3sClusterObservation,
16
+ type K3sClusterSpec,
17
+ type K3sControlPlane,
18
+ type K3sNodeAccess,
19
+ } from '@ankhorage/k3s';
20
+ import {
21
+ createInfraAdapter as createR2InfraAdapter,
22
+ infraAdapterDescriptor as r2InfraAdapterDescriptor,
23
+ type R2BucketControlPlane,
24
+ type R2BucketObservation,
25
+ type R2CloudRequest,
26
+ } from '@ankhorage/r2';
27
+ import {
28
+ createInfraAdapter as createSupabaseInfraAdapter,
29
+ infraAdapterDescriptor as supabaseInfraAdapterDescriptor,
30
+ type SupabaseControlPlane,
31
+ type SupabaseControlPlaneRequest,
32
+ } from '@ankhorage/supabase';
33
+ import { expect, test } from 'bun:test';
34
+
35
+ import { planInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/planInfraEnvironmentAsync.js';
36
+ import { statusInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/statusInfraEnvironmentAsync.js';
37
+ import { upInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/upInfraEnvironmentAsync.js';
38
+ import type { InfraOrchestrationDependencies } from './types/infraOrchestration.js';
39
+
40
+ const projectId = 'infra163-production-r2';
41
+ const publicBaseUrl = 'https://api.r2-production.example.test';
42
+ const domain = 'api.r2-production.example.test';
43
+ const r2AccountId = 'phase10-r2-account';
44
+ const r2Bucket = 'media';
45
+
46
+ const manifest = {
47
+ environments: {
48
+ production: {
49
+ deployment: {
50
+ compute: { provider: 'hetzner', location: 'fsn1', serverType: 'cx23' },
51
+ runtime: { provider: 'k3s', topology: { servers: 1, agents: 0 } },
52
+ },
53
+ database: { provider: 'supabase', tier: 'prod' },
54
+ auth: { provider: 'supabase' },
55
+ objectStorage: { provider: 'r2', accountId: r2AccountId, buckets: [r2Bucket] },
56
+ networking: {
57
+ domain,
58
+ publicBaseUrl,
59
+ tls: { mode: 'acme-http-01', contactEmail: 'infra@example.test' },
60
+ },
61
+ },
62
+ },
63
+ modules: [],
64
+ } as const satisfies InfraManifest;
65
+
66
+ test('composes Hetzner, k3s, Supabase database/auth and independent R2 object storage', async () => {
67
+ const fixture = new ProductionR2Fixture();
68
+ const dependencies = createDependencies(fixture);
69
+
70
+ const initialPlan = requireSuccess(
71
+ await planInfraEnvironmentAsync(
72
+ { projectId, manifest, environment: 'production' },
73
+ dependencies,
74
+ ),
75
+ );
76
+ const initialOwners = new Set(initialPlan.actions.map(({ owner }) => owner.adapter));
77
+ expect(initialOwners.has('supabase')).toBe(true);
78
+ expect(initialOwners.has('r2')).toBe(true);
79
+ expect(initialPlan.actions.some(({ operation }) => operation === 'create')).toBe(true);
80
+
81
+ const firstUp = requireSuccess(
82
+ await upInfraEnvironmentAsync({ projectId, manifest, environment: 'production' }, dependencies),
83
+ );
84
+ const serializedWorkloads = fixture.kubernetes.serializedResources();
85
+ expect(serializedWorkloads).toContain('supabase-db');
86
+ expect(serializedWorkloads).toContain('supabase-auth');
87
+ expect(serializedWorkloads).toContain('supabase-gateway');
88
+ expect(serializedWorkloads).not.toContain('supabase-storage');
89
+ expect(serializedWorkloads).not.toContain('supabase-imgproxy');
90
+ expect(serializedWorkloads).not.toContain('/storage/v1/');
91
+ expect(fixture.supabase.created).toEqual([]);
92
+ expect(fixture.r2.created).toEqual([r2Bucket]);
93
+
94
+ expect(
95
+ firstUp.resources.some(
96
+ ({ identity }) => identity.adapter === 'r2' && identity.resourceId === `bucket/${r2Bucket}`,
97
+ ),
98
+ ).toBe(true);
99
+ expect(
100
+ firstUp.resources.some(
101
+ ({ identity }) =>
102
+ identity.adapter === 'supabase' && identity.resourceId.startsWith('bucket/'),
103
+ ),
104
+ ).toBe(false);
105
+
106
+ const r2Outputs = firstUp.outputs.filter(({ owner }) => owner.adapter === 'r2');
107
+ expect(r2Outputs.map(({ name }) => name)).toEqual(['bucket', 'accountId', 's3Endpoint']);
108
+ expect(r2Outputs.every(({ visibility }) => visibility === 'public')).toBe(true);
109
+ expect(r2Outputs.map(({ value }) => value)).toEqual([
110
+ r2Bucket,
111
+ r2AccountId,
112
+ `https://${r2AccountId}.r2.cloudflarestorage.com`,
113
+ ]);
114
+
115
+ const serializedOutputs = JSON.stringify(firstUp.outputs);
116
+ expect(serializedOutputs).not.toContain('phase10-r2-api-token');
117
+ expect(serializedOutputs).not.toContain('phase10-private-key');
118
+ expect(serializedOutputs).not.toContain('phase10-postgres-password');
119
+ expect(serializedOutputs).not.toContain('phase10-jwt-secret');
120
+ expect(serializedOutputs).not.toContain('phase10-service-role-key');
121
+
122
+ const status = requireSuccess(
123
+ await statusInfraEnvironmentAsync(
124
+ { projectId, manifest, environment: 'production', previous: firstUp.ledger },
125
+ dependencies,
126
+ ),
127
+ );
128
+ expect(status.state).toBe('ready');
129
+
130
+ const converged = requireSuccess(
131
+ await planInfraEnvironmentAsync(
132
+ { projectId, manifest, environment: 'production', previous: firstUp.ledger },
133
+ dependencies,
134
+ ),
135
+ );
136
+ expect(converged.actions.every(({ operation }) => operation === 'noop')).toBe(true);
137
+
138
+ const secondUp = requireSuccess(
139
+ await upInfraEnvironmentAsync(
140
+ { projectId, manifest, environment: 'production', previous: firstUp.ledger },
141
+ dependencies,
142
+ ),
143
+ );
144
+ expect(fixture.r2.created).toEqual([r2Bucket]);
145
+ expect(secondUp.outputs.filter(({ owner }) => owner.adapter === 'r2')).toEqual(r2Outputs);
146
+ });
147
+
148
+ class ProductionR2Fixture {
149
+ readonly hetzner = new FakeHetznerCloudApi();
150
+ readonly hostKeyProbe = new FakeHostKeyProbe();
151
+ readonly k3s = new FakeK3sControlPlane();
152
+ readonly kubernetes = this.k3s.api;
153
+ readonly supabase = new FakeSupabaseControlPlane();
154
+ readonly r2 = new FakeR2ControlPlane();
155
+ }
156
+
157
+ function createDependencies(fixture: ProductionR2Fixture): InfraOrchestrationDependencies {
158
+ return {
159
+ adapterResolver: {
160
+ loadAsync: (packageName) => {
161
+ switch (packageName) {
162
+ case hetznerInfraAdapterDescriptor.package:
163
+ return Promise.resolve({
164
+ infraAdapterDescriptor: hetznerInfraAdapterDescriptor,
165
+ createInfraAdapter: () =>
166
+ createHetznerInfraAdapter({
167
+ api: fixture.hetzner,
168
+ hostKeyProbe: fixture.hostKeyProbe,
169
+ }),
170
+ });
171
+ case k3sInfraAdapterDescriptor.package:
172
+ return Promise.resolve({
173
+ infraAdapterDescriptor: k3sInfraAdapterDescriptor,
174
+ createInfraAdapter: () => createK3sInfraAdapter({ controlPlane: fixture.k3s }),
175
+ });
176
+ case supabaseInfraAdapterDescriptor.package:
177
+ return Promise.resolve({
178
+ infraAdapterDescriptor: supabaseInfraAdapterDescriptor,
179
+ createInfraAdapter: () =>
180
+ createSupabaseInfraAdapter({ controlPlane: fixture.supabase }),
181
+ });
182
+ case r2InfraAdapterDescriptor.package:
183
+ return Promise.resolve({
184
+ infraAdapterDescriptor: r2InfraAdapterDescriptor,
185
+ createInfraAdapter: () => createR2InfraAdapter({ cloud: fixture.r2 }),
186
+ });
187
+ default:
188
+ return Promise.reject(new Error(`Unexpected adapter package: ${packageName}`));
189
+ }
190
+ },
191
+ },
192
+ credentials: {
193
+ resolveAsync: ({ name }) => Promise.resolve(resolveCredential(name)),
194
+ },
195
+ secrets: {
196
+ resolveAsync: () =>
197
+ Promise.resolve({
198
+ ok: false,
199
+ diagnostics: [
200
+ { severity: 'error', code: 'unexpected-secret', message: 'No secret is expected.' },
201
+ ],
202
+ }),
203
+ },
204
+ };
205
+ }
206
+
207
+ function resolveCredential(name: string): InfraResult<Readonly<Record<string, string>>> {
208
+ if (name === 'HCLOUD_TOKEN') return success({ token: 'phase10-hcloud-token' });
209
+ if (name === 'HETZNER_SSH') {
210
+ return success({
211
+ publicKey: 'ssh-ed25519 AAAA phase10',
212
+ privateKey: 'phase10-private-key',
213
+ });
214
+ }
215
+ if (name === 'SUPABASE_BOOTSTRAP') {
216
+ return success({
217
+ postgresPassword: 'phase10-postgres-password',
218
+ jwtSecret: 'phase10-jwt-secret-0123456789abcdef',
219
+ anonKey: 'phase10-anon-key',
220
+ serviceRoleKey: 'phase10-service-role-key',
221
+ realtimeSecretKeyBase:
222
+ 'phase10-realtime-secret-key-base-0123456789abcdefghijklmnopqrstuvwxyz',
223
+ realtimeDatabaseEncryptionKey: '1234567890abcdef',
224
+ pgMetaCryptoKey: 'phase10-pg-meta-crypto-key-0123456789abcdef',
225
+ });
226
+ }
227
+ if (name === 'CLOUDFLARE_R2') return success({ apiToken: 'phase10-r2-api-token' });
228
+ return {
229
+ ok: false,
230
+ diagnostics: [
231
+ {
232
+ severity: 'error',
233
+ code: 'unexpected-credential',
234
+ message: `Unexpected credential reference: ${name}`,
235
+ },
236
+ ],
237
+ };
238
+ }
239
+
240
+ class FakeHetznerCloudApi implements HetznerCloudApi {
241
+ observation: HetznerCloudObservation = { resources: [] };
242
+
243
+ validateAsync(): Promise<InfraResult<null>> {
244
+ return Promise.resolve(success(null));
245
+ }
246
+
247
+ inspectAsync(): Promise<InfraResult<HetznerCloudObservation>> {
248
+ return Promise.resolve(success(this.observation));
249
+ }
250
+
251
+ reconcileAsync(
252
+ _token: string,
253
+ desired: HetznerDesiredCompute,
254
+ ): Promise<InfraResult<HetznerCloudObservation>> {
255
+ this.observation = {
256
+ resources: [desired.network, desired.firewall, desired.sshKey, desired.server].map(
257
+ (resource, index) => ({
258
+ resourceId: resource.owner.identity.resourceId as HetznerResourceId,
259
+ externalId: String(index + 1),
260
+ configurationHash: resource.configurationHash,
261
+ state: 'ready' as const,
262
+ ...(resource.owner.identity.resourceId === 'server'
263
+ ? { publicIpv4: '203.0.113.10', architecture: 'amd64' as const }
264
+ : {}),
265
+ }),
266
+ ),
267
+ };
268
+ return Promise.resolve(success(this.observation));
269
+ }
270
+
271
+ destroyAsync(
272
+ _token: string,
273
+ _identity: HetznerProjectIdentity,
274
+ resourceIds: readonly HetznerResourceId[],
275
+ ): Promise<InfraResult<HetznerCloudObservation>> {
276
+ this.observation = {
277
+ resources: this.observation.resources.filter(
278
+ ({ resourceId }) => !resourceIds.includes(resourceId),
279
+ ),
280
+ };
281
+ return Promise.resolve(success(this.observation));
282
+ }
283
+ }
284
+
285
+ class FakeHostKeyProbe implements HetznerHostKeyProbe {
286
+ fingerprintAsync(): Promise<InfraResult<string>> {
287
+ return Promise.resolve(success('SHA256:phase10-host'));
288
+ }
289
+ }
290
+
291
+ type KubernetesApi = NonNullable<K3sClusterObservation['api']>;
292
+ type KubernetesOwnershipQuery = Parameters<KubernetesApi['listOwnedAsync']>[0];
293
+ type KubernetesResource = Awaited<ReturnType<KubernetesApi['listOwnedAsync']>>[number];
294
+ type KubernetesResourceReference = Parameters<KubernetesApi['deleteAsync']>[0];
295
+ type KubernetesResourceObservation = Awaited<ReturnType<KubernetesApi['observeAsync']>>;
296
+
297
+ class FakeK3sControlPlane implements K3sControlPlane {
298
+ readonly api = new FakeKubernetesApi();
299
+ lastAccess: readonly K3sNodeAccess[] = [];
300
+ lastSpec?: K3sClusterSpec;
301
+ state: K3sClusterObservation['state'] = 'absent';
302
+ nodes: K3sClusterObservation['nodes'] = [];
303
+
304
+ validateAsync(
305
+ _spec: K3sClusterSpec,
306
+ access: readonly K3sNodeAccess[],
307
+ ): Promise<InfraResult<null>> {
308
+ this.lastAccess = access;
309
+ return Promise.resolve(success(null));
310
+ }
311
+
312
+ inspectAsync(): Promise<InfraResult<K3sClusterObservation>> {
313
+ return Promise.resolve(success(this.observation()));
314
+ }
315
+
316
+ ensureAsync(
317
+ spec: K3sClusterSpec,
318
+ access: readonly K3sNodeAccess[],
319
+ ): Promise<InfraResult<K3sClusterObservation>> {
320
+ this.lastAccess = access;
321
+ this.lastSpec = spec;
322
+ this.state = 'ready';
323
+ this.nodes = spec.nodes.map(({ id }) => ({
324
+ id,
325
+ state: 'ready',
326
+ configurationMatches: true,
327
+ }));
328
+ return Promise.resolve(success(this.observation()));
329
+ }
330
+
331
+ waitUntilReadyAsync(): Promise<InfraResult<K3sClusterObservation>> {
332
+ return Promise.resolve(success(this.observation()));
333
+ }
334
+
335
+ loadImagesAsync(
336
+ _spec: K3sClusterSpec,
337
+ _access: readonly K3sNodeAccess[],
338
+ _images: readonly string[],
339
+ ): Promise<InfraResult<null>> {
340
+ return Promise.resolve(success(null));
341
+ }
342
+
343
+ suspendAsync(): Promise<InfraResult<null>> {
344
+ this.state = 'stopped';
345
+ this.nodes = this.nodes.map((node) => ({ ...node, state: 'stopped' }));
346
+ return Promise.resolve(success(null));
347
+ }
348
+
349
+ destroyAsync(): Promise<InfraResult<null>> {
350
+ this.state = 'absent';
351
+ this.nodes = [];
352
+ return Promise.resolve(success(null));
353
+ }
354
+
355
+ private observation(): K3sClusterObservation {
356
+ return {
357
+ state: this.state,
358
+ configurationMatches: true,
359
+ nodes: this.nodes,
360
+ ...(this.state === 'ready' ? { api: this.api } : {}),
361
+ };
362
+ }
363
+ }
364
+
365
+ class FakeKubernetesApi implements KubernetesApi {
366
+ readonly resources: KubernetesResource[] = [];
367
+
368
+ listOwnedAsync(query: KubernetesOwnershipQuery): Promise<readonly KubernetesResource[]> {
369
+ return Promise.resolve(
370
+ this.resources.filter(({ metadata }) => includesLabels(metadata.labels, query.labels)),
371
+ );
372
+ }
373
+
374
+ applyAsync(resource: KubernetesResource): Promise<void> {
375
+ const index = this.resources.findIndex((candidate) => sameResource(candidate, resource));
376
+ if (index === -1) this.resources.push(resource);
377
+ else this.resources.splice(index, 1, resource);
378
+ return Promise.resolve();
379
+ }
380
+
381
+ deleteAsync(reference: KubernetesResourceReference): Promise<void> {
382
+ const index = this.resources.findIndex((resource) => sameResource(resource, reference));
383
+ if (index >= 0) this.resources.splice(index, 1);
384
+ return Promise.resolve();
385
+ }
386
+
387
+ observeAsync(reference: KubernetesResourceReference): Promise<KubernetesResourceObservation> {
388
+ return Promise.resolve({
389
+ state: 'ready',
390
+ ...(reference.kind === 'Service' ? { publicOutputs: { endpoint: publicBaseUrl } } : {}),
391
+ });
392
+ }
393
+
394
+ waitUntilReadyAsync(): Promise<KubernetesResourceObservation> {
395
+ return Promise.resolve({ state: 'ready' });
396
+ }
397
+
398
+ serializedResources(): string {
399
+ return JSON.stringify(this.resources);
400
+ }
401
+ }
402
+
403
+ class FakeSupabaseControlPlane implements SupabaseControlPlane {
404
+ readonly created: string[] = [];
405
+
406
+ healthAsync(_request: SupabaseControlPlaneRequest): Promise<InfraResult<null>> {
407
+ return Promise.resolve(success(null));
408
+ }
409
+
410
+ listBucketsAsync(_request: SupabaseControlPlaneRequest): Promise<InfraResult<readonly string[]>> {
411
+ return Promise.resolve(success([]));
412
+ }
413
+
414
+ createBucketAsync(
415
+ request: SupabaseControlPlaneRequest & { readonly bucket: string },
416
+ ): Promise<InfraResult<null>> {
417
+ this.created.push(request.bucket);
418
+ return Promise.resolve(success(null));
419
+ }
420
+
421
+ deleteBucketAsync(
422
+ _request: SupabaseControlPlaneRequest & { readonly bucket: string },
423
+ ): Promise<InfraResult<null>> {
424
+ return Promise.resolve(success(null));
425
+ }
426
+ }
427
+
428
+ class FakeR2ControlPlane implements R2BucketControlPlane {
429
+ readonly created: string[] = [];
430
+ private readonly buckets = new Set<string>();
431
+
432
+ listBucketsAsync(): Promise<InfraResult<readonly R2BucketObservation[]>> {
433
+ return Promise.resolve(success([...this.buckets].map((name) => ({ name }))));
434
+ }
435
+
436
+ createBucketAsync(
437
+ request: R2CloudRequest & { readonly bucket: string },
438
+ ): Promise<InfraResult<R2BucketObservation>> {
439
+ this.created.push(request.bucket);
440
+ this.buckets.add(request.bucket);
441
+ return Promise.resolve(success({ name: request.bucket }));
442
+ }
443
+
444
+ deleteBucketAsync(
445
+ request: R2CloudRequest & { readonly bucket: string },
446
+ ): Promise<InfraResult<null>> {
447
+ this.buckets.delete(request.bucket);
448
+ return Promise.resolve(success(null));
449
+ }
450
+ }
451
+
452
+ function includesLabels(
453
+ actual: Readonly<Record<string, string>>,
454
+ expected: Readonly<Record<string, string>>,
455
+ ): boolean {
456
+ return Object.entries(expected).every(([expectedKey, expectedValue]) =>
457
+ Object.entries(actual).some(
458
+ ([actualKey, actualValue]) => actualKey === expectedKey && actualValue === expectedValue,
459
+ ),
460
+ );
461
+ }
462
+
463
+ function sameResource(
464
+ left: KubernetesResource,
465
+ right: KubernetesResource | KubernetesResourceReference,
466
+ ): boolean {
467
+ return (
468
+ left.apiVersion === right.apiVersion &&
469
+ left.kind === right.kind &&
470
+ left.metadata.name === ('metadata' in right ? right.metadata.name : right.name) &&
471
+ left.metadata.namespace === ('metadata' in right ? right.metadata.namespace : right.namespace)
472
+ );
473
+ }
474
+
475
+ function requireSuccess<T>(result: InfraResult<T>): T {
476
+ if (!result.ok) throw new Error(result.diagnostics.map(({ message }) => message).join(' '));
477
+ return result.value;
478
+ }
479
+
480
+ function success<T>(value: T): InfraResult<T> {
481
+ return { ok: true, value, diagnostics: [] };
482
+ }
@@ -0,0 +1,448 @@
1
+ import type {
2
+ InfraComputeTarget,
3
+ InfraLedger,
4
+ InfraManifest,
5
+ InfraResourceIdentity,
6
+ InfraResult,
7
+ } from '@ankhorage/contracts/infra';
8
+ import {
9
+ createInfraAdapter as createK3sInfraAdapter,
10
+ infraAdapterDescriptor as k3sInfraAdapterDescriptor,
11
+ type K3sClusterObservation,
12
+ type K3sClusterSpec,
13
+ type K3sControlPlane,
14
+ type K3sNodeAccess,
15
+ } from '@ankhorage/k3s';
16
+ import {
17
+ createInfraAdapter as createLocalInfraAdapter,
18
+ infraAdapterDescriptor as localInfraAdapterDescriptor,
19
+ type LocalHostObservation,
20
+ type LocalHostProbe,
21
+ } from '@ankhorage/local';
22
+ import {
23
+ createInfraAdapter as createSupabaseInfraAdapter,
24
+ infraAdapterDescriptor as supabaseInfraAdapterDescriptor,
25
+ type SupabaseControlPlane,
26
+ type SupabaseControlPlaneRequest,
27
+ } from '@ankhorage/supabase';
28
+ import { expect, test } from 'bun:test';
29
+
30
+ import { destroyInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/destroyInfraEnvironmentAsync.js';
31
+ import { downInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/downInfraEnvironmentAsync.js';
32
+ import { getInfraEnvironmentOutputs } from './features/environment-lifecycle/application/use-cases/getInfraEnvironmentOutputs.js';
33
+ import { planInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/planInfraEnvironmentAsync.js';
34
+ import { statusInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/statusInfraEnvironmentAsync.js';
35
+ import { upInfraEnvironmentAsync } from './features/environment-lifecycle/application/use-cases/upInfraEnvironmentAsync.js';
36
+ import type { InfraOrchestrationDependencies } from './types/infraOrchestration.js';
37
+
38
+ const projectId = 'infra164-local-k3s-supabase';
39
+ const publicBaseUrl = 'http://127.0.0.1:54321';
40
+ const bucket = 'infra164-bucket';
41
+ const target: Extract<InfraComputeTarget, { kind: 'local-host' }> = {
42
+ id: 'local',
43
+ kind: 'local-host',
44
+ os: 'linux',
45
+ architecture: 'amd64',
46
+ };
47
+ const manifest = {
48
+ environments: {
49
+ local: {
50
+ deployment: {
51
+ compute: { provider: 'local' },
52
+ runtime: { provider: 'k3s', topology: { servers: 1, agents: 0 } },
53
+ },
54
+ database: { provider: 'supabase', tier: 'dev' },
55
+ auth: { provider: 'supabase' },
56
+ objectStorage: { provider: 'supabase', buckets: [bucket] },
57
+ networking: { publicBaseUrl },
58
+ },
59
+ },
60
+ modules: [],
61
+ } as const satisfies InfraManifest;
62
+
63
+ test('runs local k3s and Supabase through the portable compute lifecycle', async () => {
64
+ const fixture = new LocalK3sFixture();
65
+ const dependencies = createDependencies(fixture);
66
+
67
+ const initialPlan = requireSuccess(
68
+ await planInfraEnvironmentAsync({ projectId, manifest }, dependencies),
69
+ );
70
+ expect(initialPlan.actions.some(({ operation }) => operation === 'create')).toBe(true);
71
+
72
+ const firstUp = requireSuccess(
73
+ await upInfraEnvironmentAsync({ projectId, manifest }, dependencies),
74
+ );
75
+ const firstLedger: InfraLedger = firstUp.ledger;
76
+ expect(firstUp.targets).toEqual([target]);
77
+ expect([...new Set(fixture.loadedPackages)].sort()).toEqual(
78
+ [
79
+ localInfraAdapterDescriptor.package,
80
+ k3sInfraAdapterDescriptor.package,
81
+ supabaseInfraAdapterDescriptor.package,
82
+ ].sort(),
83
+ );
84
+ expect(fixture.k3s.lastAccess).toHaveLength(1);
85
+ expect(fixture.k3s.lastAccess[0]?.transport).toEqual({ kind: 'local' });
86
+ expect(fixture.k3s.lastSpec?.nodes[0]?.target).toEqual(target);
87
+ expect(fixture.kubernetes.serializedResources()).toContain('PersistentVolumeClaim');
88
+ expect(fixture.kubernetes.serializedResources()).toContain('/etc/postgresql-custom');
89
+ expect(fixture.kubernetes.serializedResources()).toContain('.ankhorage-image-seeded');
90
+ expect(fixture.supabase.buckets.has(bucket)).toBe(true);
91
+ expect(JSON.stringify(firstUp)).not.toContain('infra164-service-role-key');
92
+ expect(JSON.stringify(firstUp)).not.toContain('infra164-postgres-password');
93
+
94
+ const outputs = requireSuccess(
95
+ getInfraEnvironmentOutputs({
96
+ projectId,
97
+ manifest,
98
+ environment: 'local',
99
+ previous: firstLedger,
100
+ }),
101
+ );
102
+ expect(outputs.outputs).toEqual(firstUp.outputs);
103
+ expect(
104
+ outputs.outputs.some(
105
+ ({ environmentVariable, value }) =>
106
+ environmentVariable === 'EXPO_PUBLIC_SUPABASE_URL' && value === publicBaseUrl,
107
+ ),
108
+ ).toBe(true);
109
+ expect(outputs.outputs.some(({ name, value }) => name === 'bucket' && value === bucket)).toBe(
110
+ true,
111
+ );
112
+
113
+ const status = requireSuccess(
114
+ await statusInfraEnvironmentAsync(
115
+ { projectId, manifest, environment: 'local', previous: firstLedger },
116
+ dependencies,
117
+ ),
118
+ );
119
+ expect(status.state).toBe('ready');
120
+
121
+ const converged = requireSuccess(
122
+ await planInfraEnvironmentAsync(
123
+ { projectId, manifest, environment: 'local', previous: firstLedger },
124
+ dependencies,
125
+ ),
126
+ );
127
+ expect(converged.actions.every(({ operation }) => operation === 'noop')).toBe(true);
128
+
129
+ const identitiesBeforeRestart = resourceIdentities(firstUp.resources);
130
+ const down = requireSuccess(
131
+ await downInfraEnvironmentAsync(
132
+ { projectId, manifest, environment: 'local', previous: firstLedger },
133
+ dependencies,
134
+ ),
135
+ );
136
+ expect(fixture.k3s.state).toBe('stopped');
137
+
138
+ const resumed = requireSuccess(
139
+ await upInfraEnvironmentAsync(
140
+ { projectId, manifest, environment: 'local', previous: down.ledger },
141
+ dependencies,
142
+ ),
143
+ );
144
+ expect(fixture.k3s.state).toBe('ready');
145
+ expect(resumed.targets).toEqual([target]);
146
+ expect(resourceIdentities(resumed.resources)).toEqual(identitiesBeforeRestart);
147
+
148
+ const destroyed = requireSuccess(
149
+ await destroyInfraEnvironmentAsync(
150
+ {
151
+ projectId,
152
+ manifest,
153
+ environment: 'local',
154
+ previous: resumed.ledger,
155
+ confirmation: { projectId, environment: 'local' },
156
+ persistence: {
157
+ policy: 'delete',
158
+ confirmedResources: persistentIdentities(resumed.ledger),
159
+ },
160
+ },
161
+ dependencies,
162
+ ),
163
+ );
164
+ expect(destroyed.ledger).toBeNull();
165
+ expect(fixture.k3s.state).toBe('absent');
166
+ expect(fixture.k3s.calls).toContain('destroy');
167
+ });
168
+
169
+ class LocalK3sFixture {
170
+ readonly local = new FakeLocalHostProbe();
171
+ readonly k3s = new FakeK3sControlPlane();
172
+ readonly kubernetes = this.k3s.api;
173
+ readonly supabase = new FakeSupabaseControlPlane();
174
+ readonly loadedPackages: string[] = [];
175
+ }
176
+
177
+ function createDependencies(fixture: LocalK3sFixture): InfraOrchestrationDependencies {
178
+ return {
179
+ adapterResolver: {
180
+ loadAsync: (packageName) => {
181
+ fixture.loadedPackages.push(packageName);
182
+ switch (packageName) {
183
+ case localInfraAdapterDescriptor.package:
184
+ return Promise.resolve({
185
+ infraAdapterDescriptor: localInfraAdapterDescriptor,
186
+ createInfraAdapter: () => createLocalInfraAdapter({ probe: fixture.local }),
187
+ });
188
+ case k3sInfraAdapterDescriptor.package:
189
+ return Promise.resolve({
190
+ infraAdapterDescriptor: k3sInfraAdapterDescriptor,
191
+ createInfraAdapter: () => createK3sInfraAdapter({ controlPlane: fixture.k3s }),
192
+ });
193
+ case supabaseInfraAdapterDescriptor.package:
194
+ return Promise.resolve({
195
+ infraAdapterDescriptor: supabaseInfraAdapterDescriptor,
196
+ createInfraAdapter: () =>
197
+ createSupabaseInfraAdapter({ controlPlane: fixture.supabase }),
198
+ });
199
+ default:
200
+ return Promise.reject(new Error(`Unexpected adapter package: ${packageName}`));
201
+ }
202
+ },
203
+ },
204
+ credentials: {
205
+ resolveAsync: ({ name }) => Promise.resolve(resolveCredential(name)),
206
+ },
207
+ secrets: {
208
+ resolveAsync: () =>
209
+ Promise.resolve({
210
+ ok: false,
211
+ diagnostics: [
212
+ { severity: 'error', code: 'unexpected-secret', message: 'No secret is expected.' },
213
+ ],
214
+ }),
215
+ },
216
+ };
217
+ }
218
+
219
+ function resolveCredential(name: string): InfraResult<Readonly<Record<string, string>>> {
220
+ if (name === 'SUPABASE_BOOTSTRAP') {
221
+ return success({
222
+ postgresPassword: 'infra164-postgres-password',
223
+ jwtSecret: 'infra164-jwt-secret-0123456789abcdef',
224
+ anonKey: 'infra164-anon-key',
225
+ serviceRoleKey: 'infra164-service-role-key',
226
+ realtimeSecretKeyBase:
227
+ 'infra164-realtime-secret-key-base-0123456789abcdefghijklmnopqrstuvwxyz',
228
+ realtimeDatabaseEncryptionKey: '1234567890abcdef',
229
+ pgMetaCryptoKey: 'infra164-pg-meta-crypto-key-0123456789abcdef',
230
+ });
231
+ }
232
+ return {
233
+ ok: false,
234
+ diagnostics: [
235
+ {
236
+ severity: 'error',
237
+ code: 'unexpected-credential',
238
+ message: `Unexpected credential reference: ${name}`,
239
+ },
240
+ ],
241
+ };
242
+ }
243
+
244
+ class FakeLocalHostProbe implements LocalHostProbe {
245
+ inspectAsync(workingDirectory: string): Promise<InfraResult<LocalHostObservation>> {
246
+ return Promise.resolve(
247
+ success({
248
+ target,
249
+ workingDirectory,
250
+ exists: true,
251
+ readable: true,
252
+ writable: true,
253
+ }),
254
+ );
255
+ }
256
+ }
257
+
258
+ type KubernetesApi = NonNullable<K3sClusterObservation['api']>;
259
+ type KubernetesOwnershipQuery = Parameters<KubernetesApi['listOwnedAsync']>[0];
260
+ type KubernetesResource = Awaited<ReturnType<KubernetesApi['listOwnedAsync']>>[number];
261
+ type KubernetesResourceReference = Parameters<KubernetesApi['deleteAsync']>[0];
262
+ type KubernetesResourceObservation = Awaited<ReturnType<KubernetesApi['observeAsync']>>;
263
+
264
+ class FakeK3sControlPlane implements K3sControlPlane {
265
+ readonly api = new FakeKubernetesApi();
266
+ readonly calls: string[] = [];
267
+ lastAccess: readonly K3sNodeAccess[] = [];
268
+ lastSpec?: K3sClusterSpec;
269
+ state: K3sClusterObservation['state'] = 'absent';
270
+ nodes: K3sClusterObservation['nodes'] = [];
271
+
272
+ validateAsync(
273
+ _spec: K3sClusterSpec,
274
+ access: readonly K3sNodeAccess[],
275
+ ): Promise<InfraResult<null>> {
276
+ this.calls.push('validate');
277
+ this.lastAccess = access;
278
+ return Promise.resolve(success(null));
279
+ }
280
+
281
+ inspectAsync(): Promise<InfraResult<K3sClusterObservation>> {
282
+ this.calls.push('inspect');
283
+ return Promise.resolve(success(this.observation()));
284
+ }
285
+
286
+ ensureAsync(
287
+ spec: K3sClusterSpec,
288
+ access: readonly K3sNodeAccess[],
289
+ ): Promise<InfraResult<K3sClusterObservation>> {
290
+ this.calls.push('ensure');
291
+ this.lastAccess = access;
292
+ this.lastSpec = spec;
293
+ this.state = 'ready';
294
+ this.nodes = spec.nodes.map(({ id }) => ({
295
+ id,
296
+ state: 'ready',
297
+ configurationMatches: true,
298
+ }));
299
+ return Promise.resolve(success(this.observation()));
300
+ }
301
+
302
+ waitUntilReadyAsync(): Promise<InfraResult<K3sClusterObservation>> {
303
+ this.calls.push('wait');
304
+ return Promise.resolve(success(this.observation()));
305
+ }
306
+
307
+ loadImagesAsync(
308
+ _spec: K3sClusterSpec,
309
+ _access: readonly K3sNodeAccess[],
310
+ images: readonly string[],
311
+ ): Promise<InfraResult<null>> {
312
+ this.calls.push(`images:${images.join(',')}`);
313
+ return Promise.resolve(success(null));
314
+ }
315
+
316
+ suspendAsync(): Promise<InfraResult<null>> {
317
+ this.calls.push('suspend');
318
+ this.state = 'stopped';
319
+ this.nodes = this.nodes.map((node) => ({ ...node, state: 'stopped' }));
320
+ return Promise.resolve(success(null));
321
+ }
322
+
323
+ destroyAsync(): Promise<InfraResult<null>> {
324
+ this.calls.push('destroy');
325
+ this.state = 'absent';
326
+ this.nodes = [];
327
+ return Promise.resolve(success(null));
328
+ }
329
+
330
+ private observation(): K3sClusterObservation {
331
+ return {
332
+ state: this.state,
333
+ configurationMatches: true,
334
+ nodes: this.nodes,
335
+ ...(this.state === 'ready' ? { api: this.api } : {}),
336
+ };
337
+ }
338
+ }
339
+
340
+ class FakeKubernetesApi implements KubernetesApi {
341
+ readonly resources: KubernetesResource[] = [];
342
+
343
+ listOwnedAsync(query: KubernetesOwnershipQuery): Promise<readonly KubernetesResource[]> {
344
+ return Promise.resolve(
345
+ this.resources.filter(({ metadata }) => includesLabels(metadata.labels, query.labels)),
346
+ );
347
+ }
348
+
349
+ applyAsync(resource: KubernetesResource): Promise<void> {
350
+ const index = this.resources.findIndex((candidate) => sameResource(candidate, resource));
351
+ if (index === -1) this.resources.push(resource);
352
+ else this.resources.splice(index, 1, resource);
353
+ return Promise.resolve();
354
+ }
355
+
356
+ deleteAsync(reference: KubernetesResourceReference): Promise<void> {
357
+ const index = this.resources.findIndex((resource) => sameResource(resource, reference));
358
+ if (index >= 0) this.resources.splice(index, 1);
359
+ return Promise.resolve();
360
+ }
361
+
362
+ observeAsync(reference: KubernetesResourceReference): Promise<KubernetesResourceObservation> {
363
+ return Promise.resolve({
364
+ state: 'ready',
365
+ ...(reference.kind === 'Service' ? { publicOutputs: { endpoint: publicBaseUrl } } : {}),
366
+ });
367
+ }
368
+
369
+ waitUntilReadyAsync(): Promise<KubernetesResourceObservation> {
370
+ return Promise.resolve({ state: 'ready' });
371
+ }
372
+
373
+ serializedResources(): string {
374
+ return JSON.stringify(this.resources);
375
+ }
376
+ }
377
+
378
+ class FakeSupabaseControlPlane implements SupabaseControlPlane {
379
+ readonly buckets = new Set<string>();
380
+
381
+ healthAsync(_request: SupabaseControlPlaneRequest): Promise<InfraResult<null>> {
382
+ return Promise.resolve(success(null));
383
+ }
384
+
385
+ listBucketsAsync(_request: SupabaseControlPlaneRequest): Promise<InfraResult<readonly string[]>> {
386
+ return Promise.resolve(success([...this.buckets]));
387
+ }
388
+
389
+ createBucketAsync(
390
+ request: SupabaseControlPlaneRequest & { readonly bucket: string },
391
+ ): Promise<InfraResult<null>> {
392
+ this.buckets.add(request.bucket);
393
+ return Promise.resolve(success(null));
394
+ }
395
+
396
+ deleteBucketAsync(
397
+ request: SupabaseControlPlaneRequest & { readonly bucket: string },
398
+ ): Promise<InfraResult<null>> {
399
+ this.buckets.delete(request.bucket);
400
+ return Promise.resolve(success(null));
401
+ }
402
+ }
403
+
404
+ function persistentIdentities(ledger: InfraLedger): readonly InfraResourceIdentity[] {
405
+ return ledger.resources.filter(({ persistent }) => persistent).map(({ identity }) => identity);
406
+ }
407
+
408
+ function resourceIdentities(
409
+ resources: readonly { readonly identity: InfraResourceIdentity }[],
410
+ ): readonly string[] {
411
+ return resources
412
+ .map(({ identity }) =>
413
+ [identity.projectId, identity.environment, identity.adapter, identity.resourceId].join(':'),
414
+ )
415
+ .sort();
416
+ }
417
+
418
+ function includesLabels(
419
+ actual: Readonly<Record<string, string>>,
420
+ expected: Readonly<Record<string, string>>,
421
+ ): boolean {
422
+ return Object.entries(expected).every(([expectedKey, expectedValue]) =>
423
+ Object.entries(actual).some(
424
+ ([actualKey, actualValue]) => actualKey === expectedKey && actualValue === expectedValue,
425
+ ),
426
+ );
427
+ }
428
+
429
+ function sameResource(
430
+ left: KubernetesResource,
431
+ right: KubernetesResource | KubernetesResourceReference,
432
+ ): boolean {
433
+ return (
434
+ left.apiVersion === right.apiVersion &&
435
+ left.kind === right.kind &&
436
+ left.metadata.name === ('metadata' in right ? right.metadata.name : right.name) &&
437
+ left.metadata.namespace === ('metadata' in right ? right.metadata.namespace : right.namespace)
438
+ );
439
+ }
440
+
441
+ function requireSuccess<T>(result: InfraResult<T>): T {
442
+ if (!result.ok) throw new Error(result.diagnostics.map(({ message }) => message).join(' '));
443
+ return result.value;
444
+ }
445
+
446
+ function success<T>(value: T): InfraResult<T> {
447
+ return { ok: true, value, diagnostics: [] };
448
+ }
@@ -0,0 +1,322 @@
1
+ import type {
2
+ InfraComputeAdapter,
3
+ InfraComputeSnapshot,
4
+ InfraManifest,
5
+ InfraPlanAction,
6
+ InfraReconcileResult,
7
+ InfraResourceStatus,
8
+ InfraResult,
9
+ } from '@ankhorage/contracts/infra';
10
+ import { infraAdapterDescriptor as hetznerInfraAdapterDescriptor } from '@ankhorage/hetzner';
11
+ import {
12
+ createInfraAdapter as createK3sInfraAdapter,
13
+ infraAdapterDescriptor as k3sInfraAdapterDescriptor,
14
+ type K3sClusterObservation,
15
+ type K3sClusterSpec,
16
+ type K3sControlPlane,
17
+ type K3sNodeAccess,
18
+ } from '@ankhorage/k3s';
19
+ import { expect, test } from 'bun:test';
20
+
21
+ import { type InfraOrchestrationDependencies, upInfraEnvironmentAsync } from './index.js';
22
+
23
+ const projectId = 'infra162-server-runtime-environment';
24
+ const serverImage = 'example/server:production';
25
+
26
+ const manifest = {
27
+ environments: {
28
+ local: {
29
+ deployment: {
30
+ compute: { provider: 'local' },
31
+ runtime: { provider: 'docker-compose' },
32
+ },
33
+ },
34
+ preview: {
35
+ deployment: {
36
+ compute: { provider: 'hetzner', location: 'fsn1' },
37
+ runtime: { provider: 'k3s', topology: { servers: 1, agents: 0 } },
38
+ },
39
+ workloads: [serverWorkload('development')],
40
+ },
41
+ production: {
42
+ deployment: {
43
+ compute: { provider: 'hetzner', location: 'fsn1' },
44
+ runtime: { provider: 'k3s', topology: { servers: 1, agents: 0 } },
45
+ },
46
+ workloads: [serverWorkload('production')],
47
+ },
48
+ },
49
+ modules: [],
50
+ } as const satisfies InfraManifest;
51
+
52
+ test('projects explicit production server environment through the generic k3s workload path', async () => {
53
+ const fixture = new ProductionServerFixture();
54
+ const dependencies = createDependencies(fixture);
55
+
56
+ const first = requireSuccess(
57
+ await upInfraEnvironmentAsync({ projectId, manifest, environment: 'production' }, dependencies),
58
+ );
59
+ const firstProjection = fixture.kubernetes.serializedResources();
60
+
61
+ expect(first.environment).toBe('production');
62
+ expect(firstProjection).toContain('"name":"NODE_ENV","value":"production"');
63
+ expect(fixture.k3s.loadedImages).toEqual([serverImage]);
64
+
65
+ requireSuccess(
66
+ await upInfraEnvironmentAsync(
67
+ {
68
+ projectId,
69
+ manifest,
70
+ environment: 'production',
71
+ previous: first.ledger,
72
+ },
73
+ dependencies,
74
+ ),
75
+ );
76
+
77
+ expect(fixture.kubernetes.serializedResources()).toBe(firstProjection);
78
+ });
79
+
80
+ test('preserves an explicitly non-production server environment without rewriting it', async () => {
81
+ const fixture = new ProductionServerFixture();
82
+
83
+ const result = requireSuccess(
84
+ await upInfraEnvironmentAsync(
85
+ { projectId, manifest, environment: 'preview' },
86
+ createDependencies(fixture),
87
+ ),
88
+ );
89
+ const projection = fixture.kubernetes.serializedResources();
90
+
91
+ expect(result.environment).toBe('preview');
92
+ expect(projection).toContain('"name":"NODE_ENV","value":"development"');
93
+ expect(projection).not.toContain('"name":"NODE_ENV","value":"production"');
94
+ });
95
+
96
+ function serverWorkload(nodeEnvironment: 'development' | 'production') {
97
+ return {
98
+ id: 'server',
99
+ artifact: { kind: 'image' as const, image: serverImage },
100
+ environment: {
101
+ NODE_ENV: { kind: 'literal' as const, value: nodeEnvironment },
102
+ },
103
+ };
104
+ }
105
+
106
+ class ProductionServerFixture {
107
+ readonly compute = new FakeHetznerComputeAdapter();
108
+ readonly k3s = new FakeK3sControlPlane();
109
+ readonly kubernetes = this.k3s.api;
110
+ }
111
+
112
+ function createDependencies(fixture: ProductionServerFixture): InfraOrchestrationDependencies {
113
+ return {
114
+ adapterResolver: {
115
+ loadAsync: (packageName) => {
116
+ switch (packageName) {
117
+ case hetznerInfraAdapterDescriptor.package:
118
+ return Promise.resolve({
119
+ infraAdapterDescriptor: hetznerInfraAdapterDescriptor,
120
+ createInfraAdapter: () => fixture.compute,
121
+ });
122
+ case k3sInfraAdapterDescriptor.package:
123
+ return Promise.resolve({
124
+ infraAdapterDescriptor: k3sInfraAdapterDescriptor,
125
+ createInfraAdapter: () => createK3sInfraAdapter({ controlPlane: fixture.k3s }),
126
+ });
127
+ default:
128
+ return Promise.reject(new Error(`Unexpected adapter package: ${packageName}`));
129
+ }
130
+ },
131
+ },
132
+ credentials: {
133
+ resolveAsync: () => Promise.resolve(success({ token: 'fixture-token' })),
134
+ },
135
+ secrets: {
136
+ resolveAsync: () =>
137
+ Promise.resolve({
138
+ ok: false,
139
+ diagnostics: [
140
+ { severity: 'error', code: 'unexpected-secret', message: 'No secret is expected.' },
141
+ ],
142
+ }),
143
+ },
144
+ };
145
+ }
146
+
147
+ class FakeHetznerComputeAdapter implements InfraComputeAdapter<'hetzner'> {
148
+ readonly descriptor = hetznerInfraAdapterDescriptor;
149
+ readonly snapshot: InfraComputeSnapshot = {
150
+ targets: [
151
+ {
152
+ id: 'server',
153
+ kind: 'ssh-host',
154
+ os: 'linux',
155
+ architecture: 'amd64',
156
+ host: '203.0.113.162',
157
+ port: 22,
158
+ user: 'root',
159
+ credential: { source: 'control-plane', name: 'SERVER_SSH' },
160
+ hostKeyFingerprint: 'SHA256:infra162-server',
161
+ },
162
+ ],
163
+ resources: [],
164
+ outputs: [],
165
+ };
166
+
167
+ validateAsync(): Promise<InfraResult<null>> {
168
+ return Promise.resolve(success(null));
169
+ }
170
+
171
+ inspectAsync(): Promise<InfraResult<InfraComputeSnapshot>> {
172
+ return Promise.resolve(success(this.snapshot));
173
+ }
174
+
175
+ planAsync(): Promise<InfraResult<readonly InfraPlanAction[]>> {
176
+ return Promise.resolve(success([]));
177
+ }
178
+
179
+ ensureAsync(): Promise<InfraResult<InfraComputeSnapshot>> {
180
+ return Promise.resolve(success(this.snapshot));
181
+ }
182
+
183
+ statusAsync(): Promise<InfraResult<readonly InfraResourceStatus[]>> {
184
+ return Promise.resolve(success([]));
185
+ }
186
+
187
+ destroyAsync(): Promise<InfraResult<InfraReconcileResult>> {
188
+ return Promise.resolve(success({ resources: [], outputs: [] }));
189
+ }
190
+ }
191
+
192
+ type KubernetesApi = NonNullable<K3sClusterObservation['api']>;
193
+ type KubernetesOwnershipQuery = Parameters<KubernetesApi['listOwnedAsync']>[0];
194
+ type KubernetesResource = Awaited<ReturnType<KubernetesApi['listOwnedAsync']>>[number];
195
+ type KubernetesResourceReference = Parameters<KubernetesApi['deleteAsync']>[0];
196
+ type KubernetesResourceObservation = Awaited<ReturnType<KubernetesApi['observeAsync']>>;
197
+
198
+ class FakeK3sControlPlane implements K3sControlPlane {
199
+ readonly api = new FakeKubernetesApi();
200
+ loadedImages: readonly string[] = [];
201
+ state: K3sClusterObservation['state'] = 'absent';
202
+ nodes: K3sClusterObservation['nodes'] = [];
203
+
204
+ validateAsync(): Promise<InfraResult<null>> {
205
+ return Promise.resolve(success(null));
206
+ }
207
+
208
+ inspectAsync(): Promise<InfraResult<K3sClusterObservation>> {
209
+ return Promise.resolve(success(this.observation()));
210
+ }
211
+
212
+ ensureAsync(spec: K3sClusterSpec): Promise<InfraResult<K3sClusterObservation>> {
213
+ this.state = 'ready';
214
+ this.nodes = spec.nodes.map(({ id }) => ({
215
+ id,
216
+ state: 'ready',
217
+ configurationMatches: true,
218
+ }));
219
+ return Promise.resolve(success(this.observation()));
220
+ }
221
+
222
+ waitUntilReadyAsync(): Promise<InfraResult<K3sClusterObservation>> {
223
+ return Promise.resolve(success(this.observation()));
224
+ }
225
+
226
+ loadImagesAsync(
227
+ _spec: K3sClusterSpec,
228
+ _access: readonly K3sNodeAccess[],
229
+ images: readonly string[],
230
+ ): Promise<InfraResult<null>> {
231
+ this.loadedImages = [...images];
232
+ return Promise.resolve(success(null));
233
+ }
234
+
235
+ suspendAsync(): Promise<InfraResult<null>> {
236
+ this.state = 'stopped';
237
+ this.nodes = this.nodes.map((node) => ({ ...node, state: 'stopped' }));
238
+ return Promise.resolve(success(null));
239
+ }
240
+
241
+ destroyAsync(): Promise<InfraResult<null>> {
242
+ this.state = 'absent';
243
+ this.nodes = [];
244
+ return Promise.resolve(success(null));
245
+ }
246
+
247
+ private observation(): K3sClusterObservation {
248
+ return {
249
+ state: this.state,
250
+ configurationMatches: true,
251
+ nodes: this.nodes,
252
+ ...(this.state === 'ready' ? { api: this.api } : {}),
253
+ };
254
+ }
255
+ }
256
+
257
+ class FakeKubernetesApi implements KubernetesApi {
258
+ readonly resources: KubernetesResource[] = [];
259
+
260
+ listOwnedAsync(query: KubernetesOwnershipQuery): Promise<readonly KubernetesResource[]> {
261
+ return Promise.resolve(
262
+ this.resources.filter(({ metadata }) => includesLabels(metadata.labels, query.labels)),
263
+ );
264
+ }
265
+
266
+ applyAsync(resource: KubernetesResource): Promise<void> {
267
+ const index = this.resources.findIndex((candidate) => sameResource(candidate, resource));
268
+ if (index === -1) this.resources.push(resource);
269
+ else this.resources.splice(index, 1, resource);
270
+ return Promise.resolve();
271
+ }
272
+
273
+ deleteAsync(reference: KubernetesResourceReference): Promise<void> {
274
+ const index = this.resources.findIndex((resource) => sameResource(resource, reference));
275
+ if (index >= 0) this.resources.splice(index, 1);
276
+ return Promise.resolve();
277
+ }
278
+
279
+ observeAsync(): Promise<KubernetesResourceObservation> {
280
+ return Promise.resolve({ state: 'ready' });
281
+ }
282
+
283
+ waitUntilReadyAsync(): Promise<KubernetesResourceObservation> {
284
+ return Promise.resolve({ state: 'ready' });
285
+ }
286
+
287
+ serializedResources(): string {
288
+ return JSON.stringify(this.resources);
289
+ }
290
+ }
291
+
292
+ function includesLabels(
293
+ actual: Readonly<Record<string, string>>,
294
+ expected: Readonly<Record<string, string>>,
295
+ ): boolean {
296
+ return Object.entries(expected).every(([expectedKey, expectedValue]) =>
297
+ Object.entries(actual).some(
298
+ ([actualKey, actualValue]) => actualKey === expectedKey && actualValue === expectedValue,
299
+ ),
300
+ );
301
+ }
302
+
303
+ function sameResource(
304
+ left: KubernetesResource,
305
+ right: KubernetesResource | KubernetesResourceReference,
306
+ ): boolean {
307
+ return (
308
+ left.apiVersion === right.apiVersion &&
309
+ left.kind === right.kind &&
310
+ left.metadata.name === ('metadata' in right ? right.metadata.name : right.name) &&
311
+ left.metadata.namespace === ('metadata' in right ? right.metadata.namespace : right.namespace)
312
+ );
313
+ }
314
+
315
+ function requireSuccess<T>(result: InfraResult<T>): T {
316
+ if (!result.ok) throw new Error(result.diagnostics.map(({ message }) => message).join(' '));
317
+ return result.value;
318
+ }
319
+
320
+ function success<T>(value: T): InfraResult<T> {
321
+ return { ok: true, value, diagnostics: [] };
322
+ }