@johnhenry/browsermesh-apps 0.9.0 → 0.11.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.
@@ -54,7 +54,7 @@
54
54
  *
55
55
  * Content is split into `chunkSize`-byte pieces (default `TORRENT_DEFAULTS
56
56
  * .chunkSize`, 64KB) and stored by this file in its OWN `ChunkStore`
57
- * (content-addressed, SHA-256 CIDs -- see "CHUNKSTORE DURABILITY DECISION"
57
+ * (content-addressed, SHA-256 CIDs -- see "DURABILITY"
58
58
  * below), separate from `TorrentManager`'s own opaque whole-blob store. A
59
59
  * peer that finishes downloading calls `tm.seed()` on the reassembled bytes
60
60
  * (see `download()`'s own comment for why this is exactly correct, not a
@@ -74,8 +74,9 @@
74
74
  *
75
75
  * Announce (fire-and-forget, from `api.share()`, bridging `shareWithPeers`):
76
76
  * `{ type, kind: 'announce', magnetURI, manifest, info }`
77
- * -- `manifest` is `{ infoHash, name, size, chunkCids }` (undefined if
78
- * the announcer doesn't actually hold the content -- see `share()`).
77
+ * -- `manifest` is `{ infoHash, name, size, chunkCids, chunkSize?, cid? }`
78
+ * (`cid` = SHA-256 hex of the whole content), or undefined if the
79
+ * announcer doesn't actually hold the content -- see `share()`.
79
80
  * The RECEIVER records the sender as a known provider for every
80
81
  * `chunkCids` entry -- this is how `chunkOwners` bootstraps without
81
82
  * a separate discovery round trip.
@@ -85,74 +86,65 @@
85
86
  * band):
86
87
  * `{ type, kind: 'manifest-request', requestId, magnetURI }`
87
88
  * `{ type, kind: 'manifest-response', requestId, magnetURI, manifest }`
88
- * -- a peer with no manifest for that magnetURI stays silent (matches
89
- * `chunk-replication.mjs`'s established "don't have it" = silence
90
- * convention); the requester's `requestManifest()` is timeout-bounded.
89
+ * -- `manifest` is `null` when the responder does not hold that magnetURI
90
+ * OR will not serve it to this requester (see AUTHORIZATION below):
91
+ * the two cases are indistinguishable. A requester that asked several
92
+ * peers keeps waiting until one sends a manifest or every one has
93
+ * said `null`. (Older nodes stayed silent instead of sending `null`;
94
+ * a requester treats that as "no answer" and falls back to its
95
+ * `manifestTimeoutMs`.)
91
96
  *
92
97
  * Chunk request/response (the actual piece exchange):
93
98
  * `{ type, kind: 'chunk-request', requestId, cid }`
94
99
  * `{ type, kind: 'chunk-response', requestId, cid, data }` (`data` base64)
95
- * or `{ ..., error: 'not-found' }`.
100
+ * or `{ ..., error: 'not-found' }` (unknown piece, or one this peer
101
+ * will not serve to the requester -- indistinguishable)
102
+ * or `{ ..., error: 'busy' }` (a serve cap is full; says nothing about
103
+ * the piece, and downloaders retry after a short backoff).
96
104
  *
97
- * DELIBERATELY NO AUTHORIZATION GATE on any of the above (the one explicit
98
- * divergence from `chunk-replication.mjs`'s otherwise-identical shape, which
99
- * gates every chunk transfer on `registry.checkAccess()`): issue #122's own
100
- * framing is "swarm-distribute one large payload to many anonymous/
101
- * unauthorized downloaders at once" -- an admin-designated-replica-style ACL
102
- * gate would contradict the entire reason this module exists alongside
103
- * CloudStorage rather than being redundant with it. A caller that DOES want
104
- * access control on top of swarm distribution can still gate WHO gets handed
105
- * a magnetURI in the first place (outside this file, e.g. via `api.share()`'s
106
- * explicit `peerIds` list) -- once a peer legitimately has a magnetURI, this
107
- * protocol does not additionally gate serving its pieces.
105
+ * AUTHORIZATION (opt-in): with no `authorize` option anyone on the mesh who
106
+ * knows a magnet URI can fetch its manifest and pieces, as before -- issue
107
+ * #122's framing is swarm distribution to many unvetted downloaders, so the
108
+ * default stays open (unlike `chunk-replication.mjs`, which always gates on
109
+ * `registry.checkAccess()`). A host that wants a gate passes
110
+ * `authorize(fromPubKey, { kind, magnetURI, infoHash, cid, chunkCid? })`;
111
+ * it is consulted before every manifest and every piece is served, a piece
112
+ * held by several torrents is served if ANY of them allows, and a throw or a
113
+ * non-`true` result denies. A denied request is answered with exactly what an
114
+ * unknown one gets (`manifest: null` / `error: 'not-found'`), so a peer cannot
115
+ * probe which content exists. (Timing is not equalised.) `announce` stays
116
+ * unauthenticated -- it only tells this node who might hold a piece -- but is
117
+ * rate limited per peer. A node only ever serves pieces listed by a manifest
118
+ * it holds, so a shared chunk store's unrelated contents are not reachable.
108
119
  *
109
- * Every fetched chunk is verified against its own CID (`ChunkStore.verify()`)
120
+ * SERVE LIMITS: `maxConcurrentServes` (all peers), `maxConcurrentServesPerPeer`
121
+ * and `maxBytesPerPeerPerSec` bound what one node spends on serving. They apply
122
+ * to every chunk-request regardless of content, before any lookup.
123
+ *
124
+ * Every fetched chunk is verified against its own CID (SHA-256)
110
125
  * before being trusted/stored/re-served -- content-addressing's integrity
111
126
  * property holds regardless of which swarm peer relayed a piece, exactly
112
127
  * `chunk-replication.mjs`'s own reasoning for why its wire messages need no
113
128
  * signature.
114
129
  *
115
130
  * ---------------------------------------------------------------------------
116
- * CHUNKSTORE DURABILITY DECISION (explicitly flagged as open by the
117
- * migration plan's Phase 5 section -- resolved here, not left arbitrary):
118
- *
119
- * This file's own piece store uses the in-memory `ChunkStore`
120
- * (`@johnhenry/browsermesh-sync`'s `files.mjs`), NOT the durable
121
- * `IndexedDBChunkStore` (`storage-indexeddb-chunks.mjs`) CloudStorage uses.
122
- * Reasoning, concretely:
131
+ * DURABILITY (the "CHUNKSTORE DURABILITY DECISION" the migration plan left
132
+ * open, resolved as an injection point rather than a hard-coded choice):
123
133
  *
124
- * - Torrent-style swarm participation is inherently ephemeral BY DESIGN,
125
- * not by accident: a peer seeds or downloads while it's online and
126
- * interested; once it closes the tab, there is no expectation -- in
127
- * real BitTorrent OR here -- that its pieces "belong" to it across a
128
- * reload the way a CloudStorage object durably belongs to a bucket.
129
- * Nothing reads this file's `ChunkStore` as a source of truth the way
130
- * `CloudStorageBackend` treats its manifest+chunks; losing it on reload
131
- * just means this peer re-fetches pieces from the swarm next time it's
132
- * relevant, exactly the self-healing property a swarm is supposed to
133
- * have.
134
- * - The counter-argument is real and was weighed: a peer mid-download
135
- * that reloads loses partial progress, and a long-lived seeder loses
136
- * its ability to serve after a reload without re-seeding. Both are
137
- * genuine costs, not nothing.
138
- * - But `TorrentManager` ITSELF already made this exact call for its own
139
- * `FallbackStore` (`peer-torrent.mjs`, unmodified by this phase) -- it's
140
- * a private in-memory `Map`, same non-durable shape, same module. Making
141
- * ONLY this file's piece store durable while the class it wraps stays
142
- * resolutely in-memory would produce a torrent service that's durable
143
- * exactly until `tm.seed()`'s own bookkeeping (magnetURI/infoHash
144
- * generation, `listTorrents()`, `getStats()`) resets on reload anyway --
145
- * inconsistent durability that doesn't actually deliver "survives a
146
- * reload" for the feature as a whole, only for raw chunk bytes with no
147
- * index pointing at them.
148
- * - Per the plan's own explicit guidance for this exact decision ("if
149
- * unsure, default to keeping in-memory `ChunkStore` as the lower-risk,
150
- * smaller change"): this is the call made here. A future revision that
151
- * wants "resume a partial download/reseed after reload" as a real,
152
- * deliberate feature should swap BOTH this file's chunk store AND
153
- * `TorrentManager`'s own `FallbackStore`/`#activeTorrents` together, as
154
- * one coherent durability upgrade -- not something to back into
155
- * one-sidedly here.
134
+ * By default this service keeps pieces in an in-memory `ChunkStore` and
135
+ * manifests in an in-memory map, so everything is gone on reload -- exactly
136
+ * the old behaviour. Pass `chunkStore` and `manifestStore` and both survive:
137
+ * pieces go to `chunkStore`, one JSON-safe record per held torrent goes to
138
+ * `manifestStore` (the index of what to serve), and on attach the service
139
+ * reloads that index, so a seeder that comes back with the same stores keeps
140
+ * serving (`api.ensureLoaded()` additionally restores `listTorrents()`).
141
+ * `IndexedDBChunkStore` from `@johnhenry/browsermesh-sync` is the intended
142
+ * durable `chunkStore`; its `save/get/has/remove` return Promises and the
143
+ * service awaits every store call, so sync and async stores are both fine.
144
+ * The stores are handed to the internal `TorrentManager` too, so both halves
145
+ * stay consistent. A store you inject is never cleared by `destroy()`.
146
+ * Only content this node holds in full is persisted; manifests learned from
147
+ * other peers' announces live in memory.
156
148
  *
157
149
  * ---------------------------------------------------------------------------
158
150
  * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
@@ -171,12 +163,24 @@
171
163
  * - `torrent:chunk-served` `{to, cid, size}` -- this peer answered another
172
164
  * peer's `chunk-request` from its own local piece store -- the direct,
173
165
  * observable proof of peer-to-peer (not origin-only) exchange.
166
+ * - `torrent:request-denied` `{from, kind: 'manifest'|'chunk', magnetURI?, cid?}`
167
+ * -- `authorize` refused a request that named content this node holds
168
+ * (local observability only; the requester is told nothing).
169
+ * - `torrent:serve-busy` `{from, cid}` -- a serve cap was full.
174
170
  *
175
171
  * No browser-only imports at module level.
176
172
  */
177
173
 
178
- import { TorrentManager } from './peer-torrent.mjs'
174
+ import { TorrentManager, TORRENT_DEFAULTS } from './peer-torrent.mjs'
179
175
  import { ChunkStore } from '@johnhenry/browsermesh-sync'
176
+ import {
177
+ MemoryManifestStore,
178
+ toSeedBytes,
179
+ releaseChunks,
180
+ splitIntoChunks,
181
+ saveChunks,
182
+ createByteBucket,
183
+ } from './internal/torrent-store.mjs'
180
184
 
181
185
  /** Default `envelope.type` used to route all mesh-torrent wire traffic. */
182
186
  const DEFAULT_ENVELOPE_TYPE = 'mesh-torrent'
@@ -190,6 +194,24 @@ const DEFAULT_MANIFEST_TIMEOUT_MS = 5000
190
194
  /** How long a single `fetchChunkFrom()` call waits for its `chunk-response` before treating that peer as unreachable for this attempt. */
191
195
  const DEFAULT_CHUNK_TIMEOUT_MS = 5000
192
196
 
197
+ /** Chunk-responses a node will have in flight across all peers (`maxConcurrentServes`). */
198
+ const DEFAULT_MAX_CONCURRENT_SERVES = 16
199
+
200
+ /** Chunk-responses in flight for any one peer (`maxConcurrentServesPerPeer`). */
201
+ const DEFAULT_MAX_CONCURRENT_SERVES_PER_PEER = 4
202
+
203
+ /** Served bytes per second per peer (`maxBytesPerPeerPerSec`); `0` = unlimited. */
204
+ const DEFAULT_MAX_BYTES_PER_PEER_PER_SEC = 0
205
+
206
+ /** `announce` messages accepted per peer per minute (`maxAnnouncesPerPeerPerMinute`). */
207
+ const DEFAULT_MAX_ANNOUNCES_PER_PEER_PER_MINUTE = 30
208
+
209
+ /** Extra attempts a downloader makes on one provider after a `busy` answer. */
210
+ const DEFAULT_BUSY_RETRIES = 3
211
+
212
+ /** Backoff before the first `busy` retry; grows linearly per attempt. */
213
+ const DEFAULT_BUSY_BACKOFF_MS = 250
214
+
193
215
  // ---------------------------------------------------------------------------
194
216
  // Base64 helpers -- deliberately duplicated rather than shared, matching
195
217
  // this family's established convention (see chunk-replication.mjs's /
@@ -200,7 +222,8 @@ const DEFAULT_CHUNK_TIMEOUT_MS = 5000
200
222
  function toBase64(bytes) {
201
223
  if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
202
224
  let bin = ''
203
- for (const b of bytes) bin += String.fromCharCode(b)
225
+ const STEP = 0x8000
226
+ for (let i = 0; i < bytes.length; i += STEP) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + STEP))
204
227
  return btoa(bin)
205
228
  }
206
229
 
@@ -213,36 +236,6 @@ function fromBase64(str) {
213
236
  return bytes
214
237
  }
215
238
 
216
- /**
217
- * Normalize seed() input to a Uint8Array for chunking/hashing. Unlike
218
- * `TorrentManager.seed()` itself (which also tolerates a `Blob`, for its
219
- * real-WebTorrent browser path), this file's own manifest/piece-exchange
220
- * logic needs synchronous byte access, so a `Blob` is not supported here.
221
- * @param {Uint8Array|ArrayBuffer} data
222
- * @returns {Uint8Array}
223
- */
224
- function normalizeToUint8Array(data) {
225
- if (data instanceof Uint8Array) return data
226
- if (data instanceof ArrayBuffer) return new Uint8Array(data)
227
- throw new Error(
228
- 'mesh-torrent: seed() requires Uint8Array or ArrayBuffer data for this service\'s own ' +
229
- 'chunking/manifest logic (a Blob is only usable via TorrentManager\'s own real-WebTorrent path directly).',
230
- )
231
- }
232
-
233
- /**
234
- * @param {Uint8Array} bytes
235
- * @param {number} chunkSize
236
- * @returns {Uint8Array[]}
237
- */
238
- function splitIntoChunks(bytes, chunkSize) {
239
- const pieces = []
240
- for (let offset = 0; offset < bytes.length; offset += chunkSize) {
241
- pieces.push(bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)))
242
- }
243
- return pieces
244
- }
245
-
246
239
  /**
247
240
  * @param {Uint8Array[]} pieces
248
241
  * @returns {Uint8Array}
@@ -258,6 +251,22 @@ function concatChunks(pieces) {
258
251
  return out
259
252
  }
260
253
 
254
+ /** A manifest a peer sent us: only the fields we rely on, checked for shape. */
255
+ function isUsableManifest(m) {
256
+ return !!m && typeof m === 'object'
257
+ && Array.isArray(m.chunkCids) && m.chunkCids.every((c) => typeof c === 'string')
258
+ && Number.isSafeInteger(m.size) && m.size >= 0
259
+ }
260
+
261
+ function checkLimit(name, value) {
262
+ if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {
263
+ throw new TypeError(`createTorrentService: ${name} must be a non-negative number (0 or Infinity = unlimited), got ${String(value)}`)
264
+ }
265
+ }
266
+
267
+ /** Treat 0 as "no limit" for every cap option. */
268
+ const orUnlimited = (n) => (n === 0 ? Infinity : n)
269
+
261
270
  // ---------------------------------------------------------------------------
262
271
  // createTorrentService
263
272
  // ---------------------------------------------------------------------------
@@ -275,6 +284,34 @@ function concatChunks(pieces) {
275
284
  * @param {number} [opts.manifestTimeoutMs=5000]
276
285
  * @param {number} [opts.chunkTimeoutMs=5000]
277
286
  * @param {Function} [opts.onLog]
287
+ * @param {object} [opts.chunkStore] - Piece store, default a fresh in-memory
288
+ * `ChunkStore`. Any object with `save(cid, bytes)`, `get(cid)`, `has(cid)`
289
+ * and `remove(cid)` (each sync or async) -- browsermesh-sync's
290
+ * `IndexedDBChunkStore` is the durable fit. Shared with the internal
291
+ * `TorrentManager`. Never cleared by this service: it belongs to the caller.
292
+ * @param {object} [opts.manifestStore] - `{ get(magnetURI), set(magnetURI,
293
+ * manifest), delete(magnetURI), entries() }` (each sync or async), holding
294
+ * one JSON-safe record per torrent this node holds. Default in-memory. It is
295
+ * the index of what `chunkStore` contains: a node only serves pieces that a
296
+ * manifest in this store lists, so persist both or neither.
297
+ * @param {(fromPubKey: string, req: { kind: 'manifest'|'chunk', magnetURI: string,
298
+ * infoHash: string, cid?: string, chunkCid?: string }) => boolean|Promise<boolean>} [opts.authorize]
299
+ * Called before serving a manifest or a piece. `cid` is the SHA-256 hex CID
300
+ * of the whole content (when known); `chunkCid` is set for `kind: 'chunk'`.
301
+ * Only a strict `true` allows; `false`, anything else, or a throw denies.
302
+ * A denied request gets exactly the reply an unknown one gets. Omitted =
303
+ * serve everyone (the previous behaviour).
304
+ * @param {number} [opts.maxConcurrentServes=16] - Chunk-responses in flight
305
+ * across all peers. Over the cap the requester is told `busy`. `0` = unlimited.
306
+ * @param {number} [opts.maxConcurrentServesPerPeer=4] - Same, per requesting peer.
307
+ * @param {number} [opts.maxBytesPerPeerPerSec=0] - Served-bytes budget per
308
+ * peer (token bucket, one-second burst); excess serves wait. `0` = unlimited.
309
+ * @param {number} [opts.maxAnnouncesPerPeerPerMinute=30] - Inbound
310
+ * `announce`s accepted per peer per rolling minute; extras are dropped. `0` = unlimited.
311
+ * @param {number} [opts.busyRetries=3] - Downloader: retries on one provider after `busy`.
312
+ * @param {number} [opts.busyBackoffMs=250] - Downloader: first backoff after `busy` (grows linearly).
313
+ * @param {() => number} [opts.now] - Clock for rate limits (tests).
314
+ * @param {(ms: number) => Promise<void>} [opts.sleep] - Sleep for rate limits/backoff (tests).
278
315
  * @returns {import('./mesh-service.mjs').MeshService}
279
316
  */
280
317
  export function createTorrentService({
@@ -284,29 +321,118 @@ export function createTorrentService({
284
321
  manifestTimeoutMs = DEFAULT_MANIFEST_TIMEOUT_MS,
285
322
  chunkTimeoutMs = DEFAULT_CHUNK_TIMEOUT_MS,
286
323
  onLog,
324
+ chunkStore: injectedChunkStore,
325
+ manifestStore: injectedManifestStore,
326
+ authorize,
327
+ maxConcurrentServes = DEFAULT_MAX_CONCURRENT_SERVES,
328
+ maxConcurrentServesPerPeer = DEFAULT_MAX_CONCURRENT_SERVES_PER_PEER,
329
+ maxBytesPerPeerPerSec = DEFAULT_MAX_BYTES_PER_PEER_PER_SEC,
330
+ maxAnnouncesPerPeerPerMinute = DEFAULT_MAX_ANNOUNCES_PER_PEER_PER_MINUTE,
331
+ busyRetries = DEFAULT_BUSY_RETRIES,
332
+ busyBackoffMs = DEFAULT_BUSY_BACKOFF_MS,
333
+ now = Date.now,
334
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
287
335
  } = {}) {
288
336
  const log = onLog || (() => {})
289
337
 
338
+ if (authorize !== undefined && typeof authorize !== 'function') {
339
+ throw new TypeError('createTorrentService: authorize must be a function (fromPubKey, request) => boolean|Promise<boolean>')
340
+ }
341
+ for (const [n, v] of Object.entries({ maxConcurrentServes, maxConcurrentServesPerPeer, maxBytesPerPeerPerSec, maxAnnouncesPerPeerPerMinute })) {
342
+ checkLimit(n, v)
343
+ }
344
+ for (const [n, o] of [['chunkStore', injectedChunkStore], ['manifestStore', injectedManifestStore]]) {
345
+ if (o !== undefined && (o === null || typeof o !== 'object')) {
346
+ throw new TypeError(`createTorrentService: ${n} must be an object`)
347
+ }
348
+ }
349
+ for (const m of ['save', 'get', 'has', 'remove']) {
350
+ if (injectedChunkStore && typeof injectedChunkStore[m] !== 'function') {
351
+ throw new TypeError(`createTorrentService: chunkStore must implement ${m}()`)
352
+ }
353
+ }
354
+ for (const m of ['get', 'set', 'delete', 'entries']) {
355
+ if (injectedManifestStore && typeof injectedManifestStore[m] !== 'function') {
356
+ throw new TypeError(`createTorrentService: manifestStore must implement ${m}()`)
357
+ }
358
+ }
359
+ const globalServeCap = orUnlimited(maxConcurrentServes)
360
+ const perPeerServeCap = orUnlimited(maxConcurrentServesPerPeer)
361
+ const announceCap = orUnlimited(maxAnnouncesPerPeerPerMinute)
362
+
290
363
  return {
291
364
  name: 'torrent',
292
365
 
293
366
  attach(peerNode, ctx) {
367
+ /** This service's piece store: the caller's, or a private in-memory one -- see module doc comment's "DURABILITY". */
368
+ const chunkStore = injectedChunkStore ?? new ChunkStore()
369
+ const manifestStore = injectedManifestStore ?? new MemoryManifestStore()
370
+
294
371
  const tm = new TorrentManager({
295
372
  trackerUrl,
373
+ chunkSize,
374
+ chunkStore,
375
+ manifestStore,
296
376
  onLog: (level, msg) => log('mesh-torrent:internal', { level, msg }),
297
377
  })
298
378
 
299
- /** This file's own piece store -- see module doc comment's "CHUNKSTORE DURABILITY DECISION". */
300
- const chunkStore = new ChunkStore()
379
+ /**
380
+ * magnetURI -> manifest, for content this node HOLDS in full (persisted
381
+ * through `manifestStore`; reloaded into this map by `ready`).
382
+ * @type {Map<string, {infoHash: string, name: string, size: number, chunkSize?: number, chunkCids: string[], cid?: string}>}
383
+ */
384
+ const held = new Map()
385
+
386
+ /** magnetURI -> manifest a peer announced or answered with, for content we do NOT hold. Memory only. */
387
+ const remoteManifests = new Map()
301
388
 
302
- /** @type {Map<string, {infoHash: string, name: string, size: number, chunkCids: string[]}>} magnetURI -> manifest */
303
- const manifests = new Map()
389
+ /** piece cid -> magnetURIs (in `held`) that list it: what a chunk-request may be served from. */
390
+ const chunkIndex = new Map()
304
391
 
305
392
  /** @type {Map<string, Set<string>>} cid -> pubKeys known to currently hold that piece */
306
393
  const chunkOwners = new Map()
307
394
 
395
+ const manifestFor = (magnetURI) => held.get(magnetURI) ?? remoteManifests.get(magnetURI)
396
+
397
+ function indexHeld(magnetURI, manifest) {
398
+ for (const cid of manifest.chunkCids) {
399
+ let set = chunkIndex.get(cid)
400
+ if (!set) chunkIndex.set(cid, (set = new Set()))
401
+ set.add(magnetURI)
402
+ }
403
+ }
404
+
405
+ function unindexHeld(magnetURI, manifest) {
406
+ for (const cid of manifest.chunkCids) {
407
+ const set = chunkIndex.get(cid)
408
+ if (!set) continue
409
+ set.delete(magnetURI)
410
+ if (set.size === 0) chunkIndex.delete(cid)
411
+ }
412
+ }
413
+
414
+ /** Writes and cleanups still running; awaited by `api.flush()`. */
415
+ const pendingWrites = new Set()
416
+ const track = (promise) => {
417
+ const p = promise.catch((err) => log('mesh-torrent:store-error', { error: err?.message || String(err) }))
418
+ .finally(() => pendingWrites.delete(p))
419
+ pendingWrites.add(p)
420
+ return p
421
+ }
422
+
423
+ /** Reload what a previous run persisted: this is what lets a seeder keep serving after a reload. */
424
+ const ready = (async () => {
425
+ for (const [magnetURI, manifest] of await manifestStore.entries()) {
426
+ if (!isUsableManifest(manifest) || held.has(magnetURI)) continue
427
+ held.set(magnetURI, manifest)
428
+ indexHeld(magnetURI, manifest)
429
+ }
430
+ })().catch((err) => {
431
+ log('mesh-torrent:manifest-restore-failed', { error: err?.message || String(err) })
432
+ })
433
+
308
434
  let reqSeq = 0
309
- const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
435
+ const nextRequestId = () => `${peerNode.podId}:${now()}:${++reqSeq}`
310
436
 
311
437
  /** @param {string} pubKey @param {string[]} cids */
312
438
  function recordOwner(pubKey, cids) {
@@ -328,14 +454,55 @@ export function createTorrentService({
328
454
  const onTmSeed = (info) => ctx.emit('torrent:seed', info)
329
455
  tm.on('seed', onTmSeed)
330
456
 
457
+ // -----------------------------------------------------------------
458
+ // Serving limits and authorization
459
+ // -----------------------------------------------------------------
460
+
461
+ /** pubKey -> chunk-responses in flight */
462
+ const inFlight = new Map()
463
+ let totalInFlight = 0
464
+ /** pubKey -> byte bucket */
465
+ const buckets = new Map()
466
+ /** pubKey -> timestamps of recent announces */
467
+ const announceTimes = new Map()
468
+
469
+ function announceAllowed(pubKey) {
470
+ if (announceCap === Infinity) return true
471
+ const t = now()
472
+ const recent = (announceTimes.get(pubKey) ?? []).filter((x) => t - x < 60_000)
473
+ const ok = recent.length < announceCap
474
+ if (ok) recent.push(t)
475
+ announceTimes.set(pubKey, recent)
476
+ return ok
477
+ }
478
+
479
+ /** Strict `true` allows; a throw, a rejection or any other value denies (fail closed). */
480
+ async function mayServe(fromPubKey, request) {
481
+ if (!authorize) return true
482
+ try {
483
+ return (await authorize(fromPubKey, request)) === true
484
+ } catch (err) {
485
+ log('mesh-torrent:authorize-error', { from: fromPubKey, kind: request.kind, error: err?.message || String(err) })
486
+ return false
487
+ }
488
+ }
489
+
490
+ const requestFor = (kind, magnetURI, manifest, chunkCid) => ({
491
+ kind,
492
+ magnetURI,
493
+ infoHash: manifest.infoHash,
494
+ cid: manifest.cid,
495
+ ...(chunkCid !== undefined ? { chunkCid } : {}),
496
+ })
497
+
331
498
  // -----------------------------------------------------------------
332
499
  // In-flight request tracking
333
500
  // -----------------------------------------------------------------
334
501
 
335
- /** @type {Map<string, {resolve: (manifest: object|null) => void, timer: ReturnType<typeof setTimeout>, magnetURI: string}>} */
502
+ /** @type {Map<string, {resolve: (manifest: object|null) => void, timer: ReturnType<typeof setTimeout>, magnetURI: string, targets: Set<string>, expected: number}>} */
336
503
  const pendingManifestRequests = new Map()
337
504
 
338
- /** @type {Map<string, {resolve: (bytes: Uint8Array) => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout>}>} */
505
+ /** @type {Map<string, {resolve: (bytes: Uint8Array) => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout>, peer: string}>} */
339
506
  const pendingChunkFetches = new Map()
340
507
 
341
508
  // -----------------------------------------------------------------
@@ -343,9 +510,13 @@ export function createTorrentService({
343
510
  // -----------------------------------------------------------------
344
511
 
345
512
  function handleAnnounce(fromPubKey, msg) {
346
- if (typeof msg.magnetURI !== 'string') return
347
- if (msg.manifest && Array.isArray(msg.manifest.chunkCids)) {
348
- manifests.set(msg.magnetURI, msg.manifest)
513
+ if (typeof msg.magnetURI !== 'string' || msg.magnetURI.length > 512) return
514
+ if (!announceAllowed(fromPubKey)) {
515
+ log('mesh-torrent:announce-rate-limited', { from: fromPubKey })
516
+ return
517
+ }
518
+ if (isUsableManifest(msg.manifest)) {
519
+ if (!held.has(msg.magnetURI)) remoteManifests.set(msg.magnetURI, msg.manifest)
349
520
  recordOwner(fromPubKey, msg.manifest.chunkCids)
350
521
  }
351
522
  ctx.emit('torrent:announce-received', {
@@ -355,11 +526,16 @@ export function createTorrentService({
355
526
  })
356
527
  }
357
528
 
358
- function handleManifestRequest(fromPubKey, msg) {
529
+ async function handleManifestRequest(fromPubKey, msg) {
359
530
  if (typeof msg.magnetURI !== 'string' || typeof msg.requestId !== 'string') return
360
- const manifest = manifests.get(msg.magnetURI)
361
- if (!manifest) return // silent "don't have it" -- matches chunk-replication.mjs's own convention
362
- ctx.sendTo(fromPubKey, envelopeType, {
531
+ await ready
532
+ let manifest = manifestFor(msg.magnetURI) ?? null
533
+ if (manifest && !(await mayServe(fromPubKey, requestFor('manifest', msg.magnetURI, manifest)))) {
534
+ ctx.emit('torrent:request-denied', { from: fromPubKey, kind: 'manifest', magnetURI: msg.magnetURI })
535
+ manifest = null
536
+ }
537
+ // Unknown and refused answer identically (`manifest: null`): a requester learns nothing about what exists.
538
+ await ctx.sendTo(fromPubKey, envelopeType, {
363
539
  kind: 'manifest-response', requestId: msg.requestId, magnetURI: msg.magnetURI, manifest,
364
540
  }).catch((err) => {
365
541
  log('mesh-torrent:manifest-response-send-failed', { to: fromPubKey, magnetURI: msg.magnetURI, error: err?.message || String(err) })
@@ -368,40 +544,96 @@ export function createTorrentService({
368
544
 
369
545
  function handleManifestResponse(fromPubKey, msg) {
370
546
  const pending = pendingManifestRequests.get(msg.requestId)
371
- if (!pending) return
372
- clearTimeout(pending.timer)
373
- pendingManifestRequests.delete(msg.requestId)
374
- if (msg.manifest && Array.isArray(msg.manifest.chunkCids)) {
375
- manifests.set(pending.magnetURI, msg.manifest)
547
+ if (!pending || !pending.targets.has(fromPubKey)) return
548
+ pending.targets.delete(fromPubKey)
549
+ if (isUsableManifest(msg.manifest)) {
550
+ clearTimeout(pending.timer)
551
+ pendingManifestRequests.delete(msg.requestId)
552
+ if (!held.has(pending.magnetURI)) remoteManifests.set(pending.magnetURI, msg.manifest)
376
553
  recordOwner(fromPubKey, msg.manifest.chunkCids)
554
+ pending.resolve(msg.manifest)
555
+ return
556
+ }
557
+ // A "don't have it / won't tell you" answer: only give up once every asked peer has said so.
558
+ if (--pending.expected <= 0) {
559
+ clearTimeout(pending.timer)
560
+ pendingManifestRequests.delete(msg.requestId)
561
+ pending.resolve(null)
377
562
  }
378
- pending.resolve(msg.manifest || null)
379
563
  }
380
564
 
381
565
  async function handleChunkRequest(fromPubKey, msg) {
382
566
  if (typeof msg.cid !== 'string' || typeof msg.requestId !== 'string') return
383
- const bytes = chunkStore.get(msg.cid)
384
- if (!bytes) {
385
- await ctx.sendTo(fromPubKey, envelopeType, {
386
- kind: 'chunk-response', requestId: msg.requestId, cid: msg.cid, error: 'not-found',
387
- }).catch(() => {})
567
+ const respond = (payload, sendOpts) => ctx.sendTo(fromPubKey, envelopeType, {
568
+ kind: 'chunk-response', requestId: msg.requestId, cid: msg.cid, ...payload,
569
+ }, sendOpts)
570
+ const notFound = () => respond({ error: 'not-found' }).catch(() => {})
571
+
572
+ // Load limits apply to every request from a peer, whatever it asks
573
+ // for, so `busy` says nothing about which content exists.
574
+ const mine = inFlight.get(fromPubKey) ?? 0
575
+ if (mine >= perPeerServeCap || totalInFlight >= globalServeCap) {
576
+ ctx.emit('torrent:serve-busy', { from: fromPubKey, cid: msg.cid })
577
+ await respond({ error: 'busy' }).catch(() => {})
388
578
  return
389
579
  }
390
- await ctx.sendTo(fromPubKey, envelopeType, {
391
- kind: 'chunk-response', requestId: msg.requestId, cid: msg.cid, data: toBase64(bytes),
392
- }).catch((err) => {
393
- log('mesh-torrent:chunk-response-send-failed', { to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
394
- })
395
- ctx.emit('torrent:chunk-served', { to: fromPubKey, cid: msg.cid, size: bytes.length })
580
+ inFlight.set(fromPubKey, mine + 1)
581
+ totalInFlight++
582
+ try {
583
+ await ready
584
+ // Only pieces listed by a manifest this node holds are ever served,
585
+ // so a shared/durable chunkStore's other contents stay unreachable.
586
+ let allowed = false
587
+ let allowedBy = null
588
+ for (const magnetURI of chunkIndex.get(msg.cid) ?? []) {
589
+ const manifest = held.get(magnetURI)
590
+ if (manifest && await mayServe(fromPubKey, requestFor('chunk', magnetURI, manifest, msg.cid))) {
591
+ allowed = true
592
+ allowedBy = magnetURI
593
+ break
594
+ }
595
+ }
596
+ if (!allowed) {
597
+ if (chunkIndex.has(msg.cid)) ctx.emit('torrent:request-denied', { from: fromPubKey, kind: 'chunk', cid: msg.cid })
598
+ return await notFound()
599
+ }
600
+
601
+ const bytes = await chunkStore.get(msg.cid)
602
+ if (!bytes) {
603
+ log('mesh-torrent:held-chunk-missing', { cid: msg.cid, magnetURI: allowedBy })
604
+ return await notFound()
605
+ }
606
+
607
+ let bucket = buckets.get(fromPubKey)
608
+ if (!bucket) buckets.set(fromPubKey, (bucket = createByteBucket({ rate: maxBytesPerPeerPerSec, now, sleep })))
609
+ await bucket.take(bytes.length)
610
+
611
+ let sent = true
612
+ // Piece data should ride the bulk lane so it cannot starve control traffic.
613
+ // #198 lands the `{ channel: 'bulk' }` option on ctx.sendTo; until then the
614
+ // extra argument is ignored and everything uses the default lane.
615
+ await respond({ data: toBase64(bytes) }, { channel: 'bulk' }).catch((err) => {
616
+ sent = false
617
+ log('mesh-torrent:chunk-response-send-failed', { to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
618
+ })
619
+ if (sent) ctx.emit('torrent:chunk-served', { to: fromPubKey, cid: msg.cid, size: bytes.length })
620
+ } finally {
621
+ const left = (inFlight.get(fromPubKey) ?? 1) - 1
622
+ if (left > 0) inFlight.set(fromPubKey, left)
623
+ else inFlight.delete(fromPubKey)
624
+ totalInFlight--
625
+ }
396
626
  }
397
627
 
398
628
  function handleChunkResponse(fromPubKey, msg) {
399
629
  const pending = pendingChunkFetches.get(msg.requestId)
400
- if (!pending) return
630
+ if (!pending || pending.peer !== fromPubKey) return // a response only counts from the peer we asked
401
631
  clearTimeout(pending.timer)
402
632
  pendingChunkFetches.delete(msg.requestId)
403
633
  if (msg.error) {
404
- pending.reject(new Error(`mesh-torrent: chunk ${msg.cid} fetch from ${fromPubKey} failed: ${msg.error}`))
634
+ const err = new Error(`mesh-torrent: chunk ${msg.cid} fetch from ${fromPubKey} failed: ${msg.error}`)
635
+ err.code = msg.error
636
+ pending.reject(err)
405
637
  return
406
638
  }
407
639
  if (typeof msg.data !== 'string') {
@@ -438,9 +670,9 @@ export function createTorrentService({
438
670
  * @returns {Promise<object|null>}
439
671
  */
440
672
  async function requestManifest(magnetURI, candidatePeers) {
441
- const known = manifests.get(magnetURI)
673
+ const known = manifestFor(magnetURI)
442
674
  if (known) return known
443
- const targets = candidatePeers && candidatePeers.length ? candidatePeers : []
675
+ const targets = candidatePeers && candidatePeers.length ? [...new Set(candidatePeers)] : []
444
676
  if (targets.length === 0) return null
445
677
 
446
678
  const requestId = nextRequestId()
@@ -449,11 +681,18 @@ export function createTorrentService({
449
681
  pendingManifestRequests.delete(requestId)
450
682
  resolve(null)
451
683
  }, manifestTimeoutMs)
452
- pendingManifestRequests.set(requestId, { resolve, timer, magnetURI })
684
+ pendingManifestRequests.set(requestId, { resolve, timer, magnetURI, targets: new Set(targets), expected: targets.length })
453
685
  })
454
686
 
455
687
  await Promise.all(targets.map((pubKey) =>
456
688
  ctx.sendTo(pubKey, envelopeType, { kind: 'manifest-request', requestId, magnetURI }).catch((err) => {
689
+ // A peer we could not even ask will never answer: stop waiting for it.
690
+ const p = pendingManifestRequests.get(requestId)
691
+ if (p && p.targets.delete(pubKey) && --p.expected <= 0) {
692
+ clearTimeout(p.timer)
693
+ pendingManifestRequests.delete(requestId)
694
+ p.resolve(null)
695
+ }
457
696
  log('mesh-torrent:manifest-request-send-failed', { to: pubKey, magnetURI, error: err?.message || String(err) })
458
697
  }),
459
698
  ))
@@ -473,7 +712,7 @@ export function createTorrentService({
473
712
  pendingChunkFetches.delete(requestId)
474
713
  reject(new Error(`mesh-torrent: chunk ${cid} fetch from ${pubKey} timed out after ${chunkTimeoutMs}ms`))
475
714
  }, chunkTimeoutMs)
476
- pendingChunkFetches.set(requestId, { resolve, reject, timer })
715
+ pendingChunkFetches.set(requestId, { resolve, reject, timer, peer: pubKey })
477
716
  })
478
717
 
479
718
  try {
@@ -498,31 +737,38 @@ export function createTorrentService({
498
737
  * @returns {Promise<Uint8Array>}
499
738
  */
500
739
  async function fetchChunk(cid, candidatePeers) {
501
- const already = chunkStore.get(cid)
740
+ const already = await chunkStore.get(cid)
502
741
  if (already) return already
503
742
 
504
743
  const owners = new Set([...(chunkOwners.get(cid) || []), ...(candidatePeers || [])])
744
+ owners.delete(peerNode.podId)
505
745
  if (owners.size === 0) {
506
746
  throw new Error(`mesh-torrent: no known provider for chunk ${cid} (supply opts.peers)`)
507
747
  }
508
748
 
509
749
  let lastErr = null
510
750
  for (const pubKey of owners) {
511
- try {
512
- const bytes = await fetchChunkFrom(pubKey, cid)
513
- const valid = await chunkStore.verify(cid, bytes)
514
- if (!valid) {
515
- lastErr = new Error(`mesh-torrent: chunk ${cid} from ${pubKey} failed integrity verification`)
516
- log('mesh-torrent:chunk-integrity-failed', { cid, from: pubKey })
517
- continue
751
+ for (let attempt = 0; attempt <= busyRetries; attempt++) {
752
+ try {
753
+ const bytes = await fetchChunkFrom(pubKey, cid)
754
+ if ((await ChunkStore.computeCid(bytes)) !== cid) {
755
+ lastErr = new Error(`mesh-torrent: chunk ${cid} from ${pubKey} failed integrity verification`)
756
+ log('mesh-torrent:chunk-integrity-failed', { cid, from: pubKey })
757
+ break
758
+ }
759
+ await chunkStore.save(cid, bytes)
760
+ recordOwner(pubKey, [cid])
761
+ ctx.emit('torrent:chunk-received', { from: pubKey, cid, size: bytes.length })
762
+ return bytes
763
+ } catch (err) {
764
+ lastErr = err
765
+ if (err?.code === 'busy' && attempt < busyRetries) {
766
+ await sleep(busyBackoffMs * (attempt + 1))
767
+ continue
768
+ }
769
+ log('mesh-torrent:fetch-attempt-failed', { cid, from: pubKey, error: err?.message || String(err) })
770
+ break
518
771
  }
519
- chunkStore.save(cid, bytes)
520
- recordOwner(pubKey, [cid])
521
- ctx.emit('torrent:chunk-received', { from: pubKey, cid, size: bytes.length })
522
- return bytes
523
- } catch (err) {
524
- lastErr = err
525
- log('mesh-torrent:fetch-attempt-failed', { cid, from: pubKey, error: err?.message || String(err) })
526
772
  }
527
773
  }
528
774
  throw lastErr || new Error(`mesh-torrent: failed to fetch chunk ${cid} from any known provider`)
@@ -532,27 +778,45 @@ export function createTorrentService({
532
778
  // api.seed / api.share / api.download
533
779
  // -----------------------------------------------------------------
534
780
 
781
+ /**
782
+ * Record `manifest` as held: memory, index, and `manifestStore`.
783
+ * @returns {Promise<void>}
784
+ */
785
+ async function holdManifest(magnetURI, manifest) {
786
+ const prior = held.get(magnetURI)
787
+ if (prior) unindexHeld(magnetURI, prior)
788
+ held.set(magnetURI, manifest)
789
+ remoteManifests.delete(magnetURI)
790
+ indexHeld(magnetURI, manifest)
791
+ await manifestStore.set(magnetURI, manifest)
792
+ }
793
+
535
794
  /**
536
795
  * Seed content: reuses `TorrentManager.seed()` verbatim for real
537
796
  * magnet/infoHash generation and its own bookkeeping, then chunks the
538
- * data into this file's own content-addressed piece store and records
797
+ * data into this service's content-addressed piece store and records
539
798
  * a manifest, so this peer can answer `chunk-request`s for it.
540
- * @param {Uint8Array|ArrayBuffer} data
799
+ * @param {string|Uint8Array|ArrayBufferView|ArrayBuffer|Blob} data - a string is UTF-8 encoded
541
800
  * @param {object} [opts] - Forwarded to `TorrentManager.seed()`.
542
801
  * @returns {Promise<import('./peer-torrent.mjs').TorrentInfo>}
543
802
  */
544
803
  async function seed(data, opts = {}) {
545
- const bytes = normalizeToUint8Array(data)
546
- const info = await tm.seed(data, opts)
547
-
548
- const chunkCids = []
549
- for (const piece of splitIntoChunks(bytes, chunkSize)) {
550
- const cid = await ChunkStore.computeCid(piece)
551
- chunkStore.save(cid, piece)
552
- chunkCids.push(cid)
804
+ await ready
805
+ const bytes = await toSeedBytes(data)
806
+ const info = await tm.seed(bytes, { ...opts, chunkSize })
807
+
808
+ // In the fallback path tm has already written the pieces and manifest
809
+ // into the shared stores; reuse them instead of hashing twice. In the
810
+ // real-WebTorrent path it writes nothing, so build them here.
811
+ let manifest = await tm.getManifest(info.magnetURI)
812
+ if (!manifest) {
813
+ const chunkCids = await saveChunks(chunkStore, splitIntoChunks(bytes, chunkSize), (p) => ChunkStore.computeCid(p))
814
+ manifest = {
815
+ infoHash: info.infoHash, name: info.name, size: info.size, chunkSize, chunkCids,
816
+ cid: await ChunkStore.computeCid(bytes),
817
+ }
553
818
  }
554
-
555
- manifests.set(info.magnetURI, { infoHash: info.infoHash, name: info.name, size: info.size, chunkCids })
819
+ await holdManifest(info.magnetURI, manifest)
556
820
  return info
557
821
  }
558
822
 
@@ -566,7 +830,7 @@ export function createTorrentService({
566
830
  * @param {string[]} peerIds
567
831
  */
568
832
  function share(magnetURI, peerIds) {
569
- const manifest = manifests.get(magnetURI)
833
+ const manifest = manifestFor(magnetURI)
570
834
  tm.shareWithPeers(magnetURI, peerIds, (peerId, message) => {
571
835
  ctx.sendTo(peerId, envelopeType, {
572
836
  kind: 'announce', magnetURI, manifest, info: message.info,
@@ -589,9 +853,10 @@ export function createTorrentService({
589
853
  * @returns {Promise<{data: Uint8Array, info: import('./peer-torrent.mjs').TorrentInfo}>}
590
854
  */
591
855
  async function download(magnetURI, opts = {}) {
856
+ await ready
592
857
  ctx.emit('torrent:download-start', { magnetURI })
593
858
 
594
- const manifest = manifests.get(magnetURI) || await requestManifest(magnetURI, opts.peers)
859
+ const manifest = manifestFor(magnetURI) || await requestManifest(magnetURI, opts.peers)
595
860
  if (!manifest) {
596
861
  throw new Error(
597
862
  `mesh-torrent: no manifest known for ${magnetURI} (no prior announce, and no peer responded -- supply opts.peers)`,
@@ -608,6 +873,10 @@ export function createTorrentService({
608
873
  `mesh-torrent: reassembled ${data.length} bytes but manifest for ${magnetURI} declares size ${manifest.size}`,
609
874
  )
610
875
  }
876
+ const contentCid = await ChunkStore.computeCid(data)
877
+ if (typeof manifest.cid === 'string' && manifest.cid !== contentCid) {
878
+ throw new Error(`mesh-torrent: reassembled content for ${magnetURI} does not match the manifest's cid`)
879
+ }
611
880
 
612
881
  // Register this peer as a full holder via TorrentManager's own
613
882
  // seed() -- genuinely correct, not a hack: a peer with every piece
@@ -616,24 +885,63 @@ export function createTorrentService({
616
885
  // these identical bytes deterministically reproduces the SAME
617
886
  // magnetURI/infoHash (same hash, same truncation), so this doesn't
618
887
  // create a second, different torrent identity for the same content.
619
- const info = await tm.seed(data, { name: manifest.name })
888
+ // The pieces are re-cut at the size the manifest used (inferred from
889
+ // its first piece when the announcing peer did not say), so they are
890
+ // the ones already in the store and nothing is stored twice.
891
+ const pieceSize = manifest.chunkSize
892
+ ?? (pieces.length > 1 ? pieces[0].length : Math.max(data.length, 1))
893
+ const info = await tm.seed(data, { name: manifest.name, chunkSize: pieceSize })
620
894
  if (info.magnetURI !== magnetURI) {
621
895
  log('mesh-torrent:magnet-mismatch-after-reassembly', { expected: magnetURI, got: info.magnetURI })
622
896
  }
897
+ const stored = await tm.getManifest(info.magnetURI)
898
+ await holdManifest(info.magnetURI, stored ?? {
899
+ infoHash: info.infoHash, name: manifest.name, size: data.length, chunkSize: pieceSize,
900
+ chunkCids: manifest.chunkCids, cid: contentCid,
901
+ })
902
+ if (info.magnetURI !== magnetURI) remoteManifests.delete(magnetURI)
623
903
 
624
904
  ctx.emit('torrent:download-complete', { magnetURI, name: manifest.name, size: data.length })
625
905
  return { data, info }
626
906
  }
627
907
 
908
+ /** Stop serving a torrent now; its stored manifest and unshared pieces are released in the background (`flush()` waits for that). */
909
+ function removeTorrent(magnetURI) {
910
+ const removedByTm = tm.removeTorrent(magnetURI)
911
+ remoteManifests.delete(magnetURI)
912
+ const manifest = held.get(magnetURI)
913
+ if (!manifest) return removedByTm
914
+ held.delete(magnetURI)
915
+ unindexHeld(magnetURI, manifest)
916
+ track((async () => {
917
+ await manifestStore.delete(magnetURI)
918
+ await releaseChunks(chunkStore, manifestStore, manifest, magnetURI)
919
+ })())
920
+ return true
921
+ }
922
+
628
923
  async function destroy() {
629
924
  await tm.destroy()
630
- chunkStore.clear()
631
- manifests.clear()
925
+ await flush()
926
+ // A store the caller injected is theirs and may be durable: leave its contents alone.
927
+ if (!injectedChunkStore && typeof chunkStore.clear === 'function') await chunkStore.clear()
928
+ if (!injectedManifestStore && typeof manifestStore.clear === 'function') await manifestStore.clear()
929
+ held.clear()
930
+ remoteManifests.clear()
931
+ chunkIndex.clear()
632
932
  chunkOwners.clear()
633
933
  }
634
934
 
935
+ async function flush() {
936
+ await ready
937
+ while (pendingWrites.size) await Promise.all([...pendingWrites])
938
+ }
939
+
635
940
  const api = {
636
- ensureLoaded: () => tm.ensureLoaded(),
941
+ /** Resolves once manifests persisted by an earlier run are loaded (serving and downloads wait for it internally). */
942
+ ready,
943
+ /** Load the underlying TorrentManager; after a reload this also restores `listTorrents()` from `manifestStore`. */
944
+ ensureLoaded: async () => { await ready; await tm.ensureLoaded() },
637
945
  get loaded() { return tm.loaded },
638
946
  get available() { return tm.available },
639
947
  seed,
@@ -641,15 +949,13 @@ export function createTorrentService({
641
949
  download,
642
950
  listTorrents: () => tm.listTorrents(),
643
951
  getTorrent: (magnetURI) => tm.getTorrent(magnetURI),
644
- removeTorrent: (magnetURI) => {
645
- const removed = tm.removeTorrent(magnetURI)
646
- manifests.delete(magnetURI)
647
- return removed
648
- },
952
+ removeTorrent,
649
953
  getStats: () => tm.getStats(),
650
- getManifest: (magnetURI) => manifests.get(magnetURI) ?? null,
954
+ getManifest: (magnetURI) => manifestFor(magnetURI) ?? null,
651
955
  /** @param {string} cid @returns {string[]} pubKeys this peer currently believes hold `cid`, for introspection/tests. */
652
956
  listKnownProviders: (cid) => [...(chunkOwners.get(cid) || [])],
957
+ /** Resolves when background store writes/cleanups started by this service have finished. */
958
+ flush,
653
959
  toJSON: () => tm.toJSON(),
654
960
  destroy,
655
961
  }
@@ -680,4 +986,8 @@ export {
680
986
  DEFAULT_CHUNK_SIZE,
681
987
  DEFAULT_MANIFEST_TIMEOUT_MS,
682
988
  DEFAULT_CHUNK_TIMEOUT_MS,
989
+ DEFAULT_MAX_CONCURRENT_SERVES,
990
+ DEFAULT_MAX_CONCURRENT_SERVES_PER_PEER,
991
+ DEFAULT_MAX_BYTES_PER_PEER_PER_SEC,
992
+ DEFAULT_MAX_ANNOUNCES_PER_PEER_PER_MINUTE,
683
993
  }