@dasl/fisl 0.0.0-stage → 0.2.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.
@@ -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,110 @@
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
+ function sleep(ms, signal) {
12
+ if (signal?.aborted)
13
+ return Promise.resolve();
14
+ return new Promise((resolve) => {
15
+ const onAbort = () => {
16
+ clearTimeout(timer);
17
+ resolve();
18
+ };
19
+ const timer = setTimeout(() => {
20
+ signal?.removeEventListener("abort", onAbort);
21
+ resolve();
22
+ }, ms);
23
+ signal?.addEventListener("abort", onAbort, { once: true });
24
+ });
25
+ }
26
+ /** Follow Jetstream until the signal aborts. Reconnects with backoff. */
27
+ export async function followJetstream(store, verifier, { url = JETSTREAM, dids = [], log = () => { }, signal } = {}) {
28
+ let backoff = 1000;
29
+ while (!signal?.aborted) {
30
+ const u = new URL(url);
31
+ u.searchParams.set("wantedCollections", NSID);
32
+ for (const did of dids)
33
+ u.searchParams.append("wantedDids", did);
34
+ let cursor = await store.getCursor(CURSOR);
35
+ if (!cursor) {
36
+ cursor = String(Date.now() * 1000);
37
+ await store.setCursor(CURSOR, cursor);
38
+ }
39
+ if (cursor) {
40
+ u.searchParams.set("cursor", String(Number(cursor) - REWIND_US));
41
+ }
42
+ const closed = Promise.withResolvers();
43
+ const ws = new WebSocket(u);
44
+ const abort = () => ws.close();
45
+ signal?.addEventListener("abort", abort);
46
+ // Handle events one at a time, in order.
47
+ let queue = Promise.resolve();
48
+ let lastSaved = 0;
49
+ let failed = false;
50
+ let pending = 0;
51
+ let draining = false;
52
+ ws.onopen = () => {
53
+ backoff = 1000;
54
+ log(`connected to ${u.host}${cursor ? ` from cursor ${cursor}` : ""}`);
55
+ };
56
+ ws.onmessage = (msg) => {
57
+ if (draining || failed)
58
+ return;
59
+ // Drain a bounded batch before reconnecting from durable progress.
60
+ if (pending >= 256) {
61
+ draining = true;
62
+ ws.close();
63
+ return;
64
+ }
65
+ let ev;
66
+ try {
67
+ ev = JSON.parse(String(msg.data));
68
+ }
69
+ catch {
70
+ log("ignoring malformed Jetstream message");
71
+ return;
72
+ }
73
+ if (ev.kind !== "commit" || ev.commit?.collection !== NSID)
74
+ return;
75
+ const { rkey, operation } = ev.commit;
76
+ pending++;
77
+ queue = queue.then(async () => {
78
+ pending--;
79
+ if (failed)
80
+ return;
81
+ try {
82
+ const result = await ingest(store, verifier, ev.did, rkey);
83
+ log(`${operation} ${result} ${ev.did} ${rkey}`);
84
+ }
85
+ catch (e) {
86
+ log(`error ${ev.did} ${rkey}: ${e.message}`);
87
+ // Reconnect from the last saved cursor; never advance past a failed proof.
88
+ failed = true;
89
+ ws.close();
90
+ return;
91
+ }
92
+ // Save the cursor at most once a second.
93
+ if (ev.time_us - lastSaved > 1_000_000) {
94
+ lastSaved = ev.time_us;
95
+ await store.setCursor(CURSOR, String(ev.time_us));
96
+ }
97
+ });
98
+ };
99
+ ws.onerror = () => { };
100
+ ws.onclose = () => closed.resolve();
101
+ await closed.promise;
102
+ await queue;
103
+ signal?.removeEventListener("abort", abort);
104
+ if (signal?.aborted)
105
+ break;
106
+ log(`disconnected, retrying in ${backoff / 1000}s`);
107
+ await sleep(backoff, signal);
108
+ backoff = Math.min(backoff * 2, 60_000);
109
+ }
110
+ }
@@ -0,0 +1,15 @@
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, signal }?: {
6
+ log?: Log;
7
+ known?: Set<string>;
8
+ signal?: AbortSignal;
9
+ }): Promise<Set<string>>;
10
+ /** Backfill a set of repos, then poll them again every `interval` ms. */
11
+ export declare function pollRepos(store: Store, verifier: Verifier, dids: string[], { interval, log, signal }?: {
12
+ interval?: number;
13
+ log?: Log;
14
+ signal?: AbortSignal;
15
+ }): Promise<void>;
@@ -0,0 +1,69 @@
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
+ function sleep(ms, signal) {
5
+ if (signal?.aborted)
6
+ return Promise.resolve();
7
+ return new Promise((resolve) => {
8
+ const onAbort = () => {
9
+ clearTimeout(timer);
10
+ resolve();
11
+ };
12
+ const timer = setTimeout(() => {
13
+ signal?.removeEventListener("abort", onAbort);
14
+ resolve();
15
+ }, ms);
16
+ signal?.addEventListener("abort", onAbort, { once: true });
17
+ });
18
+ }
19
+ /** Index every record in one repo, and remove rows for records it no longer has. */
20
+ export async function backfill(store, verifier, did, { log = () => { }, known, signal } = {}) {
21
+ const id = await verifier.identity(did);
22
+ const seen = new Set();
23
+ const index = async (cid) => {
24
+ try {
25
+ log(`${await ingest(store, verifier, did, cid)} ${did} ${cid}`);
26
+ }
27
+ catch (e) {
28
+ log(`error ${did} ${cid}: ${e.message}`);
29
+ // Preserve failed deletion checks in known so the next poll retries them.
30
+ seen.add(cid);
31
+ }
32
+ };
33
+ for await (const { cid } of listRecords(id, signal)) {
34
+ if (signal?.aborted)
35
+ break;
36
+ seen.add(cid);
37
+ await index(cid);
38
+ }
39
+ // Records listed last time but not now were deleted. The proof confirms it.
40
+ for (const cid of known ?? []) {
41
+ if (signal?.aborted)
42
+ break;
43
+ if (!seen.has(cid))
44
+ await index(cid);
45
+ }
46
+ return seen;
47
+ }
48
+ /** Backfill a set of repos, then poll them again every `interval` ms. */
49
+ export async function pollRepos(store, verifier, dids, { interval = 60_000, log = () => { }, signal } = {}) {
50
+ const known = new Map();
51
+ while (!signal?.aborted) {
52
+ for (const did of dids) {
53
+ if (signal?.aborted)
54
+ break;
55
+ try {
56
+ known.set(did, await backfill(store, verifier, did, {
57
+ log,
58
+ known: known.get(did),
59
+ signal,
60
+ }));
61
+ }
62
+ catch (e) {
63
+ if (!signal?.aborted)
64
+ log(`error ${did}: ${e.message}`);
65
+ }
66
+ }
67
+ await sleep(interval, signal);
68
+ }
69
+ }
@@ -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,130 @@
1
+ // A Store backed by node:sqlite. Needs Node 22.13 or later.
2
+ import { DatabaseSync } from "node:sqlite";
3
+ import { isNewer, recordExpiry, } 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
+ deleted INTEGER NOT NULL DEFAULT 0,
15
+ expires_at INTEGER,
16
+ PRIMARY KEY (cid, did)
17
+ ) WITHOUT ROWID;
18
+ CREATE TABLE IF NOT EXISTS cursor (
19
+ name TEXT PRIMARY KEY,
20
+ value TEXT NOT NULL
21
+ ) WITHOUT ROWID;
22
+ `);
23
+ this.#migrate();
24
+ db.exec(`
25
+ CREATE INDEX IF NOT EXISTS rec_expires
26
+ ON rec (expires_at)
27
+ WHERE deleted = 0 AND expires_at IS NOT NULL;
28
+ `);
29
+ }
30
+ #migrate() {
31
+ const cols = new Set(this.db.prepare("PRAGMA table_info(rec)").all()
32
+ .map((c) => c.name));
33
+ if (cols.has("deleted") && cols.has("expires_at"))
34
+ return;
35
+ this.#transaction(() => {
36
+ if (!cols.has("deleted")) {
37
+ this.db.exec("ALTER TABLE rec ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0");
38
+ }
39
+ if (!cols.has("expires_at")) {
40
+ this.db.exec("ALTER TABLE rec ADD COLUMN expires_at INTEGER");
41
+ }
42
+ const rows = this.db.prepare("SELECT cid, did, value FROM rec").all();
43
+ const update = this.db.prepare("UPDATE rec SET deleted = ?, expires_at = ? WHERE cid = ? AND did = ?");
44
+ for (const row of rows) {
45
+ const r = JSON.parse(row.value);
46
+ update.run(r.deleted ? 1 : 0, r.deleted ? null : recordExpiry(r.record), row.cid, row.did);
47
+ }
48
+ });
49
+ }
50
+ /** Open a database file. Use ":memory:" for a temporary store. */
51
+ static open(path = ":memory:") {
52
+ return Promise.resolve(new SqliteStore(new DatabaseSync(path)));
53
+ }
54
+ #row(cid, did) {
55
+ const row = this.db
56
+ .prepare("SELECT value FROM rec WHERE cid = ? AND did = ?")
57
+ .get(cid, did);
58
+ return row && JSON.parse(row.value);
59
+ }
60
+ #set(r) {
61
+ this.db.prepare("INSERT OR REPLACE INTO rec (cid, did, value, deleted, expires_at) VALUES (?, ?, ?, ?, ?)").run(r.cid, r.did, JSON.stringify(r), r.deleted ? 1 : 0, r.deleted ? null : recordExpiry(r.record));
62
+ }
63
+ // Other processes can share the file, so read and write in one transaction.
64
+ #transaction(fn) {
65
+ this.db.exec("BEGIN IMMEDIATE");
66
+ try {
67
+ const result = fn();
68
+ this.db.exec("COMMIT");
69
+ return result;
70
+ }
71
+ catch (e) {
72
+ this.db.exec("ROLLBACK");
73
+ throw e;
74
+ }
75
+ }
76
+ get(cid) {
77
+ const rows = this.db
78
+ .prepare("SELECT value FROM rec WHERE cid = ? AND deleted = 0")
79
+ .all(cid);
80
+ return Promise.resolve(rows.map((r) => JSON.parse(r.value)));
81
+ }
82
+ put(r) {
83
+ return Promise.resolve(this.#transaction(() => {
84
+ if (!isNewer(r.rev, this.#row(r.cid, r.did)))
85
+ return false;
86
+ this.#set(r);
87
+ return true;
88
+ }));
89
+ }
90
+ delete(cid, did, rev) {
91
+ this.#transaction(() => {
92
+ const old = this.#row(cid, did);
93
+ if (!isNewer(rev, old))
94
+ return;
95
+ this.#set({
96
+ cid,
97
+ did,
98
+ rev: rev ?? old?.rev ?? "",
99
+ record: { addrs: [] },
100
+ deleted: true,
101
+ });
102
+ });
103
+ return Promise.resolve();
104
+ }
105
+ sweep(now = Date.now()) {
106
+ return Promise.resolve(this.#transaction(() => {
107
+ let n = 0;
108
+ const rows = this.db.prepare("SELECT value FROM rec WHERE deleted = 0 AND expires_at IS NOT NULL AND expires_at <= ?").all(now);
109
+ for (const { value } of rows) {
110
+ const r = JSON.parse(value);
111
+ this.#set({ ...r, record: { addrs: [] }, deleted: true });
112
+ n++;
113
+ }
114
+ return n;
115
+ }));
116
+ }
117
+ getCursor(name) {
118
+ const row = this.db.prepare("SELECT value FROM cursor WHERE name = ?")
119
+ .get(name);
120
+ return Promise.resolve(row?.value);
121
+ }
122
+ setCursor(name, value) {
123
+ this.db.prepare("INSERT OR REPLACE INTO cursor VALUES (?, ?)")
124
+ .run(name, value);
125
+ return Promise.resolve();
126
+ }
127
+ close() {
128
+ this.db.close();
129
+ }
130
+ }
@@ -0,0 +1,39 @@
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
+ /** Timestamp (ms) when every addr in a record is expired, or null if any never expires. */
29
+ export declare function recordExpiry(r: AtfislRecord): number | null;
30
+ export declare function isExpired(r: AtfislRecord, now?: number): boolean;
31
+ export declare class MemoryStore implements Store {
32
+ #private;
33
+ get(cid: string): Promise<StoredRecord[]>;
34
+ put(r: StoredRecord): Promise<boolean>;
35
+ delete(cid: string, did: string, rev?: string): Promise<void>;
36
+ sweep(now?: number): Promise<number>;
37
+ getCursor(name: string): Promise<string | undefined>;
38
+ setCursor(name: string, value: string): Promise<void>;
39
+ }
@@ -0,0 +1,74 @@
1
+ // Storage for indexed dev.fisl.at records: one row per (cid, did).
2
+ import { effectiveExpiry, liveRecord, } from "../record.js";
3
+ /** True if a stored row may be replaced or deleted by a write at rev. */
4
+ export function isNewer(rev, stored) {
5
+ return !stored || rev === undefined || rev > stored.rev;
6
+ }
7
+ /** Timestamp (ms) when every addr in a record is expired, or null if any never expires. */
8
+ export function recordExpiry(r) {
9
+ if (!Array.isArray(r.addrs) || !r.addrs.length)
10
+ return 0;
11
+ let latest = 0;
12
+ for (const a of r.addrs) {
13
+ const exp = effectiveExpiry(a, r);
14
+ if (exp === null)
15
+ return null;
16
+ if (exp > latest)
17
+ latest = exp;
18
+ }
19
+ return latest;
20
+ }
21
+ export function isExpired(r, now = Date.now()) {
22
+ return liveRecord(r, now) === null;
23
+ }
24
+ export class MemoryStore {
25
+ #rows = new Map();
26
+ #cursors = new Map();
27
+ get(cid) {
28
+ return Promise.resolve([...(this.#rows.get(cid)?.values() ?? [])].filter((r) => !r.deleted));
29
+ }
30
+ put(r) {
31
+ const rows = this.#rows.get(r.cid) ?? new Map();
32
+ if (!isNewer(r.rev, rows.get(r.did)))
33
+ return Promise.resolve(false);
34
+ rows.set(r.did, r);
35
+ this.#rows.set(r.cid, rows);
36
+ return Promise.resolve(true);
37
+ }
38
+ delete(cid, did, rev) {
39
+ const rows = this.#rows.get(cid) ?? new Map();
40
+ const old = rows.get(did);
41
+ if (isNewer(rev, old)) {
42
+ rows.set(did, {
43
+ cid,
44
+ did,
45
+ rev: rev ?? old?.rev ?? "",
46
+ record: { addrs: [] },
47
+ deleted: true,
48
+ });
49
+ this.#rows.set(cid, rows);
50
+ }
51
+ return Promise.resolve();
52
+ }
53
+ sweep(now = Date.now()) {
54
+ let n = 0;
55
+ for (const [cid, rows] of this.#rows) {
56
+ for (const [did, r] of rows) {
57
+ if (!r.deleted && isExpired(r.record, now)) {
58
+ rows.set(did, { ...r, record: { addrs: [] }, deleted: true });
59
+ n++;
60
+ }
61
+ }
62
+ if (!rows.size)
63
+ this.#rows.delete(cid);
64
+ }
65
+ return Promise.resolve(n);
66
+ }
67
+ getCursor(name) {
68
+ return Promise.resolve(this.#cursors.get(name));
69
+ }
70
+ setCursor(name, value) {
71
+ this.#cursors.set(name, value);
72
+ return Promise.resolve();
73
+ }
74
+ }
@@ -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
+ }
@@ -0,0 +1,70 @@
1
+ // Verify a dev.fisl.at record against a signed commit (ATFISL indexing step 2).
2
+ //
3
+ // com.atproto.sync.getRecord returns a CAR with the signed commit and the
4
+ // MST path to the record, or a proof that the record does not exist.
5
+ import { def, MemoryBlockstore, MST, readCarWithRoot, verifyCommitSig, } from "@atproto/repo";
6
+ import { resolveIdentity, xrpc, XrpcError } from "../atproto.js";
7
+ import { NSID } from "../record.js";
8
+ /** Check a getRecord proof and extract the record and commit rev. */
9
+ export async function verifyProof(car, id, rkey, collection = NSID) {
10
+ if (!id.signingKey)
11
+ throw new Error(`${id.did} has no signing key`);
12
+ const { root, blocks } = await readCarWithRoot(car);
13
+ const store = new MemoryBlockstore(blocks);
14
+ const commit = await store.readObj(root, def.commit);
15
+ if (commit.did !== id.did)
16
+ throw new Error(`Commit is for ${commit.did}`);
17
+ if (!(await verifyCommitSig(commit, id.signingKey))) {
18
+ throw new Error(`Bad commit signature for ${id.did}`);
19
+ }
20
+ const leaf = await MST.load(store, commit.data).get(`${collection}/${rkey}`);
21
+ const record = leaf
22
+ ? (await store.readRecord(leaf))
23
+ : null;
24
+ return { record, rev: commit.rev };
25
+ }
26
+ const MAX_CACHED_IDS = 10_000;
27
+ const ID_TTL_MS = 60 * 60 * 1000;
28
+ /**
29
+ * Fetch and verify records from their PDS. Caches identities, and
30
+ * resolves again once if a proof fails, in case the key or PDS changed.
31
+ */
32
+ export class Verifier {
33
+ #ids = new Map();
34
+ async identity(did, fresh = false) {
35
+ const now = Date.now();
36
+ const cached = fresh ? undefined : this.#ids.get(did);
37
+ if (cached && cached.expiresAt > now)
38
+ return cached.id;
39
+ const id = await resolveIdentity(did);
40
+ this.#ids.delete(did);
41
+ if (this.#ids.size >= MAX_CACHED_IDS) {
42
+ const oldest = this.#ids.keys().next().value;
43
+ if (oldest !== undefined)
44
+ this.#ids.delete(oldest);
45
+ }
46
+ this.#ids.set(did, { id, expiresAt: now + ID_TTL_MS });
47
+ return id;
48
+ }
49
+ async verify(did, cid) {
50
+ try {
51
+ return await this.#fetch(await this.identity(did), cid);
52
+ }
53
+ catch {
54
+ return await this.#fetch(await this.identity(did, true), cid);
55
+ }
56
+ }
57
+ async #fetch(id, cid) {
58
+ try {
59
+ const car = await xrpc(id.pds, "com.atproto.sync.getRecord", { params: { did: id.did, collection: NSID, rkey: cid } });
60
+ return await verifyProof(car, id, cid);
61
+ }
62
+ catch (e) {
63
+ // Some PDSes answer with an error, not a proof of absence.
64
+ if (e instanceof XrpcError && e.error === "RecordNotFound") {
65
+ return { record: null };
66
+ }
67
+ throw e;
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,11 @@
1
+ import { type Session } from "./atproto.ts";
2
+ import { type AtfislRecord } from "./record.ts";
3
+ export interface Announcement {
4
+ cid: string;
5
+ record: AtfislRecord;
6
+ }
7
+ /**
8
+ * Publish one record per CID, replacing any existing record for that CID.
9
+ * Writes in batches of up to 200 records per commit.
10
+ */
11
+ export declare function publish(session: Session, items: Announcement[]): Promise<void>;
@@ -0,0 +1,33 @@
1
+ // Publish dev.fisl.at records for CIDs.
2
+ import { listRecords, putRecords } from "./atproto.js";
3
+ import { parseCid } from "./cid.js";
4
+ import { validate } from "./record.js";
5
+ const BATCH = 200;
6
+ /**
7
+ * Publish one record per CID, replacing any existing record for that CID.
8
+ * Writes in batches of up to 200 records per commit.
9
+ */
10
+ export async function publish(session, items) {
11
+ if (!items.length)
12
+ return;
13
+ const deduped = new Map();
14
+ for (const item of items) {
15
+ const { cid, record } = item;
16
+ if (!parseCid(cid))
17
+ throw new Error(`Not a DASL CID: ${cid}`);
18
+ const errors = validate(record);
19
+ if (errors.length)
20
+ throw new Error(`${cid}: ${errors.join("; ")}`);
21
+ deduped.set(cid, item);
22
+ }
23
+ const unique = [...deduped.values()];
24
+ const existing = new Set();
25
+ for await (const r of listRecords(session))
26
+ existing.add(r.cid);
27
+ for (let i = 0; i < unique.length; i += BATCH) {
28
+ const batch = unique.slice(i, i + BATCH);
29
+ await putRecords(session, batch, existing);
30
+ for (const { cid } of batch)
31
+ existing.add(cid);
32
+ }
33
+ }
@@ -0,0 +1,24 @@
1
+ export interface IndexedFile {
2
+ cid: string;
3
+ path: string;
4
+ /** Path relative to the served directory. */
5
+ name: string;
6
+ size: number;
7
+ }
8
+ /** Immutable snapshots owned by this index. Dispose after stopping the server. */
9
+ export declare class IndexedFiles extends Map<string, IndexedFile> {
10
+ readonly snapshotDir: string;
11
+ constructor(snapshotDir: string);
12
+ dispose(): Promise<void>;
13
+ }
14
+ export declare const RASL_PREFIX = "/.well-known/rasl/";
15
+ /** Hash every file in a directory. Files with the same content share a CID. */
16
+ export declare function indexDir(dir: string, { concurrency, onFile }?: {
17
+ concurrency?: number;
18
+ onFile?: (f: IndexedFile) => void;
19
+ }): Promise<IndexedFiles>;
20
+ /**
21
+ * A handler for RASL requests. Returns null for paths outside
22
+ * /.well-known/rasl/, so it can be combined with other handlers.
23
+ */
24
+ export declare function raslHandler(files: Map<string, IndexedFile>): (req: Request) => Promise<Response | null>;