@dasl/fisl 0.1.0 → 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.
package/dist/src/fetch.js CHANGED
@@ -15,7 +15,21 @@ export function requestUrls(url, cid, allowHttp = false) {
15
15
  }
16
16
  // rasl://<cid>/?hint=<host>
17
17
  if (u.protocol === "rasl:" && u.hostname === cid) {
18
- return u.searchParams.getAll("hint").map((h) => new URL(`https://${h}${RASL_PREFIX}${cid}`));
18
+ const out = [];
19
+ for (const h of u.searchParams.getAll("hint")) {
20
+ if (!h || /[/?#@\s]/.test(h))
21
+ continue;
22
+ try {
23
+ const target = new URL(`https://${h}${RASL_PREFIX}${cid}`);
24
+ if (!target.username && !target.password &&
25
+ target.pathname === `${RASL_PREFIX}${cid}` &&
26
+ !target.search && !target.hash) {
27
+ out.push(target);
28
+ }
29
+ }
30
+ catch { /* skip malformed hint */ }
31
+ }
32
+ return out;
19
33
  }
20
34
  return [];
21
35
  }
@@ -27,32 +41,57 @@ const PRIVATE_V4 = [
27
41
  [0xa9fe0000, 16], // 169.254.0.0/16
28
42
  [0xac100000, 12], // 172.16.0.0/12
29
43
  [0xc0a80000, 16], // 192.168.0.0/16
44
+ [0xe0000000, 4], // 224.0.0.0/4 (multicast)
45
+ [0xf0000000, 4], // 240.0.0.0/4 (reserved / broadcast)
30
46
  ];
47
+ const v4FromWords = (hi, lo) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
31
48
  export function isPrivateIp(ip) {
32
49
  ip = ip.replace(/^\[|\]$/g, "").toLowerCase();
33
50
  if (ip.includes(":")) {
34
51
  const dotted = ip.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
35
52
  if (dotted) {
36
53
  const octets = dotted.slice(1).map(Number);
54
+ if (octets.some((n) => n > 255))
55
+ return true;
37
56
  ip = ip.slice(0, dotted.index) +
38
57
  ((octets[0] << 8) | octets[1]).toString(16) + ":" +
39
58
  ((octets[2] << 8) | octets[3]).toString(16);
40
59
  }
41
60
  const halves = ip.split("::");
61
+ if (halves.length > 2)
62
+ return true;
42
63
  const left = halves[0] ? halves[0].split(":") : [];
43
64
  const right = halves[1] ? halves[1].split(":") : [];
44
- const words = (halves.length === 2
45
- ? [...left, ...Array(8 - left.length - right.length).fill("0"), ...right]
46
- : left).map((w) => parseInt(w, 16));
47
- if (words.length !== 8 || words.some(Number.isNaN)) {
65
+ const rawWords = halves.length === 2
66
+ ? [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right]
67
+ : left;
68
+ if (rawWords.length !== 8 ||
69
+ rawWords.some((w) => !/^[0-9a-f]{1,4}$/.test(w))) {
48
70
  return true;
49
71
  }
50
- if (words.slice(0, 5).every((w) => w === 0) && words[5] === 0xffff) {
51
- return isPrivateIp(`${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`);
72
+ const words = rawWords.map((w) => parseInt(w, 16));
73
+ const zeroPrefix5 = words.slice(0, 5).every((w) => w === 0);
74
+ // IPv4-mapped (::ffff:0:0/96)
75
+ if (zeroPrefix5 && words[5] === 0xffff) {
76
+ return isPrivateIp(v4FromWords(words[6], words[7]));
77
+ }
78
+ // Unspecified (::), loopback (::1), and IPv4-compatible (::/96)
79
+ if (zeroPrefix5 && words[5] === 0) {
80
+ return (words[6] === 0 && words[7] <= 1) ||
81
+ isPrivateIp(v4FromWords(words[6], words[7]));
52
82
  }
53
- return words.every((w) => w === 0) || (words.slice(0, 7).every((w) => w === 0) && words[7] === 1) ||
54
- (words[0] & 0xfe00) === 0xfc00 ||
55
- (words[0] & 0xffc0) === 0xfe80;
83
+ // NAT64 well-known prefix (64:ff9b::/96)
84
+ if (words[0] === 0x0064 && words[1] === 0xff9b &&
85
+ words.slice(2, 6).every((w) => w === 0)) {
86
+ return isPrivateIp(v4FromWords(words[6], words[7]));
87
+ }
88
+ // 6to4 (2002::/16)
89
+ if (words[0] === 0x2002 && isPrivateIp(v4FromWords(words[1], words[2]))) {
90
+ return true;
91
+ }
92
+ return (words[0] & 0xfe00) === 0xfc00 || // unique local (fc00::/7)
93
+ (words[0] & 0xffc0) === 0xfe80 || // link-local (fe80::/10)
94
+ (words[0] & 0xff00) === 0xff00; // multicast (ff00::/8)
56
95
  }
57
96
  const v4 = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
58
97
  if (!v4)
@@ -101,32 +140,44 @@ async function pinnedFetch(url, opts) {
101
140
  ? await import("node:https")
102
141
  : await import("node:http");
103
142
  const { Readable } = await import("node:stream");
104
- const destination = addresses[0];
105
- return new Promise((resolve, reject) => {
106
- const requestOptions = {
107
- agent: false,
108
- family: destination.family,
109
- autoSelectFamily: false,
110
- signal: opts.signal,
111
- lookup: (_hostname, _options, callback) => callback(null, destination.address, destination.family),
112
- };
113
- const req = request(url, requestOptions, (res) => {
114
- const headers = new Headers();
115
- for (let i = 0; i < res.rawHeaders.length; i += 2) {
116
- headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
117
- }
118
- if ([204, 205, 304].includes(res.statusCode))
119
- res.resume();
120
- resolve(new Response([204, 205, 304].includes(res.statusCode)
121
- ? null
122
- : Readable.toWeb(res), {
123
- status: res.statusCode,
124
- headers,
125
- }));
126
- });
127
- req.on("error", reject);
128
- req.end();
129
- });
143
+ let lastError;
144
+ for (const destination of addresses) {
145
+ opts.signal?.throwIfAborted();
146
+ try {
147
+ return await new Promise((resolve, reject) => {
148
+ const requestOptions = {
149
+ agent: false,
150
+ family: destination.family,
151
+ autoSelectFamily: false,
152
+ signal: opts.signal,
153
+ lookup: (_hostname, _options, callback) => callback(null, destination.address, destination.family),
154
+ };
155
+ const req = request(url, requestOptions, (res) => {
156
+ const headers = new Headers();
157
+ for (let i = 0; i < res.rawHeaders.length; i += 2) {
158
+ headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
159
+ }
160
+ if ([204, 205, 304].includes(res.statusCode))
161
+ res.resume();
162
+ resolve(new Response([204, 205, 304].includes(res.statusCode)
163
+ ? null
164
+ : Readable.toWeb(res), {
165
+ status: res.statusCode,
166
+ statusText: res.statusMessage,
167
+ headers,
168
+ }));
169
+ });
170
+ req.on("error", reject);
171
+ req.end();
172
+ });
173
+ }
174
+ catch (e) {
175
+ if (opts.signal?.aborted)
176
+ throw e;
177
+ lastError = e;
178
+ }
179
+ }
180
+ throw lastError;
130
181
  }
131
182
  /** GET a URL statelessly, following redirects and checking every hop. */
132
183
  async function get(url, opts) {
@@ -284,8 +335,11 @@ export function fetchCid(cidString, opts = {}) {
284
335
  * The destination is replaced only after verification. No default size limit.
285
336
  */
286
337
  export async function downloadCid(cidString, destination, opts = {}) {
287
- const { dirname, join } = await import("node:path");
288
- const { open, rename, rm } = await import("node:fs/promises");
338
+ const [{ createHash }, { dirname, join }, { open, rename, rm }] = await Promise.all([
339
+ import("node:crypto"),
340
+ import("node:path"),
341
+ import("node:fs/promises"),
342
+ ]);
289
343
  const paths = new Set();
290
344
  try {
291
345
  const path = await retrieve(cidString, opts, async (res, cid) => {
@@ -296,7 +350,9 @@ export async function downloadCid(cidString, destination, opts = {}) {
296
350
  const path = join(dirname(destination), `.fisl-${crypto.randomUUID()}`);
297
351
  const file = await open(path, "wx");
298
352
  paths.add(path);
299
- const hash = cid.hash === HASH_BLAKE3 ? blake3.create() : sha256.create();
353
+ const hash = cid.hash === HASH_BLAKE3
354
+ ? blake3.create()
355
+ : createHash("sha256");
300
356
  let size = 0;
301
357
  try {
302
358
  for await (const chunk of res.body) {
@@ -305,9 +361,14 @@ export async function downloadCid(cidString, destination, opts = {}) {
305
361
  throw new FetchError("download exceeds size limit");
306
362
  }
307
363
  hash.update(chunk);
308
- await file.write(chunk); // writes the whole chunk
364
+ let offset = 0;
365
+ while (offset < chunk.byteLength) {
366
+ const { bytesWritten } = await file.write(chunk, offset);
367
+ offset += bytesWritten;
368
+ }
309
369
  }
310
- if (!hash.digest().every((b, i) => b === cid.digest[i])) {
370
+ const digest = new Uint8Array(hash.digest());
371
+ if (!digest.every((b, i) => b === cid.digest[i])) {
311
372
  throw new FetchError("content does not match the CID");
312
373
  }
313
374
  await file.sync();
@@ -109,8 +109,16 @@ export async function* resolve(cid, opts) {
109
109
  yield queue.shift();
110
110
  else {
111
111
  await new Promise((resolve) => {
112
- wake = resolve;
113
- signal.addEventListener("abort", () => resolve(), { once: true });
112
+ if (signal.aborted) {
113
+ resolve();
114
+ return;
115
+ }
116
+ const done = () => {
117
+ signal.removeEventListener("abort", done);
118
+ resolve();
119
+ };
120
+ wake = done;
121
+ signal.addEventListener("abort", done, { once: true });
114
122
  });
115
123
  }
116
124
  }
@@ -5,7 +5,7 @@ import { earliestExpiry, liveRecord, toLocation, } from "../record.js";
5
5
  export const FISL_PREFIX = "/routing/locations/";
6
6
  const CORS = {
7
7
  "access-control-allow-origin": "*",
8
- "access-control-allow-methods": "GET, OPTIONS",
8
+ "access-control-allow-methods": "GET, HEAD, OPTIONS",
9
9
  };
10
10
  /** Find the live locations for a CID. */
11
11
  export async function lookup(store, cid, now = Date.now()) {
@@ -1,8 +1,14 @@
1
1
  import type { Store } from "./store.ts";
2
- import type { Verifier } from "./verify.ts";
2
+ import type { Verified, Verifier } from "./verify.ts";
3
3
  export type IngestResult = "stored" | "deleted" | "discarded" | "stale";
4
4
  /**
5
5
  * Index the current state of (did, cid). The event only says that something
6
6
  * changed: the record itself comes from a verified proof from the PDS.
7
7
  */
8
8
  export declare function ingest(store: Store, verifier: Verifier, did: string, cid: string): Promise<IngestResult>;
9
+ /**
10
+ * Index a record that the caller already has, for example from a Jetstream
11
+ * event. Nothing is verified, so the caller must trust the record's source.
12
+ * A null record deletes (did, cid).
13
+ */
14
+ export declare function ingestUnverified(store: Store, did: string, cid: string, { record, rev }: Verified): Promise<IngestResult>;
@@ -8,7 +8,16 @@ import { liveRecord } from "../record.js";
8
8
  export async function ingest(store, verifier, did, cid) {
9
9
  if (!parseCid(cid))
10
10
  return "discarded";
11
- const { record, rev } = await verifier.verify(did, cid);
11
+ return ingestUnverified(store, did, cid, await verifier.verify(did, cid));
12
+ }
13
+ /**
14
+ * Index a record that the caller already has, for example from a Jetstream
15
+ * event. Nothing is verified, so the caller must trust the record's source.
16
+ * A null record deletes (did, cid).
17
+ */
18
+ export async function ingestUnverified(store, did, cid, { record, rev }) {
19
+ if (!parseCid(cid))
20
+ return "discarded";
12
21
  const live = record && liveRecord(record);
13
22
  if (!live) {
14
23
  // Absent, expired or without usable addrs: remove any older row.
@@ -8,6 +8,21 @@ export const JETSTREAM = "wss://jetstream2.us-east.bsky.network/subscribe";
8
8
  const CURSOR = "jetstream";
9
9
  // Rewind the cursor on reconnect, so no event is lost in the gap.
10
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
+ }
11
26
  /** Follow Jetstream until the signal aborts. Reconnects with backoff. */
12
27
  export async function followJetstream(store, verifier, { url = JETSTREAM, dids = [], log = () => { }, signal } = {}) {
13
28
  let backoff = 1000;
@@ -47,7 +62,14 @@ export async function followJetstream(store, verifier, { url = JETSTREAM, dids =
47
62
  ws.close();
48
63
  return;
49
64
  }
50
- const ev = JSON.parse(msg.data);
65
+ let ev;
66
+ try {
67
+ ev = JSON.parse(String(msg.data));
68
+ }
69
+ catch {
70
+ log("ignoring malformed Jetstream message");
71
+ return;
72
+ }
51
73
  if (ev.kind !== "commit" || ev.commit?.collection !== NSID)
52
74
  return;
53
75
  const { rkey, operation } = ev.commit;
@@ -82,7 +104,7 @@ export async function followJetstream(store, verifier, { url = JETSTREAM, dids =
82
104
  if (signal?.aborted)
83
105
  break;
84
106
  log(`disconnected, retrying in ${backoff / 1000}s`);
85
- await new Promise((r) => setTimeout(r, backoff));
107
+ await sleep(backoff, signal);
86
108
  backoff = Math.min(backoff * 2, 60_000);
87
109
  }
88
110
  }
@@ -2,9 +2,10 @@ import type { Store } from "./store.ts";
2
2
  import type { Verifier } from "./verify.ts";
3
3
  export type Log = (msg: string) => void;
4
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 }?: {
5
+ export declare function backfill(store: Store, verifier: Verifier, did: string, { log, known, signal }?: {
6
6
  log?: Log;
7
7
  known?: Set<string>;
8
+ signal?: AbortSignal;
8
9
  }): Promise<Set<string>>;
9
10
  /** Backfill a set of repos, then poll them again every `interval` ms. */
10
11
  export declare function pollRepos(store: Store, verifier: Verifier, dids: string[], { interval, log, signal }?: {
@@ -1,8 +1,23 @@
1
1
  // Index dev.fisl.at records by reading repos directly from their PDS.
2
2
  import { listRecords } from "../atproto.js";
3
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
+ }
4
19
  /** 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 } = {}) {
20
+ export async function backfill(store, verifier, did, { log = () => { }, known, signal } = {}) {
6
21
  const id = await verifier.identity(did);
7
22
  const seen = new Set();
8
23
  const index = async (cid) => {
@@ -15,14 +30,19 @@ export async function backfill(store, verifier, did, { log = () => { }, known }
15
30
  seen.add(cid);
16
31
  }
17
32
  };
18
- for await (const { cid } of listRecords(id)) {
33
+ for await (const { cid } of listRecords(id, signal)) {
34
+ if (signal?.aborted)
35
+ break;
19
36
  seen.add(cid);
20
37
  await index(cid);
21
38
  }
22
39
  // Records listed last time but not now were deleted. The proof confirms it.
23
- for (const cid of known ?? [])
40
+ for (const cid of known ?? []) {
41
+ if (signal?.aborted)
42
+ break;
24
43
  if (!seen.has(cid))
25
44
  await index(cid);
45
+ }
26
46
  return seen;
27
47
  }
28
48
  /** Backfill a set of repos, then poll them again every `interval` ms. */
@@ -30,13 +50,20 @@ export async function pollRepos(store, verifier, dids, { interval = 60_000, log
30
50
  const known = new Map();
31
51
  while (!signal?.aborted) {
32
52
  for (const did of dids) {
53
+ if (signal?.aborted)
54
+ break;
33
55
  try {
34
- known.set(did, await backfill(store, verifier, did, { log, known: known.get(did) }));
56
+ known.set(did, await backfill(store, verifier, did, {
57
+ log,
58
+ known: known.get(did),
59
+ signal,
60
+ }));
35
61
  }
36
62
  catch (e) {
37
- log(`error ${did}: ${e.message}`);
63
+ if (!signal?.aborted)
64
+ log(`error ${did}: ${e.message}`);
38
65
  }
39
66
  }
40
- await new Promise((r) => setTimeout(r, interval));
67
+ await sleep(interval, signal);
41
68
  }
42
69
  }
@@ -1,6 +1,6 @@
1
1
  // A Store backed by node:sqlite. Needs Node 22.13 or later.
2
2
  import { DatabaseSync } from "node:sqlite";
3
- import { isExpired, isNewer } from "./store.js";
3
+ import { isNewer, recordExpiry, } from "./store.js";
4
4
  export class SqliteStore {
5
5
  db;
6
6
  constructor(db) {
@@ -11,6 +11,8 @@ export class SqliteStore {
11
11
  cid TEXT NOT NULL,
12
12
  did TEXT NOT NULL,
13
13
  value TEXT NOT NULL,
14
+ deleted INTEGER NOT NULL DEFAULT 0,
15
+ expires_at INTEGER,
14
16
  PRIMARY KEY (cid, did)
15
17
  ) WITHOUT ROWID;
16
18
  CREATE TABLE IF NOT EXISTS cursor (
@@ -18,6 +20,32 @@ export class SqliteStore {
18
20
  value TEXT NOT NULL
19
21
  ) WITHOUT ROWID;
20
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
+ });
21
49
  }
22
50
  /** Open a database file. Use ":memory:" for a temporary store. */
23
51
  static open(path = ":memory:") {
@@ -30,8 +58,7 @@ export class SqliteStore {
30
58
  return row && JSON.parse(row.value);
31
59
  }
32
60
  #set(r) {
33
- this.db.prepare("INSERT OR REPLACE INTO rec VALUES (?, ?, ?)")
34
- .run(r.cid, r.did, JSON.stringify(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));
35
62
  }
36
63
  // Other processes can share the file, so read and write in one transaction.
37
64
  #transaction(fn) {
@@ -47,10 +74,10 @@ export class SqliteStore {
47
74
  }
48
75
  }
49
76
  get(cid) {
50
- const rows = this.db.prepare("SELECT value FROM rec WHERE cid = ?")
77
+ const rows = this.db
78
+ .prepare("SELECT value FROM rec WHERE cid = ? AND deleted = 0")
51
79
  .all(cid);
52
- return Promise.resolve(rows.map((r) => JSON.parse(r.value))
53
- .filter((r) => !r.deleted));
80
+ return Promise.resolve(rows.map((r) => JSON.parse(r.value)));
54
81
  }
55
82
  put(r) {
56
83
  return Promise.resolve(this.#transaction(() => {
@@ -78,13 +105,11 @@ export class SqliteStore {
78
105
  sweep(now = Date.now()) {
79
106
  return Promise.resolve(this.#transaction(() => {
80
107
  let n = 0;
81
- const rows = this.db.prepare("SELECT value FROM rec").all();
108
+ const rows = this.db.prepare("SELECT value FROM rec WHERE deleted = 0 AND expires_at IS NOT NULL AND expires_at <= ?").all(now);
82
109
  for (const { value } of rows) {
83
110
  const r = JSON.parse(value);
84
- if (!r.deleted && isExpired(r.record, now)) {
85
- this.#set({ ...r, record: { addrs: [] }, deleted: true });
86
- n++;
87
- }
111
+ this.#set({ ...r, record: { addrs: [] }, deleted: true });
112
+ n++;
88
113
  }
89
114
  return n;
90
115
  }));
@@ -1,4 +1,4 @@
1
- import type { AtfislRecord } from "../record.ts";
1
+ import { type AtfislRecord } from "../record.ts";
2
2
  export interface StoredRecord {
3
3
  cid: string;
4
4
  did: string;
@@ -25,6 +25,8 @@ export interface Store {
25
25
  }
26
26
  /** True if a stored row may be replaced or deleted by a write at rev. */
27
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;
28
30
  export declare function isExpired(r: AtfislRecord, now?: number): boolean;
29
31
  export declare class MemoryStore implements Store {
30
32
  #private;
@@ -1,10 +1,25 @@
1
1
  // Storage for indexed dev.fisl.at records: one row per (cid, did).
2
+ import { effectiveExpiry, liveRecord, } from "../record.js";
2
3
  /** True if a stored row may be replaced or deleted by a write at rev. */
3
4
  export function isNewer(rev, stored) {
4
5
  return !stored || rev === undefined || rev > stored.rev;
5
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
+ }
6
21
  export function isExpired(r, now = Date.now()) {
7
- return r.expires !== undefined && Date.parse(r.expires) <= now;
22
+ return liveRecord(r, now) === null;
8
23
  }
9
24
  export class MemoryStore {
10
25
  #rows = new Map();
@@ -23,6 +23,8 @@ export async function verifyProof(car, id, rkey, collection = NSID) {
23
23
  : null;
24
24
  return { record, rev: commit.rev };
25
25
  }
26
+ const MAX_CACHED_IDS = 10_000;
27
+ const ID_TTL_MS = 60 * 60 * 1000;
26
28
  /**
27
29
  * Fetch and verify records from their PDS. Caches identities, and
28
30
  * resolves again once if a proof fails, in case the key or PDS changed.
@@ -30,11 +32,18 @@ export async function verifyProof(car, id, rkey, collection = NSID) {
30
32
  export class Verifier {
31
33
  #ids = new Map();
32
34
  async identity(did, fresh = false) {
33
- let id = fresh ? undefined : this.#ids.get(did);
34
- if (!id) {
35
- id = await resolveIdentity(did);
36
- this.#ids.set(did, id);
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);
37
45
  }
46
+ this.#ids.set(did, { id, expiresAt: now + ID_TTL_MS });
38
47
  return id;
39
48
  }
40
49
  async verify(did, cid) {
@@ -8,17 +8,26 @@ const BATCH = 200;
8
8
  * Writes in batches of up to 200 records per commit.
9
9
  */
10
10
  export async function publish(session, items) {
11
- for (const { cid, record } of items) {
11
+ if (!items.length)
12
+ return;
13
+ const deduped = new Map();
14
+ for (const item of items) {
15
+ const { cid, record } = item;
12
16
  if (!parseCid(cid))
13
17
  throw new Error(`Not a DASL CID: ${cid}`);
14
18
  const errors = validate(record);
15
19
  if (errors.length)
16
20
  throw new Error(`${cid}: ${errors.join("; ")}`);
21
+ deduped.set(cid, item);
17
22
  }
23
+ const unique = [...deduped.values()];
18
24
  const existing = new Set();
19
25
  for await (const r of listRecords(session))
20
26
  existing.add(r.cid);
21
- for (let i = 0; i < items.length; i += BATCH) {
22
- await putRecords(session, items.slice(i, i + BATCH), existing);
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);
23
32
  }
24
33
  }
@@ -31,7 +31,7 @@ async function* walk(dir) {
31
31
  }
32
32
  /** Hash every file in a directory. Files with the same content share a CID. */
33
33
  export async function indexDir(dir, { concurrency = 4, onFile } = {}) {
34
- const { copyFile, mkdtemp, stat } = await import("node:fs/promises");
34
+ const { copyFile, mkdtemp, rm, stat } = await import("node:fs/promises");
35
35
  const { join, relative } = await import("node:path");
36
36
  const { tmpdir } = await import("node:os");
37
37
  const snapshots = await mkdtemp(join(tmpdir(), "fisl-rasl-"));
@@ -51,7 +51,10 @@ export async function indexDir(dir, { concurrency = 4, onFile } = {}) {
51
51
  name: relative(dir, path),
52
52
  size: info.size,
53
53
  };
54
+ const prev = files.get(cid);
54
55
  files.set(cid, f);
56
+ if (prev)
57
+ await rm(prev.path, { force: true }).catch(() => { });
55
58
  onFile?.(f);
56
59
  }
57
60
  };
@@ -30,7 +30,7 @@ export function liveRecord(r, now = Date.now()) {
30
30
  return false;
31
31
  const exp = effectiveExpiry(a, rec);
32
32
  return exp === null || exp > now;
33
- });
33
+ }).slice(0, 32);
34
34
  if (!addrs.length)
35
35
  return null;
36
36
  return { ...rec, addrs };
package/dist/src/serve.js CHANGED
@@ -23,8 +23,17 @@ export function serve(handler, { port = 0, hostname = "0.0.0.0" } = {}) {
23
23
  const server = createServer(async (req, res) => {
24
24
  const abort = new AbortController();
25
25
  res.on("close", () => abort.abort());
26
+ let request;
26
27
  try {
27
- const response = await handler(toRequest(req, abort.signal));
28
+ request = toRequest(req, abort.signal);
29
+ }
30
+ catch {
31
+ res.statusCode = 400;
32
+ res.end("Bad request");
33
+ return;
34
+ }
35
+ try {
36
+ const response = await handler(request);
28
37
  res.statusCode = response.status;
29
38
  for (const [name, value] of response.headers) {
30
39
  res.appendHeader(name, value);