@homeflare/alchemy 0.37.6 → 0.37.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/linux/container-form.d.ts +1 -1
  2. package/dist/linux/container-generator.d.ts +28 -0
  3. package/dist/linux/container-generator.d.ts.map +1 -1
  4. package/dist/linux/container-lifecycle.d.ts +18 -1
  5. package/dist/linux/container-lifecycle.d.ts.map +1 -1
  6. package/dist/linux/container-preflight.d.ts +34 -0
  7. package/dist/linux/container-preflight.d.ts.map +1 -1
  8. package/dist/linux/container-settle.d.ts.map +1 -1
  9. package/dist/linux/fake-sudo.d.ts +14 -2
  10. package/dist/linux/fake-sudo.d.ts.map +1 -1
  11. package/dist/linux/index.js +76 -29
  12. package/dist/linux/index.js.map +11 -10
  13. package/dist/linux/sudo-exec.d.ts +16 -0
  14. package/dist/linux/sudo-exec.d.ts.map +1 -1
  15. package/dist/linux/unit-form.d.ts.map +1 -1
  16. package/dist/linux/unit-text.d.ts +35 -0
  17. package/dist/linux/unit-text.d.ts.map +1 -0
  18. package/dist/proxmox/firewall-alias-config.d.ts +36 -0
  19. package/dist/proxmox/firewall-alias-config.d.ts.map +1 -0
  20. package/dist/proxmox/firewall-alias-form.d.ts +3 -1
  21. package/dist/proxmox/firewall-alias-form.d.ts.map +1 -1
  22. package/dist/proxmox/firewall-alias-lifecycle.d.ts +43 -0
  23. package/dist/proxmox/firewall-alias-lifecycle.d.ts.map +1 -0
  24. package/dist/proxmox/firewall-alias.d.ts +2 -8
  25. package/dist/proxmox/firewall-alias.d.ts.map +1 -1
  26. package/dist/proxmox/index.js +795 -526
  27. package/dist/proxmox/index.js.map +23 -10
  28. package/dist/proxmox/lxc-errors.d.ts +12 -0
  29. package/dist/proxmox/lxc-errors.d.ts.map +1 -0
  30. package/dist/proxmox/lxc-lifecycle.d.ts +9 -31
  31. package/dist/proxmox/lxc-lifecycle.d.ts.map +1 -1
  32. package/dist/proxmox/lxc-read.d.ts +4 -0
  33. package/dist/proxmox/lxc-read.d.ts.map +1 -0
  34. package/dist/proxmox/lxc-task.d.ts +15 -0
  35. package/dist/proxmox/lxc-task.d.ts.map +1 -0
  36. package/dist/proxmox/network-apply-read.d.ts +7 -14
  37. package/dist/proxmox/network-apply-read.d.ts.map +1 -1
  38. package/dist/proxmox/network-apply-run.d.ts +7 -0
  39. package/dist/proxmox/network-apply-run.d.ts.map +1 -0
  40. package/dist/proxmox/network-apply.d.ts +2 -3
  41. package/dist/proxmox/network-apply.d.ts.map +1 -1
  42. package/dist/proxmox/qemu-errors.d.ts +5 -0
  43. package/dist/proxmox/qemu-errors.d.ts.map +1 -0
  44. package/dist/proxmox/qemu-form.d.ts +22 -0
  45. package/dist/proxmox/qemu-form.d.ts.map +1 -0
  46. package/dist/proxmox/qemu-lifecycle.d.ts +26 -0
  47. package/dist/proxmox/qemu-lifecycle.d.ts.map +1 -0
  48. package/dist/proxmox/qemu-read.d.ts +5 -0
  49. package/dist/proxmox/qemu-read.d.ts.map +1 -0
  50. package/dist/proxmox/qemu-task.d.ts +9 -0
  51. package/dist/proxmox/qemu-task.d.ts.map +1 -0
  52. package/dist/proxmox/qemu.d.ts +9 -14
  53. package/dist/proxmox/qemu.d.ts.map +1 -1
  54. package/dist/proxmox/replication-firewall-fixtures.d.ts +30 -0
  55. package/dist/proxmox/replication-firewall-fixtures.d.ts.map +1 -0
  56. package/dist/proxmox/replication-job-config.d.ts +56 -0
  57. package/dist/proxmox/replication-job-config.d.ts.map +1 -0
  58. package/dist/proxmox/replication-job-lifecycle.d.ts +62 -0
  59. package/dist/proxmox/replication-job-lifecycle.d.ts.map +1 -0
  60. package/dist/proxmox/replication-job.d.ts +5 -6
  61. package/dist/proxmox/replication-job.d.ts.map +1 -1
  62. package/dist/release/archive.d.ts.map +1 -1
  63. package/dist/release/index.js +3 -2
  64. package/dist/release/index.js.map +3 -3
  65. package/docs/linux-sudo.md +18 -7
  66. package/docs/proxmox-lxc-distilled.md +56 -0
  67. package/docs/proxmox-replication-firewall-distilled.md +53 -0
  68. package/docs/proxmox-sdk-migration.md +23 -18
  69. package/package.json +2 -2
  70. package/src/linux/container-form.ts +1 -1
  71. package/src/linux/container-generator.test.ts +33 -0
  72. package/src/linux/container-generator.ts +72 -0
  73. package/src/linux/container-lifecycle.test.ts +6 -3
  74. package/src/linux/container-lifecycle.ts +23 -2
  75. package/src/linux/container-preflight.ts +47 -0
  76. package/src/linux/container-settle.ts +12 -1
  77. package/src/linux/container-shadow.test.ts +131 -0
  78. package/src/linux/fake-sudo.ts +21 -5
  79. package/src/linux/sudo-exec.ts +60 -10
  80. package/src/linux/sudo-lifecycle.test.ts +64 -3
  81. package/src/linux/unit-form.ts +4 -18
  82. package/src/linux/unit-text.test.ts +67 -0
  83. package/src/linux/unit-text.ts +58 -0
  84. package/src/proxmox/firewall-alias-config.ts +39 -0
  85. package/src/proxmox/firewall-alias-form.ts +1 -1
  86. package/src/proxmox/firewall-alias-lifecycle.ts +100 -0
  87. package/src/proxmox/firewall-alias.ts +4 -67
  88. package/src/proxmox/lxc-create.test.ts +4 -1
  89. package/src/proxmox/lxc-distilled.test.ts +239 -0
  90. package/src/proxmox/lxc-errors.ts +9 -0
  91. package/src/proxmox/lxc-lifecycle.ts +31 -113
  92. package/src/proxmox/lxc-read.test.ts +29 -6
  93. package/src/proxmox/lxc-read.ts +88 -0
  94. package/src/proxmox/lxc-task.ts +71 -0
  95. package/src/proxmox/network-apply-distilled.test.ts +76 -0
  96. package/src/proxmox/network-apply-read.ts +18 -39
  97. package/src/proxmox/network-apply-run.ts +97 -0
  98. package/src/proxmox/network-apply.ts +5 -94
  99. package/src/proxmox/qemu-errors.ts +7 -0
  100. package/src/proxmox/qemu-form.ts +15 -0
  101. package/src/proxmox/qemu-lifecycle.test.ts +171 -0
  102. package/src/proxmox/qemu-lifecycle.ts +134 -0
  103. package/src/proxmox/qemu-read.ts +73 -0
  104. package/src/proxmox/qemu-task.ts +64 -0
  105. package/src/proxmox/qemu.ts +11 -44
  106. package/src/proxmox/replication-firewall-fixtures.ts +71 -0
  107. package/src/proxmox/replication-firewall-lifecycle.test.ts +109 -0
  108. package/src/proxmox/replication-firewall-wire.test.ts +173 -0
  109. package/src/proxmox/replication-job-config.ts +79 -0
  110. package/src/proxmox/replication-job-lifecycle.ts +113 -0
  111. package/src/proxmox/replication-job.ts +7 -84
  112. package/src/release/archive.ts +4 -1
@@ -0,0 +1,239 @@
1
+ /** Real SDK HTTP boundary: credential continuity, dynamic fields, digest and task uncertainty. */
2
+ import { expect, test } from 'bun:test';
3
+ import * as nodes from '@distilled.cloud/proxmox/nodes';
4
+ import * as Deferred from 'effect/Deferred';
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Exit from 'effect/Exit';
7
+ import * as Fiber from 'effect/Fiber';
8
+ import * as Layer from 'effect/Layer';
9
+ import * as TestClock from 'effect/testing/TestClock';
10
+ import * as FetchHttpClient from 'effect/unstable/http/FetchHttpClient';
11
+ import { FAKE_TARGET, withoutBao } from './fake-pve.ts';
12
+ import { createGuest, updateGuest } from './lxc-lifecycle.ts';
13
+ import type { LxcProps } from './lxc-props.ts';
14
+ import { readLive } from './lxc-read.ts';
15
+ import { lxcTask } from './lxc-task.ts';
16
+
17
+ const props: LxcProps = {
18
+ hostname: 'ct-example',
19
+ node: 'pve1',
20
+ vmid: 900,
21
+ target: FAKE_TARGET,
22
+ ostemplate: 'local:vztmpl/test.tar.zst',
23
+ rootfs: 'local-zfs:8',
24
+ net0: 'name=eth0,bridge=vmbr0,ip=dhcp',
25
+ mp0: 'tank:10,mp=/data',
26
+ };
27
+ type Seen = { method: string; path: string; auth: string | null; form: URLSearchParams };
28
+ const UPID = 'UPID:pve1:00000001:0:0:vzcreate:900:test@pve!lease:';
29
+
30
+ const transport = (
31
+ poll: () => Response = () => Response.json({ data: { status: 'stopped', exitstatus: 'OK' } }),
32
+ index: unknown = [],
33
+ ) => {
34
+ const seen: Seen[] = [];
35
+ let mints = 0;
36
+ const stub = async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
37
+ const request =
38
+ input instanceof Request ? new Request(input, init) : new Request(String(input), init);
39
+ const url = new URL(request.url);
40
+ if (url.pathname.includes('/creds/')) {
41
+ mints++;
42
+ return Response.json({
43
+ data: { secret: `fake-${mints}`, token_id: `test@pve!lease-${mints}` },
44
+ lease_duration: 0,
45
+ });
46
+ }
47
+ const body = await request.text();
48
+ if (request.method === 'GET') expect(body).toBe('');
49
+ const path = decodeURIComponent(url.pathname.replace(/^\/api2\/json\//, ''));
50
+ seen.push({
51
+ method: request.method,
52
+ path,
53
+ auth: request.headers.get('Authorization'),
54
+ form: new URLSearchParams(body),
55
+ });
56
+ if (path.endsWith('/status')) return poll();
57
+ if (request.method === 'GET' && path.endsWith('/config'))
58
+ return Response.json(
59
+ { data: null, message: "Configuration file 'nodes/pve1/lxc/900.conf' does not exist\n" },
60
+ { status: 500 },
61
+ );
62
+ if (path === 'cluster/resources') {
63
+ expect(url.searchParams.get('type')).toBe('vm');
64
+ return Response.json({ data: index });
65
+ }
66
+ return Response.json({ data: path.endsWith('/config') ? null : UPID });
67
+ };
68
+ const fake = Object.assign(stub, { preconnect: globalThis.fetch.preconnect }) as typeof fetch;
69
+ return {
70
+ seen,
71
+ mints: () => mints,
72
+ layer: FetchHttpClient.layer.pipe(
73
+ Layer.provideMerge(Layer.succeed(FetchHttpClient.Fetch, fake)),
74
+ ),
75
+ };
76
+ };
77
+
78
+ test('missing config and permission-filtered guest index use one read credential', async () => {
79
+ const fake = transport();
80
+ const result = await withoutBao(() =>
81
+ Effect.runPromise(readLive(props).pipe(Effect.provide(fake.layer))),
82
+ );
83
+ expect(result).toBeUndefined();
84
+ expect(fake.mints()).toBe(1);
85
+ expect(fake.seen.map((call) => call.path)).toEqual([
86
+ 'nodes/pve1/lxc/900/config',
87
+ 'cluster/resources',
88
+ ]);
89
+ expect(fake.seen[0]?.auth).toBe(fake.seen[1]?.auth);
90
+ });
91
+
92
+ test('each task starts with a fresh credential and every poll keeps its owner', async () => {
93
+ const fake = transport();
94
+ await withoutBao(() =>
95
+ Effect.runPromise(
96
+ Effect.gen(function* () {
97
+ yield* createGuest(props);
98
+ yield* updateGuest(
99
+ props,
100
+ { put: {}, clear: [], resize: [{ disk: 'rootfs', size: '12G' }], refuse: [], drift: [] },
101
+ 'digest-live',
102
+ );
103
+ }).pipe(Effect.provide(fake.layer)),
104
+ ),
105
+ );
106
+ expect(fake.mints()).toBe(2);
107
+ expect(fake.seen.map((call) => call.method)).toEqual(['POST', 'GET', 'PUT', 'GET']);
108
+ expect(fake.seen[0]?.auth).toBe(fake.seen[1]?.auth);
109
+ expect(fake.seen[2]?.auth).toBe(fake.seen[3]?.auth);
110
+ expect(fake.seen[0]?.auth).not.toBe(fake.seen[2]?.auth);
111
+ const form = fake.seen[0]?.form;
112
+ expect(form?.get('net0')).toBe(props.net0);
113
+ expect(form?.get('mp0')).toBe(props.mp0);
114
+ expect(form?.has('net[n]')).toBe(false);
115
+ expect(form?.has('node')).toBe(false);
116
+ expect(fake.seen[2]?.form.get('size')).toBe('12G');
117
+ });
118
+
119
+ test('config updates retain the observed digest and concrete indexed form keys', async () => {
120
+ const fake = transport();
121
+ await withoutBao(() =>
122
+ Effect.runPromise(
123
+ updateGuest(
124
+ props,
125
+ {
126
+ put: { net1: 'name=eth1,bridge=vmbr1,ip=dhcp' },
127
+ clear: ['tags'],
128
+ resize: [],
129
+ refuse: [],
130
+ drift: [],
131
+ },
132
+ 'observed-digest',
133
+ ).pipe(Effect.provide(fake.layer)),
134
+ ),
135
+ );
136
+ expect(fake.seen).toHaveLength(1);
137
+ const form = fake.seen[0]?.form;
138
+ expect(form?.get('digest')).toBe('observed-digest');
139
+ expect(form?.get('net1')).toBe('name=eth1,bridge=vmbr1,ip=dhcp');
140
+ expect(form?.get('delete')).toBe('tags');
141
+ expect(form?.has('vmid')).toBe(false);
142
+ expect(form?.has('node')).toBe(false);
143
+ });
144
+
145
+ for (const [name, response] of [
146
+ ['denied', () => Response.json({ data: null, message: 'denied' }, { status: 403 })],
147
+ ['malformed', () => Response.json({ data: null })],
148
+ ] as const) {
149
+ test(`${name} task polling reports uncertainty with UPID, never repeats POST`, async () => {
150
+ const fake = transport(response);
151
+ const error = await withoutBao(() =>
152
+ Effect.runPromise(createGuest(props).pipe(Effect.flip, Effect.provide(fake.layer))),
153
+ );
154
+ expect(String(error)).toContain(UPID);
155
+ expect(String(error)).toContain('task could not be read');
156
+ expect(fake.seen.map((call) => call.method)).toEqual(['POST', 'GET']);
157
+ });
158
+ }
159
+
160
+ test('a still-running task stops at its bound with no second POST', async () => {
161
+ let polls = 0;
162
+ const fake = transport(() => {
163
+ polls++;
164
+ return Response.json({ data: { status: 'running' } });
165
+ });
166
+ const outcome = await withoutBao(() =>
167
+ Effect.runPromise(
168
+ Effect.gen(function* () {
169
+ const ready = yield* Deferred.make<void>();
170
+ // Start the virtual clock only after the SDK transport has completed its first response.
171
+ const observed = fake.layer;
172
+ const worker = yield* lxcTask(
173
+ props,
174
+ nodes.createNodeLxc({
175
+ node: props.node,
176
+ vmid: String(props.vmid),
177
+ ostemplate: props.ostemplate ?? '',
178
+ }),
179
+ 'create test CT',
180
+ 2,
181
+ ).pipe(Effect.exit, Effect.provide(observed), Effect.forkChild);
182
+ const signal = yield* Effect.gen(function* () {
183
+ while (polls < 1) yield* Effect.yieldNow;
184
+ yield* Deferred.succeed(ready, undefined);
185
+ }).pipe(Effect.forkChild);
186
+ yield* Deferred.await(ready);
187
+ yield* TestClock.adjust('2 seconds');
188
+ yield* Fiber.join(signal);
189
+ return yield* Fiber.join(worker);
190
+ }).pipe(Effect.provide(TestClock.layer())),
191
+ ),
192
+ );
193
+ expect(Exit.isFailure(outcome)).toBe(true);
194
+ expect(polls).toBe(2);
195
+ expect(fake.seen.filter((call) => call.method === 'POST')).toHaveLength(1);
196
+ });
197
+
198
+ test('a transitional status value keeps polling, never aborts like an unreadable poll', async () => {
199
+ // ⚠️ `GetNodeTaskStatusResponseStatus` TYPES `status` AS "running" | "stopped" BUT VALIDATES IT
200
+ // AT RUNTIME AS A PLAIN STRING — that union is not actually enforced on the wire, so a value
201
+ // this endpoint's real contract was never proven to exclude must be tolerated the same way
202
+ // `awaitTask` (network-apply-read.ts) tolerates it, rather than read as "task could not be
203
+ // read" and abort the deploy. The sibling malformed-answer tests above pin the other half:
204
+ // a response with no `status` field at all still aborts (2026-09-25 adversarial review).
205
+ let polls = 0;
206
+ const fake = transport(() => {
207
+ polls++;
208
+ return Response.json({
209
+ data: { status: polls === 1 ? 'queued' : 'stopped', exitstatus: 'OK' },
210
+ });
211
+ });
212
+ const outcome = await withoutBao(() =>
213
+ Effect.runPromise(
214
+ lxcTask(
215
+ props,
216
+ nodes.createNodeLxc({
217
+ node: props.node,
218
+ vmid: String(props.vmid),
219
+ ostemplate: props.ostemplate ?? '',
220
+ }),
221
+ 'create test CT',
222
+ 5,
223
+ ).pipe(Effect.provide(fake.layer)),
224
+ ),
225
+ );
226
+ expect(outcome).toBeUndefined();
227
+ expect(polls).toBe(2);
228
+ });
229
+
230
+ for (const index of [null, [{}], [{ vmid: 'unknown', node: 'pve1', type: 'lxc' }]]) {
231
+ test(`malformed guest index ${JSON.stringify(index)} cannot prove absence`, async () => {
232
+ const fake = transport(undefined, index);
233
+ const error = await withoutBao(() =>
234
+ Effect.runPromise(readLive(props).pipe(Effect.flip, Effect.provide(fake.layer))),
235
+ );
236
+ expect(String(error)).toContain('did not identify its rows');
237
+ expect(fake.seen.every((call) => call.method === 'GET')).toBe(true);
238
+ });
239
+ }
@@ -0,0 +1,9 @@
1
+ import type { PveTarget } from './credentials.ts';
2
+
3
+ /** A lifecycle refusal. Post-write refusals carry the task diagnostic, never imply rollback. */
4
+ export class LxcRefusedError extends Error {
5
+ override readonly name = 'LxcRefusedError';
6
+ }
7
+
8
+ /** Where one guest lives. Its identity, and nothing else. */
9
+ export type LxcWhere = { readonly target: PveTarget; readonly node: string; readonly vmid: number };
@@ -1,50 +1,33 @@
1
1
  /**
2
2
  * The calls a `Proxmox.Lxc` makes: read one config, create, update in place, grow, delete.
3
3
  *
4
- * ⛔ A READ FAILURE IS A FAILURE HERE, NOT "ABSENT" — THE ONE PLACE THIS PACKAGE DEPARTS FROM
5
- * resource.ts. `pveOperations.read` folds every error into `undefined`, which for a guest means a
6
- * 403 or a node that did not answer plans a CREATE over a running container. PVE answers a
7
- * missing guest with HTTP 500, `Configuration file 'nodes/<node>/lxc/<vmid>.conf' does not
8
- * exist` (pve-guest-common `AbstractConfig::load_config`), so only a 500 may mean absent — and
9
- * even then only after the cluster says so, below. Anything else fails the plan.
10
- *
11
- * ⛔ "ABSENT" IS DECIDED BY THE WHOLE CLUSTER, NOT BY THE ERROR TEXT. A config lives under its
12
- * node, so a guest migrated to another node — or a QEMU VM holding the same cluster-wide vmid —
13
- * also reads as missing at the declared path. `GET /cluster/resources?type=vm` settles it: the
14
- * vmid nowhere is absent; the vmid anywhere else FAILS the read with where it is; the vmid on
15
- * the declared node fails with PVE's own error. ★ Keyed on the cluster rather than on matching
16
- * the message, so a PVE that words it differently still cannot turn into a create.
4
+ * ★ Discovery lives in lxc-read.ts; it proves precise absence with one read credential.
5
+ * Writes use named distilled operations, and lxc-task.ts preserves task ownership and bounds.
17
6
  *
18
7
  * ⚠️ CREATE, RESIZE AND DELETE ARE ASYNCHRONOUS; A CONFIG PUT IS NOT. The first three answer a
19
8
  * UPID the moment PVE forks the worker (`NodesNodeLxcPostReturn`, `…ResizePutReturn`,
20
9
  * `…VmidDeleteReturn` are all `string`), so each waits for its task's exitstatus. `PUT …/config`
21
10
  * answers `null` after writing (`…ConfigPutReturn`), so it needs no wait.
22
- * ⛔ EACH TASK IS POLLED WITH THE CREDENTIAL THAT STARTED IT — see `awaitTask`: only the owner
11
+ * ⛔ EACH TASK IS POLLED WITH THE CREDENTIAL THAT STARTED IT — see `lxcTask`: only the owner
23
12
  * skips `Sys.Audit`. A fresh `provision` mint per write gives the full 300s lease a create needs;
24
13
  * a cached lease can be handed out with 60s left (lease-cache.ts).
25
14
  */
26
15
  import * as Effect from 'effect/Effect';
27
- import { PveError, pve, pveWith } from './client.ts';
16
+ import * as nodes from '@distilled.cloud/proxmox/nodes';
17
+ import { runPve } from './distilled-pve.ts';
18
+ import { LxcRefusedError, type LxcWhere } from './lxc-errors.ts';
19
+ import { readLive } from './lxc-read.ts';
20
+ import { lxcTask } from './lxc-task.ts';
28
21
  import { guardForm } from './constraint-guard.ts';
29
22
  import type { EndpointKey } from './constraints.ts';
30
- import type { PveTarget } from './credentials.ts';
31
- import { mint } from './mint.ts';
32
23
  import { createForm } from './lxc-create-form.ts';
33
24
  import { type LxcChange, judge } from './lxc-judge.ts';
34
25
  import type { LxcAttributes, LxcProps } from './lxc-props.ts';
35
26
  import { rawKeysOf, storedConfig } from './lxc-props.ts';
36
- import { awaitTask } from './network-apply-read.ts';
37
27
  import { text, withClears } from './values.ts';
38
28
 
39
- /** A plan-time or apply-time refusal. Nothing was written when one of these is raised. */
40
- export class LxcRefusedError extends Error {
41
- override readonly name = 'LxcRefusedError';
42
- }
43
-
44
- /** Where one guest lives. Its identity, and nothing else. */
45
- export type LxcWhere = { readonly target: PveTarget; readonly node: string; readonly vmid: number };
46
-
47
- export const guestPath = (where: LxcWhere) => `nodes/${where.node}/lxc/${String(where.vmid)}`;
29
+ export { LxcRefusedError, type LxcWhere } from './lxc-errors.ts';
30
+ export { readLive } from './lxc-read.ts';
48
31
 
49
32
  /**
50
33
  * The three vendor endpoints a guest is written through, as the generated tables key them.
@@ -70,52 +53,6 @@ const LXC_ENDPOINTS = {
70
53
  const CREATE_POLLS = 180;
71
54
  const TASK_POLLS = 60;
72
55
 
73
- const isServerError = (error: unknown): error is PveError =>
74
- error instanceof PveError && error.status === 500;
75
-
76
- /** One `GET /cluster/resources?type=vm` row. */
77
- type GuestRow = { readonly vmid?: unknown; readonly node?: unknown; readonly type?: unknown };
78
-
79
- /** The live config, or undefined when no guest holds this vmid anywhere in the cluster. */
80
- export const readLive = (where: LxcWhere) =>
81
- Effect.gen(function* () {
82
- const answer = yield* pve<Record<string, unknown> | null>(
83
- where.target,
84
- 'read',
85
- 'GET',
86
- `${guestPath(where)}/config`,
87
- ).pipe(
88
- Effect.map((data) => ({ data, error: undefined })),
89
- Effect.catchIf(isServerError, (error) => Effect.succeed({ data: undefined, error })),
90
- );
91
- if (answer.data !== undefined && answer.data !== null) return answer.data;
92
- const rows = yield* pve<readonly GuestRow[]>(
93
- where.target,
94
- 'read',
95
- 'GET',
96
- 'cluster/resources?type=vm',
97
- );
98
- // ⚠️ `Number()`, NOT `===` ON THE RAW VALUE: a vmid that came back as `"900"` would otherwise
99
- // match nothing, and "listed nowhere" is the one answer that turns into a create.
100
- const found = (rows ?? []).find((row) => Number(row.vmid) === where.vmid);
101
- if (found !== undefined && found.node === where.node && found.type === 'lxc') {
102
- return yield* Effect.fail(
103
- answer.error ??
104
- new LxcRefusedError(`CT ${String(where.vmid)} is listed but its config read empty.`),
105
- );
106
- }
107
- if (found !== undefined) {
108
- return yield* Effect.fail(
109
- new LxcRefusedError(
110
- `vmid ${String(where.vmid)} is a ${text(found.type, 'guest')} on ` +
111
- `${text(found.node, '?')}, not a container on ${where.node}. A migration is not an ` +
112
- 'update and vmids are cluster-wide: declare the node it is on, or pick a free vmid.',
113
- ),
114
- );
115
- }
116
- return undefined;
117
- });
118
-
119
56
  export const attributesOf = (where: LxcWhere, live: Record<string, unknown>): LxcAttributes => ({
120
57
  config: storedConfig(live),
121
58
  node: where.node,
@@ -123,36 +60,6 @@ export const attributesOf = (where: LxcWhere, live: Record<string, unknown>): Lx
123
60
  vmid: where.vmid,
124
61
  });
125
62
 
126
- /** Run one task-starting call and wait for it on the same credential. Fails unless `OK`. */
127
- const task = (
128
- where: LxcWhere,
129
- method: 'POST' | 'PUT' | 'DELETE',
130
- path: string,
131
- what: string,
132
- polls: number,
133
- form?: Record<string, string>,
134
- ) =>
135
- Effect.gen(function* () {
136
- const credential = yield* mint(where.target, 'provision');
137
- const upid = text(yield* pveWith<string>(where.target, credential, method, path, form));
138
- if (upid === '') {
139
- return yield* Effect.fail(
140
- new LxcRefusedError(
141
- `${what}: PVE returned no task id, so the write cannot be confirmed and is not claimed.`,
142
- ),
143
- );
144
- }
145
- const exit = yield* awaitTask(where.target, credential, where.node, upid, polls);
146
- if (exit !== 'OK') {
147
- return yield* Effect.fail(
148
- new LxcRefusedError(
149
- `${what}: task ${upid} ended "${exit}". Read \`pvesh get /nodes/${where.node}/tasks/` +
150
- `${upid}/log\` before running the deploy again.`,
151
- ),
152
- );
153
- }
154
- });
155
-
156
63
  /** POST the create and wait for the template to unpack. ⛔ Refusals are the caller's to check. */
157
64
  export const createGuest = (props: LxcProps) =>
158
65
  Effect.gen(function* () {
@@ -165,13 +72,16 @@ export const createGuest = (props: LxcProps) =>
165
72
  * knew: `cores` 1..8192, `memory` ≥ 16, `hostname` as a dns-name, `tags`, `startup`.
166
73
  */
167
74
  yield* guardForm(LXC_ENDPOINTS.create, form, true);
168
- return yield* task(
75
+ return yield* lxcTask(
169
76
  props,
170
- 'POST',
171
- `nodes/${props.node}/lxc`,
77
+ nodes.createNodeLxc({
78
+ ...form,
79
+ node: props.node,
80
+ vmid: String(props.vmid),
81
+ ostemplate: text(form['ostemplate']),
82
+ }),
172
83
  `create CT ${String(props.vmid)}`,
173
84
  CREATE_POLLS,
174
- form,
175
85
  );
176
86
  });
177
87
 
@@ -194,20 +104,23 @@ export const updateGuest = (props: LxcProps, change: LxcChange, digest: string)
194
104
  );
195
105
  /** ⚠️ NO PRESENCE: this form is partial by construction — it is `judge`'s answer. */
196
106
  yield* guardForm(LXC_ENDPOINTS.update, form, false);
197
- yield* pve(props.target, 'provision', 'PUT', `${guestPath(props)}/config`, form);
107
+ yield* runPve(
108
+ props.target,
109
+ 'provision',
110
+ true,
111
+ nodes.putNodeLxcConfig({ ...form, node: props.node, vmid: String(props.vmid) }),
112
+ );
198
113
  }
199
114
  for (const grow of change.resize) {
200
115
  const grown = { disk: grow.disk, size: grow.size };
201
116
  // ⛔ WITH PRESENCE: `disk` and `size` are both required and both always sent, so this is a
202
117
  // value check over PVE's own `+<n>` size pattern and its `rootfs|mp0..mp255` enum.
203
118
  yield* guardForm(LXC_ENDPOINTS.resize, grown, true);
204
- yield* task(
119
+ yield* lxcTask(
205
120
  props,
206
- 'PUT',
207
- `${guestPath(props)}/resize`,
121
+ nodes.putNodeLxcResize({ ...grown, node: props.node, vmid: String(props.vmid) }),
208
122
  `grow ${grow.disk} of CT ${String(props.vmid)} to ${grow.size}`,
209
123
  TASK_POLLS,
210
- grown,
211
124
  );
212
125
  }
213
126
  });
@@ -236,5 +149,10 @@ export const destroyGuest = (where: LxcWhere, declared: LxcProps) =>
236
149
  ),
237
150
  );
238
151
  }
239
- yield* task(where, 'DELETE', guestPath(where), `destroy CT ${String(where.vmid)}`, TASK_POLLS);
152
+ yield* lxcTask(
153
+ where,
154
+ nodes.deleteNodeLxc({ node: where.node, vmid: String(where.vmid) }),
155
+ `destroy CT ${String(where.vmid)}`,
156
+ TASK_POLLS,
157
+ );
240
158
  });
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * When a container read counts as "absent" — the question that decides between adopt and create.
3
3
  *
4
- * ⛔ WHAT THESE PIN: only a 500 whose vmid the cluster does not list anywhere is absent, whatever
5
- * the message says; a 403 or a 500 for a guest the cluster lists on the declared node FAILS the
6
- * plan with PVE's own error; nothing is written in any case. resource.ts's fold of every error
4
+ * ⛔ WHAT THESE PIN: only the SDK's exact missing-config tag may consult the same credential's
5
+ * cluster index for absence. A 403 or any other 500 FAILS the plan with PVE's own error;
6
+ * nothing is written in any case. resource.ts's fold of every error
7
7
  * into "absent" is exactly what this resource must not inherit — under it, a lease without
8
8
  * VM.Audit plans a CREATE over a running guest.
9
9
  */
@@ -31,11 +31,14 @@ const declared = (vmid: number) =>
31
31
  }).pipe(adopt(true));
32
32
 
33
33
  describe('absent means the cluster does not list the vmid', () => {
34
- test('a 500 with no message, for a vmid nowhere in the cluster, plans a create', async () => {
34
+ test('a 500 with no message never uses a filtered empty index to authorize creation', async () => {
35
35
  fake = fakePve();
36
36
  fake.configErrors.set(`${NODE}/150`, { body: { data: null }, status: 500 });
37
37
  const run = await lxcEngine(fake).plan(declared(150));
38
- expect(run).toMatchObject({ actions: { ct: 'create' }, failure: '' });
38
+ expect(run.failure).toContain('InternalServerError');
39
+ expect(run.actions).toEqual({});
40
+ expect(writesOf(fake)).toEqual([]);
41
+ expect(fake.seen.some((call) => call.path.endsWith('/cluster/resources'))).toBe(false);
39
42
  });
40
43
 
41
44
  test('a 500 for a guest the cluster lists on this node fails with PVE’s error', async () => {
@@ -54,7 +57,27 @@ describe('absent means the cluster does not list the vmid', () => {
54
57
  const message = 'Permission check failed (/vms/150, VM.Audit)\n';
55
58
  fake.configErrors.set(`${NODE}/150`, { body: { data: null, message }, status: 403 });
56
59
  const run = await lxcEngine(fake).plan(declared(150));
57
- expect(run.failure).toContain('-> 403');
60
+ expect(run.failure).toContain('Forbidden');
58
61
  expect(run.actions).toEqual({});
62
+ expect(writesOf(fake)).toEqual([]);
63
+ expect(fake.seen.some((call) => call.path.endsWith('/cluster/resources'))).toBe(false);
59
64
  });
65
+
66
+ test('exact missing config plus an empty index permits the existing create plan', async () => {
67
+ fake = fakePve();
68
+ const run = await lxcEngine(fake).plan(declared(150));
69
+ expect(run).toMatchObject({ actions: { ct: 'create' }, failure: '' });
70
+ expect(writesOf(fake)).toEqual([]);
71
+ });
72
+
73
+ for (const data of [null, {}, { hostname: 'example' }]) {
74
+ test(`malformed config success ${JSON.stringify(data)} is not absence`, async () => {
75
+ fake = fakePve();
76
+ fake.configErrors.set(`${NODE}/150`, { body: { data }, status: 200 });
77
+ const run = await lxcEngine(fake).plan(declared(150));
78
+ expect(run.failure).toContain('digest-bearing config');
79
+ expect(run.actions).toEqual({});
80
+ expect(writesOf(fake)).toEqual([]);
81
+ });
82
+ }
60
83
  });
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Precise container discovery, with cluster-wide vmid collision checks.
3
+ * ⛔ A config path missing on one node does not mean its vmid is free: migration or a QEMU
4
+ * guest may hold it. Only the SDK's exact LxcConfigNotFound permits the second observation.
5
+ * Generic 500s, permission failures and malformed successes never authorize creation.
6
+ * ★ SAME CREDENTIAL FOR BOTH READS. Installed pve-container6.1.13 Config.pm:31 checks
7
+ * VM.Audit on /vms/{vmid} before AbstractConfig.pm:58 raises the missing-config error.
8
+ * The pinned pve-manager9.2.11 Cluster.pm:588 filters rows by that SAME permission. Keeping
9
+ * the credential makes an absent row meaningful for this vmid without claiming the entire
10
+ * cluster list is unfiltered. A newly minted credential would not carry that evidence.
11
+ */
12
+ import * as cluster from '@distilled.cloud/proxmox/cluster';
13
+ import * as nodes from '@distilled.cloud/proxmox/nodes';
14
+ import * as Effect from 'effect/Effect';
15
+ import { runPveWith } from './distilled-pve.ts';
16
+ import { leased } from './lease-cache.ts';
17
+ import { LxcRefusedError, type LxcWhere } from './lxc-errors.ts';
18
+ import { text } from './values.ts';
19
+
20
+ export const readLive = (where: LxcWhere) =>
21
+ Effect.gen(function* () {
22
+ const credential = yield* leased(where.target, 'read');
23
+ const answer = yield* runPveWith(
24
+ where.target,
25
+ credential,
26
+ false,
27
+ nodes.getNodeLxcConfig({ node: where.node, vmid: String(where.vmid) }),
28
+ ).pipe(
29
+ Effect.map((data) => ({ data, error: undefined })),
30
+ Effect.catchTag('LxcConfigNotFound', (error) => Effect.succeed({ data: undefined, error })),
31
+ );
32
+ if (answer.error === undefined) {
33
+ const live: unknown = answer.data;
34
+ // ⛔ The vendor requires digest on a real config. Null/empty output is not absence.
35
+ if (
36
+ live === null ||
37
+ typeof live !== 'object' ||
38
+ Array.isArray(live) ||
39
+ !('digest' in live) ||
40
+ typeof live.digest !== 'string' ||
41
+ live.digest === ''
42
+ ) {
43
+ return yield* Effect.fail(
44
+ new LxcRefusedError(
45
+ `CT ${String(where.vmid)}: config read did not return a valid digest-bearing config.`,
46
+ ),
47
+ );
48
+ }
49
+ return live as Record<string, unknown>;
50
+ }
51
+ const rows = yield* runPveWith(
52
+ where.target,
53
+ credential,
54
+ false,
55
+ cluster.listClusterResources({ type: 'vm' }),
56
+ );
57
+ // ⛔ Unknown row identities cannot establish that this cluster-wide vmid is free.
58
+ if (
59
+ !Array.isArray(rows) ||
60
+ rows.some(
61
+ (row) =>
62
+ !Number.isSafeInteger(Number(row?.vmid)) ||
63
+ Number(row?.vmid) <= 0 ||
64
+ typeof row?.node !== 'string' ||
65
+ row.node === '' ||
66
+ !['lxc', 'qemu'].includes(row.type),
67
+ )
68
+ ) {
69
+ return yield* Effect.fail(
70
+ new LxcRefusedError('The cluster guest index did not identify its rows.'),
71
+ );
72
+ }
73
+ // Number() preserves the vendor's numeric/string vmid spellings.
74
+ const found = rows.find((row) => Number(row.vmid) === where.vmid);
75
+ if (found !== undefined && found.node === where.node && found.type === 'lxc') {
76
+ return yield* Effect.fail(answer.error);
77
+ }
78
+ if (found !== undefined) {
79
+ return yield* Effect.fail(
80
+ new LxcRefusedError(
81
+ `vmid ${String(where.vmid)} is a ${text(found.type, 'guest')} on ` +
82
+ `${text(found.node, '?')}, not a container on ${where.node}. A migration is not an ` +
83
+ 'update and vmids are cluster-wide: declare the node it is on, or pick a free vmid.',
84
+ ),
85
+ );
86
+ }
87
+ return undefined;
88
+ });