@torrent-tv/proxy 2.107.51 → 2.107.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Cross-request measurements owned by one live viewing. A viewer is the key,
3
+ * rather than its reusable wire id, so a later viewing with the same id starts
4
+ * with fresh measurements.
5
+ */
6
+ export class ViewerPlaybackState {
7
+ #byViewer = new Map();
8
+ #waitOrder = new Map();
9
+
10
+ #stateFor(viewer, create = false) {
11
+ if (!viewer || typeof viewer !== "object") return null;
12
+ let state = this.#byViewer.get(viewer);
13
+ if (!state && create) {
14
+ state = { ratesByOutput: new Map(), waits: new Map() };
15
+ this.#byViewer.set(viewer, state);
16
+ }
17
+ return state ?? null;
18
+ }
19
+
20
+ rateState(viewer, output, playbackReadiness, lookaheadSeconds) {
21
+ const owner = this.#stateFor(viewer, true);
22
+ let state = owner.ratesByOutput.get(output);
23
+ if (!state) {
24
+ state = { link: new playbackReadiness.RateTrend(lookaheadSeconds), sources: new Map() };
25
+ owner.ratesByOutput.set(output, state);
26
+ }
27
+ return state;
28
+ }
29
+
30
+ owns(viewer, output, state) {
31
+ return this.#stateFor(viewer)?.ratesByOutput.get(output) === state;
32
+ }
33
+
34
+ forgetOutput(output) {
35
+ for (const [viewer, owner] of this.#byViewer) {
36
+ owner.ratesByOutput.delete(output);
37
+ this.#deleteIfEmpty(viewer, owner);
38
+ }
39
+ }
40
+
41
+ forgetViewerOutput(viewer, output) {
42
+ const owner = this.#stateFor(viewer);
43
+ if (!owner) return false;
44
+ const removed = owner.ratesByOutput.delete(output);
45
+ this.#deleteIfEmpty(viewer, owner);
46
+ return removed;
47
+ }
48
+
49
+ addLinkReading(state, at, mbps) {
50
+ state.link.add(at, mbps * 1_000_000);
51
+ }
52
+
53
+ sourceRateReadings(state, id, stats, now, playbackReadiness, lookaheadSeconds) {
54
+ let source = state.sources.get(id);
55
+ if (!source) {
56
+ const { RateTrend, SessionRate } = playbackReadiness;
57
+ source = { delivered: new RateTrend(lookaheadSeconds), free: new RateTrend(lookaheadSeconds),
58
+ deliveredAll: new SessionRate(), freeAll: new SessionRate(), limit: null };
59
+ state.sources.set(id, source);
60
+ }
61
+ if (Number.isFinite(stats?.downloadSpeed) && stats.downloadSpeed >= 0) {
62
+ source.delivered.add(now, stats.downloadSpeed);
63
+ source.deliveredAll.add(now, stats.downloadSpeed);
64
+ }
65
+ const limit = stats?.selectionLimit;
66
+ if (limit && source.limit && limit.freeMs > source.limit.freeMs) {
67
+ const free = Math.max(0, limit.freeBytes - source.limit.freeBytes) * 1000 / (limit.freeMs - source.limit.freeMs);
68
+ source.free.add(now, free);
69
+ source.freeAll.add(now, free);
70
+ }
71
+ if (limit) source.limit = limit;
72
+ return sourceService(source.free.snapshot(), source.delivered.snapshot(),
73
+ summary => playbackReadiness.forecastRate(summary, now, 0, "time"));
74
+ }
75
+
76
+ sourceTailRateReadings(state, id, now, playbackReadiness) {
77
+ const source = state.sources.get(id);
78
+ if (!source) return null;
79
+ return sourceService(source.freeAll.snapshot(), source.deliveredAll.snapshot(),
80
+ summary => playbackReadiness.forecastRate(summary, now, 0, "time"));
81
+ }
82
+
83
+ sourceRateSummaries(state, id) {
84
+ const source = state.sources.get(id);
85
+ return source ? { free: source.free.snapshot(), delivered: source.delivered.snapshot() } : null;
86
+ }
87
+
88
+ getWait(viewer, waitId) {
89
+ return this.#stateFor(viewer)?.waits.get(waitId) ?? null;
90
+ }
91
+
92
+ hasWait(viewer, waitId) {
93
+ return this.#stateFor(viewer)?.waits.has(waitId) ?? false;
94
+ }
95
+
96
+ recordWaitSnapshot({ viewer, consumerId, generation, sourceKey, fileIndex, waitId, features }) {
97
+ const owner = this.#stateFor(viewer, true);
98
+ const current = owner.waits.get(waitId);
99
+ const context = current?.waitId === waitId ? current : {
100
+ consumerId, generation, sourceKey, fileIndex, waitId, snapshots: [], observedWaits: new Set()
101
+ };
102
+ const measuredAt = performance.now();
103
+ const ageElapsedMs = Number.isFinite(context.featuresMeasuredAt)
104
+ ? Math.max(0, measuredAt - context.featuresMeasuredAt) : 0;
105
+ const mergedFeatures = mergeWaitFeatures(context.features, features, ageElapsedMs);
106
+ Object.assign(context, { consumerId, generation, sourceKey, fileIndex, waitId, features: mergedFeatures,
107
+ featuresMeasuredAt: measuredAt, updatedAt: Date.now() });
108
+ const previous = context.snapshots.at(-1);
109
+ if (!previous || JSON.stringify(previous) !== JSON.stringify(mergedFeatures)) {
110
+ const snapshot = { ...mergedFeatures };
111
+ if (context.snapshots.length < 2) context.snapshots.push(snapshot);
112
+ else context.snapshots[1] = snapshot;
113
+ }
114
+ owner.waits.set(waitId, context);
115
+ if (!this.#waitOrder.has(context)) this.#waitOrder.set(context, { viewer, waitId });
116
+ return context;
117
+ }
118
+
119
+ noteFirstFrame({ viewer, generation, waitId, wait, elapsedMs, stages, record }) {
120
+ const observation = this.getWait(viewer, waitId);
121
+ if (!observation || observation.generation !== generation || !Number.isSafeInteger(wait) || wait < 0 ||
122
+ observation.observedWaits.has(wait) || !Number.isFinite(elapsedMs) || elapsedMs < 0) return false;
123
+ const initialFeatures = observation.snapshots[0];
124
+ if (initialFeatures) record({ seconds: elapsedMs / 1000, features: initialFeatures,
125
+ featureSnapshots: observation.snapshots.slice(1), stages });
126
+ observation.observedWaits.add(wait);
127
+ observation.updatedAt = Date.now();
128
+ return true;
129
+ }
130
+
131
+ deleteWait(viewer, waitId) {
132
+ const owner = this.#stateFor(viewer);
133
+ if (!owner) return false;
134
+ const context = owner.waits.get(waitId);
135
+ const removed = owner.waits.delete(waitId);
136
+ if (context) this.#waitOrder.delete(context);
137
+ this.#deleteIfEmpty(viewer, owner);
138
+ return removed;
139
+ }
140
+
141
+ pruneWaits(now = Date.now(), maxObservations = 1000) {
142
+ const cutoff = now - 30 * 60_000;
143
+ for (const [viewer, owner] of this.#byViewer) {
144
+ for (const [waitId, value] of owner.waits) {
145
+ if (value.updatedAt < cutoff) {
146
+ owner.waits.delete(waitId);
147
+ this.#waitOrder.delete(value);
148
+ }
149
+ }
150
+ if (owner) this.#deleteIfEmpty(viewer, owner);
151
+ }
152
+ while (this.#waitOrder.size > maxObservations) {
153
+ const [context, { viewer, waitId }] = this.#waitOrder.entries().next().value;
154
+ const owner = this.#stateFor(viewer);
155
+ owner?.waits.delete(waitId);
156
+ this.#waitOrder.delete(context);
157
+ if (owner) this.#deleteIfEmpty(viewer, owner);
158
+ }
159
+ }
160
+
161
+ forgetViewer(viewer) {
162
+ const owner = this.#stateFor(viewer);
163
+ if (!owner) return false;
164
+ for (const context of owner.waits.values()) this.#waitOrder.delete(context);
165
+ return this.#byViewer.delete(viewer);
166
+ }
167
+
168
+ viewerCount() {
169
+ return this.#byViewer.size;
170
+ }
171
+
172
+ waitCount(viewer) {
173
+ return this.#stateFor(viewer)?.waits.size ?? 0;
174
+ }
175
+
176
+ #deleteIfEmpty(viewer, owner) {
177
+ if (owner.ratesByOutput.size === 0 && owner.waits.size === 0) this.#byViewer.delete(viewer);
178
+ }
179
+ }
180
+
181
+ export function sourceService(free, delivered, rateOf) {
182
+ if (!free) return delivered;
183
+ if (!delivered) return free;
184
+ return (rateOf(delivered) ?? 0) > (rateOf(free) ?? 0) ? delivered : free;
185
+ }
186
+
187
+ function mergeWaitFeatures(previous, incoming, ageElapsedMs) {
188
+ const merged = { ...(previous ?? {}) };
189
+ for (const [key, value] of Object.entries(incoming ?? {})) {
190
+ if (value === null || value === undefined) {
191
+ if (!Object.hasOwn(merged, key)) merged[key] = null;
192
+ continue;
193
+ }
194
+ if (key === "extension") {
195
+ if (typeof value === "string" && value.length > 0) merged[key] = value;
196
+ continue;
197
+ }
198
+ if (key === "fileAvailable") {
199
+ if (typeof value === "boolean") merged[key] = value;
200
+ continue;
201
+ }
202
+ if (key === "videoOperation" || key === "audioOperation") {
203
+ if (value === "copy" || value === "encode") merged[key] = value;
204
+ continue;
205
+ }
206
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 ||
207
+ ((key === "fileLength" || key === "linkMbps") && value === 0)) continue;
208
+ merged[key] = value;
209
+ }
210
+ const hasIncomingAge = Number.isFinite(incoming?.linkSampleAgeMs) && incoming.linkSampleAgeMs >= 0;
211
+ if (Number.isFinite(merged.linkSampleAgeMs) && !hasIncomingAge) {
212
+ merged.linkSampleAgeMs += Number.isFinite(ageElapsedMs) ? Math.max(0, ageElapsedMs) : 0;
213
+ }
214
+ return merged;
215
+ }
@@ -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
- }