@johnhenry/browsermesh-apps 0.12.0 → 0.14.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.
@@ -212,6 +212,21 @@ const DEFAULT_BUSY_RETRIES = 3
212
212
  /** Backoff before the first `busy` retry; grows linearly per attempt. */
213
213
  const DEFAULT_BUSY_BACKOFF_MS = 250
214
214
 
215
+ /** Pieces `download()` keeps in flight at once unless told otherwise. */
216
+ const DEFAULT_DOWNLOAD_CONCURRENCY = 4
217
+
218
+ /** Hard ceiling on piece concurrency, whatever a caller asks for. */
219
+ const MAX_DOWNLOAD_CONCURRENCY = 32
220
+
221
+ /** Longest `chunkCids` list accepted in a manifest a remote peer sends (`maxManifestChunks`); 16384 x 64KB = 1GiB. */
222
+ const DEFAULT_MAX_MANIFEST_CHUNKS = 16384
223
+
224
+ /** Remembered remote manifests, least recently used evicted first (`maxRemoteManifests`). */
225
+ const DEFAULT_MAX_REMOTE_MANIFESTS = 64
226
+
227
+ /** A piece CID: the lowercase hex SHA-256 of the piece. */
228
+ const CID_RE = /^[0-9a-f]{64}$/
229
+
215
230
  // ---------------------------------------------------------------------------
216
231
  // Base64 helpers -- deliberately duplicated rather than shared, matching
217
232
  // this family's established convention (see chunk-replication.mjs's /
@@ -258,12 +273,49 @@ function isUsableManifest(m) {
258
273
  && Number.isSafeInteger(m.size) && m.size >= 0
259
274
  }
260
275
 
276
+ /**
277
+ * A manifest a REMOTE peer sent us, held to the bounds the receiver chose:
278
+ * the basic shape of `isUsableManifest`, plus at most `maxChunks` pieces (and
279
+ * `maxSize` bytes), every piece CID a 64-hex SHA-256, and a piece count that
280
+ * matches the declared size (`ceil(size / chunkSize)` when the manifest says
281
+ * its `chunkSize`). Returns the reason it was refused, or `null` when fine.
282
+ *
283
+ * @param {*} m
284
+ * @param {{ maxChunks: number, maxSize: number }} bounds - `Infinity` = unbounded
285
+ * @returns {string|null}
286
+ */
287
+ function remoteManifestProblem(m, { maxChunks, maxSize }) {
288
+ if (!isUsableManifest(m)) return 'malformed'
289
+ if (m.chunkCids.length > maxChunks) return 'too-many-chunks'
290
+ if (m.size > maxSize) return 'too-large'
291
+ for (const cid of m.chunkCids) {
292
+ if (!CID_RE.test(cid)) return 'bad-chunk-cid'
293
+ }
294
+ if (m.cid !== undefined && !(typeof m.cid === 'string' && CID_RE.test(m.cid))) return 'bad-cid'
295
+ if (m.name !== undefined && (typeof m.name !== 'string' || m.name.length > 1024)) return 'bad-name'
296
+ if (m.chunkSize !== undefined && !(Number.isSafeInteger(m.chunkSize) && m.chunkSize > 0)) return 'bad-chunk-size'
297
+ const expected = m.size === 0 ? 0 : (m.chunkSize !== undefined ? Math.ceil(m.size / m.chunkSize) : null)
298
+ if (expected !== null) {
299
+ if (m.chunkCids.length !== expected) return 'size-mismatch'
300
+ } else if (m.chunkCids.length < 1 || m.chunkCids.length > m.size) {
301
+ return 'size-mismatch'
302
+ }
303
+ return null
304
+ }
305
+
261
306
  function checkLimit(name, value) {
262
307
  if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {
263
308
  throw new TypeError(`createTorrentService: ${name} must be a non-negative number (0 or Infinity = unlimited), got ${String(value)}`)
264
309
  }
265
310
  }
266
311
 
312
+ /** A piece concurrency: a whole number from 1 to MAX_DOWNLOAD_CONCURRENCY. */
313
+ function checkConcurrency(name, value) {
314
+ if (!Number.isInteger(value) || value < 1 || value > MAX_DOWNLOAD_CONCURRENCY) {
315
+ throw new TypeError(`createTorrentService: ${name} must be a whole number from 1 to ${MAX_DOWNLOAD_CONCURRENCY}, got ${String(value)}`)
316
+ }
317
+ }
318
+
267
319
  /** Treat 0 as "no limit" for every cap option. */
268
320
  const orUnlimited = (n) => (n === 0 ? Infinity : n)
269
321
 
@@ -310,6 +362,22 @@ const orUnlimited = (n) => (n === 0 ? Infinity : n)
310
362
  * `announce`s accepted per peer per rolling minute; extras are dropped. `0` = unlimited.
311
363
  * @param {number} [opts.busyRetries=3] - Downloader: retries on one provider after `busy`.
312
364
  * @param {number} [opts.busyBackoffMs=250] - Downloader: first backoff after `busy` (grows linearly).
365
+ * @param {number} [opts.downloadConcurrency=4] - Default number of pieces
366
+ * `api.download()` fetches in parallel (a per-call `concurrency` overrides it).
367
+ * Whole numbers 1-32; `1` fetches strictly one piece at a time.
368
+ * @param {number} [opts.maxManifestChunks=16384] - Longest `chunkCids` list
369
+ * accepted in a manifest sent by another peer. Longer ones are ignored, as
370
+ * are manifests whose piece CIDs are not 64-hex SHA-256 digests or whose piece
371
+ * count does not match their declared size. `0` or `Infinity` = unlimited.
372
+ * @param {number} [opts.maxManifestSize=0] - Largest `size` (bytes) accepted in
373
+ * a manifest sent by another peer. `0` = unlimited.
374
+ * @param {number} [opts.maxRemoteManifests=64] - Manifests learned from other
375
+ * peers (via `announce` or a manifest request) that are remembered at once;
376
+ * the least recently used is forgotten, along with the providers recorded only
377
+ * for its pieces. `0` = unlimited.
378
+ * @param {Function|object} [opts.webtorrent] - Forwarded to `new TorrentManager()`:
379
+ * the WebTorrent constructor or client to use for real BitTorrent swarming.
380
+ * Nothing is ever loaded from a CDN. See `TorrentManager`.
313
381
  * @param {() => number} [opts.now] - Clock for rate limits (tests).
314
382
  * @param {(ms: number) => Promise<void>} [opts.sleep] - Sleep for rate limits/backoff (tests).
315
383
  * @returns {import('./mesh-service.mjs').MeshService}
@@ -330,6 +398,11 @@ export function createTorrentService({
330
398
  maxAnnouncesPerPeerPerMinute = DEFAULT_MAX_ANNOUNCES_PER_PEER_PER_MINUTE,
331
399
  busyRetries = DEFAULT_BUSY_RETRIES,
332
400
  busyBackoffMs = DEFAULT_BUSY_BACKOFF_MS,
401
+ downloadConcurrency = DEFAULT_DOWNLOAD_CONCURRENCY,
402
+ maxManifestChunks = DEFAULT_MAX_MANIFEST_CHUNKS,
403
+ maxManifestSize = 0,
404
+ maxRemoteManifests = DEFAULT_MAX_REMOTE_MANIFESTS,
405
+ webtorrent,
333
406
  now = Date.now,
334
407
  sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
335
408
  } = {}) {
@@ -338,9 +411,13 @@ export function createTorrentService({
338
411
  if (authorize !== undefined && typeof authorize !== 'function') {
339
412
  throw new TypeError('createTorrentService: authorize must be a function (fromPubKey, request) => boolean|Promise<boolean>')
340
413
  }
341
- for (const [n, v] of Object.entries({ maxConcurrentServes, maxConcurrentServesPerPeer, maxBytesPerPeerPerSec, maxAnnouncesPerPeerPerMinute })) {
414
+ for (const [n, v] of Object.entries({
415
+ maxConcurrentServes, maxConcurrentServesPerPeer, maxBytesPerPeerPerSec, maxAnnouncesPerPeerPerMinute,
416
+ maxManifestChunks, maxManifestSize, maxRemoteManifests,
417
+ })) {
342
418
  checkLimit(n, v)
343
419
  }
420
+ checkConcurrency('downloadConcurrency', downloadConcurrency)
344
421
  for (const [n, o] of [['chunkStore', injectedChunkStore], ['manifestStore', injectedManifestStore]]) {
345
422
  if (o !== undefined && (o === null || typeof o !== 'object')) {
346
423
  throw new TypeError(`createTorrentService: ${n} must be an object`)
@@ -359,6 +436,8 @@ export function createTorrentService({
359
436
  const globalServeCap = orUnlimited(maxConcurrentServes)
360
437
  const perPeerServeCap = orUnlimited(maxConcurrentServesPerPeer)
361
438
  const announceCap = orUnlimited(maxAnnouncesPerPeerPerMinute)
439
+ const manifestBounds = { maxChunks: orUnlimited(maxManifestChunks), maxSize: orUnlimited(maxManifestSize) }
440
+ const remoteCap = orUnlimited(maxRemoteManifests)
362
441
 
363
442
  return {
364
443
  name: 'torrent',
@@ -373,6 +452,7 @@ export function createTorrentService({
373
452
  chunkSize,
374
453
  chunkStore,
375
454
  manifestStore,
455
+ webtorrent,
376
456
  onLog: (level, msg) => log('mesh-torrent:internal', { level, msg }),
377
457
  })
378
458
 
@@ -383,16 +463,73 @@ export function createTorrentService({
383
463
  */
384
464
  const held = new Map()
385
465
 
386
- /** magnetURI -> manifest a peer announced or answered with, for content we do NOT hold. Memory only. */
466
+ /**
467
+ * magnetURI -> manifest a peer announced or answered with, for content we do NOT hold. Memory only.
468
+ * Bounded (`maxRemoteManifests`): Map insertion order is recency order, oldest first.
469
+ */
387
470
  const remoteManifests = new Map()
388
471
 
472
+ /** piece cid -> number of `remoteManifests` listing it, so providers recorded only for forgotten manifests can be dropped. */
473
+ const remoteCidRefs = new Map()
474
+
475
+ /** magnetURI -> number of in-flight downloads using that remote manifest; those are never evicted. */
476
+ const pinnedRemote = new Map()
477
+
389
478
  /** piece cid -> magnetURIs (in `held`) that list it: what a chunk-request may be served from. */
390
479
  const chunkIndex = new Map()
391
480
 
392
481
  /** @type {Map<string, Set<string>>} cid -> pubKeys known to currently hold that piece */
393
482
  const chunkOwners = new Map()
394
483
 
395
- const manifestFor = (magnetURI) => held.get(magnetURI) ?? remoteManifests.get(magnetURI)
484
+ function manifestFor(magnetURI) {
485
+ const mine = held.get(magnetURI)
486
+ if (mine) return mine
487
+ const remote = remoteManifests.get(magnetURI)
488
+ if (remote) {
489
+ // Use counts as recency: move it to the young end.
490
+ remoteManifests.delete(magnetURI)
491
+ remoteManifests.set(magnetURI, remote)
492
+ }
493
+ return remote
494
+ }
495
+
496
+ /** Forget a remote manifest, and the providers known only because of it. */
497
+ function dropRemote(magnetURI) {
498
+ const manifest = remoteManifests.get(magnetURI)
499
+ if (!manifest) return false
500
+ remoteManifests.delete(magnetURI)
501
+ for (const cid of new Set(manifest.chunkCids)) {
502
+ const left = (remoteCidRefs.get(cid) ?? 1) - 1
503
+ if (left > 0) {
504
+ remoteCidRefs.set(cid, left)
505
+ continue
506
+ }
507
+ remoteCidRefs.delete(cid)
508
+ if (!chunkIndex.has(cid)) chunkOwners.delete(cid)
509
+ }
510
+ return true
511
+ }
512
+
513
+ /** Remember a remote manifest, evicting the least recently used ones past `maxRemoteManifests`. */
514
+ function rememberRemote(magnetURI, manifest) {
515
+ dropRemote(magnetURI)
516
+ remoteManifests.set(magnetURI, manifest)
517
+ for (const cid of new Set(manifest.chunkCids)) remoteCidRefs.set(cid, (remoteCidRefs.get(cid) ?? 0) + 1)
518
+ if (remoteCap === Infinity) return
519
+ for (const key of [...remoteManifests.keys()]) {
520
+ if (remoteManifests.size <= remoteCap) break
521
+ if (key === magnetURI || pinnedRemote.has(key)) continue
522
+ dropRemote(key)
523
+ }
524
+ }
525
+
526
+ /** Vet a manifest another peer sent; log and return false when it is outside the configured bounds. */
527
+ function acceptableRemote(manifest, from, magnetURI) {
528
+ const problem = remoteManifestProblem(manifest, manifestBounds)
529
+ if (!problem) return true
530
+ log('mesh-torrent:remote-manifest-rejected', { from, magnetURI, reason: problem })
531
+ return false
532
+ }
396
533
 
397
534
  function indexHeld(magnetURI, manifest) {
398
535
  for (const cid of manifest.chunkCids) {
@@ -515,8 +652,8 @@ export function createTorrentService({
515
652
  log('mesh-torrent:announce-rate-limited', { from: fromPubKey })
516
653
  return
517
654
  }
518
- if (isUsableManifest(msg.manifest)) {
519
- if (!held.has(msg.magnetURI)) remoteManifests.set(msg.magnetURI, msg.manifest)
655
+ if (acceptableRemote(msg.manifest, fromPubKey, msg.magnetURI)) {
656
+ if (!held.has(msg.magnetURI)) rememberRemote(msg.magnetURI, msg.manifest)
520
657
  recordOwner(fromPubKey, msg.manifest.chunkCids)
521
658
  }
522
659
  ctx.emit('torrent:announce-received', {
@@ -546,10 +683,10 @@ export function createTorrentService({
546
683
  const pending = pendingManifestRequests.get(msg.requestId)
547
684
  if (!pending || !pending.targets.has(fromPubKey)) return
548
685
  pending.targets.delete(fromPubKey)
549
- if (isUsableManifest(msg.manifest)) {
686
+ if (acceptableRemote(msg.manifest, fromPubKey, pending.magnetURI)) {
550
687
  clearTimeout(pending.timer)
551
688
  pendingManifestRequests.delete(msg.requestId)
552
- if (!held.has(pending.magnetURI)) remoteManifests.set(pending.magnetURI, msg.manifest)
689
+ if (!held.has(pending.magnetURI)) rememberRemote(pending.magnetURI, msg.manifest)
553
690
  recordOwner(fromPubKey, msg.manifest.chunkCids)
554
691
  pending.resolve(msg.manifest)
555
692
  return
@@ -734,11 +871,12 @@ export function createTorrentService({
734
871
  * whichever known/candidate provider actually delivers it.
735
872
  * @param {string} cid
736
873
  * @param {string[]} [candidatePeers]
737
- * @returns {Promise<Uint8Array>}
874
+ * @returns {Promise<{ bytes: Uint8Array, from: string|null, written: boolean }>} `from` is
875
+ * null and `written` false when the piece was already in the local store.
738
876
  */
739
877
  async function fetchChunk(cid, candidatePeers) {
740
878
  const already = await chunkStore.get(cid)
741
- if (already) return already
879
+ if (already) return { bytes: already, from: null, written: false }
742
880
 
743
881
  const owners = new Set([...(chunkOwners.get(cid) || []), ...(candidatePeers || [])])
744
882
  owners.delete(peerNode.podId)
@@ -759,7 +897,7 @@ export function createTorrentService({
759
897
  await chunkStore.save(cid, bytes)
760
898
  recordOwner(pubKey, [cid])
761
899
  ctx.emit('torrent:chunk-received', { from: pubKey, cid, size: bytes.length })
762
- return bytes
900
+ return { bytes, from: pubKey, written: true }
763
901
  } catch (err) {
764
902
  lastErr = err
765
903
  if (err?.code === 'busy' && attempt < busyRetries) {
@@ -786,8 +924,8 @@ export function createTorrentService({
786
924
  const prior = held.get(magnetURI)
787
925
  if (prior) unindexHeld(magnetURI, prior)
788
926
  held.set(magnetURI, manifest)
789
- remoteManifests.delete(magnetURI)
790
927
  indexHeld(magnetURI, manifest)
928
+ dropRemote(magnetURI) // after indexHeld, so providers of pieces we now hold are kept
791
929
  await manifestStore.set(magnetURI, manifest)
792
930
  }
793
931
 
@@ -840,75 +978,188 @@ export function createTorrentService({
840
978
  })
841
979
  }
842
980
 
981
+ /** piece cid -> number of in-flight downloads that newly wrote it (cleanup must not delete a piece another download is still using) */
982
+ const inflightWrites = new Map()
983
+
843
984
  /**
844
985
  * Download content from the swarm: piece-by-piece, from whichever
845
986
  * peer(s) are known (via a prior `announce`, or `opts.peers`) to hold
846
987
  * each piece -- not necessarily the original seeder. See module doc
847
988
  * comment's "WHAT MAKES THIS A REAL SWARM" section.
989
+ *
990
+ * Between learning the manifest and requesting the first piece,
991
+ * `opts.onManifest` can veto the download (a storage-quota gate). Pieces
992
+ * are fetched `opts.concurrency` at a time (default `downloadConcurrency`,
993
+ * 4); `1` is strictly sequential. If the download fails after some pieces
994
+ * were stored, the ones this call wrote itself (and no held torrent lists)
995
+ * are removed again, so a quota-accounting host stays consistent.
996
+ *
848
997
  * @param {string} magnetURI
849
998
  * @param {object} [opts]
850
999
  * @param {string[]} [opts.peers] - Candidate peers to ask for the
851
1000
  * manifest (if not already known) and/or any piece with no other
852
1001
  * known provider.
1002
+ * @param {(manifest: { magnetURI: string, infoHash: string, name: string,
1003
+ * size: number, chunkSize?: number, chunkCids: string[], cid?: string }) => boolean|void|Promise<boolean|void>} [opts.onManifest]
1004
+ * Awaited once the manifest is known and before any piece is requested
1005
+ * or written. Return `false` (or throw/reject) to abort: the download
1006
+ * rejects, nothing is fetched. A `false` rejects with `code:
1007
+ * 'manifest-rejected'`; a throw propagates unchanged. Any other return
1008
+ * value lets the download proceed. The manifest is a copy; mutating it
1009
+ * changes nothing.
1010
+ * @param {(p: { received: number, total: number, bytes: number, size: number,
1011
+ * cid: string, from: string|null }) => void} [opts.onProgress] - Called
1012
+ * after each piece is in hand: `received` of `total` pieces, `bytes`
1013
+ * received so far of `size`; `from` is the provider's pubKey, or `null`
1014
+ * for a piece already in the local store. A throw here is logged, not fatal.
1015
+ * @param {number} [opts.concurrency] - Pieces fetched in parallel, a whole
1016
+ * number from 1 to 32. Defaults to the service's `downloadConcurrency`.
1017
+ * Each provider is still held to its own `busy` limits (see `busyRetries`).
853
1018
  * @returns {Promise<{data: Uint8Array, info: import('./peer-torrent.mjs').TorrentInfo}>}
854
1019
  */
855
1020
  async function download(magnetURI, opts = {}) {
1021
+ const { onManifest, onProgress, peers } = opts
1022
+ if (onManifest !== undefined && typeof onManifest !== 'function') {
1023
+ throw new TypeError('download: onManifest must be a function')
1024
+ }
1025
+ if (onProgress !== undefined && typeof onProgress !== 'function') {
1026
+ throw new TypeError('download: onProgress must be a function')
1027
+ }
1028
+ const concurrency = opts.concurrency ?? downloadConcurrency
1029
+ checkConcurrency('concurrency', concurrency)
1030
+
856
1031
  await ready
857
1032
  ctx.emit('torrent:download-start', { magnetURI })
858
1033
 
859
- const manifest = manifestFor(magnetURI) || await requestManifest(magnetURI, opts.peers)
1034
+ const manifest = manifestFor(magnetURI) || await requestManifest(magnetURI, peers)
860
1035
  if (!manifest) {
861
1036
  throw new Error(
862
1037
  `mesh-torrent: no manifest known for ${magnetURI} (no prior announce, and no peer responded -- supply opts.peers)`,
863
1038
  )
864
1039
  }
865
1040
 
866
- const pieces = []
867
- for (const cid of manifest.chunkCids) {
868
- pieces.push(await fetchChunk(cid, opts.peers))
869
- }
870
- const data = concatChunks(pieces)
871
- if (data.length !== manifest.size) {
872
- throw new Error(
873
- `mesh-torrent: reassembled ${data.length} bytes but manifest for ${magnetURI} declares size ${manifest.size}`,
874
- )
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`)
1041
+ // While this download runs its remote manifest must not be evicted by other announces.
1042
+ const pinned = remoteManifests.has(magnetURI)
1043
+ if (pinned) pinnedRemote.set(magnetURI, (pinnedRemote.get(magnetURI) ?? 0) + 1)
1044
+ /** pieces this call newly wrote */
1045
+ const written = new Set()
1046
+ let finished = false
1047
+ const settleWrites = async (keep) => {
1048
+ if (finished) return
1049
+ finished = true
1050
+ const removable = []
1051
+ for (const cid of written) {
1052
+ const left = (inflightWrites.get(cid) ?? 1) - 1
1053
+ if (left > 0) inflightWrites.set(cid, left)
1054
+ else {
1055
+ inflightWrites.delete(cid)
1056
+ if (!keep && !chunkIndex.has(cid)) removable.push(cid)
1057
+ }
1058
+ }
1059
+ if (pinned) {
1060
+ const n = (pinnedRemote.get(magnetURI) ?? 1) - 1
1061
+ if (n > 0) pinnedRemote.set(magnetURI, n)
1062
+ else pinnedRemote.delete(magnetURI)
1063
+ }
1064
+ await Promise.all(removable.map((cid) => Promise.resolve(chunkStore.remove(cid)).catch((err) => {
1065
+ log('mesh-torrent:cleanup-failed', { cid, error: err?.message || String(err) })
1066
+ })))
879
1067
  }
880
1068
 
881
- // Register this peer as a full holder via TorrentManager's own
882
- // seed() -- genuinely correct, not a hack: a peer with every piece
883
- // of a torrent IS, in real BitTorrent terms, now a seed for it, and
884
- // content-addressing makes this self-consistent -- tm.seed() on
885
- // these identical bytes deterministically reproduces the SAME
886
- // magnetURI/infoHash (same hash, same truncation), so this doesn't
887
- // create a second, different torrent identity for the same content.
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 })
894
- if (info.magnetURI !== magnetURI) {
895
- log('mesh-torrent:magnet-mismatch-after-reassembly', { expected: magnetURI, got: info.magnetURI })
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)
1069
+ try {
1070
+ if (onManifest) {
1071
+ const verdict = await onManifest({ ...manifest, magnetURI, chunkCids: [...manifest.chunkCids] })
1072
+ if (verdict === false) {
1073
+ const err = new Error(`mesh-torrent: download of ${magnetURI} refused by onManifest`)
1074
+ err.code = 'manifest-rejected'
1075
+ throw err
1076
+ }
1077
+ }
1078
+
1079
+ const cids = manifest.chunkCids
1080
+ const total = cids.length
1081
+ const pieces = new Array(total)
1082
+ let next = 0
1083
+ let received = 0
1084
+ let bytes = 0
1085
+ let failure = null
1086
+ const worker = async () => {
1087
+ while (failure === null) {
1088
+ const index = next++
1089
+ if (index >= total) return
1090
+ try {
1091
+ const got = await fetchChunk(cids[index], peers)
1092
+ if (got.written && !written.has(cids[index])) {
1093
+ written.add(cids[index])
1094
+ inflightWrites.set(cids[index], (inflightWrites.get(cids[index]) ?? 0) + 1)
1095
+ }
1096
+ pieces[index] = got.bytes
1097
+ received++
1098
+ bytes += got.bytes.length
1099
+ if (onProgress) {
1100
+ try {
1101
+ onProgress({ received, total, bytes, size: manifest.size, cid: cids[index], from: got.from })
1102
+ } catch (err) {
1103
+ log('mesh-torrent:progress-callback-error', { magnetURI, error: err?.message || String(err) })
1104
+ }
1105
+ }
1106
+ } catch (err) {
1107
+ failure ??= err
1108
+ return
1109
+ }
1110
+ }
1111
+ }
1112
+ await Promise.all(Array.from({ length: Math.min(concurrency, total) }, worker))
1113
+ if (failure) throw failure
1114
+
1115
+ const data = concatChunks(pieces)
1116
+ if (data.length !== manifest.size) {
1117
+ throw new Error(
1118
+ `mesh-torrent: reassembled ${data.length} bytes but manifest for ${magnetURI} declares size ${manifest.size}`,
1119
+ )
1120
+ }
1121
+ const contentCid = await ChunkStore.computeCid(data)
1122
+ if (typeof manifest.cid === 'string' && manifest.cid !== contentCid) {
1123
+ throw new Error(`mesh-torrent: reassembled content for ${magnetURI} does not match the manifest's cid`)
1124
+ }
1125
+
1126
+ // Register this peer as a full holder via TorrentManager's own
1127
+ // seed() -- genuinely correct, not a hack: a peer with every piece
1128
+ // of a torrent IS, in real BitTorrent terms, now a seed for it, and
1129
+ // content-addressing makes this self-consistent -- tm.seed() on
1130
+ // these identical bytes deterministically reproduces the SAME
1131
+ // magnetURI/infoHash (same hash, same truncation), so this doesn't
1132
+ // create a second, different torrent identity for the same content.
1133
+ // The pieces are re-cut at the size the manifest used (inferred from
1134
+ // its first piece when the announcing peer did not say), so they are
1135
+ // the ones already in the store and nothing is stored twice.
1136
+ const pieceSize = manifest.chunkSize
1137
+ ?? (pieces.length > 1 ? pieces[0].length : Math.max(data.length, 1))
1138
+ const info = await tm.seed(data, { name: manifest.name, chunkSize: pieceSize })
1139
+ if (info.magnetURI !== magnetURI) {
1140
+ log('mesh-torrent:magnet-mismatch-after-reassembly', { expected: magnetURI, got: info.magnetURI })
1141
+ }
1142
+ const stored = await tm.getManifest(info.magnetURI)
1143
+ await holdManifest(info.magnetURI, stored ?? {
1144
+ infoHash: info.infoHash, name: manifest.name, size: data.length, chunkSize: pieceSize,
1145
+ chunkCids: manifest.chunkCids, cid: contentCid,
1146
+ })
1147
+ if (info.magnetURI !== magnetURI) dropRemote(magnetURI)
903
1148
 
904
- ctx.emit('torrent:download-complete', { magnetURI, name: manifest.name, size: data.length })
905
- return { data, info }
1149
+ ctx.emit('torrent:download-complete', { magnetURI, name: manifest.name, size: data.length })
1150
+ await settleWrites(true)
1151
+ return { data, info }
1152
+ } catch (err) {
1153
+ await settleWrites(false)
1154
+ ctx.emit('torrent:download-failed', { magnetURI, error: err?.message || String(err) })
1155
+ throw err
1156
+ }
906
1157
  }
907
1158
 
908
1159
  /** Stop serving a torrent now; its stored manifest and unshared pieces are released in the background (`flush()` waits for that). */
909
1160
  function removeTorrent(magnetURI) {
910
1161
  const removedByTm = tm.removeTorrent(magnetURI)
911
- remoteManifests.delete(magnetURI)
1162
+ dropRemote(magnetURI)
912
1163
  const manifest = held.get(magnetURI)
913
1164
  if (!manifest) return removedByTm
914
1165
  held.delete(magnetURI)
@@ -928,6 +1179,8 @@ export function createTorrentService({
928
1179
  if (!injectedManifestStore && typeof manifestStore.clear === 'function') await manifestStore.clear()
929
1180
  held.clear()
930
1181
  remoteManifests.clear()
1182
+ remoteCidRefs.clear()
1183
+ pinnedRemote.clear()
931
1184
  chunkIndex.clear()
932
1185
  chunkOwners.clear()
933
1186
  }