@dasl/fisl 0.0.0-stage → 0.1.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/CLI.md +111 -0
- package/README.md +108 -2
- package/dist/cli.d.ts +13 -0
- package/dist/cli.js +315 -0
- package/dist/mod.d.ts +21 -0
- package/dist/mod.js +21 -0
- package/dist/src/atproto.d.ts +67 -0
- package/dist/src/atproto.js +163 -0
- package/dist/src/cid-core.d.ts +9 -0
- package/dist/src/cid-core.js +39 -0
- package/dist/src/cid.d.ts +18 -0
- package/dist/src/cid.js +40 -0
- package/dist/src/fetch.d.ts +27 -0
- package/dist/src/fetch.js +328 -0
- package/dist/src/fisl/client.d.ts +17 -0
- package/dist/src/fisl/client.js +124 -0
- package/dist/src/fisl/server.d.ts +19 -0
- package/dist/src/fisl/server.js +69 -0
- package/dist/src/index/ingest.d.ts +8 -0
- package/dist/src/index/ingest.js +22 -0
- package/dist/src/index/jetstream.d.ts +13 -0
- package/dist/src/index/jetstream.js +88 -0
- package/dist/src/index/pds.d.ts +14 -0
- package/dist/src/index/pds.js +42 -0
- package/dist/src/index/sqlite.d.ts +16 -0
- package/dist/src/index/sqlite.js +105 -0
- package/dist/src/index/store.d.ts +37 -0
- package/dist/src/index/store.js +59 -0
- package/dist/src/index/verify.d.ts +19 -0
- package/dist/src/index/verify.js +61 -0
- package/dist/src/publish.d.ts +11 -0
- package/dist/src/publish.js +24 -0
- package/dist/src/rasl/server.d.ts +24 -0
- package/dist/src/rasl/server.js +110 -0
- package/dist/src/record-core.d.ts +8 -0
- package/dist/src/record-core.js +58 -0
- package/dist/src/record.d.ts +35 -0
- package/dist/src/record.js +47 -0
- package/dist/src/serve.d.ts +12 -0
- package/dist/src/serve.js +69 -0
- package/package.json +50 -4
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Look up locations for a CID, from a FISL indexer or directly from a PDS.
|
|
2
|
+
import { getRecord, resolveIdentity } from "../atproto.js";
|
|
3
|
+
import { liveRecord, toLocation } from "../record.js";
|
|
4
|
+
import { FISL_PREFIX } from "./server.js";
|
|
5
|
+
/** Split a byte stream into lines, without a bound on their number. */
|
|
6
|
+
async function* lines(body) {
|
|
7
|
+
const decoder = new TextDecoder();
|
|
8
|
+
let buf = "";
|
|
9
|
+
for await (const chunk of body) {
|
|
10
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
11
|
+
let i;
|
|
12
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
13
|
+
yield buf.slice(0, i);
|
|
14
|
+
buf = buf.slice(i + 1);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
buf += decoder.decode();
|
|
18
|
+
if (buf)
|
|
19
|
+
yield buf;
|
|
20
|
+
}
|
|
21
|
+
/** Stream locations for a CID from a FISL indexer, using the jsonl format. */
|
|
22
|
+
export async function* resolveFromIndexer(cid, indexer, signal) {
|
|
23
|
+
const url = new URL(`${FISL_PREFIX}${cid}/jsonl`, indexer);
|
|
24
|
+
const res = await fetch(url, { signal });
|
|
25
|
+
if (!res.ok || !res.body) {
|
|
26
|
+
await res.body?.cancel();
|
|
27
|
+
throw new Error(`${url}: ${res.status} ${res.statusText}`);
|
|
28
|
+
}
|
|
29
|
+
for await (const line of lines(res.body)) {
|
|
30
|
+
if (!line.trim())
|
|
31
|
+
continue;
|
|
32
|
+
const loc = liveRecord(JSON.parse(line));
|
|
33
|
+
if (loc)
|
|
34
|
+
yield loc;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Read the location a publisher announced for a CID, straight from its PDS. */
|
|
38
|
+
export async function resolveFromPds(cid, handleOrDid, signal) {
|
|
39
|
+
const id = await resolveIdentity(handleOrDid, signal);
|
|
40
|
+
const record = await getRecord(id, cid, signal);
|
|
41
|
+
const live = record && liveRecord(record);
|
|
42
|
+
return live ? toLocation(live, id.did) : null;
|
|
43
|
+
}
|
|
44
|
+
/** Locations from every indexer and publisher. Failing sources are skipped. */
|
|
45
|
+
export async function* resolve(cid, opts) {
|
|
46
|
+
const stop = new AbortController();
|
|
47
|
+
const signal = opts.signal
|
|
48
|
+
? AbortSignal.any([opts.signal, stop.signal])
|
|
49
|
+
: stop.signal;
|
|
50
|
+
const sources = [
|
|
51
|
+
...(opts.publishers ?? []).map((source) => ({ source, publisher: true })),
|
|
52
|
+
...(opts.indexers ?? []).map((source) => ({ source, publisher: false })),
|
|
53
|
+
];
|
|
54
|
+
const queue = [];
|
|
55
|
+
let wake = () => { };
|
|
56
|
+
let remaining = sources.length;
|
|
57
|
+
const worker = async () => {
|
|
58
|
+
while (sources.length && !signal.aborted) {
|
|
59
|
+
const { source, publisher } = sources.shift();
|
|
60
|
+
const timeout = AbortSignal.any([
|
|
61
|
+
signal,
|
|
62
|
+
AbortSignal.timeout(opts.resolutionTimeoutMs ?? 10_000),
|
|
63
|
+
]);
|
|
64
|
+
const work = (async () => {
|
|
65
|
+
if (publisher) {
|
|
66
|
+
const loc = await resolveFromPds(cid, source, timeout);
|
|
67
|
+
if (loc && !timeout.aborted) {
|
|
68
|
+
queue.push(loc);
|
|
69
|
+
wake();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
for await (const loc of resolveFromIndexer(cid, source, timeout)) {
|
|
74
|
+
if (timeout.aborted)
|
|
75
|
+
break;
|
|
76
|
+
queue.push(loc);
|
|
77
|
+
wake();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
})();
|
|
81
|
+
try {
|
|
82
|
+
await Promise.race([
|
|
83
|
+
work,
|
|
84
|
+
new Promise((_, reject) => {
|
|
85
|
+
if (timeout.aborted)
|
|
86
|
+
reject(timeout.reason);
|
|
87
|
+
else {
|
|
88
|
+
timeout.addEventListener("abort", () => reject(timeout.reason), { once: true });
|
|
89
|
+
}
|
|
90
|
+
}),
|
|
91
|
+
]);
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
if (!signal.aborted)
|
|
95
|
+
opts.onError?.(source, e);
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
remaining--;
|
|
99
|
+
wake();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
const workers = Array.from({
|
|
104
|
+
length: Math.min(sources.length, Math.max(1, opts.resolutionConcurrency ?? 4)),
|
|
105
|
+
}, worker);
|
|
106
|
+
try {
|
|
107
|
+
while (remaining && !signal.aborted || queue.length) {
|
|
108
|
+
if (queue.length)
|
|
109
|
+
yield queue.shift();
|
|
110
|
+
else {
|
|
111
|
+
await new Promise((resolve) => {
|
|
112
|
+
wake = resolve;
|
|
113
|
+
signal.addEventListener("abort", () => resolve(), { once: true });
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (opts.signal?.aborted)
|
|
118
|
+
throw opts.signal.reason;
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
stop.abort();
|
|
122
|
+
await Promise.allSettled(workers);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Store } from "../index/store.ts";
|
|
2
|
+
import { type Location } from "../record.ts";
|
|
3
|
+
export declare const FISL_PREFIX = "/routing/locations/";
|
|
4
|
+
export interface FislOptions {
|
|
5
|
+
/** max-age in seconds when no record states an expiry. */
|
|
6
|
+
ttl?: number;
|
|
7
|
+
/** max-age in seconds for an empty result. */
|
|
8
|
+
emptyTtl?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Find the live locations for a CID. */
|
|
11
|
+
export declare function lookup(store: Store, cid: string, now?: number): Promise<{
|
|
12
|
+
locations: Location[];
|
|
13
|
+
expires: number | null;
|
|
14
|
+
}>;
|
|
15
|
+
/**
|
|
16
|
+
* A handler for FISL requests. Returns null for paths outside
|
|
17
|
+
* /routing/locations/, so it can be combined with other handlers.
|
|
18
|
+
*/
|
|
19
|
+
export declare function fislHandler(store: Store, { ttl, emptyTtl }?: FislOptions): (req: Request) => Promise<Response | null>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// The FISL HTTP endpoint: GET /routing/locations/{cid}/{format}
|
|
2
|
+
// See specs/fisl.md.
|
|
3
|
+
import { parseCid } from "../cid.js";
|
|
4
|
+
import { earliestExpiry, liveRecord, toLocation, } from "../record.js";
|
|
5
|
+
export const FISL_PREFIX = "/routing/locations/";
|
|
6
|
+
const CORS = {
|
|
7
|
+
"access-control-allow-origin": "*",
|
|
8
|
+
"access-control-allow-methods": "GET, OPTIONS",
|
|
9
|
+
};
|
|
10
|
+
/** Find the live locations for a CID. */
|
|
11
|
+
export async function lookup(store, cid, now = Date.now()) {
|
|
12
|
+
const locations = [];
|
|
13
|
+
let expires = null;
|
|
14
|
+
for (const row of await store.get(cid)) {
|
|
15
|
+
const rec = liveRecord(row.record, now);
|
|
16
|
+
if (!rec)
|
|
17
|
+
continue;
|
|
18
|
+
locations.push(toLocation(rec, row.did));
|
|
19
|
+
const exp = earliestExpiry(rec);
|
|
20
|
+
if (exp !== null)
|
|
21
|
+
expires = Math.min(expires ?? exp, exp);
|
|
22
|
+
}
|
|
23
|
+
return { locations, expires };
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A handler for FISL requests. Returns null for paths outside
|
|
27
|
+
* /routing/locations/, so it can be combined with other handlers.
|
|
28
|
+
*/
|
|
29
|
+
export function fislHandler(store, { ttl = 60, emptyTtl = 5 } = {}) {
|
|
30
|
+
return async (req) => {
|
|
31
|
+
const { pathname } = new URL(req.url);
|
|
32
|
+
if (!pathname.startsWith(FISL_PREFIX))
|
|
33
|
+
return null;
|
|
34
|
+
if (req.method === "OPTIONS") {
|
|
35
|
+
return new Response(null, { status: 204, headers: CORS });
|
|
36
|
+
}
|
|
37
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
38
|
+
return new Response("Method not allowed", { status: 405, headers: CORS });
|
|
39
|
+
}
|
|
40
|
+
const [cid, format, ...extra] = pathname.slice(FISL_PREFIX.length).split("/");
|
|
41
|
+
if (!parseCid(cid)) {
|
|
42
|
+
return new Response("Not a DASL or BDASL CID", {
|
|
43
|
+
status: 400,
|
|
44
|
+
headers: CORS,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if ((format !== "json" && format !== "jsonl") || extra.length) {
|
|
48
|
+
return new Response("Unsupported format", { status: 404, headers: CORS });
|
|
49
|
+
}
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
const { locations, expires } = await lookup(store, cid, now);
|
|
52
|
+
// max-age must not outlive the earliest expiry in the response.
|
|
53
|
+
let maxAge = locations.length ? ttl : emptyTtl;
|
|
54
|
+
if (expires !== null) {
|
|
55
|
+
maxAge = Math.min(maxAge, Math.floor((expires - now) / 1000));
|
|
56
|
+
}
|
|
57
|
+
const headers = {
|
|
58
|
+
...CORS,
|
|
59
|
+
"cache-control": `public, max-age=${Math.max(0, maxAge)}`,
|
|
60
|
+
"content-type": format === "json"
|
|
61
|
+
? "application/json"
|
|
62
|
+
: "application/jsonl",
|
|
63
|
+
};
|
|
64
|
+
const body = format === "json"
|
|
65
|
+
? JSON.stringify({ locations })
|
|
66
|
+
: locations.map((l) => JSON.stringify(l) + "\n").join("");
|
|
67
|
+
return new Response(req.method === "HEAD" ? null : body, { headers });
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Store } from "./store.ts";
|
|
2
|
+
import type { Verifier } from "./verify.ts";
|
|
3
|
+
export type IngestResult = "stored" | "deleted" | "discarded" | "stale";
|
|
4
|
+
/**
|
|
5
|
+
* Index the current state of (did, cid). The event only says that something
|
|
6
|
+
* changed: the record itself comes from a verified proof from the PDS.
|
|
7
|
+
*/
|
|
8
|
+
export declare function ingest(store: Store, verifier: Verifier, did: string, cid: string): Promise<IngestResult>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Apply ATFISL indexing steps 2 to 6 to one record event.
|
|
2
|
+
import { parseCid } from "../cid.js";
|
|
3
|
+
import { liveRecord } from "../record.js";
|
|
4
|
+
/**
|
|
5
|
+
* Index the current state of (did, cid). The event only says that something
|
|
6
|
+
* changed: the record itself comes from a verified proof from the PDS.
|
|
7
|
+
*/
|
|
8
|
+
export async function ingest(store, verifier, did, cid) {
|
|
9
|
+
if (!parseCid(cid))
|
|
10
|
+
return "discarded";
|
|
11
|
+
const { record, rev } = await verifier.verify(did, cid);
|
|
12
|
+
const live = record && liveRecord(record);
|
|
13
|
+
if (!live) {
|
|
14
|
+
// Absent, expired or without usable addrs: remove any older row.
|
|
15
|
+
await store.delete(cid, did, rev);
|
|
16
|
+
return record ? "discarded" : "deleted";
|
|
17
|
+
}
|
|
18
|
+
if (!rev)
|
|
19
|
+
return "discarded";
|
|
20
|
+
const stored = await store.put({ cid, did, rev, record: live });
|
|
21
|
+
return stored ? "stored" : "stale";
|
|
22
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Log } from "./pds.ts";
|
|
2
|
+
import type { Store } from "./store.ts";
|
|
3
|
+
import type { Verifier } from "./verify.ts";
|
|
4
|
+
export declare const JETSTREAM = "wss://jetstream2.us-east.bsky.network/subscribe";
|
|
5
|
+
export interface JetstreamOptions {
|
|
6
|
+
url?: string;
|
|
7
|
+
/** Only follow these DIDs. Empty means every DID. */
|
|
8
|
+
dids?: string[];
|
|
9
|
+
log?: Log;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
/** Follow Jetstream until the signal aborts. Reconnects with backoff. */
|
|
13
|
+
export declare function followJetstream(store: Store, verifier: Verifier, { url, dids, log, signal }?: JetstreamOptions): Promise<void>;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Follow dev.fisl.at commits on Jetstream.
|
|
2
|
+
//
|
|
3
|
+
// Jetstream events carry no commit proof, so each event only triggers
|
|
4
|
+
// ingest(), which fetches and verifies the record from the PDS.
|
|
5
|
+
import { NSID } from "../record.js";
|
|
6
|
+
import { ingest } from "./ingest.js";
|
|
7
|
+
export const JETSTREAM = "wss://jetstream2.us-east.bsky.network/subscribe";
|
|
8
|
+
const CURSOR = "jetstream";
|
|
9
|
+
// Rewind the cursor on reconnect, so no event is lost in the gap.
|
|
10
|
+
const REWIND_US = 5_000_000;
|
|
11
|
+
/** Follow Jetstream until the signal aborts. Reconnects with backoff. */
|
|
12
|
+
export async function followJetstream(store, verifier, { url = JETSTREAM, dids = [], log = () => { }, signal } = {}) {
|
|
13
|
+
let backoff = 1000;
|
|
14
|
+
while (!signal?.aborted) {
|
|
15
|
+
const u = new URL(url);
|
|
16
|
+
u.searchParams.set("wantedCollections", NSID);
|
|
17
|
+
for (const did of dids)
|
|
18
|
+
u.searchParams.append("wantedDids", did);
|
|
19
|
+
let cursor = await store.getCursor(CURSOR);
|
|
20
|
+
if (!cursor) {
|
|
21
|
+
cursor = String(Date.now() * 1000);
|
|
22
|
+
await store.setCursor(CURSOR, cursor);
|
|
23
|
+
}
|
|
24
|
+
if (cursor) {
|
|
25
|
+
u.searchParams.set("cursor", String(Number(cursor) - REWIND_US));
|
|
26
|
+
}
|
|
27
|
+
const closed = Promise.withResolvers();
|
|
28
|
+
const ws = new WebSocket(u);
|
|
29
|
+
const abort = () => ws.close();
|
|
30
|
+
signal?.addEventListener("abort", abort);
|
|
31
|
+
// Handle events one at a time, in order.
|
|
32
|
+
let queue = Promise.resolve();
|
|
33
|
+
let lastSaved = 0;
|
|
34
|
+
let failed = false;
|
|
35
|
+
let pending = 0;
|
|
36
|
+
let draining = false;
|
|
37
|
+
ws.onopen = () => {
|
|
38
|
+
backoff = 1000;
|
|
39
|
+
log(`connected to ${u.host}${cursor ? ` from cursor ${cursor}` : ""}`);
|
|
40
|
+
};
|
|
41
|
+
ws.onmessage = (msg) => {
|
|
42
|
+
if (draining || failed)
|
|
43
|
+
return;
|
|
44
|
+
// Drain a bounded batch before reconnecting from durable progress.
|
|
45
|
+
if (pending >= 256) {
|
|
46
|
+
draining = true;
|
|
47
|
+
ws.close();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const ev = JSON.parse(msg.data);
|
|
51
|
+
if (ev.kind !== "commit" || ev.commit?.collection !== NSID)
|
|
52
|
+
return;
|
|
53
|
+
const { rkey, operation } = ev.commit;
|
|
54
|
+
pending++;
|
|
55
|
+
queue = queue.then(async () => {
|
|
56
|
+
pending--;
|
|
57
|
+
if (failed)
|
|
58
|
+
return;
|
|
59
|
+
try {
|
|
60
|
+
const result = await ingest(store, verifier, ev.did, rkey);
|
|
61
|
+
log(`${operation} ${result} ${ev.did} ${rkey}`);
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
log(`error ${ev.did} ${rkey}: ${e.message}`);
|
|
65
|
+
// Reconnect from the last saved cursor; never advance past a failed proof.
|
|
66
|
+
failed = true;
|
|
67
|
+
ws.close();
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
// Save the cursor at most once a second.
|
|
71
|
+
if (ev.time_us - lastSaved > 1_000_000) {
|
|
72
|
+
lastSaved = ev.time_us;
|
|
73
|
+
await store.setCursor(CURSOR, String(ev.time_us));
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
ws.onerror = () => { };
|
|
78
|
+
ws.onclose = () => closed.resolve();
|
|
79
|
+
await closed.promise;
|
|
80
|
+
await queue;
|
|
81
|
+
signal?.removeEventListener("abort", abort);
|
|
82
|
+
if (signal?.aborted)
|
|
83
|
+
break;
|
|
84
|
+
log(`disconnected, retrying in ${backoff / 1000}s`);
|
|
85
|
+
await new Promise((r) => setTimeout(r, backoff));
|
|
86
|
+
backoff = Math.min(backoff * 2, 60_000);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Store } from "./store.ts";
|
|
2
|
+
import type { Verifier } from "./verify.ts";
|
|
3
|
+
export type Log = (msg: string) => void;
|
|
4
|
+
/** Index every record in one repo, and remove rows for records it no longer has. */
|
|
5
|
+
export declare function backfill(store: Store, verifier: Verifier, did: string, { log, known }?: {
|
|
6
|
+
log?: Log;
|
|
7
|
+
known?: Set<string>;
|
|
8
|
+
}): Promise<Set<string>>;
|
|
9
|
+
/** Backfill a set of repos, then poll them again every `interval` ms. */
|
|
10
|
+
export declare function pollRepos(store: Store, verifier: Verifier, dids: string[], { interval, log, signal }?: {
|
|
11
|
+
interval?: number;
|
|
12
|
+
log?: Log;
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Index dev.fisl.at records by reading repos directly from their PDS.
|
|
2
|
+
import { listRecords } from "../atproto.js";
|
|
3
|
+
import { ingest } from "./ingest.js";
|
|
4
|
+
/** Index every record in one repo, and remove rows for records it no longer has. */
|
|
5
|
+
export async function backfill(store, verifier, did, { log = () => { }, known } = {}) {
|
|
6
|
+
const id = await verifier.identity(did);
|
|
7
|
+
const seen = new Set();
|
|
8
|
+
const index = async (cid) => {
|
|
9
|
+
try {
|
|
10
|
+
log(`${await ingest(store, verifier, did, cid)} ${did} ${cid}`);
|
|
11
|
+
}
|
|
12
|
+
catch (e) {
|
|
13
|
+
log(`error ${did} ${cid}: ${e.message}`);
|
|
14
|
+
// Preserve failed deletion checks in known so the next poll retries them.
|
|
15
|
+
seen.add(cid);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
for await (const { cid } of listRecords(id)) {
|
|
19
|
+
seen.add(cid);
|
|
20
|
+
await index(cid);
|
|
21
|
+
}
|
|
22
|
+
// Records listed last time but not now were deleted. The proof confirms it.
|
|
23
|
+
for (const cid of known ?? [])
|
|
24
|
+
if (!seen.has(cid))
|
|
25
|
+
await index(cid);
|
|
26
|
+
return seen;
|
|
27
|
+
}
|
|
28
|
+
/** Backfill a set of repos, then poll them again every `interval` ms. */
|
|
29
|
+
export async function pollRepos(store, verifier, dids, { interval = 60_000, log = () => { }, signal } = {}) {
|
|
30
|
+
const known = new Map();
|
|
31
|
+
while (!signal?.aborted) {
|
|
32
|
+
for (const did of dids) {
|
|
33
|
+
try {
|
|
34
|
+
known.set(did, await backfill(store, verifier, did, { log, known: known.get(did) }));
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
log(`error ${did}: ${e.message}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { type Store, type StoredRecord } from "./store.ts";
|
|
3
|
+
export declare class SqliteStore implements Store {
|
|
4
|
+
#private;
|
|
5
|
+
readonly db: DatabaseSync;
|
|
6
|
+
constructor(db: DatabaseSync);
|
|
7
|
+
/** Open a database file. Use ":memory:" for a temporary store. */
|
|
8
|
+
static open(path?: string): Promise<SqliteStore>;
|
|
9
|
+
get(cid: string): Promise<StoredRecord[]>;
|
|
10
|
+
put(r: StoredRecord): Promise<boolean>;
|
|
11
|
+
delete(cid: string, did: string, rev?: string): Promise<void>;
|
|
12
|
+
sweep(now?: number): Promise<number>;
|
|
13
|
+
getCursor(name: string): Promise<string | undefined>;
|
|
14
|
+
setCursor(name: string, value: string): Promise<void>;
|
|
15
|
+
close(): void;
|
|
16
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// A Store backed by node:sqlite. Needs Node 22.13 or later.
|
|
2
|
+
import { DatabaseSync } from "node:sqlite";
|
|
3
|
+
import { isExpired, isNewer } from "./store.js";
|
|
4
|
+
export class SqliteStore {
|
|
5
|
+
db;
|
|
6
|
+
constructor(db) {
|
|
7
|
+
this.db = db;
|
|
8
|
+
db.exec(`
|
|
9
|
+
PRAGMA journal_mode = WAL;
|
|
10
|
+
CREATE TABLE IF NOT EXISTS rec (
|
|
11
|
+
cid TEXT NOT NULL,
|
|
12
|
+
did TEXT NOT NULL,
|
|
13
|
+
value TEXT NOT NULL,
|
|
14
|
+
PRIMARY KEY (cid, did)
|
|
15
|
+
) WITHOUT ROWID;
|
|
16
|
+
CREATE TABLE IF NOT EXISTS cursor (
|
|
17
|
+
name TEXT PRIMARY KEY,
|
|
18
|
+
value TEXT NOT NULL
|
|
19
|
+
) WITHOUT ROWID;
|
|
20
|
+
`);
|
|
21
|
+
}
|
|
22
|
+
/** Open a database file. Use ":memory:" for a temporary store. */
|
|
23
|
+
static open(path = ":memory:") {
|
|
24
|
+
return Promise.resolve(new SqliteStore(new DatabaseSync(path)));
|
|
25
|
+
}
|
|
26
|
+
#row(cid, did) {
|
|
27
|
+
const row = this.db
|
|
28
|
+
.prepare("SELECT value FROM rec WHERE cid = ? AND did = ?")
|
|
29
|
+
.get(cid, did);
|
|
30
|
+
return row && JSON.parse(row.value);
|
|
31
|
+
}
|
|
32
|
+
#set(r) {
|
|
33
|
+
this.db.prepare("INSERT OR REPLACE INTO rec VALUES (?, ?, ?)")
|
|
34
|
+
.run(r.cid, r.did, JSON.stringify(r));
|
|
35
|
+
}
|
|
36
|
+
// Other processes can share the file, so read and write in one transaction.
|
|
37
|
+
#transaction(fn) {
|
|
38
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
39
|
+
try {
|
|
40
|
+
const result = fn();
|
|
41
|
+
this.db.exec("COMMIT");
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
this.db.exec("ROLLBACK");
|
|
46
|
+
throw e;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
get(cid) {
|
|
50
|
+
const rows = this.db.prepare("SELECT value FROM rec WHERE cid = ?")
|
|
51
|
+
.all(cid);
|
|
52
|
+
return Promise.resolve(rows.map((r) => JSON.parse(r.value))
|
|
53
|
+
.filter((r) => !r.deleted));
|
|
54
|
+
}
|
|
55
|
+
put(r) {
|
|
56
|
+
return Promise.resolve(this.#transaction(() => {
|
|
57
|
+
if (!isNewer(r.rev, this.#row(r.cid, r.did)))
|
|
58
|
+
return false;
|
|
59
|
+
this.#set(r);
|
|
60
|
+
return true;
|
|
61
|
+
}));
|
|
62
|
+
}
|
|
63
|
+
delete(cid, did, rev) {
|
|
64
|
+
this.#transaction(() => {
|
|
65
|
+
const old = this.#row(cid, did);
|
|
66
|
+
if (!isNewer(rev, old))
|
|
67
|
+
return;
|
|
68
|
+
this.#set({
|
|
69
|
+
cid,
|
|
70
|
+
did,
|
|
71
|
+
rev: rev ?? old?.rev ?? "",
|
|
72
|
+
record: { addrs: [] },
|
|
73
|
+
deleted: true,
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
return Promise.resolve();
|
|
77
|
+
}
|
|
78
|
+
sweep(now = Date.now()) {
|
|
79
|
+
return Promise.resolve(this.#transaction(() => {
|
|
80
|
+
let n = 0;
|
|
81
|
+
const rows = this.db.prepare("SELECT value FROM rec").all();
|
|
82
|
+
for (const { value } of rows) {
|
|
83
|
+
const r = JSON.parse(value);
|
|
84
|
+
if (!r.deleted && isExpired(r.record, now)) {
|
|
85
|
+
this.#set({ ...r, record: { addrs: [] }, deleted: true });
|
|
86
|
+
n++;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return n;
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
getCursor(name) {
|
|
93
|
+
const row = this.db.prepare("SELECT value FROM cursor WHERE name = ?")
|
|
94
|
+
.get(name);
|
|
95
|
+
return Promise.resolve(row?.value);
|
|
96
|
+
}
|
|
97
|
+
setCursor(name, value) {
|
|
98
|
+
this.db.prepare("INSERT OR REPLACE INTO cursor VALUES (?, ?)")
|
|
99
|
+
.run(name, value);
|
|
100
|
+
return Promise.resolve();
|
|
101
|
+
}
|
|
102
|
+
close() {
|
|
103
|
+
this.db.close();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { AtfislRecord } from "../record.ts";
|
|
2
|
+
export interface StoredRecord {
|
|
3
|
+
cid: string;
|
|
4
|
+
did: string;
|
|
5
|
+
/** The repo revision (a TID) of the commit that wrote the record. */
|
|
6
|
+
rev: string;
|
|
7
|
+
record: AtfislRecord;
|
|
8
|
+
deleted?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface Store {
|
|
11
|
+
/** Every record stored for a CID, from any publisher. */
|
|
12
|
+
get(cid: string): Promise<StoredRecord[]>;
|
|
13
|
+
/**
|
|
14
|
+
* Store a record, replacing the row for the same (cid, did).
|
|
15
|
+
* Ignored, and returns false, unless rev is greater than the stored rev.
|
|
16
|
+
*/
|
|
17
|
+
put(r: StoredRecord): Promise<boolean>;
|
|
18
|
+
/** Hide a row while retaining its revision watermark. Only newer revisions apply. */
|
|
19
|
+
delete(cid: string, did: string, rev?: string): Promise<void>;
|
|
20
|
+
/** Hide expired records while retaining their revision watermarks. */
|
|
21
|
+
sweep(now?: number): Promise<number>;
|
|
22
|
+
/** A saved position, such as a Jetstream cursor. */
|
|
23
|
+
getCursor(name: string): Promise<string | undefined>;
|
|
24
|
+
setCursor(name: string, value: string): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
/** True if a stored row may be replaced or deleted by a write at rev. */
|
|
27
|
+
export declare function isNewer(rev: string | undefined, stored?: StoredRecord): boolean;
|
|
28
|
+
export declare function isExpired(r: AtfislRecord, now?: number): boolean;
|
|
29
|
+
export declare class MemoryStore implements Store {
|
|
30
|
+
#private;
|
|
31
|
+
get(cid: string): Promise<StoredRecord[]>;
|
|
32
|
+
put(r: StoredRecord): Promise<boolean>;
|
|
33
|
+
delete(cid: string, did: string, rev?: string): Promise<void>;
|
|
34
|
+
sweep(now?: number): Promise<number>;
|
|
35
|
+
getCursor(name: string): Promise<string | undefined>;
|
|
36
|
+
setCursor(name: string, value: string): Promise<void>;
|
|
37
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Storage for indexed dev.fisl.at records: one row per (cid, did).
|
|
2
|
+
/** True if a stored row may be replaced or deleted by a write at rev. */
|
|
3
|
+
export function isNewer(rev, stored) {
|
|
4
|
+
return !stored || rev === undefined || rev > stored.rev;
|
|
5
|
+
}
|
|
6
|
+
export function isExpired(r, now = Date.now()) {
|
|
7
|
+
return r.expires !== undefined && Date.parse(r.expires) <= now;
|
|
8
|
+
}
|
|
9
|
+
export class MemoryStore {
|
|
10
|
+
#rows = new Map();
|
|
11
|
+
#cursors = new Map();
|
|
12
|
+
get(cid) {
|
|
13
|
+
return Promise.resolve([...(this.#rows.get(cid)?.values() ?? [])].filter((r) => !r.deleted));
|
|
14
|
+
}
|
|
15
|
+
put(r) {
|
|
16
|
+
const rows = this.#rows.get(r.cid) ?? new Map();
|
|
17
|
+
if (!isNewer(r.rev, rows.get(r.did)))
|
|
18
|
+
return Promise.resolve(false);
|
|
19
|
+
rows.set(r.did, r);
|
|
20
|
+
this.#rows.set(r.cid, rows);
|
|
21
|
+
return Promise.resolve(true);
|
|
22
|
+
}
|
|
23
|
+
delete(cid, did, rev) {
|
|
24
|
+
const rows = this.#rows.get(cid) ?? new Map();
|
|
25
|
+
const old = rows.get(did);
|
|
26
|
+
if (isNewer(rev, old)) {
|
|
27
|
+
rows.set(did, {
|
|
28
|
+
cid,
|
|
29
|
+
did,
|
|
30
|
+
rev: rev ?? old?.rev ?? "",
|
|
31
|
+
record: { addrs: [] },
|
|
32
|
+
deleted: true,
|
|
33
|
+
});
|
|
34
|
+
this.#rows.set(cid, rows);
|
|
35
|
+
}
|
|
36
|
+
return Promise.resolve();
|
|
37
|
+
}
|
|
38
|
+
sweep(now = Date.now()) {
|
|
39
|
+
let n = 0;
|
|
40
|
+
for (const [cid, rows] of this.#rows) {
|
|
41
|
+
for (const [did, r] of rows) {
|
|
42
|
+
if (!r.deleted && isExpired(r.record, now)) {
|
|
43
|
+
rows.set(did, { ...r, record: { addrs: [] }, deleted: true });
|
|
44
|
+
n++;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (!rows.size)
|
|
48
|
+
this.#rows.delete(cid);
|
|
49
|
+
}
|
|
50
|
+
return Promise.resolve(n);
|
|
51
|
+
}
|
|
52
|
+
getCursor(name) {
|
|
53
|
+
return Promise.resolve(this.#cursors.get(name));
|
|
54
|
+
}
|
|
55
|
+
setCursor(name, value) {
|
|
56
|
+
this.#cursors.set(name, value);
|
|
57
|
+
return Promise.resolve();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Identity } from "../atproto.ts";
|
|
2
|
+
import { type AtfislRecord } from "../record.ts";
|
|
3
|
+
export interface Verified {
|
|
4
|
+
/** The record, or null if the commit proves it does not exist. */
|
|
5
|
+
record: AtfislRecord | null;
|
|
6
|
+
/** The repo revision of the commit, if the PDS sent a proof. */
|
|
7
|
+
rev?: string;
|
|
8
|
+
}
|
|
9
|
+
/** Check a getRecord proof and extract the record and commit rev. */
|
|
10
|
+
export declare function verifyProof(car: Uint8Array, id: Identity, rkey: string, collection?: "dev.fisl.at"): Promise<Verified>;
|
|
11
|
+
/**
|
|
12
|
+
* Fetch and verify records from their PDS. Caches identities, and
|
|
13
|
+
* resolves again once if a proof fails, in case the key or PDS changed.
|
|
14
|
+
*/
|
|
15
|
+
export declare class Verifier {
|
|
16
|
+
#private;
|
|
17
|
+
identity(did: string, fresh?: boolean): Promise<Identity>;
|
|
18
|
+
verify(did: string, cid: string): Promise<Verified>;
|
|
19
|
+
}
|