@ipab/ipfs-store 0.0.0 → 0.1.0-rc.0
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 +244 -1
- package/dist/configuration.d.ts +21 -0
- package/dist/configuration.d.ts.map +1 -0
- package/dist/configuration.js +62 -0
- package/dist/configuration.js.map +1 -0
- package/dist/dag.d.ts +49 -0
- package/dist/dag.d.ts.map +1 -0
- package/dist/dag.js +216 -0
- package/dist/dag.js.map +1 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +57 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +417 -0
- package/dist/index.js.map +1 -0
- package/dist/kubo.d.ts +38 -0
- package/dist/kubo.d.ts.map +1 -0
- package/dist/kubo.js +189 -0
- package/dist/kubo.js.map +1 -0
- package/dist/node.d.ts +11 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +60 -0
- package/dist/node.js.map +1 -0
- package/dist/retention.d.ts +44 -0
- package/dist/retention.d.ts.map +1 -0
- package/dist/retention.js +328 -0
- package/dist/retention.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +161 -0
- package/dist/storage.js.map +1 -0
- package/dist/store.d.ts +71 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +412 -0
- package/dist/store.js.map +1 -0
- package/package.json +67 -5
- package/src/configuration.ts +93 -0
- package/src/dag.ts +281 -0
- package/src/errors.ts +25 -0
- package/src/index.ts +520 -0
- package/src/kubo.ts +293 -0
- package/src/node.ts +78 -0
- package/src/retention.ts +398 -0
- package/src/storage.ts +181 -0
- package/src/store.ts +577 -0
package/dist/kubo.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { CID } from "multiformats/cid";
|
|
2
|
+
import { verifyBlock } from "./dag.js";
|
|
3
|
+
import { ContentError } from "./errors.js";
|
|
4
|
+
export class KuboContent {
|
|
5
|
+
apiUrl;
|
|
6
|
+
blockBytes;
|
|
7
|
+
timeoutMs;
|
|
8
|
+
lifetime = new AbortController();
|
|
9
|
+
pending = new Set();
|
|
10
|
+
constructor(apiUrl, blockBytes, timeoutMs = 30_000) {
|
|
11
|
+
this.apiUrl = apiUrl;
|
|
12
|
+
this.blockBytes = blockBytes;
|
|
13
|
+
this.timeoutMs = timeoutMs;
|
|
14
|
+
}
|
|
15
|
+
request(command, args, maxBytes, options = {}, body) {
|
|
16
|
+
const operation = this.fetch(command, args, maxBytes, options, body);
|
|
17
|
+
this.pending.add(operation);
|
|
18
|
+
void operation
|
|
19
|
+
.finally(() => this.pending.delete(operation))
|
|
20
|
+
.catch(() => { });
|
|
21
|
+
return operation;
|
|
22
|
+
}
|
|
23
|
+
async fetch(command, args, maxBytes, options, body) {
|
|
24
|
+
const signal = AbortSignal.any([
|
|
25
|
+
this.lifetime.signal,
|
|
26
|
+
AbortSignal.timeout(this.timeoutMs),
|
|
27
|
+
...(options.signal ? [options.signal] : []),
|
|
28
|
+
]);
|
|
29
|
+
signal.throwIfAborted();
|
|
30
|
+
const url = new URL(this.apiUrl);
|
|
31
|
+
url.pathname = `${url.pathname.replace(/\/(?:api\/v0\/?)?$/, "")}/api/v0/${command}`;
|
|
32
|
+
const headers = {};
|
|
33
|
+
if (url.username || url.password) {
|
|
34
|
+
headers.Authorization = `Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`).toString("base64")}`;
|
|
35
|
+
url.username = "";
|
|
36
|
+
url.password = "";
|
|
37
|
+
}
|
|
38
|
+
for (const [key, value] of Object.entries(args))
|
|
39
|
+
url.searchParams.set(key, value);
|
|
40
|
+
let response;
|
|
41
|
+
try {
|
|
42
|
+
response = await fetch(url, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
...(body ? { body } : {}),
|
|
45
|
+
headers,
|
|
46
|
+
signal,
|
|
47
|
+
redirect: "error",
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
signal.throwIfAborted();
|
|
52
|
+
throw new ContentError("rpc_unavailable", `Kubo ${command} RPC is unavailable.`);
|
|
53
|
+
}
|
|
54
|
+
const bound = response.ok ? maxBytes : Math.min(maxBytes, 8192);
|
|
55
|
+
const reader = response.body?.getReader();
|
|
56
|
+
const parts = [];
|
|
57
|
+
let size = 0;
|
|
58
|
+
try {
|
|
59
|
+
if (reader)
|
|
60
|
+
for (;;) {
|
|
61
|
+
const item = await reader.read();
|
|
62
|
+
if (item.done)
|
|
63
|
+
break;
|
|
64
|
+
const chunk = item.value;
|
|
65
|
+
if (!(chunk instanceof Uint8Array))
|
|
66
|
+
throw new ContentError("rpc_failed", "Kubo RPC must return bytes.");
|
|
67
|
+
size += chunk.byteLength;
|
|
68
|
+
if (size > bound)
|
|
69
|
+
throw new ContentError("capacity_exceeded", "Kubo RPC response capacity exceeded.");
|
|
70
|
+
parts.push(chunk);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
signal.throwIfAborted();
|
|
75
|
+
if (error instanceof ContentError)
|
|
76
|
+
throw error;
|
|
77
|
+
throw new ContentError("rpc_unavailable", `Kubo ${command} response was interrupted.`);
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
await reader?.cancel().catch(() => { });
|
|
81
|
+
reader?.releaseLock();
|
|
82
|
+
}
|
|
83
|
+
signal.throwIfAborted();
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
if (command === "pin/ls" &&
|
|
86
|
+
response.status === 500 &&
|
|
87
|
+
/is not pinned/i.test(Buffer.concat(parts, size).toString()))
|
|
88
|
+
return Buffer.from('{"Keys":{}}');
|
|
89
|
+
const body = Buffer.concat(parts, size).toString();
|
|
90
|
+
const missing = command === "block/get" &&
|
|
91
|
+
/(?:not found|could not find|blockservice: key not found|block not found|no such block)/i.test(body);
|
|
92
|
+
throw new ContentError(response.status === 404 || missing ? "missing_block" : "rpc_failed", missing
|
|
93
|
+
? "Kubo block is missing."
|
|
94
|
+
: `Kubo ${command} RPC failed (HTTP ${response.status}); operation outcome may be unknown.`);
|
|
95
|
+
}
|
|
96
|
+
return Buffer.concat(parts, size);
|
|
97
|
+
}
|
|
98
|
+
async json(command, args, options, body) {
|
|
99
|
+
const bytes = await this.request(command, args, 1024 * 1024, options, body);
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new ContentError("rpc_failed", `Invalid Kubo ${command} response.`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
block = {
|
|
108
|
+
get: (value, options = {}) => this.readBlock(value, options),
|
|
109
|
+
};
|
|
110
|
+
async readBlock(value, options = {}) {
|
|
111
|
+
const cid = CID.parse(value);
|
|
112
|
+
if (cid.multihash.code !== 0x12)
|
|
113
|
+
throw new Error("Unsupported content hash.");
|
|
114
|
+
const bytes = await this.request("block/get", { arg: value }, this.blockBytes, options);
|
|
115
|
+
await verifyBlock(cid, bytes);
|
|
116
|
+
return bytes;
|
|
117
|
+
}
|
|
118
|
+
async put(cid, bytes, options = {}, staged = false) {
|
|
119
|
+
if (bytes.byteLength > this.blockBytes)
|
|
120
|
+
throw new ContentError("capacity_exceeded", "Content block capacity exceeded.");
|
|
121
|
+
const snapshot = Uint8Array.from(bytes);
|
|
122
|
+
await verifyBlock(cid, snapshot);
|
|
123
|
+
const format = new Map([
|
|
124
|
+
[0x55, "raw"],
|
|
125
|
+
[0x70, "dag-pb"],
|
|
126
|
+
[0x71, "dag-cbor"],
|
|
127
|
+
]).get(cid.code);
|
|
128
|
+
if (!format)
|
|
129
|
+
throw new ContentError("unsupported_content", "Unsupported Kubo block codec.");
|
|
130
|
+
const body = new FormData();
|
|
131
|
+
body.append("file", new Blob([snapshot]), "block");
|
|
132
|
+
const result = (await this.json("block/put", {
|
|
133
|
+
"cid-codec": format,
|
|
134
|
+
mhtype: "sha2-256",
|
|
135
|
+
mhlen: "32",
|
|
136
|
+
pin: String(staged),
|
|
137
|
+
}, options, body));
|
|
138
|
+
if (!result.Key || !CID.parse(result.Key).toV1().equals(cid.toV1()))
|
|
139
|
+
throw new ContentError("rpc_failed", "Kubo returned a different block CID.");
|
|
140
|
+
}
|
|
141
|
+
async pinStatus(cid, options = {}) {
|
|
142
|
+
const result = await this.json("pin/ls", { arg: cid, type: "all", names: "true" }, options);
|
|
143
|
+
if (!result ||
|
|
144
|
+
typeof result !== "object" ||
|
|
145
|
+
!("Keys" in result) ||
|
|
146
|
+
!result.Keys ||
|
|
147
|
+
typeof result.Keys !== "object" ||
|
|
148
|
+
Array.isArray(result.Keys))
|
|
149
|
+
throw new ContentError("rpc_failed", "Invalid Kubo pin listing.");
|
|
150
|
+
const status = Object.entries(result.Keys).find(([key]) => CID.parse(key).toV1().equals(CID.parse(cid).toV1()))?.[1];
|
|
151
|
+
if (status === undefined)
|
|
152
|
+
return undefined;
|
|
153
|
+
if (!status || typeof status !== "object")
|
|
154
|
+
throw new ContentError("rpc_failed", "Invalid Kubo pin status.");
|
|
155
|
+
let type = "Type" in status ? status.Type : undefined;
|
|
156
|
+
const name = "Name" in status ? status.Name : undefined;
|
|
157
|
+
if (typeof type === "string" && type.startsWith("indirect through ")) {
|
|
158
|
+
try {
|
|
159
|
+
CID.parse(type.slice("indirect through ".length));
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
throw new ContentError("rpc_failed", "Invalid Kubo pin status.");
|
|
163
|
+
}
|
|
164
|
+
type = "indirect";
|
|
165
|
+
}
|
|
166
|
+
if (typeof type !== "string" ||
|
|
167
|
+
!["recursive", "direct", "indirect"].includes(type) ||
|
|
168
|
+
(name !== undefined && typeof name !== "string"))
|
|
169
|
+
throw new ContentError("rpc_failed", "Invalid Kubo pin status.");
|
|
170
|
+
return { Type: type, ...(name === undefined ? {} : { Name: name }) };
|
|
171
|
+
}
|
|
172
|
+
async pin(cid, name, options = {}, recursive = true) {
|
|
173
|
+
const result = (await this.json("pin/add", { arg: cid, recursive: String(recursive), name }, options));
|
|
174
|
+
if (!Array.isArray(result.Pins) ||
|
|
175
|
+
!result.Pins.some((value) => CID.parse(value).toV1().equals(CID.parse(cid).toV1())))
|
|
176
|
+
throw new ContentError("rpc_failed", "Kubo pin confirmation did not include the requested CID.");
|
|
177
|
+
}
|
|
178
|
+
async unpin(cid, options = {}) {
|
|
179
|
+
const result = (await this.json("pin/rm", { arg: cid, recursive: "true" }, options));
|
|
180
|
+
if (!Array.isArray(result.Pins) ||
|
|
181
|
+
!result.Pins.some((value) => CID.parse(value).toV1().equals(CID.parse(cid).toV1())))
|
|
182
|
+
throw new ContentError("rpc_failed", "Kubo unpin confirmation did not include the requested CID.");
|
|
183
|
+
}
|
|
184
|
+
async close() {
|
|
185
|
+
this.lifetime.abort(new Error("Kubo content store is closed."));
|
|
186
|
+
await Promise.allSettled([...this.pending]);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
//# sourceMappingURL=kubo.js.map
|
package/dist/kubo.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kubo.js","sourceRoot":"","sources":["../src/kubo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAM3C,MAAM,OAAO,WAAW;IAIH;IACA;IACA;IALF,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAC;IACjC,OAAO,GAAG,IAAI,GAAG,EAAoB,CAAC;IACvD,YACmB,MAAc,EACd,UAAkB,EAClB,YAAY,MAAM;QAFlB,WAAM,GAAN,MAAM,CAAQ;QACd,eAAU,GAAV,UAAU,CAAQ;QAClB,cAAS,GA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.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { IpfsStore } from "./store.js";
|
|
2
|
+
import { type StoreConfiguration } from "./configuration.js";
|
|
3
|
+
export { SharedContent } from "./storage.js";
|
|
4
|
+
export type ContentConfiguration = StoreConfiguration;
|
|
5
|
+
export declare function contentConfigPath(): string;
|
|
6
|
+
export declare function readContentConfiguration(overrides?: Partial<ContentConfiguration>, path?: string): Promise<ContentConfiguration>;
|
|
7
|
+
/** Explicit host helper; never called as a library import side effect. */
|
|
8
|
+
export declare function createConfiguredContent(overrides?: Partial<ContentConfiguration>): Promise<IpfsStore & {
|
|
9
|
+
configuration: ContentConfiguration;
|
|
10
|
+
}>;
|
|
11
|
+
//# sourceMappingURL=node.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,MAAM,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AACtD,wBAAgB,iBAAiB,IAAI,MAAM,CAW1C;AACD,wBAAsB,wBAAwB,CAC5C,SAAS,GAAE,OAAO,CAAC,oBAAoB,CAAM,EAC7C,IAAI,SAAsB,GACzB,OAAO,CAAC,oBAAoB,CAAC,CA4C/B;AACD,0EAA0E;AAC1E,wBAAsB,uBAAuB,CAC3C,SAAS,GAAE,OAAO,CAAC,oBAAoB,CAAM,GAC5C,OAAO,CAAC,SAAS,GAAG;IAAE,aAAa,EAAE,oBAAoB,CAAA;CAAE,CAAC,CAG9D"}
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { IpfsStore } from "./store.js";
|
|
5
|
+
import { validateConfiguration, } from "./configuration.js";
|
|
6
|
+
export { SharedContent } from "./storage.js";
|
|
7
|
+
export function contentConfigPath() {
|
|
8
|
+
return (process.env.TASK_CONTENT_CONFIG ??
|
|
9
|
+
(process.platform === "win32"
|
|
10
|
+
? join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "TaskContent", "config.json")
|
|
11
|
+
: join(homedir(), ".config", "task-content", "config.json")));
|
|
12
|
+
}
|
|
13
|
+
export async function readContentConfiguration(overrides = {}, path = contentConfigPath()) {
|
|
14
|
+
let value = {};
|
|
15
|
+
try {
|
|
16
|
+
value = JSON.parse(await readFile(path, "utf8"));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error.code !== "ENOENT")
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
23
|
+
throw new Error(`Invalid public content configuration: ${path}`);
|
|
24
|
+
const record = value;
|
|
25
|
+
const backend = record.backend ??
|
|
26
|
+
(Object.keys(record).length === 0
|
|
27
|
+
? (overrides.backend ?? "local")
|
|
28
|
+
: "local");
|
|
29
|
+
const defaults = backend === "local"
|
|
30
|
+
? { dataDir: join(homedir(), ".silvermoon.work", "content") }
|
|
31
|
+
: {};
|
|
32
|
+
// Validate both the file and merged value: overrides cannot hide malformed file fields.
|
|
33
|
+
try {
|
|
34
|
+
if (Object.keys(record).length)
|
|
35
|
+
validateConfiguration({ ...defaults, ...record });
|
|
36
|
+
const config = validateConfiguration({
|
|
37
|
+
...defaults,
|
|
38
|
+
...record,
|
|
39
|
+
...overrides,
|
|
40
|
+
});
|
|
41
|
+
if (Object.keys(record).length && config.backend !== backend)
|
|
42
|
+
throw new Error("Backend overrides must replace the configuration file explicitly.");
|
|
43
|
+
if (config.coordinationDir)
|
|
44
|
+
config.coordinationDir = resolve(dirname(path), config.coordinationDir);
|
|
45
|
+
if (config.backend === "local")
|
|
46
|
+
config.dataDir = isAbsolute(config.dataDir)
|
|
47
|
+
? resolve(config.dataDir)
|
|
48
|
+
: resolve(dirname(path), config.dataDir);
|
|
49
|
+
return config;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new Error(`Invalid public content configuration: ${path}; check backend-specific fields.`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Explicit host helper; never called as a library import side effect. */
|
|
56
|
+
export async function createConfiguredContent(overrides = {}) {
|
|
57
|
+
const configuration = await readContentConfiguration(overrides);
|
|
58
|
+
return new IpfsStore(configuration);
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EACL,qBAAqB,GAEtB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,UAAU,iBAAiB;IAC/B,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,mBAAmB;QAC/B,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO;YAC3B,CAAC,CAAC,IAAI,CACF,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,EAC/D,aAAa,EACb,aAAa,CACd;YACH,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,EAA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AAG,MAAM;YACT,GAAG,SAAS;SACb,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,OAAO,KAAK,OAAO;YAC1D,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;QACJ,IAAI,MAAM,CAAC,eAAe;YACxB,MAAM,CAAC,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC;QAC1E,IAAI,MAAM,CAAC,OAAO,KAAK,OAAO;YAC5B,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC;gBACzC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC;gBACzB,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;QAC7C,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CACb,yCAAyC,IAAI,kCAAkC,CAChF,CAAC;IACJ,CAAC;AACH,CAAC;AACD,0EAA0E;AAC1E,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,YAA2C,EAAE;IAE7C,MAAM,aAAa,GAAG,MAAM,wBAAwB,CAAC,SAAS,CAAC,CAAC;IAChE,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,CAAC;AACtC,CAAC"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { PinRecord } from "./kubo.js";
|
|
2
|
+
interface RetentionPort {
|
|
3
|
+
prepare(root: string, signal?: AbortSignal): Promise<void>;
|
|
4
|
+
status?(root: string, signal?: AbortSignal): Promise<PinRecord | undefined>;
|
|
5
|
+
pin?(root: string, name: string, signal?: AbortSignal): Promise<void>;
|
|
6
|
+
unpin?(root: string, signal?: AbortSignal): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
/** The SQLite mutex is separate so write-ahead intents survive a crash during an RPC. */
|
|
9
|
+
export declare class Retention {
|
|
10
|
+
private readonly port;
|
|
11
|
+
private readonly Database;
|
|
12
|
+
readonly name: string;
|
|
13
|
+
private readonly db;
|
|
14
|
+
private readonly mutexPath;
|
|
15
|
+
private readonly pending;
|
|
16
|
+
private closed;
|
|
17
|
+
constructor(directory: string, port: RetentionPort);
|
|
18
|
+
private roots;
|
|
19
|
+
private readOwner;
|
|
20
|
+
private publish;
|
|
21
|
+
private begin;
|
|
22
|
+
register(owner: string, roots: readonly string[]): void;
|
|
23
|
+
private locked;
|
|
24
|
+
private lock;
|
|
25
|
+
private phase;
|
|
26
|
+
private restoreClaim;
|
|
27
|
+
private ensure;
|
|
28
|
+
pin(root: string, signal?: AbortSignal): Promise<void>;
|
|
29
|
+
retain(owner: string, roots: readonly string[], signal?: AbortSignal): Promise<void>;
|
|
30
|
+
confirm(owner: string, roots: readonly string[], signal?: AbortSignal): Promise<void>;
|
|
31
|
+
private intent;
|
|
32
|
+
discard(session: string, signal?: AbortSignal): Promise<void>;
|
|
33
|
+
recover(owner: string, roots: readonly string[] | (() => readonly string[]), signal?: AbortSignal, isIdle?: () => boolean): Promise<void>;
|
|
34
|
+
stage(session: string, root: string, write: (name: string, claim: boolean) => Promise<void>, signal?: AbortSignal): Promise<void>;
|
|
35
|
+
finish(session: string, root: string, owner?: string, signal?: AbortSignal): Promise<void>;
|
|
36
|
+
private remove;
|
|
37
|
+
unpin(root: string, signal?: AbortSignal): Promise<void>;
|
|
38
|
+
private allRoots;
|
|
39
|
+
reconcile(owner: string, roots: readonly string[] | (() => readonly string[]), signal?: AbortSignal): Promise<number>;
|
|
40
|
+
pins(): string[];
|
|
41
|
+
close(): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
export {};
|
|
44
|
+
//# sourceMappingURL=retention.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retention.d.ts","sourceRoot":"","sources":["../src/retention.ts"],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G,CAAC,MAAM,SAAS,MAAM,EAAE,CAAC,EACpD,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC;IAgBlB,IAAI,IAAI,MAAM,EAAE;IAMV,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAK7B"}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
6
|
+
import { CID } from "multiformats/cid";
|
|
7
|
+
import { ContentError } from "./errors.js";
|
|
8
|
+
/** The SQLite mutex is separate so write-ahead intents survive a crash during an RPC. */
|
|
9
|
+
export class Retention {
|
|
10
|
+
port;
|
|
11
|
+
Database;
|
|
12
|
+
name;
|
|
13
|
+
db;
|
|
14
|
+
mutexPath;
|
|
15
|
+
pending = new Set();
|
|
16
|
+
closed = false;
|
|
17
|
+
constructor(directory, port) {
|
|
18
|
+
this.port = port;
|
|
19
|
+
this.Database = createRequire(import.meta.url)("node:sqlite").DatabaseSync;
|
|
20
|
+
mkdirSync(directory, { recursive: true });
|
|
21
|
+
this.db = new this.Database(join(directory, "retention.sqlite"));
|
|
22
|
+
this.mutexPath = join(directory, "mutex.sqlite");
|
|
23
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
|
|
24
|
+
CREATE TABLE IF NOT EXISTS identity (id TEXT PRIMARY KEY);
|
|
25
|
+
CREATE TABLE IF NOT EXISTS owners (id TEXT PRIMARY KEY, roots TEXT NOT NULL);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS stages (id TEXT NOT NULL, cid TEXT NOT NULL, PRIMARY KEY(id,cid));
|
|
27
|
+
CREATE TABLE IF NOT EXISTS stage_claims (cid TEXT PRIMARY KEY);
|
|
28
|
+
CREATE TABLE IF NOT EXISTS intents (
|
|
29
|
+
id TEXT NOT NULL, cid TEXT NOT NULL, count INTEGER NOT NULL CHECK(count>0), PRIMARY KEY(id,cid));
|
|
30
|
+
CREATE TABLE IF NOT EXISTS pins (cid TEXT PRIMARY KEY, phase TEXT NOT NULL);`);
|
|
31
|
+
this.db
|
|
32
|
+
.prepare("INSERT INTO identity SELECT ? WHERE NOT EXISTS (SELECT 1 FROM identity)")
|
|
33
|
+
.run(randomUUID());
|
|
34
|
+
this.name = `@silvermoon-work/task-engine/${String(this.db.prepare("SELECT id FROM identity").get().id)}`;
|
|
35
|
+
}
|
|
36
|
+
roots(values) {
|
|
37
|
+
return [
|
|
38
|
+
...new Set(values.map((value) => CID.parse(value).toV1().toString())),
|
|
39
|
+
].sort();
|
|
40
|
+
}
|
|
41
|
+
readOwner(owner) {
|
|
42
|
+
const row = this.db
|
|
43
|
+
.prepare("SELECT roots FROM owners WHERE id=?")
|
|
44
|
+
.get(owner);
|
|
45
|
+
if (!row)
|
|
46
|
+
return [];
|
|
47
|
+
const roots = JSON.parse(String(row.roots));
|
|
48
|
+
if (!Array.isArray(roots) || roots.some((root) => typeof root !== "string"))
|
|
49
|
+
throw new Error("Invalid retention owner references.");
|
|
50
|
+
return this.roots(roots);
|
|
51
|
+
}
|
|
52
|
+
publish(owner, roots, replace = false) {
|
|
53
|
+
if (typeof owner !== "string" || !owner || owner.length > 4096)
|
|
54
|
+
throw new Error("A stable retention owner is required.");
|
|
55
|
+
const values = this.roots(replace ? roots : [...this.readOwner(owner), ...roots]);
|
|
56
|
+
this.db
|
|
57
|
+
.prepare("INSERT OR REPLACE INTO owners VALUES (?,?)")
|
|
58
|
+
.run(owner, JSON.stringify(values));
|
|
59
|
+
}
|
|
60
|
+
begin(mutex) {
|
|
61
|
+
if (this.closed)
|
|
62
|
+
throw new Error("Retention coordinator is closed.");
|
|
63
|
+
mutex.exec("BEGIN IMMEDIATE");
|
|
64
|
+
}
|
|
65
|
+
register(owner, roots) {
|
|
66
|
+
const mutex = new this.Database(this.mutexPath);
|
|
67
|
+
mutex.exec("PRAGMA busy_timeout=0");
|
|
68
|
+
try {
|
|
69
|
+
this.begin(mutex);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
mutex.close();
|
|
73
|
+
throw new ContentError("retention_unfinished", "Retention coordination is unavailable; retry.");
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
this.publish(owner, roots);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
mutex.exec("ROLLBACK");
|
|
80
|
+
mutex.close();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async locked(signal, action) {
|
|
84
|
+
const operation = this.lock(signal, action);
|
|
85
|
+
this.pending.add(operation);
|
|
86
|
+
void operation
|
|
87
|
+
.finally(() => this.pending.delete(operation))
|
|
88
|
+
.catch(() => { });
|
|
89
|
+
return operation;
|
|
90
|
+
}
|
|
91
|
+
async lock(signal, action) {
|
|
92
|
+
const mutex = new this.Database(this.mutexPath);
|
|
93
|
+
mutex.exec("PRAGMA busy_timeout=0");
|
|
94
|
+
const deadline = Date.now() + 30_000;
|
|
95
|
+
try {
|
|
96
|
+
for (;;) {
|
|
97
|
+
signal?.throwIfAborted();
|
|
98
|
+
try {
|
|
99
|
+
this.begin(mutex);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (error.errcode !== 5 ||
|
|
104
|
+
Date.now() >= deadline)
|
|
105
|
+
throw new ContentError("retention_unfinished", "Retention coordination is unavailable.");
|
|
106
|
+
await sleep(10, undefined, signal ? { signal } : {});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
mutex.close();
|
|
112
|
+
signal?.throwIfAborted();
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
return await action();
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (signal?.aborted)
|
|
120
|
+
throw signal.reason;
|
|
121
|
+
throw new ContentError("retention_unfinished", `Retention hints are unfinished; durable intents remain for retry. ${error instanceof ContentError
|
|
122
|
+
? `${error.code}: ${error.message}`
|
|
123
|
+
: error instanceof Error &&
|
|
124
|
+
["TimeoutError", "AbortError"].includes(error.name)
|
|
125
|
+
? error.name
|
|
126
|
+
: "verification_or_storage_failure"}`, { cause: error });
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
mutex.exec("ROLLBACK");
|
|
130
|
+
mutex.close();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
phase(root, phase) {
|
|
134
|
+
this.db
|
|
135
|
+
.prepare("INSERT OR REPLACE INTO pins VALUES (?,?)")
|
|
136
|
+
.run(root, phase);
|
|
137
|
+
}
|
|
138
|
+
async restoreClaim(root, signal) {
|
|
139
|
+
if (!this.db.prepare("SELECT 1 FROM stage_claims WHERE cid=?").get(root))
|
|
140
|
+
return;
|
|
141
|
+
if (!this.port.status || !this.port.pin)
|
|
142
|
+
throw new Error("The staging claim's RPC backend is unavailable.");
|
|
143
|
+
let status = await this.port.status(root, signal);
|
|
144
|
+
if (status && status.Type !== "indirect" && !status.Name) {
|
|
145
|
+
if (status.Type !== "recursive")
|
|
146
|
+
throw new Error("An uncertain staging pin changed type; ownership is unfinished.");
|
|
147
|
+
// Only a durable absent/indirect/own before-state authorizes this recovery.
|
|
148
|
+
await this.port.prepare(root, signal);
|
|
149
|
+
await this.port.pin(root, this.name, signal);
|
|
150
|
+
status = await this.port.status(root, signal);
|
|
151
|
+
if (status && status.Type !== "indirect" && !status.Name)
|
|
152
|
+
throw new Error("The staging pin is still unnamed; ownership is unfinished.");
|
|
153
|
+
}
|
|
154
|
+
this.db.prepare("DELETE FROM stage_claims WHERE cid=?").run(root);
|
|
155
|
+
}
|
|
156
|
+
async ensure(root, signal) {
|
|
157
|
+
await this.restoreClaim(root, signal);
|
|
158
|
+
this.phase(root, "pin-pending");
|
|
159
|
+
await this.port.prepare(root, signal);
|
|
160
|
+
const status = await this.port.status?.(root, signal);
|
|
161
|
+
if (status && status.Type !== "indirect" && status.Name !== this.name) {
|
|
162
|
+
if (status.Type !== "recursive")
|
|
163
|
+
throw new ContentError("retention_unfinished", "An external direct pin cannot be renamed into a recursive system hint.");
|
|
164
|
+
// Do not turn another application's visible pin into our hint.
|
|
165
|
+
this.phase(root, "external");
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
await this.port.pin?.(root, this.name, signal);
|
|
169
|
+
this.phase(root, "pinned");
|
|
170
|
+
}
|
|
171
|
+
pin(root, signal) {
|
|
172
|
+
root = this.roots([root])[0];
|
|
173
|
+
return this.locked(signal, () => this.ensure(root, signal));
|
|
174
|
+
}
|
|
175
|
+
retain(owner, roots, signal) {
|
|
176
|
+
return this.locked(signal, async () => {
|
|
177
|
+
this.publish(owner, roots);
|
|
178
|
+
for (const root of this.roots(roots))
|
|
179
|
+
this.intent(owner, root);
|
|
180
|
+
for (const root of this.roots(roots))
|
|
181
|
+
await this.ensure(root, signal);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
confirm(owner, roots, signal) {
|
|
185
|
+
return this.locked(signal, () => {
|
|
186
|
+
this.publish(owner, roots);
|
|
187
|
+
for (const root of this.roots(roots)) {
|
|
188
|
+
const row = this.db
|
|
189
|
+
.prepare("SELECT count FROM intents WHERE id=? AND cid=?")
|
|
190
|
+
.get(owner, root);
|
|
191
|
+
if (row && Number(row.count) > 1)
|
|
192
|
+
this.db
|
|
193
|
+
.prepare("UPDATE intents SET count=count-1 WHERE id=? AND cid=?")
|
|
194
|
+
.run(owner, root);
|
|
195
|
+
else
|
|
196
|
+
this.db
|
|
197
|
+
.prepare("DELETE FROM intents WHERE id=? AND cid=?")
|
|
198
|
+
.run(owner, root);
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
intent(owner, root) {
|
|
203
|
+
this.db
|
|
204
|
+
.prepare(`INSERT INTO intents VALUES (?,?,1)
|
|
205
|
+
ON CONFLICT(id,cid) DO UPDATE SET count=count+1`)
|
|
206
|
+
.run(owner, root);
|
|
207
|
+
}
|
|
208
|
+
discard(session, signal) {
|
|
209
|
+
return this.locked(signal, () => {
|
|
210
|
+
this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
recover(owner, roots, signal, isIdle) {
|
|
214
|
+
return this.locked(signal, () => {
|
|
215
|
+
if (isIdle && !isIdle())
|
|
216
|
+
return;
|
|
217
|
+
this.publish(owner, typeof roots === "function" ? roots() : roots, true);
|
|
218
|
+
this.db.prepare("DELETE FROM intents WHERE id=?").run(owner);
|
|
219
|
+
for (const row of this.db.prepare("SELECT DISTINCT id FROM stages").all())
|
|
220
|
+
if (String(row.id).startsWith(`${owner}/`))
|
|
221
|
+
this.db.prepare("DELETE FROM stages WHERE id=?").run(String(row.id));
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
stage(session, root, write, signal) {
|
|
225
|
+
root = this.roots([root])[0];
|
|
226
|
+
return this.locked(signal, async () => {
|
|
227
|
+
await this.restoreClaim(root, signal);
|
|
228
|
+
this.db
|
|
229
|
+
.prepare("INSERT OR IGNORE INTO stages VALUES (?,?)")
|
|
230
|
+
.run(session, root);
|
|
231
|
+
const alreadyPinned = this.db.prepare("SELECT phase FROM pins WHERE cid=?").get(root)
|
|
232
|
+
?.phase === "pinned";
|
|
233
|
+
this.phase(root, "stage-pending");
|
|
234
|
+
const status = await this.port.status?.(root, signal);
|
|
235
|
+
const claim = !status || status.Type === "indirect" || status.Name === this.name;
|
|
236
|
+
if (claim && this.port.status)
|
|
237
|
+
this.db
|
|
238
|
+
.prepare("INSERT OR IGNORE INTO stage_claims VALUES (?)")
|
|
239
|
+
.run(root);
|
|
240
|
+
await write(this.name, claim);
|
|
241
|
+
if (claim)
|
|
242
|
+
await this.restoreClaim(root, signal);
|
|
243
|
+
this.phase(root, claim ? (alreadyPinned ? "pinned" : "staged") : "external");
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
finish(session, root, owner, signal) {
|
|
247
|
+
root = this.roots([root])[0];
|
|
248
|
+
return this.locked(signal, async () => {
|
|
249
|
+
if (owner) {
|
|
250
|
+
this.publish(owner, [root]);
|
|
251
|
+
this.intent(owner, root);
|
|
252
|
+
}
|
|
253
|
+
await this.ensure(root, signal);
|
|
254
|
+
this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
async remove(root, signal) {
|
|
258
|
+
await this.restoreClaim(root, signal);
|
|
259
|
+
const record = this.db
|
|
260
|
+
.prepare("SELECT phase FROM pins WHERE cid=?")
|
|
261
|
+
.get(root);
|
|
262
|
+
if (!record)
|
|
263
|
+
return false;
|
|
264
|
+
this.phase(root, "unpin-pending");
|
|
265
|
+
const status = await this.port.status?.(root, signal);
|
|
266
|
+
if (this.port.status && (!status || status.Name !== this.name)) {
|
|
267
|
+
this.db.prepare("DELETE FROM pins WHERE cid=?").run(root);
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
await this.port.unpin?.(root, signal);
|
|
271
|
+
this.db.prepare("DELETE FROM pins WHERE cid=?").run(root);
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
unpin(root, signal) {
|
|
275
|
+
root = this.roots([root])[0];
|
|
276
|
+
return this.locked(signal, async () => {
|
|
277
|
+
if (this.allRoots().includes(root))
|
|
278
|
+
throw new Error("A participating owner still retains this root.");
|
|
279
|
+
await this.remove(root, signal);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
allRoots() {
|
|
283
|
+
return this.roots([
|
|
284
|
+
...this.db
|
|
285
|
+
.prepare("SELECT id FROM owners")
|
|
286
|
+
.all()
|
|
287
|
+
.flatMap((row) => this.readOwner(String(row.id))),
|
|
288
|
+
...this.db
|
|
289
|
+
.prepare("SELECT cid FROM intents")
|
|
290
|
+
.all()
|
|
291
|
+
.map((row) => String(row.cid)),
|
|
292
|
+
...this.db
|
|
293
|
+
.prepare("SELECT cid FROM stages")
|
|
294
|
+
.all()
|
|
295
|
+
.map((row) => String(row.cid)),
|
|
296
|
+
]);
|
|
297
|
+
}
|
|
298
|
+
reconcile(owner, roots, signal) {
|
|
299
|
+
return this.locked(signal, async () => {
|
|
300
|
+
this.publish(owner, typeof roots === "function" ? roots() : roots, true);
|
|
301
|
+
for (const row of this.db.prepare("SELECT cid FROM stage_claims").all())
|
|
302
|
+
await this.restoreClaim(String(row.cid), signal);
|
|
303
|
+
const marked = new Set(this.allRoots());
|
|
304
|
+
// Complete the entire mark before removing any hint. Recheck real blocks, not reader caches.
|
|
305
|
+
for (const root of marked)
|
|
306
|
+
await this.ensure(root, signal);
|
|
307
|
+
let removed = 0;
|
|
308
|
+
for (const row of this.db.prepare("SELECT cid FROM pins").all()) {
|
|
309
|
+
const root = String(row.cid);
|
|
310
|
+
if (!marked.has(root) && (await this.remove(root, signal)))
|
|
311
|
+
removed++;
|
|
312
|
+
}
|
|
313
|
+
return removed;
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
pins() {
|
|
317
|
+
return this.db
|
|
318
|
+
.prepare("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid")
|
|
319
|
+
.all()
|
|
320
|
+
.map((row) => String(row.cid));
|
|
321
|
+
}
|
|
322
|
+
async close() {
|
|
323
|
+
this.closed = true;
|
|
324
|
+
await Promise.allSettled([...this.pending]);
|
|
325
|
+
this.db.close();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
//# sourceMappingURL=retention.js.map
|