@torrent-tv/proxy 2.107.51 → 2.107.52

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.107.51",
3
+ "version": "2.107.52",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -0,0 +1,155 @@
1
+ /**
2
+ * @file Decide when a second copy of a late missing block is useful.
3
+ *
4
+ * WebTorrent normally owns picking, queues and request reassignment. This
5
+ * exception is bounded to the currently required urgent pieces, a tail of at
6
+ * most 16 missing blocks, requests older than one wire queue, and two copies
7
+ * per block. The injected adapter is the only place that touches WebTorrent's
8
+ * private piece/reservation/request state.
9
+ */
10
+
11
+ /** `PIPELINE_MAX_DURATION`: WebTorrent sizes each wire queue to one second. */
12
+ const WIRE_QUEUE_MS = 1000;
13
+ const SHORT_TAIL_BLOCKS = 16;
14
+ const MAX_COPIES = 2;
15
+
16
+ export class TailRepeat {
17
+ #requiredPieces;
18
+ #adapter;
19
+ #schedule;
20
+ #wake;
21
+ #clear;
22
+ #scheduled = false;
23
+ #timer = null;
24
+ #timerAt = Number.POSITIVE_INFINITY;
25
+ #disposed = false;
26
+ #unwatch;
27
+ #log;
28
+ #now;
29
+ #reportedUnavailable = false;
30
+
31
+ /**
32
+ * @param {object} params
33
+ * @param {() => Array<{ from: number, to: number }>} params.requiredPieces
34
+ * @param {{ observe: Function, repeatBlock: Function, watch: Function }} params.adapter
35
+ * @param {(work: () => void) => void} [params.schedule]
36
+ * @param {(work: () => void, ms: number) => unknown} [params.wake]
37
+ * @param {(handle: unknown) => void} [params.clear]
38
+ * @param {(line: string) => void} [params.log]
39
+ * @param {() => number} [params.now]
40
+ */
41
+ constructor({ requiredPieces, adapter, schedule = setImmediate, wake = setTimeout, clear = clearTimeout, log = null, now = Date.now }) {
42
+ this.#requiredPieces = requiredPieces;
43
+ this.#adapter = adapter;
44
+ this.#schedule = schedule;
45
+ this.#wake = wake;
46
+ this.#clear = clear;
47
+ this.#log = log;
48
+ this.#now = now;
49
+ this.totals = { duplicated: 0, looks: 0, lateBlocks: 0 };
50
+ try {
51
+ this.#unwatch = adapter.watch(() => this.poke(), () => { this.totals.lateBlocks += 1; });
52
+ } catch {
53
+ this.#reportUnavailable();
54
+ this.#unwatch = null;
55
+ }
56
+ }
57
+
58
+ /** Look at the tails once this turn of the event loop is over. */
59
+ poke() {
60
+ if (this.#scheduled || this.#disposed) return;
61
+ this.#scheduled = true;
62
+ this.#schedule(() => this.#look());
63
+ }
64
+
65
+ /** Stop watching and cancel the one armed age check. */
66
+ dispose() {
67
+ this.#disposed = true;
68
+ this.#unwatch?.();
69
+ this.#unwatch = null;
70
+ if (this.#timer !== null) this.#clear(this.#timer);
71
+ this.#timer = null;
72
+ }
73
+
74
+ #lookAgainAt(at, now) {
75
+ if (!Number.isFinite(at) || at >= this.#timerAt || this.#disposed) return;
76
+ if (this.#timer !== null) this.#clear(this.#timer);
77
+ this.#timerAt = at;
78
+ this.#timer = this.#wake(() => {
79
+ this.#timer = null;
80
+ this.#timerAt = Number.POSITIVE_INFINITY;
81
+ this.poke();
82
+ }, Math.max(0, at - now));
83
+ this.#timer?.unref?.();
84
+ }
85
+
86
+ #look() {
87
+ this.#scheduled = false;
88
+ if (this.#disposed) return;
89
+ this.totals.looks += 1;
90
+ const now = this.#now();
91
+ let dueAt = Number.POSITIVE_INFINITY;
92
+ let unplaced = 0;
93
+ const asked = [];
94
+
95
+ for (const { from, to } of this.#requiredPieces()) {
96
+ for (let pieceIndex = from; pieceIndex <= to; pieceIndex += 1) {
97
+ if (this.#disposed) return;
98
+ let observation;
99
+ try {
100
+ observation = this.#adapter.observe(pieceIndex, SHORT_TAIL_BLOCKS);
101
+ } catch {
102
+ this.#reportUnavailable();
103
+ continue;
104
+ }
105
+ if (!observation?.available) {
106
+ this.#reportUnavailable();
107
+ continue;
108
+ }
109
+ if (observation.missingCount === 0 || observation.missingCount > SHORT_TAIL_BLOCKS) continue;
110
+
111
+ let pieceCopies = 0;
112
+ for (const block of observation.blocks) {
113
+ if (block.copies === 0 || block.copies >= MAX_COPIES) continue;
114
+ const firstAskedAt = block.firstAskedAt ?? Number.NEGATIVE_INFINITY;
115
+ if (now - firstAskedAt < WIRE_QUEUE_MS) {
116
+ dueAt = Math.min(dueAt, firstAskedAt + WIRE_QUEUE_MS);
117
+ continue;
118
+ }
119
+ let result;
120
+ try {
121
+ result = this.#adapter.repeatBlock(pieceIndex, block.index);
122
+ } catch {
123
+ this.#reportUnavailable();
124
+ continue;
125
+ }
126
+ if (result === "unavailable") {
127
+ this.#reportUnavailable();
128
+ continue;
129
+ }
130
+ if (result === "placed") {
131
+ pieceCopies += 1;
132
+ this.totals.duplicated += 1;
133
+ } else {
134
+ unplaced += 1;
135
+ }
136
+ }
137
+ if (pieceCopies > 0) asked.push(`${pieceIndex}:${pieceCopies}/${observation.missingCount}`);
138
+ }
139
+ }
140
+
141
+ if (asked.length > 0) {
142
+ this.#log?.(`tail: asked a second peer for the last blocks of piece:blocks/missing ${asked.join(" ")}; ` +
143
+ `${this.totals.duplicated} block copies asked so far, ${this.totals.lateBlocks} block(s) arrived after their piece was complete`);
144
+ }
145
+ if (unplaced > 0) dueAt = Math.min(dueAt, now + WIRE_QUEUE_MS);
146
+ this.#lookAgainAt(dueAt, now);
147
+ }
148
+
149
+ #reportUnavailable() {
150
+ if (this.#reportedUnavailable) return;
151
+ this.#reportedUnavailable = true;
152
+ this.#adapter.disable?.();
153
+ this.#log?.("tail: bounded repeat unavailable; using WebTorrent's ordinary picker");
154
+ }
155
+ }
@@ -25,14 +25,15 @@ import { deadlineOfMapZone, levelOfMapZone, priorityOfMapZone } from "./map-zone
25
25
  import { deriveSourceKey } from "../../utils/torrent-source-key.js";
26
26
  import { noteTorrentDestroyed } from "./destroyed-torrents.js";
27
27
  import { PieceTimings, describePieceTiming } from "./piece-timing.js";
28
- import { TailRepeat } from "./worker/tail-repeat.js";
28
+ import { TailRepeat } from "./download/TailRepeat.js";
29
+ import { WebTorrentTailRepeatAdapter } from "./worker/WebTorrentTailRepeatAdapter.js";
29
30
  import { tracePieceStorePut } from "./worker/trace-piece-store-put.js";
30
31
  import { beginSwarmLifecycleTrace, noteSwarmDiscovery, noteSwarmMetadata, noteSwarmPeer } from "./worker/trace-swarm-lifecycle.js";
31
32
 
32
33
  /**
33
34
  * The second-peer requests for the last blocks of a piece somebody waits for,
34
35
  * one per torrent, made when the torrent is first watched and stopped when it
35
- * is forgotten (`worker/tail-repeat.js`).
36
+ * is forgotten (`download/TailRepeat.js`).
36
37
  *
37
38
  * @type {WeakMap<object, TailRepeat>}
38
39
  */
@@ -1901,7 +1902,8 @@ export class TorrentPool {
1901
1902
  // per piece: a 2.3 GB film is 563.
1902
1903
  const timings = new PieceTimings();
1903
1904
  const waitTracePieceStarts = new Map();
1904
- tailRepeats.set(torrent, new TailRepeat({ torrent, requiredPieces: () => demandFor(torrent).selection.requiredPieces(),
1905
+ tailRepeats.set(torrent, new TailRepeat({ adapter: new WebTorrentTailRepeatAdapter(torrent),
1906
+ requiredPieces: () => demandFor(torrent).selection.requiredPieces(),
1905
1907
  log: (line) => logger.info(`download ${label()} ${line}`) }));
1906
1908
  torrent.on("wire", (wire) => {
1907
1909
  // WebTorrent asks a wire for a block by calling `request` and states
@@ -1922,7 +1924,7 @@ export class TorrentPool {
1922
1924
  trace("W8", "begin", { piece: index, startedAt, firstOffset: offset, blockLength: length });
1923
1925
  }
1924
1926
  // When this wire was asked for the block: how long it has held it is
1925
- // what decides whether a second peer is asked (`duplicateTailFor`).
1927
+ // what decides whether a second peer is asked (download/TailRepeat).
1926
1928
  this.requests.at(-1).askedAt = now;
1927
1929
  }
1928
1930
  return answer;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * @file The narrow WebTorrent 2.8.5 adapter used by torrent/download/TailRepeat.
3
+ *
4
+ * This is the only live caller allowed to inspect piece buffers and wire
5
+ * queues, or to touch Piece.cancel/reserve and Torrent._request for bounded
6
+ * late-tail repetition. Keep library-private assumptions here and update the
7
+ * compatibility check when the pinned WebTorrent/torrent-piece pair changes.
8
+ */
9
+
10
+ const BLOCK_BYTES = 1 << 14;
11
+
12
+ function speedOf(wire) {
13
+ try {
14
+ const speed = wire?.downloadSpeed?.();
15
+ return Number.isFinite(speed) ? speed : 0;
16
+ } catch {
17
+ return 0;
18
+ }
19
+ }
20
+
21
+ function usableWires(torrent, pieceIndex) {
22
+ const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
23
+ return wires.filter((wire) => {
24
+ // WebTorrent's _request uses reserveRemaining/chunkLengthRemaining for a
25
+ // webseed, which requests the piece suffix rather than one bounded block.
26
+ if (!wire || wire.type === "webSeed" || wire.destroyed || wire.peerChoking) return false;
27
+ try {
28
+ return wire.peerPieces?.get?.(pieceIndex) === true;
29
+ } catch {
30
+ return false;
31
+ }
32
+ }).sort((left, right) => speedOf(right) - speedOf(left));
33
+ }
34
+
35
+ function requestCoversBlock(request, pieceIndex, blockIndex, chunks) {
36
+ if (request?.piece !== pieceIndex || !Number.isFinite(request.offset) || request.offset < 0) return false;
37
+ const firstBlock = Math.floor(request.offset / BLOCK_BYTES);
38
+ // A request without a length is an incompatible observation. Count it
39
+ // conservatively through the piece's end rather than allowing extra copies.
40
+ const lastBlock = Number.isFinite(request.length) && request.length > 0
41
+ ? Math.min(chunks - 1, Math.ceil((request.offset + request.length) / BLOCK_BYTES) - 1)
42
+ : chunks - 1;
43
+ return blockIndex >= firstBlock && blockIndex <= lastBlock;
44
+ }
45
+
46
+ /**
47
+ * Adapts a live WebTorrent Torrent to the small observation/action contract
48
+ * needed by TailRepeat. It does not choose which piece or block to repeat.
49
+ */
50
+ export class WebTorrentTailRepeatAdapter {
51
+ #torrent;
52
+ #disabled = false;
53
+
54
+ /** @param {object} torrent A WebTorrent Torrent instance. */
55
+ constructor(torrent) {
56
+ this.#torrent = torrent;
57
+ }
58
+
59
+ /** Disable the exception after an incompatible private API is observed. */
60
+ disable() {
61
+ this.#disabled = true;
62
+ }
63
+
64
+ /**
65
+ * Read missing blocks and their in-flight copy count/age.
66
+ *
67
+ * @param {number} pieceIndex
68
+ * @param {number} maxMissing Upper bound supplied by the download policy; a
69
+ * larger tail is reported by count without allocating a per-block list.
70
+ * @returns {{ available: boolean, missingCount: number, blocks: Array<{ index: number, copies: number, firstAskedAt: number|null }> }}
71
+ */
72
+ observe(pieceIndex, maxMissing) {
73
+ const torrent = this.#torrent;
74
+ const piece = torrent?.pieces?.[pieceIndex];
75
+ // Completed pieces are removed from Torrent.pieces; a piece with no
76
+ // allocated block buffer has no request in flight, so neither is a tail.
77
+ if (!piece) return { available: true, missingCount: 0, blocks: [] };
78
+ const buffer = Array.isArray(piece?._buffer) ? piece._buffer : null;
79
+ if (!buffer) return { available: true, missingCount: 0, blocks: [] };
80
+ if (this.#disabled || typeof piece.cancel !== "function" || typeof torrent?._request !== "function") {
81
+ this.#disabled = true;
82
+ return { available: false, missingCount: 0, blocks: [] };
83
+ }
84
+
85
+ const chunks = Number.isFinite(piece._chunks) ? piece._chunks : buffer.length;
86
+ let missingCount = Number.isFinite(piece._buffered) ? chunks - piece._buffered : 0;
87
+ if (!Number.isFinite(piece._buffered)) {
88
+ for (let index = 0; index < chunks; index += 1) if (!buffer[index]) missingCount += 1;
89
+ }
90
+ if (missingCount === 0 || missingCount > maxMissing) {
91
+ return { available: true, missingCount, blocks: [] };
92
+ }
93
+
94
+ const blocks = [];
95
+ for (let index = 0; index < chunks; index += 1) {
96
+ if (buffer[index]) continue;
97
+ blocks.push({ index, copies: 0, firstAskedAt: null });
98
+ }
99
+ for (const wire of Array.isArray(torrent.wires) ? torrent.wires : []) {
100
+ for (const request of Array.isArray(wire?.requests) ? wire.requests : []) {
101
+ for (const block of blocks) {
102
+ if (!requestCoversBlock(request, pieceIndex, block.index, chunks)) continue;
103
+ block.copies += 1;
104
+ const askedAt = Number.isFinite(request.askedAt) ? request.askedAt : Number.NEGATIVE_INFINITY;
105
+ block.firstAskedAt = block.firstAskedAt === null ? askedAt : Math.min(block.firstAskedAt, askedAt);
106
+ }
107
+ }
108
+ }
109
+ return { available: true, missingCount, blocks };
110
+ }
111
+
112
+ /**
113
+ * Try one repeat for an already-selected, already-aged missing block.
114
+ * Returns a status instead of throwing so an incompatible private API cannot
115
+ * stop ordinary downloading. Every refusal restores the reservation.
116
+ *
117
+ * @param {number} pieceIndex
118
+ * @param {number} blockIndex
119
+ * @returns {"placed"|"refused"|"unavailable"}
120
+ */
121
+ repeatBlock(pieceIndex, blockIndex) {
122
+ const torrent = this.#torrent;
123
+ const piece = torrent?.pieces?.[pieceIndex];
124
+ const buffer = Array.isArray(piece?._buffer) ? piece._buffer : null;
125
+ if (this.#disabled || !piece || !buffer || buffer[blockIndex] || typeof piece.cancel !== "function" ||
126
+ typeof piece.reserve !== "function" || typeof torrent?._request !== "function") {
127
+ return "unavailable";
128
+ }
129
+
130
+ const candidates = usableWires(torrent, pieceIndex);
131
+ const chunks = Number.isFinite(piece._chunks) ? piece._chunks : buffer.length;
132
+ if (candidates.length === 0) return "refused";
133
+
134
+ for (const wire of candidates) {
135
+ if ((wire.requests ?? []).some((request) => requestCoversBlock(request, pieceIndex, blockIndex, chunks))) continue;
136
+
137
+ try {
138
+ piece.cancel(blockIndex);
139
+ } catch {
140
+ this.#disabled = true;
141
+ return "unavailable";
142
+ }
143
+
144
+ let placed = false;
145
+ try {
146
+ // false prevents WebTorrent's hotswap from freeing a third reservation.
147
+ placed = torrent._request(wire, pieceIndex, false) === true;
148
+ } catch {
149
+ // A thrown private call may have queued the request before failing.
150
+ placed = (wire.requests ?? []).some((request) => request?.piece === pieceIndex &&
151
+ Math.floor(request.offset / BLOCK_BYTES) === blockIndex);
152
+ if (!placed) {
153
+ try {
154
+ if (piece.reserve() !== blockIndex) this.#disabled = true;
155
+ } catch { this.#disabled = true; }
156
+ }
157
+ this.#disabled = true;
158
+ return placed ? "placed" : "unavailable";
159
+ }
160
+ if (placed) return "placed";
161
+
162
+ // _request refused before reserving. Claim the freed block back so the
163
+ // normal picker cannot see an unaccounted reservation.
164
+ try {
165
+ if (piece.reserve() !== blockIndex) {
166
+ this.#disabled = true;
167
+ return "unavailable";
168
+ }
169
+ } catch {
170
+ this.#disabled = true;
171
+ return "unavailable";
172
+ }
173
+ }
174
+ return "refused";
175
+ }
176
+
177
+ /** Subscribe to changes that can alter tail observations. */
178
+ watch(onChange, onLateBlock = () => {}) {
179
+ const torrent = this.#torrent;
180
+ const watched = new Map();
181
+ const poke = () => onChange();
182
+ const forget = (wire) => {
183
+ const listeners = watched.get(wire);
184
+ if (!listeners) return;
185
+ wire.removeListener?.("piece", listeners.onBlock);
186
+ for (const event of ["unchoke", "have", "bitfield"]) wire.removeListener?.(event, listeners.onPeer);
187
+ wire.removeListener?.("close", listeners.onClose);
188
+ watched.delete(wire);
189
+ };
190
+ const watchWire = (wire) => {
191
+ if (!wire || watched.has(wire) || typeof wire.on !== "function") return;
192
+ const listeners = {
193
+ onBlock: (index) => {
194
+ if (Number.isInteger(index) && torrent.bitfield?.get?.(index)) onLateBlock();
195
+ poke();
196
+ },
197
+ onPeer: poke,
198
+ onClose: () => { forget(wire); poke(); }
199
+ };
200
+ watched.set(wire, listeners);
201
+ wire.on("piece", listeners.onBlock);
202
+ for (const event of ["unchoke", "have", "bitfield"]) wire.on(event, listeners.onPeer);
203
+ wire.once?.("close", listeners.onClose);
204
+ poke();
205
+ };
206
+ const onWire = watchWire;
207
+ torrent.on?.("wire", onWire);
208
+ torrent.on?.("verified", poke);
209
+ for (const wire of Array.isArray(torrent.wires) ? torrent.wires : []) watchWire(wire);
210
+ return () => {
211
+ torrent.removeListener?.("wire", onWire);
212
+ torrent.removeListener?.("verified", poke);
213
+ for (const wire of [...watched.keys()]) forget(wire);
214
+ };
215
+ }
216
+ }
@@ -1,398 +0,0 @@
1
- /**
2
- * @file Put the piece a reader is blocked on onto the fastest wires that hold
3
- * it.
4
- *
5
- * Measured 2026-08-17: the swarm delivered 5.1-5.9 MB/s against a film consumed
6
- * at about 1 MB/s — a fivefold surplus — and the reader still blocked 47 times
7
- * in two minutes, 1.0-4.5 s each. So the shortage is not bandwidth. The piece
8
- * that blocked had been requested from a median of five peers, and what set the
9
- * tail was WHICH wire held the last outstanding block: a block is reserved for
10
- * exactly one wire, and the read finishes when the slowest holder delivers.
11
- *
12
- * What the library already does, and what it does not: `torrent.critical()`
13
- * (which the reader already sets over its window) enables HOTSWAP — an idle
14
- * wire may take a block away from the SLOWEST holder. It does not duplicate:
15
- * `piece.reserve()` returns -1 once every block is spoken for, and the
16
- * end-game that would ask a second peer for the same block is commented out in
17
- * `webtorrent/lib/torrent.js`. Hotswap therefore fires only when the library's
18
- * own picker happens to visit an idle wire while our piece is critical.
19
- *
20
- * This asks for it on purpose, and chooses who: the wires that are unchoked,
21
- * hold the piece and are measurably fastest are handed the piece through the
22
- * same entry the library's picker uses, with hotswap enabled. Nothing is
23
- * duplicated and no protocol rule is bent — the block moves to a faster holder
24
- * instead of staying with whoever got it first.
25
- */
26
-
27
- /**
28
- * How short a piece's remaining tail must be for a second copy of it to be
29
- * worth asking for.
30
- *
31
- * Sixteen blocks is 256 KB against the 4-16 MB piece they hold up. The figure
32
- * comes from what was measured rather than chosen for roundness: the tails a
33
- * blocked reader waits on were 2 to 14 blocks of 512 on 2026-08-19, and 3 of
34
- * 512 in the field failure of 2026-09-03 that took 46.3 s. Above this the piece
35
- * is still arriving normally and duplicating would spend the shared link on
36
- * bytes already on their way.
37
- */
38
- const SHORT_TAIL_BLOCKS = 16;
39
-
40
- /** A block of a piece, as `torrent-piece` cuts it (`Piece.BLOCK_LENGTH`): a request's offset over this is its block. */
41
- const BLOCK_BYTES = 1 << 14;
42
-
43
- /**
44
- * The library's own request entry. Internal, so its absence must be noticed
45
- * rather than swallowed: without it this lever silently does nothing.
46
- *
47
- * @param {object} torrent
48
- * @returns {boolean}
49
- */
50
- export function canPlaceRequests(torrent) {
51
- return typeof torrent?._request === "function";
52
- }
53
-
54
- /**
55
- * Wires that could deliver this piece right now, fastest first.
56
- *
57
- * Excluded, each for its own reason: a wire that is choking us cannot be asked
58
- * at all; one that does not hold the piece has nothing to give; a destroyed one
59
- * is a corpse. Speed is the library's own measurement over its own window, so
60
- * nothing here needs a history of its own.
61
- *
62
- * @param {object} torrent
63
- * @param {number} pieceIndex
64
- * @returns {object[]}
65
- */
66
- export function wiresForPiece(torrent, pieceIndex) {
67
- const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
68
- const usable = [];
69
- for (const wire of wires) {
70
- if (!wire || wire.destroyed || wire.peerChoking) {
71
- continue;
72
- }
73
- if (wire.peerPieces?.get?.(pieceIndex) !== true) {
74
- continue;
75
- }
76
- usable.push(wire);
77
- }
78
- return usable.sort((left, right) => speedOf(right) - speedOf(left));
79
- }
80
-
81
- /**
82
- * A wire's measured download speed in bytes per second, or 0 when it has not
83
- * been measured. Wrapped because `downloadSpeed` is a method on the wire and a
84
- * throw from a destroyed one must not take the caller with it.
85
- *
86
- * @param {object} wire
87
- * @returns {number}
88
- */
89
- function speedOf(wire) {
90
- try {
91
- const speed = wire?.downloadSpeed?.();
92
- return Number.isFinite(speed) ? speed : 0;
93
- } catch {
94
- // A wire that cannot say how fast it is ranks last, which is the honest
95
- // answer — and the caller's own log line reports how many were asked.
96
- return 0;
97
- }
98
- }
99
-
100
- /**
101
- * Ask the fastest holders of `pieceIndex` for it.
102
- *
103
- * @param {object} torrent
104
- * @param {number} pieceIndex
105
- * @param {number} [limit] - How many wires to push it onto.
106
- * @returns {{ asked: number, refusedWhileReserved: number, attempted: number, considered: number, fastestBytesPerSecond: number }}
107
- * `asked` counts requests the library actually placed: it refuses when a
108
- * wire's pipeline is full or when nothing can be reserved even with hotswap,
109
- * and that refusal is information — a piece nobody can be asked for is
110
- * waiting on the wire, not on the picker.
111
- */
112
- export function askFastestWiresFor(torrent, pieceIndex, limit = 3) {
113
- if (!canPlaceRequests(torrent) || !Number.isInteger(pieceIndex) || pieceIndex < 0) {
114
- return { asked: 0, refusedWhileReserved: 0, attempted: 0, considered: 0, fastestBytesPerSecond: 0 };
115
- }
116
- const candidates = wiresForPiece(torrent, pieceIndex);
117
- let asked = 0;
118
- let refusedWhileReserved = 0;
119
- for (const wire of candidates.slice(0, Math.max(1, limit))) {
120
- try {
121
- // `true` is hotswap: if every block is reserved, take one from the
122
- // slowest holder. That is the whole point — the reader is blocked
123
- // precisely because a slow holder has one.
124
- if (torrent._request(wire, pieceIndex, true) === true) {
125
- asked += 1;
126
- } else {
127
- // Refused. Two reasons and they are different: this wire's pipeline is
128
- // full, or every block of the piece is reserved and displacement did
129
- // not happen. The second is the interesting one, because the thresholds
130
- // that decide it are constants inside the library and not settings — a
131
- // holder at 50 KB/s is just above the 48 KB/s line and is never
132
- // displaced, however long the piece has been waited for. This counter
133
- // is what would justify replacing `_hotswap` on the torrent, and
134
- // without it that would be a change made on a hunch.
135
- if (pieceIsFullyReserved(torrent, pieceIndex)) {
136
- refusedWhileReserved += 1;
137
- }
138
- }
139
- } catch (error) {
140
- // Internal call: report it once per attempt rather than letting the lever
141
- // fail in silence.
142
- throw new Error(`could not place a request for piece ${pieceIndex}: ${error?.message ?? error}`);
143
- }
144
- }
145
- return {
146
- asked,
147
- refusedWhileReserved,
148
- considered: candidates.length,
149
- // How many of the asks the library placed, against how many it was asked
150
- // for. The caller sums these over the whole wait, and summing `asked`
151
- // against a `considered` taken from the LAST attempt is how the field log
152
- // came to read "steered onto 12 of 6 holders" — a ratio of two different
153
- // things. Both halves are returned per attempt so the caller can add each
154
- // to its own total.
155
- attempted: Math.min(candidates.length, Math.max(1, limit)),
156
- fastestBytesPerSecond: candidates.length > 0 ? speedOf(candidates[0]) : 0
157
- };
158
- }
159
-
160
- /**
161
- * What is actually holding up a piece the reader is blocked on.
162
- *
163
- * The steering above can only move a block that the library will hand over, and
164
- * the field says it often hands over nothing: `steered onto 0 of 9 asks (8
165
- * peers held it)`, recorded 2026-08-18 while eight peers had the piece. When
166
- * every block of a piece is already reserved, `Piece.reserve()` answers -1 and
167
- * there is no request left to place — the read then ends when the SLOWEST
168
- * holder delivers its block, however fast the rest of the swarm is.
169
- *
170
- * Duplicating those last blocks onto faster wires is the standard remedy, and
171
- * it is not free: every duplicate is a block's worth of traffic paid twice. So
172
- * this describes the tail before anything is built with it — how many blocks
173
- * are still missing, and on which wires they sit, with each wire's speed. If
174
- * the missing blocks turn out to sit on one slow wire, duplication is aimed at
175
- * exactly the right thing; if they are spread across fast ones, the wait has
176
- * another cause and this work should not be done at all.
177
- *
178
- * Reads only: nothing here changes a reservation or places a request.
179
- *
180
- * @param {import("webtorrent").Torrent} torrent
181
- * @param {number} pieceIndex
182
- * @returns {{ chunks: number, missing: number,
183
- * outstanding: Array<{ blocks: number, bytesPerSecond: number, choking: boolean }> } | null}
184
- * Null only when the piece object is gone — it completed and was cleared.
185
- * A piece nobody has reserved a block of yet is NOT null: `torrent-piece`
186
- * creates its buffer lazily on the first reserve, so a piece the picker has
187
- * not reached reads as every block missing and nothing outstanding, which is
188
- * the most informative answer this can give — the wait is not on a slow
189
- * holder, it is on nobody having been asked.
190
- */
191
- export function describePieceTail(torrent, pieceIndex) {
192
- const piece = torrent?.pieces?.[pieceIndex];
193
- if (!piece) {
194
- return null;
195
- }
196
- const buffer = Array.isArray(piece._buffer) ? piece._buffer : null;
197
- const chunks = Number.isFinite(piece._chunks)
198
- ? piece._chunks
199
- : (buffer ? buffer.length : 0);
200
- // No buffer means no block of this piece has been reserved yet, so all of it
201
- // is missing. Reading that as "no tail" hid the case worth seeing most.
202
- let missing = chunks;
203
- if (buffer) {
204
- missing = 0;
205
- for (let index = 0; index < chunks; index += 1) {
206
- if (!buffer[index]) {
207
- missing += 1;
208
- }
209
- }
210
- }
211
-
212
- const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
213
- const outstanding = [];
214
- for (const wire of wires) {
215
- const requests = Array.isArray(wire?.requests) ? wire.requests : [];
216
- const blocks = requests.filter((request) => request?.piece === pieceIndex).length;
217
- if (blocks > 0) {
218
- outstanding.push({
219
- blocks,
220
- bytesPerSecond: speedOf(wire),
221
- choking: wire?.peerChoking === true
222
- });
223
- }
224
- }
225
- // Slowest first: that is the wire the read is waiting on, and the one a
226
- // duplicate would be aimed past.
227
- outstanding.sort((left, right) => left.bytesPerSecond - right.bytesPerSecond);
228
- return { chunks, missing, outstanding };
229
- }
230
-
231
- /**
232
- * Ask a second wire for blocks the reader is still waiting on.
233
- *
234
- * WebTorrent reserves each block for exactly one wire, so once `Piece.reserve()`
235
- * answers -1 there is no request left to place and the read ends when the
236
- * holder of the last block delivers it — however fast the rest of the swarm is.
237
- * The library's own remedy is `_hotswap`, and it does precisely the right
238
- * thing: `piece.cancel(blockIndex)` frees the reservation while leaving the
239
- * first wire's request in flight, so a second wire can be asked for the same
240
- * block and whichever arrives first wins. What it will not do is apply that to
241
- * these tails. It is gated on speed — the held-up wire must be under 48 KB/s
242
- * (`3 * BLOCK_LENGTH`) and at least twice as slow as the asker — and measured
243
- * on a real swarm 2026-08-19, the tails a reader waits on sit at 109, 317 and
244
- * 870 KB/s. Peers the library rightly considers good, because for bulk
245
- * downloading they are; the gate is about throughput across a torrent and knows
246
- * nothing about a reader blocked on one piece now.
247
- *
248
- * Speed is not even what is wrong with them: two blocks — 32 KB — on a wire
249
- * measured at 109 KB/s is 0.3 s of transfer, and that read waited 4.6 s. The
250
- * blocks are not travelling slowly, they are queued behind that wire's other
251
- * work, which no average speed can show.
252
- *
253
- * The cost is bounded by the same measurement: the tails were 2 to 14 blocks of
254
- * 512, so 32 to 224 KB against the 8 MiB piece they hold up. A block already in
255
- * flight on `maxCopies` wires is not asked again, however often this is called:
256
- * it is called on every block that arrives (`TailRepeat`), and without that
257
- * check each call asked one more copy of the same block.
258
- *
259
- * Safe against the completion path: a block that arrives twice is dropped by
260
- * `Piece.set`, which writes only into an empty slot, and a piece already
261
- * flushed answers `false` from `Piece.init` so the second arrival returns
262
- * before `flush()` is reached.
263
- *
264
- * @param {object} torrent
265
- * @param {number} pieceIndex
266
- * @param {object} [options]
267
- * A BLOCK IS ASKED AGAIN ONLY ONCE IT IS LATE. A short tail is not by itself a
268
- * delay: copied as soon as the tail was short, 12-16 blocks of nearly every
269
- * piece were asked twice and 82 of 215 copies arrived after their piece was
270
- * complete (r41, Home Assistant, torrent-tv/meta#178). So a block is asked of a
271
- * second peer once its request to the first has been out `minAgeMs` — by
272
- * default the second WebTorrent sizes a wire's queue to fill
273
- * (`PIPELINE_MAX_DURATION`), a starting point to be checked in the field — and
274
- * the earliest moment a held block becomes late is returned, so whoever calls
275
- * this can look again then.
276
- *
277
- * @param {object} torrent
278
- * @param {number} pieceIndex
279
- * @param {object} [options]
280
- * @param {number} [options.maxCopies] - How many wires a missing block may be
281
- * in flight on at once: the first request and one copy beside it.
282
- * @param {number} [options.minAgeMs] - How long the first request must have been out.
283
- * @param {number} [options.now] - Wall clock, ms.
284
- * @returns {{ duplicated: number, missing: number, wires: number, unplaced: number, dueAt: number | null }}
285
- * `duplicated` counts requests the library actually placed for a block that
286
- * was already outstanding elsewhere; `unplaced` the late blocks in flight on
287
- * one wire alone that no other wire could be asked for now; `dueAt` when the
288
- * first block held by one wire and not yet late becomes late, or null.
289
- */
290
- export function duplicateTailFor(torrent, pieceIndex, { maxCopies = 2, minAgeMs = 1000, now = Date.now() } = {}) {
291
- const piece = torrent?.pieces?.[pieceIndex];
292
- const buffer = Array.isArray(piece?._buffer) ? piece._buffer : null;
293
- if (!piece || !buffer || typeof piece.cancel !== "function" || !canPlaceRequests(torrent)) {
294
- return { duplicated: 0, missing: 0, wires: 0, unplaced: 0, dueAt: null };
295
- }
296
- const chunks = Number.isFinite(piece._chunks) ? piece._chunks : buffer.length;
297
- // Most calls are for a piece still arriving in bulk; its own count says so
298
- // without walking its blocks or every wire's queue.
299
- if (Number.isFinite(piece._buffered) && chunks - piece._buffered > SHORT_TAIL_BLOCKS) {
300
- return { duplicated: 0, missing: chunks - piece._buffered, wires: 0, unplaced: 0, dueAt: null };
301
- }
302
-
303
- const missing = [];
304
- for (let index = 0; index < chunks; index += 1) {
305
- if (!buffer[index]) {
306
- missing.push(index);
307
- }
308
- }
309
- const candidates = wiresForPiece(torrent, pieceIndex);
310
- if (missing.length === 0 || candidates.length === 0) {
311
- return { duplicated: 0, missing: missing.length, wires: candidates.length, unplaced: 0, dueAt: null };
312
- }
313
-
314
- // A tail this short is what a blocked read is actually waiting on, and a
315
- // second copy of it costs a few dozen kilobytes. A longer one is a piece
316
- // still arriving normally, where duplicating would spend the shared link on
317
- // bytes that are already coming — measured 2026-08-19, the tails a reader
318
- // waits on are 2 to 14 blocks of 512.
319
- if (missing.length > SHORT_TAIL_BLOCKS) {
320
- return { duplicated: 0, missing: missing.length, wires: candidates.length, unplaced: 0, dueAt: null };
321
- }
322
-
323
- // Which wires each missing block is in flight on, and since when, read from
324
- // the wires' own queues: the library keeps a block's reservation for one
325
- // wire only, and a copy asked here is visible nowhere else. A request with no
326
- // time of its own was asked before anybody watched, and is old.
327
- const holders = new Map(missing.map(block => [block, { wires: new Set(), since: Number.POSITIVE_INFINITY }]));
328
- for (const wire of Array.isArray(torrent.wires) ? torrent.wires : []) {
329
- for (const request of Array.isArray(wire?.requests) ? wire.requests : []) {
330
- if (request?.piece !== pieceIndex) continue;
331
- const holding = holders.get(Math.floor(request.offset / BLOCK_BYTES));
332
- if (!holding) continue;
333
- holding.wires.add(wire);
334
- holding.since = Math.min(holding.since, Number.isFinite(request.askedAt) ? request.askedAt : Number.NEGATIVE_INFINITY);
335
- }
336
- }
337
-
338
- let duplicated = 0, unplaced = 0, dueAt = null;
339
- for (const block of missing) {
340
- const { wires: held, since } = holders.get(block);
341
- // Not in flight anywhere: the library's own picker asks for it; a block
342
- // nobody has been asked for is not a tail held by a slow peer.
343
- if (held.size === 0 || held.size >= maxCopies) continue;
344
- if (now - since < minAgeMs) {
345
- dueAt = Math.min(dueAt ?? Number.POSITIVE_INFINITY, since + minAgeMs);
346
- continue;
347
- }
348
- let placed = false;
349
- for (const wire of candidates) {
350
- if (held.has(wire)) continue;
351
- // Freeing the reservation is what makes the block askable again; the
352
- // request already in flight is deliberately left alone, because the
353
- // point is to have two of them.
354
- piece.cancel(block);
355
- // `false` is hotswap: the library's own swap must not run on top of
356
- // this, or it would free a THIRD wire's block as well.
357
- if (torrent._request(wire, pieceIndex, false) === true) {
358
- held.add(wire);
359
- duplicated += 1;
360
- placed = true;
361
- break;
362
- }
363
- // Refused before anything was reserved (that wire's pipeline is full):
364
- // the freed block is taken back, or the library would hand it to the
365
- // next wire that asks, a copy nobody counted. The next wire's pipeline
366
- // is its own, so it is still asked.
367
- piece.reserve();
368
- }
369
- if (!placed) unplaced += 1;
370
- }
371
- return { duplicated, missing: missing.length, wires: candidates.length, unplaced, dueAt };
372
- }
373
-
374
- /**
375
- * Whether every block of a piece is spoken for by some wire.
376
- *
377
- * The condition under which the library refuses a request and only displacement
378
- * could change the answer. Read from the piece's own reservation state, which
379
- * is what `_request` consults.
380
- *
381
- * @param {object} torrent
382
- * @param {number} pieceIndex
383
- * @returns {boolean}
384
- */
385
- function pieceIsFullyReserved(torrent, pieceIndex) {
386
- const piece = torrent?.pieces?.[pieceIndex];
387
- if (!piece || typeof piece.reserve !== "function") {
388
- return false;
389
- }
390
- const reservation = piece.reserve();
391
- if (reservation === -1) {
392
- return true;
393
- }
394
- // Taken only to ask the question; give it straight back, or this reader has
395
- // quietly claimed a block nobody will ever deliver.
396
- piece.cancel?.(reservation);
397
- return false;
398
- }
@@ -1,171 +0,0 @@
1
- /**
2
- * @file Ask a second peer for the last blocks of a piece somebody is waiting
3
- * for, when one slow peer holds them (torrent-tv/meta#178).
4
- *
5
- * Field r40 (Home Assistant, 2026-10-14, a cold 1080p MKV): the first run's
6
- * input waited 10.0 s, last for piece 8, whose slowest block was 4.5 s in
7
- * flight from one peer; pieces 14-16 waited 10.0-11.5 s on one peer each. A
8
- * block is reserved for one wire, and the piece completes when its slowest
9
- * holder delivers (`duplicateTailFor`). Nothing had asked a second peer since
10
- * the blocked-read path that did so was removed (`0e38ec3`, torrent-tv/meta#95).
11
- *
12
- * Which pieces: those of the urgent first class the swarm was last told
13
- * (`SwarmSelection.requiredPieces`) — what somebody waits for now. A map that
14
- * withdraws them, or an input that is ready, takes them out, and nothing more
15
- * is asked for them.
16
- *
17
- * When: a tail changes when a block arrives, a wire's queue moves on, or a
18
- * peer becomes able or unable to give the piece; so it is looked at on those —
19
- * a block arriving, a wire unchoking, a peer stating a piece, a wire joining
20
- * or closing, a piece verified, a new map. Several in one turn of the event
21
- * loop are one look. A block is asked again only once its request has been out
22
- * a wire's queue time (`duplicateTailFor`), so a block not yet late is looked
23
- * at again when it becomes late, and a late one no other wire could take is
24
- * looked at again a queue time later — once, in case nothing else happens in
25
- * between. WebTorrent sizes a wire's queue to one second of its speed
26
- * (`PIPELINE_MAX_DURATION`).
27
- */
28
-
29
- import { duplicateTailFor } from "./fastest-wires.js";
30
-
31
- /** WebTorrent's `PIPELINE_MAX_DURATION`: a wire is given one second of its speed to fetch. */
32
- const WIRE_QUEUE_SECONDS = 1;
33
-
34
- /** What a wire says, besides a block arriving, that can change who could be asked for a piece. */
35
- const WIRE_EVENTS = ["unchoke", "have", "bitfield"];
36
-
37
- export class TailRepeat {
38
- #torrent;
39
- #requiredPieces;
40
- #duplicate;
41
- #schedule;
42
- #wake;
43
- #clear;
44
- #scheduled = false;
45
- #timer = null;
46
- /** When the armed look runs, wall clock ms. */
47
- #timerAt = Number.POSITIVE_INFINITY;
48
- #disposed = false;
49
- /** @type {Map<object, { onBlock: (index: number) => void, onPeer: () => void }>} */
50
- #wires = new Map();
51
- #onWire;
52
- #onPoke;
53
- #log;
54
- #now;
55
- /**
56
- * Grow-only, for the log: block copies asked, looks taken, and blocks that
57
- * arrived after their piece was complete — what the copies cost.
58
- */
59
- totals = { duplicated: 0, looks: 0, lateBlocks: 0 };
60
-
61
- /**
62
- * @param {object} params
63
- * @param {object} params.torrent
64
- * @param {() => Array<{ from: number, to: number }>} params.requiredPieces
65
- * @param {typeof duplicateTailFor} [params.duplicate]
66
- * @param {(work: () => void) => void} [params.schedule] - Runs work once this turn of the event loop is over.
67
- * @param {(work: () => void, ms: number) => unknown} [params.wake]
68
- * @param {(handle: unknown) => void} [params.clear]
69
- * @param {(line: string) => void} [params.log]
70
- * @param {() => number} [params.now]
71
- */
72
- constructor({ torrent, requiredPieces, duplicate = duplicateTailFor, schedule = setImmediate, wake = setTimeout, clear = clearTimeout, log = null, now = Date.now }) {
73
- this.#log = log;
74
- this.#now = now;
75
- this.#torrent = torrent;
76
- this.#requiredPieces = requiredPieces;
77
- this.#duplicate = duplicate;
78
- this.#schedule = schedule;
79
- this.#wake = wake;
80
- this.#clear = clear;
81
- this.#onWire = (wire) => this.#watch(wire);
82
- this.#onPoke = () => this.poke();
83
- torrent.on?.("wire", this.#onWire);
84
- torrent.on?.("verified", this.#onPoke);
85
- for (const wire of Array.isArray(torrent.wires) ? torrent.wires : []) this.#watch(wire);
86
- }
87
-
88
- /** Look at the tails once this turn of the event loop is over. */
89
- poke() {
90
- if (this.#scheduled || this.#disposed) return;
91
- this.#scheduled = true;
92
- this.#schedule(() => this.#look());
93
- }
94
-
95
- /** Stop watching: the torrent is going. */
96
- dispose() {
97
- this.#disposed = true;
98
- this.#torrent.removeListener?.("wire", this.#onWire);
99
- this.#torrent.removeListener?.("verified", this.#onPoke);
100
- for (const wire of [...this.#wires.keys()]) this.#forget(wire);
101
- if (this.#timer !== null) this.#clear(this.#timer);
102
- this.#timer = null;
103
- }
104
-
105
- /** One look armed at a time, at the earliest moment asked for. */
106
- #lookAgainAt(at, now) {
107
- if (!Number.isFinite(at) || at >= this.#timerAt) return;
108
- if (this.#timer !== null) this.#clear(this.#timer);
109
- this.#timerAt = at;
110
- this.#timer = this.#wake(() => {
111
- this.#timer = null;
112
- this.#timerAt = Number.POSITIVE_INFINITY;
113
- this.poke();
114
- }, Math.max(0, at - now));
115
- this.#timer?.unref?.();
116
- }
117
-
118
- #watch(wire) {
119
- if (!wire || this.#wires.has(wire) || typeof wire.on !== "function") return;
120
- const listeners = {
121
- onBlock: (index) => {
122
- // A block of a piece already verified is a copy that came second; the
123
- // block that completes a piece arrives before the piece is verified.
124
- if (Number.isInteger(index) && this.#torrent.bitfield?.get?.(index)) this.totals.lateBlocks += 1;
125
- this.poke();
126
- },
127
- onPeer: () => this.poke()
128
- };
129
- this.#wires.set(wire, listeners);
130
- wire.on("piece", listeners.onBlock);
131
- for (const event of WIRE_EVENTS) wire.on(event, listeners.onPeer);
132
- wire.once?.("close", () => {
133
- this.#forget(wire);
134
- this.poke();
135
- });
136
- this.poke();
137
- }
138
-
139
- #forget(wire) {
140
- const listeners = this.#wires.get(wire);
141
- if (!listeners) return;
142
- wire.removeListener?.("piece", listeners.onBlock);
143
- for (const event of WIRE_EVENTS) wire.removeListener?.(event, listeners.onPeer);
144
- this.#wires.delete(wire);
145
- }
146
-
147
- #look() {
148
- this.#scheduled = false;
149
- if (this.#disposed) return;
150
- this.totals.looks += 1;
151
- const now = this.#now();
152
- let unplaced = 0, dueAt = Number.POSITIVE_INFINITY;
153
- const asked = [];
154
- for (const { from, to } of this.#requiredPieces()) {
155
- for (let index = from; index <= to; index += 1) {
156
- if (this.#torrent.bitfield?.get?.(index)) continue;
157
- const result = this.#duplicate(this.#torrent, index, { minAgeMs: WIRE_QUEUE_SECONDS * 1000, now });
158
- this.totals.duplicated += result.duplicated;
159
- unplaced += result.unplaced;
160
- if (Number.isFinite(result.dueAt)) dueAt = Math.min(dueAt, result.dueAt);
161
- if (result.duplicated > 0) asked.push(`${index}:${result.duplicated}/${result.missing}`);
162
- }
163
- }
164
- if (asked.length > 0) {
165
- this.#log?.(`tail: asked a second peer for the last blocks of piece:blocks/missing ${asked.join(" ")}; ` +
166
- `${this.totals.duplicated} block copies asked so far, ${this.totals.lateBlocks} block(s) arrived after their piece was complete`);
167
- }
168
- if (unplaced > 0) dueAt = Math.min(dueAt, now + WIRE_QUEUE_SECONDS * 1000);
169
- this.#lookAgainAt(dueAt, now);
170
- }
171
- }