@ipab/cli 0.0.0 → 0.1.0-rc.1
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/LICENSE +21 -0
- package/README.md +24 -1
- package/dist/app-authoring.d.ts +22 -0
- package/dist/app-authoring.d.ts.map +1 -0
- package/dist/app-authoring.js +448 -0
- package/dist/app-authoring.js.map +1 -0
- package/dist/app-definition.d.ts +103 -0
- package/dist/app-definition.d.ts.map +1 -0
- package/dist/app-definition.js +201 -0
- package/dist/app-definition.js.map +1 -0
- package/dist/app-prebuild.d.ts +12 -0
- package/dist/app-prebuild.d.ts.map +1 -0
- package/dist/app-prebuild.js +231 -0
- package/dist/app-prebuild.js.map +1 -0
- package/dist/app-templates.d.ts +13 -0
- package/dist/app-templates.d.ts.map +1 -0
- package/dist/app-templates.js +295 -0
- package/dist/app-templates.js.map +1 -0
- package/dist/authoring.d.ts +63 -0
- package/dist/authoring.d.ts.map +1 -0
- package/dist/authoring.js +411 -0
- package/dist/authoring.js.map +1 -0
- package/dist/builtins/template.node.car +0 -0
- package/dist/builtins/template.web-app.car +0 -0
- package/dist/builtins.d.ts +6 -0
- package/dist/builtins.d.ts.map +1 -0
- package/dist/builtins.js +41 -0
- package/dist/builtins.js.map +1 -0
- package/dist/child.d.ts +5 -0
- package/dist/child.d.ts.map +1 -0
- package/dist/child.js +28 -0
- package/dist/child.js.map +1 -0
- package/dist/cli.d.ts +24 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +1110 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +154 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +43 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +174 -0
- package/dist/context.js.map +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +40 -0
- package/dist/errors.js.map +1 -0
- package/dist/history.d.ts +34 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +286 -0
- package/dist/history.js.map +1 -0
- package/dist/ipc.d.ts +27 -0
- package/dist/ipc.d.ts.map +1 -0
- package/dist/ipc.js +341 -0
- package/dist/ipc.js.map +1 -0
- package/dist/logs.d.ts +15 -0
- package/dist/logs.d.ts.map +1 -0
- package/dist/logs.js +118 -0
- package/dist/logs.js.map +1 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +4 -0
- package/dist/main.js.map +1 -0
- package/dist/pins.d.ts +33 -0
- package/dist/pins.d.ts.map +1 -0
- package/dist/pins.js +165 -0
- package/dist/pins.js.map +1 -0
- package/dist/runtime.d.ts +20 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +237 -0
- package/dist/runtime.js.map +1 -0
- package/dist/source-bundle.d.ts +15 -0
- package/dist/source-bundle.d.ts.map +1 -0
- package/dist/source-bundle.js +102 -0
- package/dist/source-bundle.js.map +1 -0
- package/dist/space.d.ts +33 -0
- package/dist/space.d.ts.map +1 -0
- package/dist/space.js +269 -0
- package/dist/space.js.map +1 -0
- package/dist/state.d.ts +102 -0
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +335 -0
- package/dist/state.js.map +1 -0
- package/dist/supported-schemas.d.ts +5 -0
- package/dist/supported-schemas.d.ts.map +1 -0
- package/dist/supported-schemas.js +90 -0
- package/dist/supported-schemas.js.map +1 -0
- package/dist/template-definition.d.ts +98 -0
- package/dist/template-definition.d.ts.map +1 -0
- package/dist/template-definition.js +179 -0
- package/dist/template-definition.js.map +1 -0
- package/dist/template-source.d.ts +12 -0
- package/dist/template-source.d.ts.map +1 -0
- package/dist/template-source.js +97 -0
- package/dist/template-source.js.map +1 -0
- package/package.json +60 -3
- package/src/app-authoring.ts +616 -0
- package/src/app-definition.ts +250 -0
- package/src/app-prebuild.ts +289 -0
- package/src/app-templates.ts +395 -0
- package/src/authoring.ts +577 -0
- package/src/builtins.ts +49 -0
- package/src/child.ts +32 -0
- package/src/cli.ts +1330 -0
- package/src/config.ts +221 -0
- package/src/context.ts +242 -0
- package/src/errors.ts +46 -0
- package/src/history.ts +391 -0
- package/src/ipc.ts +366 -0
- package/src/logs.ts +132 -0
- package/src/main.ts +4 -0
- package/src/pins.ts +200 -0
- package/src/runtime.ts +301 -0
- package/src/source-bundle.ts +135 -0
- package/src/space.ts +379 -0
- package/src/state.ts +430 -0
- package/src/supported-schemas.ts +151 -0
- package/src/template-definition.ts +233 -0
- package/src/template-source.ts +128 -0
package/src/ipc.ts
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import type { ChildProcess } from "node:child_process";
|
|
2
|
+
import type { IpfsStore } from "@ipab/ipfs-store";
|
|
3
|
+
import { CID } from "multiformats/cid";
|
|
4
|
+
import { HostError, message, object } from "./errors.js";
|
|
5
|
+
import { requestFrame, type Reply } from "./context.js";
|
|
6
|
+
import { CHUNK_BYTES, type OutputSpace, relativePath } from "./space.js";
|
|
7
|
+
import type { Ownership } from "./history.js";
|
|
8
|
+
|
|
9
|
+
class ByteQueue implements AsyncIterable<Uint8Array> {
|
|
10
|
+
private item: { bytes: Uint8Array; consumed: () => void } | undefined;
|
|
11
|
+
private wake: (() => void) | undefined;
|
|
12
|
+
private ended = false;
|
|
13
|
+
private error: Error | undefined;
|
|
14
|
+
async push(bytes: Uint8Array): Promise<void> {
|
|
15
|
+
if (this.ended || this.error || this.item)
|
|
16
|
+
throw new HostError(
|
|
17
|
+
"Output stream is closed or exceeds backpressure capacity.",
|
|
18
|
+
);
|
|
19
|
+
await new Promise<void>((resolve) => {
|
|
20
|
+
this.item = { bytes, consumed: resolve };
|
|
21
|
+
this.wake?.();
|
|
22
|
+
});
|
|
23
|
+
const failure = this.failure();
|
|
24
|
+
if (failure) throw failure;
|
|
25
|
+
}
|
|
26
|
+
end(error?: Error): void {
|
|
27
|
+
this.ended = true;
|
|
28
|
+
this.error = error;
|
|
29
|
+
this.item?.consumed();
|
|
30
|
+
this.wake?.();
|
|
31
|
+
}
|
|
32
|
+
private failure(): Error | undefined {
|
|
33
|
+
return this.error;
|
|
34
|
+
}
|
|
35
|
+
async *[Symbol.asyncIterator](): AsyncGenerator<Uint8Array> {
|
|
36
|
+
for (;;) {
|
|
37
|
+
if (this.error) throw this.error;
|
|
38
|
+
if (this.item) {
|
|
39
|
+
const item = this.item;
|
|
40
|
+
this.item = undefined;
|
|
41
|
+
item.consumed();
|
|
42
|
+
yield item.bytes;
|
|
43
|
+
} else if (this.ended) return;
|
|
44
|
+
else
|
|
45
|
+
await new Promise<void>((resolve) => {
|
|
46
|
+
this.wake = resolve;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
interface ReadStream {
|
|
52
|
+
iterator: AsyncIterator<Uint8Array>;
|
|
53
|
+
pending: Uint8Array | undefined;
|
|
54
|
+
controller: AbortController;
|
|
55
|
+
pulling: boolean;
|
|
56
|
+
}
|
|
57
|
+
interface WriteStream {
|
|
58
|
+
queue: ByteQueue;
|
|
59
|
+
task: Promise<string>;
|
|
60
|
+
writing: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class ContextServer {
|
|
64
|
+
private readonly requests = new Map<number, AbortController>();
|
|
65
|
+
private readonly reads = new Map<number, ReadStream>();
|
|
66
|
+
private readonly writes = new Map<number, WriteStream>();
|
|
67
|
+
private readonly tasks = new Set<Promise<void>>();
|
|
68
|
+
private openingReads = 0;
|
|
69
|
+
private sequence = 0;
|
|
70
|
+
private closed = false;
|
|
71
|
+
constructor(
|
|
72
|
+
readonly child: ChildProcess,
|
|
73
|
+
readonly store: IpfsStore,
|
|
74
|
+
readonly owner: Ownership,
|
|
75
|
+
readonly output: OutputSpace,
|
|
76
|
+
readonly fatal: (error: Error) => void,
|
|
77
|
+
readonly appCid: string,
|
|
78
|
+
readonly resolvePin: (name: string) => string | undefined = () => {
|
|
79
|
+
throw new HostError("Pin lookup is unavailable in this context.");
|
|
80
|
+
},
|
|
81
|
+
) {
|
|
82
|
+
child.on("message", this.receive);
|
|
83
|
+
}
|
|
84
|
+
private reply(frame: Reply): void {
|
|
85
|
+
if (this.child.connected)
|
|
86
|
+
this.child.send(frame, (error) => {
|
|
87
|
+
if (error && !this.closed) this.fatal(error);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
private receive = (frame: unknown): void => {
|
|
91
|
+
if (!requestFrame(frame)) {
|
|
92
|
+
this.fatal(new HostError("Invalid IPAB context frame."));
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (this.closed) {
|
|
96
|
+
this.reply({
|
|
97
|
+
version: 1,
|
|
98
|
+
id: frame.id,
|
|
99
|
+
error: "Context server is closed.",
|
|
100
|
+
});
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (frame.operation === "cancel") {
|
|
104
|
+
this.requests
|
|
105
|
+
.get(Number(frame.args))
|
|
106
|
+
?.abort(new HostError("Context operation cancelled."));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (this.requests.size >= 32 || this.requests.has(frame.id)) {
|
|
110
|
+
this.fatal(
|
|
111
|
+
new HostError("Context request capacity or identity violation."),
|
|
112
|
+
);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const controller = new AbortController();
|
|
116
|
+
this.requests.set(frame.id, controller);
|
|
117
|
+
const task = this.handle(frame.operation, frame.args, controller.signal)
|
|
118
|
+
.then(async (result) => {
|
|
119
|
+
if (controller.signal.aborted) {
|
|
120
|
+
if (frame.operation === "read")
|
|
121
|
+
await this.cancelRead(Number(result), controller.signal.reason);
|
|
122
|
+
if (frame.operation === "link")
|
|
123
|
+
this.output.fail(controller.signal.reason);
|
|
124
|
+
controller.signal.throwIfAborted();
|
|
125
|
+
}
|
|
126
|
+
return result;
|
|
127
|
+
})
|
|
128
|
+
.then(
|
|
129
|
+
(result) => {
|
|
130
|
+
this.reply({ version: 1, id: frame.id, result });
|
|
131
|
+
},
|
|
132
|
+
(error: unknown) => {
|
|
133
|
+
this.reply({ version: 1, id: frame.id, error: message(error) });
|
|
134
|
+
},
|
|
135
|
+
)
|
|
136
|
+
.finally(() => {
|
|
137
|
+
this.requests.delete(frame.id);
|
|
138
|
+
this.tasks.delete(task);
|
|
139
|
+
});
|
|
140
|
+
this.tasks.add(task);
|
|
141
|
+
};
|
|
142
|
+
private async cancelRead(id: number, reason: unknown): Promise<void> {
|
|
143
|
+
const stream = this.reads.get(id);
|
|
144
|
+
if (!stream) return;
|
|
145
|
+
stream.controller.abort(reason);
|
|
146
|
+
try {
|
|
147
|
+
await stream.iterator.return?.();
|
|
148
|
+
} finally {
|
|
149
|
+
this.reads.delete(id);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
private async handle(
|
|
153
|
+
operation: string,
|
|
154
|
+
args: unknown,
|
|
155
|
+
signal: AbortSignal,
|
|
156
|
+
): Promise<unknown> {
|
|
157
|
+
signal.throwIfAborted();
|
|
158
|
+
if (operation === "identity") return this.appCid;
|
|
159
|
+
if (operation === "resolvePin") {
|
|
160
|
+
if (typeof args !== "string" || !args || args.length > 256)
|
|
161
|
+
throw new HostError("Pin name must contain 1..256 characters.");
|
|
162
|
+
return this.resolvePin(args) ?? null;
|
|
163
|
+
}
|
|
164
|
+
if (operation === "read") {
|
|
165
|
+
if (this.reads.size + this.writes.size + this.openingReads >= 32)
|
|
166
|
+
throw new HostError("Context stream capacity exceeded.");
|
|
167
|
+
const data = object(args, "read request");
|
|
168
|
+
if (typeof data.rootCid !== "string" || typeof data.path !== "string")
|
|
169
|
+
throw new HostError("Invalid read request.");
|
|
170
|
+
const root = CID.parse(data.rootCid).toV1().toString();
|
|
171
|
+
relativePath(data.path);
|
|
172
|
+
this.openingReads++;
|
|
173
|
+
try {
|
|
174
|
+
await this.owner.retain([root], signal);
|
|
175
|
+
signal.throwIfAborted();
|
|
176
|
+
const directory = await this.store.read(root, { signal });
|
|
177
|
+
signal.throwIfAborted();
|
|
178
|
+
if (directory.type !== "directory")
|
|
179
|
+
throw new HostError("Space root must be a UnixFS directory.");
|
|
180
|
+
const controller = new AbortController();
|
|
181
|
+
const readSignal = AbortSignal.any([signal, controller.signal]);
|
|
182
|
+
let iterator: AsyncIterator<Uint8Array> | undefined;
|
|
183
|
+
try {
|
|
184
|
+
const node = await this.store.read(`${root}/${data.path}`, {
|
|
185
|
+
signal: readSignal,
|
|
186
|
+
});
|
|
187
|
+
readSignal.throwIfAborted();
|
|
188
|
+
if (node.type === "directory")
|
|
189
|
+
throw new HostError("readFile requires a regular UnixFS file.");
|
|
190
|
+
iterator = node.content()[Symbol.asyncIterator]();
|
|
191
|
+
readSignal.throwIfAborted();
|
|
192
|
+
const id = ++this.sequence;
|
|
193
|
+
this.reads.set(id, {
|
|
194
|
+
iterator,
|
|
195
|
+
pending: undefined,
|
|
196
|
+
controller,
|
|
197
|
+
pulling: false,
|
|
198
|
+
});
|
|
199
|
+
return id;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
controller.abort(error);
|
|
202
|
+
await iterator?.return?.();
|
|
203
|
+
throw error;
|
|
204
|
+
}
|
|
205
|
+
} finally {
|
|
206
|
+
this.openingReads--;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (operation === "pull" || operation === "readCancel") {
|
|
210
|
+
const id = Number(args);
|
|
211
|
+
const stream = this.reads.get(id);
|
|
212
|
+
if (!stream) throw new HostError("Unknown read stream.");
|
|
213
|
+
if (operation === "readCancel") {
|
|
214
|
+
await this.cancelRead(id, new HostError("Read cancelled."));
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
if (stream.pulling)
|
|
218
|
+
throw new HostError(
|
|
219
|
+
"Concurrent pulls on one read stream are not supported.",
|
|
220
|
+
);
|
|
221
|
+
stream.pulling = true;
|
|
222
|
+
const abort = () => {
|
|
223
|
+
stream.controller.abort(signal.reason);
|
|
224
|
+
};
|
|
225
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
226
|
+
try {
|
|
227
|
+
stream.controller.signal.throwIfAborted();
|
|
228
|
+
if (!stream.pending) {
|
|
229
|
+
const result = await stream.iterator.next();
|
|
230
|
+
signal.throwIfAborted();
|
|
231
|
+
stream.controller.signal.throwIfAborted();
|
|
232
|
+
if (result.done) {
|
|
233
|
+
this.reads.delete(id);
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
signal.throwIfAborted();
|
|
237
|
+
stream.controller.signal.throwIfAborted();
|
|
238
|
+
stream.pending = result.value;
|
|
239
|
+
}
|
|
240
|
+
const result = stream.pending.slice(0, CHUNK_BYTES);
|
|
241
|
+
stream.pending =
|
|
242
|
+
stream.pending.length > CHUNK_BYTES
|
|
243
|
+
? stream.pending.slice(CHUNK_BYTES)
|
|
244
|
+
: undefined;
|
|
245
|
+
return result;
|
|
246
|
+
} finally {
|
|
247
|
+
stream.pulling = false;
|
|
248
|
+
signal.removeEventListener("abort", abort);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (operation === "write") {
|
|
252
|
+
if (this.reads.size + this.writes.size + this.openingReads >= 32)
|
|
253
|
+
throw new HostError("Context stream capacity exceeded.");
|
|
254
|
+
const data = object(args, "write request");
|
|
255
|
+
if (typeof data.path !== "string")
|
|
256
|
+
throw new HostError("Invalid write path.");
|
|
257
|
+
const id = ++this.sequence;
|
|
258
|
+
const queue = new ByteQueue();
|
|
259
|
+
const task = this.output.write(data.path, queue);
|
|
260
|
+
const stream: WriteStream = { queue, task, writing: false };
|
|
261
|
+
this.writes.set(id, stream);
|
|
262
|
+
void task.catch((error: unknown) => {
|
|
263
|
+
queue.end(new HostError(message(error)));
|
|
264
|
+
});
|
|
265
|
+
return id;
|
|
266
|
+
}
|
|
267
|
+
if (
|
|
268
|
+
operation === "chunk" ||
|
|
269
|
+
operation === "end" ||
|
|
270
|
+
operation === "writeCancel"
|
|
271
|
+
) {
|
|
272
|
+
const data =
|
|
273
|
+
operation === "chunk" ? object(args, "write chunk") : { id: args };
|
|
274
|
+
const id = Number(data.id);
|
|
275
|
+
const stream = this.writes.get(id);
|
|
276
|
+
if (!stream) throw new HostError("Unknown write stream.");
|
|
277
|
+
if (operation === "writeCancel") {
|
|
278
|
+
const error = new HostError(
|
|
279
|
+
"Output write cancelled.",
|
|
280
|
+
1,
|
|
281
|
+
"OUTPUT_CANCELLED",
|
|
282
|
+
"commit",
|
|
283
|
+
);
|
|
284
|
+
this.output.fail(error);
|
|
285
|
+
stream.queue.end(error);
|
|
286
|
+
await stream.task.catch(() => {});
|
|
287
|
+
this.writes.delete(id);
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
if (stream.writing)
|
|
291
|
+
throw new HostError("Concurrent writes violate stream backpressure.");
|
|
292
|
+
stream.writing = true;
|
|
293
|
+
try {
|
|
294
|
+
if (operation === "end") {
|
|
295
|
+
stream.queue.end();
|
|
296
|
+
const cid = await stream.task;
|
|
297
|
+
this.writes.delete(id);
|
|
298
|
+
return cid;
|
|
299
|
+
}
|
|
300
|
+
if (
|
|
301
|
+
!(data.bytes instanceof Uint8Array) ||
|
|
302
|
+
data.bytes.byteLength > CHUNK_BYTES
|
|
303
|
+
)
|
|
304
|
+
throw new HostError(
|
|
305
|
+
"Write chunk exceeds 65536 bytes or is not bytes.",
|
|
306
|
+
);
|
|
307
|
+
signal.throwIfAborted();
|
|
308
|
+
const cancel = () => {
|
|
309
|
+
stream.queue.end(new HostError("Write cancelled."));
|
|
310
|
+
};
|
|
311
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
312
|
+
try {
|
|
313
|
+
await stream.queue.push(data.bytes);
|
|
314
|
+
} finally {
|
|
315
|
+
signal.removeEventListener("abort", cancel);
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
} catch (error) {
|
|
319
|
+
this.output.fail(error);
|
|
320
|
+
stream.queue.end(new HostError(message(error)));
|
|
321
|
+
throw error;
|
|
322
|
+
} finally {
|
|
323
|
+
stream.writing = false;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (operation === "link") {
|
|
327
|
+
const data = object(args, "link request");
|
|
328
|
+
if (typeof data.path !== "string" || typeof data.rootCid !== "string")
|
|
329
|
+
throw new HostError("Invalid link request.");
|
|
330
|
+
signal.throwIfAborted();
|
|
331
|
+
await this.output.link(data.path, data.rootCid, signal);
|
|
332
|
+
signal.throwIfAborted();
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
throw new HostError("Unknown context operation.");
|
|
336
|
+
}
|
|
337
|
+
async close(): Promise<void> {
|
|
338
|
+
this.closed = true;
|
|
339
|
+
this.child.off("message", this.receive);
|
|
340
|
+
for (const request of this.requests.values())
|
|
341
|
+
request.abort(new HostError("App finished."));
|
|
342
|
+
for (const stream of this.writes.values()) {
|
|
343
|
+
const error = new HostError(
|
|
344
|
+
"App exited with unfinished output writes.",
|
|
345
|
+
1,
|
|
346
|
+
"OUTPUT_PENDING",
|
|
347
|
+
"commit",
|
|
348
|
+
);
|
|
349
|
+
this.output.fail(error);
|
|
350
|
+
stream.queue.end(error);
|
|
351
|
+
}
|
|
352
|
+
for (const stream of this.reads.values())
|
|
353
|
+
stream.controller.abort(new HostError("App finished."));
|
|
354
|
+
await Promise.allSettled([
|
|
355
|
+
...this.tasks,
|
|
356
|
+
...[...this.writes.values()].map((stream) => stream.task),
|
|
357
|
+
]);
|
|
358
|
+
await Promise.all(
|
|
359
|
+
[...this.reads.values()].map(async (stream) => {
|
|
360
|
+
await stream.iterator.return?.();
|
|
361
|
+
}),
|
|
362
|
+
);
|
|
363
|
+
this.reads.clear();
|
|
364
|
+
this.writes.clear();
|
|
365
|
+
}
|
|
366
|
+
}
|
package/src/logs.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import {
|
|
2
|
+
lstat,
|
|
3
|
+
mkdir,
|
|
4
|
+
open,
|
|
5
|
+
unlink,
|
|
6
|
+
rmdir,
|
|
7
|
+
type FileHandle,
|
|
8
|
+
} from "node:fs/promises";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import type { Readable, Writable } from "node:stream";
|
|
11
|
+
import { HostError } from "./errors.js";
|
|
12
|
+
|
|
13
|
+
async function directory(path: string): Promise<boolean> {
|
|
14
|
+
try {
|
|
15
|
+
const stat = await lstat(path);
|
|
16
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
17
|
+
throw new HostError("Invalid execution log directory.");
|
|
18
|
+
return true;
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function location(stateDirectory: string, id: string): string {
|
|
26
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id))
|
|
27
|
+
throw new HostError("Invalid execution log identity.");
|
|
28
|
+
return join(stateDirectory, "logs", id);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function logFiles(
|
|
32
|
+
stateDirectory: string,
|
|
33
|
+
id: string,
|
|
34
|
+
): Promise<{ stdout: string | null; stderr: string | null }> {
|
|
35
|
+
const result: { stdout: string | null; stderr: string | null } = {
|
|
36
|
+
stdout: null,
|
|
37
|
+
stderr: null,
|
|
38
|
+
};
|
|
39
|
+
if (!(await directory(join(stateDirectory, "logs")))) return result;
|
|
40
|
+
const path = location(stateDirectory, id);
|
|
41
|
+
if (!(await directory(path))) return result;
|
|
42
|
+
for (const stream of ["stdout", "stderr"] as const) {
|
|
43
|
+
const file = join(path, `${stream}.log`);
|
|
44
|
+
try {
|
|
45
|
+
const stat = await lstat(file);
|
|
46
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
47
|
+
throw new HostError("Invalid execution log file.");
|
|
48
|
+
result[stream] = file;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function removeLogs(
|
|
57
|
+
stateDirectory: string,
|
|
58
|
+
id: string,
|
|
59
|
+
): Promise<void> {
|
|
60
|
+
const files = await logFiles(stateDirectory, id);
|
|
61
|
+
for (const file of Object.values(files)) {
|
|
62
|
+
if (file) {
|
|
63
|
+
try {
|
|
64
|
+
await unlink(file);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!(await directory(join(stateDirectory, "logs")))) return;
|
|
71
|
+
const path = location(stateDirectory, id);
|
|
72
|
+
try {
|
|
73
|
+
await rmdir(path);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export class ExecutionLogs {
|
|
80
|
+
private constructor(
|
|
81
|
+
private readonly stdout: FileHandle,
|
|
82
|
+
private readonly stderr: FileHandle,
|
|
83
|
+
) {}
|
|
84
|
+
|
|
85
|
+
static async create(
|
|
86
|
+
stateDirectory: string,
|
|
87
|
+
id: string,
|
|
88
|
+
): Promise<ExecutionLogs> {
|
|
89
|
+
const parent = join(stateDirectory, "logs");
|
|
90
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
91
|
+
await directory(parent);
|
|
92
|
+
const path = location(stateDirectory, id);
|
|
93
|
+
await mkdir(path, { mode: 0o700 });
|
|
94
|
+
const stdout = await open(join(path, "stdout.log"), "wx", 0o600);
|
|
95
|
+
try {
|
|
96
|
+
return new ExecutionLogs(
|
|
97
|
+
stdout,
|
|
98
|
+
await open(join(path, "stderr.log"), "wx", 0o600),
|
|
99
|
+
);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
await stdout.close();
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async forward(
|
|
107
|
+
source: Readable,
|
|
108
|
+
destination: Writable,
|
|
109
|
+
stream: "stdout" | "stderr",
|
|
110
|
+
): Promise<void> {
|
|
111
|
+
for await (const chunk of source) {
|
|
112
|
+
if (!Buffer.isBuffer(chunk))
|
|
113
|
+
throw new HostError("Invalid execution output bytes.");
|
|
114
|
+
await this[stream].writeFile(chunk);
|
|
115
|
+
await new Promise<void>((resolve, reject) => {
|
|
116
|
+
destination.write(chunk, (error) => {
|
|
117
|
+
if (error) reject(error);
|
|
118
|
+
else resolve();
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async close(): Promise<void> {
|
|
125
|
+
const results = await Promise.allSettled([
|
|
126
|
+
this.stdout.close(),
|
|
127
|
+
this.stderr.close(),
|
|
128
|
+
]);
|
|
129
|
+
const failed = results.find((result) => result.status === "rejected");
|
|
130
|
+
if (failed?.status === "rejected") throw failed.reason;
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/main.ts
ADDED
package/src/pins.ts
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { CID } from "multiformats/cid";
|
|
3
|
+
import { IpfsStore } from "@ipab/ipfs-store";
|
|
4
|
+
import { openBundle } from "@ipab/bundle";
|
|
5
|
+
import { HostError, message } from "./errors.js";
|
|
6
|
+
import { alive, type StoreFactory } from "./history.js";
|
|
7
|
+
import {
|
|
8
|
+
exactCid,
|
|
9
|
+
pinName,
|
|
10
|
+
bundlePinMetadata,
|
|
11
|
+
type NamedPin,
|
|
12
|
+
type PinMetadata,
|
|
13
|
+
type State,
|
|
14
|
+
} from "./state.js";
|
|
15
|
+
|
|
16
|
+
export function pinDetails(pin: NamedPin) {
|
|
17
|
+
if (pin.status !== "ready" || !pin.metadata)
|
|
18
|
+
throw new HostError(
|
|
19
|
+
`Pin "${pin.name}" is ${pin.status}. Retry ipab pin add ${pin.name} ${pin.cid}, or ipab pin delete ${pin.name}.`,
|
|
20
|
+
);
|
|
21
|
+
return {
|
|
22
|
+
name: pin.name,
|
|
23
|
+
cid: pin.cid,
|
|
24
|
+
...bundlePinMetadata(pin),
|
|
25
|
+
...(pin.builtin ? { builtin: true as const } : {}),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function requiredPin(state: State, name: string): NamedPin {
|
|
30
|
+
pinName(name);
|
|
31
|
+
const pin = state.pin(name);
|
|
32
|
+
if (!pin)
|
|
33
|
+
throw new HostError(`Pin "${name}" does not exist. Run ipab pin list.`);
|
|
34
|
+
return pin;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function idleHold(state: State, pin: NamedPin) {
|
|
38
|
+
const hold = state.hold(pin.owner);
|
|
39
|
+
if (!hold)
|
|
40
|
+
throw new HostError(
|
|
41
|
+
"Pin retention metadata is missing; recovery is blocked.",
|
|
42
|
+
);
|
|
43
|
+
if (hold.pid !== null && alive(hold.pid))
|
|
44
|
+
throw new HostError(
|
|
45
|
+
`Pin "${pin.name}" has an active operation; retry after it finishes.`,
|
|
46
|
+
);
|
|
47
|
+
return hold;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function classify(
|
|
51
|
+
cid: string,
|
|
52
|
+
store: IpfsStore,
|
|
53
|
+
): Promise<Extract<PinMetadata, { kind: "bundle" }>> {
|
|
54
|
+
const root = CID.parse(cid);
|
|
55
|
+
const resolveCid = (cid: CID, options: { signal?: AbortSignal }) =>
|
|
56
|
+
store.block.get(cid.toString(), options);
|
|
57
|
+
const bundle = await openBundle(root, { resolveCid });
|
|
58
|
+
return {
|
|
59
|
+
kind: "bundle",
|
|
60
|
+
typeName: bundle.manifest.name,
|
|
61
|
+
schemaCid: bundle.schemaKey,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function addPin(
|
|
66
|
+
state: State,
|
|
67
|
+
name: string,
|
|
68
|
+
input: string,
|
|
69
|
+
configuration: IpfsStore["configuration"],
|
|
70
|
+
factory: StoreFactory = (config) => new IpfsStore(config),
|
|
71
|
+
) {
|
|
72
|
+
pinName(name);
|
|
73
|
+
const cid = exactCid(input);
|
|
74
|
+
const pin = state.transaction(() => {
|
|
75
|
+
const old = state.pin(name);
|
|
76
|
+
if (old) {
|
|
77
|
+
if (old.status !== "pending" || old.cid !== cid)
|
|
78
|
+
throw new HostError(
|
|
79
|
+
`Pin name "${name}" is occupied; no replace is supported.`,
|
|
80
|
+
);
|
|
81
|
+
const hold = idleHold(state, old);
|
|
82
|
+
state.saveHold({ ...hold, pid: process.pid });
|
|
83
|
+
return old;
|
|
84
|
+
}
|
|
85
|
+
const owner = `ipab:${state.identity}:pin:${randomUUID()}`;
|
|
86
|
+
const reserved: NamedPin = {
|
|
87
|
+
name,
|
|
88
|
+
cid,
|
|
89
|
+
owner,
|
|
90
|
+
status: "pending",
|
|
91
|
+
metadata: null,
|
|
92
|
+
};
|
|
93
|
+
state.savePin(reserved);
|
|
94
|
+
// Reserve the name and original backend before any Store side effect.
|
|
95
|
+
state.saveHold({
|
|
96
|
+
owner,
|
|
97
|
+
backend: configuration,
|
|
98
|
+
roots: [],
|
|
99
|
+
pid: process.pid,
|
|
100
|
+
session: null,
|
|
101
|
+
recordId: null,
|
|
102
|
+
});
|
|
103
|
+
return reserved;
|
|
104
|
+
});
|
|
105
|
+
let store: IpfsStore | undefined;
|
|
106
|
+
let finished = false;
|
|
107
|
+
try {
|
|
108
|
+
store = factory(state.hold(pin.owner)!.backend);
|
|
109
|
+
await store.recoverOwner(pin.owner, () => state.hold(pin.owner)!.roots);
|
|
110
|
+
const metadata = await classify(cid, store);
|
|
111
|
+
await store.retain(pin.owner, [cid]);
|
|
112
|
+
state.transaction(() => {
|
|
113
|
+
state.savePin({ ...pin, metadata });
|
|
114
|
+
state.saveHold({ ...state.hold(pin.owner)!, roots: [cid] });
|
|
115
|
+
});
|
|
116
|
+
await store.confirmRetained(pin.owner, [cid]);
|
|
117
|
+
await store.close();
|
|
118
|
+
store = undefined;
|
|
119
|
+
const ready: NamedPin = { ...pin, status: "ready", metadata };
|
|
120
|
+
state.transaction(() => {
|
|
121
|
+
state.savePin(ready);
|
|
122
|
+
state.saveHold({ ...state.hold(pin.owner)!, pid: null });
|
|
123
|
+
});
|
|
124
|
+
finished = true;
|
|
125
|
+
return pinDetails(ready);
|
|
126
|
+
} catch (cause) {
|
|
127
|
+
throw new HostError(
|
|
128
|
+
`Pin add incomplete for "${name}": ${message(cause)}. Durable recovery data is preserved; retry the same add or delete this pending pin.`,
|
|
129
|
+
1,
|
|
130
|
+
"PIN_INCOMPLETE",
|
|
131
|
+
);
|
|
132
|
+
} finally {
|
|
133
|
+
try {
|
|
134
|
+
await store?.close();
|
|
135
|
+
} finally {
|
|
136
|
+
const hold = state.hold(pin.owner);
|
|
137
|
+
if (hold && !finished) state.saveHold({ ...hold, pid: null });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function deletePin(
|
|
143
|
+
state: State,
|
|
144
|
+
name: string,
|
|
145
|
+
factory: StoreFactory = (config) => new IpfsStore(config),
|
|
146
|
+
) {
|
|
147
|
+
const pin = state.transaction(() => {
|
|
148
|
+
const pin = requiredPin(state, name);
|
|
149
|
+
const hold = idleHold(state, pin);
|
|
150
|
+
state.savePin({ ...pin, status: "deleting" });
|
|
151
|
+
state.saveHold({ ...hold, roots: [], pid: process.pid });
|
|
152
|
+
return pin;
|
|
153
|
+
});
|
|
154
|
+
let store: IpfsStore | undefined;
|
|
155
|
+
try {
|
|
156
|
+
store = factory(state.hold(pin.owner)!.backend);
|
|
157
|
+
await store.recoverOwner(pin.owner, () => state.hold(pin.owner)!.roots);
|
|
158
|
+
await store.reconcile(pin.owner, () => state.hold(pin.owner)!.roots);
|
|
159
|
+
await store.close();
|
|
160
|
+
store = undefined;
|
|
161
|
+
state.transaction(() => {
|
|
162
|
+
state.deletePin(name);
|
|
163
|
+
state.deleteHold(pin.owner);
|
|
164
|
+
});
|
|
165
|
+
return {
|
|
166
|
+
removed: [name],
|
|
167
|
+
retentionClaimsReleased: true,
|
|
168
|
+
garbageCollectionGuaranteed: false,
|
|
169
|
+
};
|
|
170
|
+
} catch (cause) {
|
|
171
|
+
throw new HostError(
|
|
172
|
+
`Pin deletion incomplete for "${name}": ${message(cause)}. Retry ipab pin delete ${name}; original backend and recovery data are preserved. No GC requested.`,
|
|
173
|
+
1,
|
|
174
|
+
"RELEASE_FAILED",
|
|
175
|
+
"cleanup",
|
|
176
|
+
);
|
|
177
|
+
} finally {
|
|
178
|
+
try {
|
|
179
|
+
await store?.close();
|
|
180
|
+
} finally {
|
|
181
|
+
const hold = state.hold(pin.owner);
|
|
182
|
+
if (hold) state.saveHold({ ...hold, pid: null });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function renamePin(state: State, oldName: string, newName: string) {
|
|
188
|
+
pinName(newName);
|
|
189
|
+
return state.transaction(() => {
|
|
190
|
+
const pin = requiredPin(state, oldName);
|
|
191
|
+
const details = pinDetails(pin);
|
|
192
|
+
idleHold(state, pin);
|
|
193
|
+
if (oldName === newName) return details;
|
|
194
|
+
if (state.pin(newName))
|
|
195
|
+
throw new HostError(`Pin name "${newName}" is occupied.`);
|
|
196
|
+
state.deletePin(oldName);
|
|
197
|
+
state.savePin({ ...pin, name: newName });
|
|
198
|
+
return { ...details, name: newName };
|
|
199
|
+
});
|
|
200
|
+
}
|