@torrent-tv/proxy 2.107.62 → 2.107.63
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 +1 -1
- package/services/encode/EncodeInputs.js +3 -10
- package/services/encode/OutputWaitLedger.js +3 -1
- package/services/encode/PauseRule.js +3 -7
- package/services/encode/available-share.js +2 -10
- package/services/encode/learned-median.js +3 -38
- package/services/encode/quality/HostLoad.js +5 -4
- package/services/encode/run-costs.js +5 -22
- package/services/media/SubtitleCues.js +2 -1
- package/services/server/ViewerRequests.js +2 -1
- package/services/server/wire-outputs.js +3 -2
- package/services/storage/Diagnostics.js +1 -7
- package/services/storage/MachineBudget.js +10 -6
- package/services/storage/machine-processor.js +1 -10
- package/services/storage/memory-report.js +17 -26
- package/services/storage/piece-store/shared-piece-store.js +6 -7
- package/services/storage/processor-report.js +2 -7
- package/services/storage/returns.js +3 -2
- package/services/storage/segment-store/SegmentStore.js +2 -1
- package/services/torrent/supply-margin.js +3 -11
- package/services/torrent/torrent-pool.js +4 -3
- package/services/torrent/worker/piece-reader.js +2 -5
- package/services/torrent/worker/worker.js +12 -11
- package/utils/clamp.js +11 -0
- package/utils/median.js +66 -0
- package/utils/units.js +35 -0
package/package.json
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { medianOf } from "../../utils/median.js";
|
|
1
2
|
import { admitInput } from "./AdmittedInput.js";
|
|
2
3
|
import { admitOriginalInput, originalInputBytes } from "./OriginalInput.js";
|
|
3
4
|
import { OriginalInputStore } from "./OriginalInputStore.js";
|
|
@@ -9,14 +10,6 @@ import { OriginalInputStore } from "./OriginalInputStore.js";
|
|
|
9
10
|
*/
|
|
10
11
|
const RECENT_READINGS = 20;
|
|
11
12
|
|
|
12
|
-
/** @param {number[]} values @returns {number | null} */
|
|
13
|
-
function middleOf(values) {
|
|
14
|
-
if (values.length === 0) return null;
|
|
15
|
-
const sorted = [...values].sort((left, right) => left - right);
|
|
16
|
-
const middle = Math.floor(sorted.length / 2);
|
|
17
|
-
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
18
|
-
}
|
|
19
|
-
|
|
20
13
|
/** @param {number[]} readings @param {number} value */
|
|
21
14
|
function keep(readings, value) {
|
|
22
15
|
readings.push(value);
|
|
@@ -373,7 +366,7 @@ export class EncodeInputs {
|
|
|
373
366
|
}
|
|
374
367
|
|
|
375
368
|
#sizingFor(output) {
|
|
376
|
-
const rate =
|
|
369
|
+
const rate = medianOf(this.#copyRates);
|
|
377
370
|
const open = this.#openOf(output);
|
|
378
371
|
return rate === null || !open ? null : { bytes: Math.floor(rate * open.seconds * 1000),
|
|
379
372
|
openMeasured: open.measured, openSeconds: open.seconds, copyBytesPerMs: rate };
|
|
@@ -388,7 +381,7 @@ export class EncodeInputs {
|
|
|
388
381
|
*/
|
|
389
382
|
stretchTerms() {
|
|
390
383
|
const capacity = this.#capacity();
|
|
391
|
-
return { copyBytesPerMs:
|
|
384
|
+
return { copyBytesPerMs: medianOf(this.#copyRates), capacityBytes: Number.isFinite(capacity) ? capacity : null };
|
|
392
385
|
}
|
|
393
386
|
|
|
394
387
|
/**
|
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
* given a rank and a number of milliseconds.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
+
import { medianOf } from "../../utils/median.js";
|
|
25
|
+
|
|
24
26
|
/** How many waits to keep per rank. A median wants a sample, not a history. */
|
|
25
27
|
const HISTORY = 200;
|
|
26
28
|
|
|
@@ -136,7 +138,7 @@ export class WaitLedger {
|
|
|
136
138
|
continue;
|
|
137
139
|
}
|
|
138
140
|
const sorted = [...held].sort((a, b) => a - b);
|
|
139
|
-
const median =
|
|
141
|
+
const median = medianOf(held);
|
|
140
142
|
parts.push(
|
|
141
143
|
`${band} ${counts.get(band) ?? held.length} wait(s) median ${Math.round(median)}ms ` +
|
|
142
144
|
`worst ${Math.round(sorted[sorted.length - 1])}ms`
|
|
@@ -49,6 +49,8 @@
|
|
|
49
49
|
* `L` waited for its input say nothing about `r` and are left out.
|
|
50
50
|
*/
|
|
51
51
|
|
|
52
|
+
import { medianOf, scatterOf } from "../../utils/median.js";
|
|
53
|
+
|
|
52
54
|
/**
|
|
53
55
|
* How many seconds of readings a run keeps. Enough for a baseline before a try
|
|
54
56
|
* and the seconds beside after it; `L`'s cost changes from piece to piece, so
|
|
@@ -354,11 +356,5 @@ function changeOf(remembered, { band, otherRunning, others, draw }) {
|
|
|
354
356
|
* @returns {{ middle: number, scatter: number }}
|
|
355
357
|
*/
|
|
356
358
|
function middleAndScatter(values) {
|
|
357
|
-
|
|
358
|
-
const sorted = [...list].sort((left, right) => left - right);
|
|
359
|
-
const half = Math.floor(sorted.length / 2);
|
|
360
|
-
return sorted.length % 2 === 0 ? (sorted[half - 1] + sorted[half]) / 2 : sorted[half];
|
|
361
|
-
};
|
|
362
|
-
const middle = median(values);
|
|
363
|
-
return { middle, scatter: median(values.map((value) => Math.abs(value - middle))) };
|
|
359
|
+
return { middle: medianOf(values), scatter: scatterOf(values) };
|
|
364
360
|
}
|
|
@@ -56,6 +56,8 @@
|
|
|
56
56
|
* nothing changes.
|
|
57
57
|
*/
|
|
58
58
|
|
|
59
|
+
import { clamp } from "../../utils/clamp.js";
|
|
60
|
+
|
|
59
61
|
/**
|
|
60
62
|
* The share of the machine available to a new encoder.
|
|
61
63
|
*
|
|
@@ -147,13 +149,3 @@ export function correctForAvailability(predictedSpeed, availability) {
|
|
|
147
149
|
function finite(value) {
|
|
148
150
|
return Number.isFinite(value) ? Number(value) : null;
|
|
149
151
|
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* @param {number} value
|
|
153
|
-
* @param {number} low
|
|
154
|
-
* @param {number} high
|
|
155
|
-
* @returns {number}
|
|
156
|
-
*/
|
|
157
|
-
function clamp(value, low, high) {
|
|
158
|
-
return Math.min(high, Math.max(low, value));
|
|
159
|
-
}
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
* but it is answered from the measurements rather than from a constant.
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
+
import { scatterOf } from "../../utils/median.js";
|
|
21
|
+
|
|
20
22
|
/**
|
|
21
23
|
* How many of the most recent readings the median is taken over.
|
|
22
24
|
*
|
|
@@ -28,44 +30,7 @@
|
|
|
28
30
|
*/
|
|
29
31
|
export const READINGS_KEPT = 7;
|
|
30
32
|
|
|
31
|
-
|
|
32
|
-
* The middle of a set of readings, or null when there are none.
|
|
33
|
-
*
|
|
34
|
-
* @param {number[]} values
|
|
35
|
-
* @returns {number | null}
|
|
36
|
-
*/
|
|
37
|
-
export function medianOf(values) {
|
|
38
|
-
const usable = (Array.isArray(values) ? values : []).filter((value) => Number.isFinite(value));
|
|
39
|
-
if (usable.length === 0) {
|
|
40
|
-
return null;
|
|
41
|
-
}
|
|
42
|
-
const sorted = [...usable].sort((left, right) => left - right);
|
|
43
|
-
const middle = Math.floor(sorted.length / 2);
|
|
44
|
-
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* How far the readings sit from their own middle — the median of their
|
|
49
|
-
* distances to it.
|
|
50
|
-
*
|
|
51
|
-
* The median distance rather than the mean one, for the same reason the value
|
|
52
|
-
* itself is a median: a single disturbed reading describes the disturbance, not
|
|
53
|
-
* the host.
|
|
54
|
-
*
|
|
55
|
-
* @param {number[]} values
|
|
56
|
-
* @returns {number | null} Null when there is nothing to measure. Zero is a
|
|
57
|
-
* real answer: readings that all agree disagree by nothing.
|
|
58
|
-
*/
|
|
59
|
-
export function scatterOf(values) {
|
|
60
|
-
const middle = medianOf(values);
|
|
61
|
-
if (middle === null) {
|
|
62
|
-
return null;
|
|
63
|
-
}
|
|
64
|
-
const distances = (Array.isArray(values) ? values : [])
|
|
65
|
-
.filter((value) => Number.isFinite(value))
|
|
66
|
-
.map((value) => Math.abs(value - middle));
|
|
67
|
-
return medianOf(distances);
|
|
68
|
-
}
|
|
33
|
+
export { medianOf, scatterOf } from "../../utils/median.js";
|
|
69
34
|
|
|
70
35
|
/**
|
|
71
36
|
* Whether a newly computed median should replace the published one.
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import os from "node:os";
|
|
11
11
|
import { monitorEventLoopDelay } from "node:perf_hooks";
|
|
12
12
|
import { logger } from "../../../utils/logger.js";
|
|
13
|
+
import { megabytesPerSecond } from "../../../utils/units.js";
|
|
13
14
|
import { availableShareFrom } from "../available-share.js";
|
|
14
15
|
import { encoderCpuBetween } from "./encoder-cpu.js";
|
|
15
16
|
import { baseDrawFrom, costPerMegabyteFrom } from "../torrent-cost.js";
|
|
@@ -40,7 +41,7 @@ function threadSays(now, previous) {
|
|
|
40
41
|
const freeBytes = (now.selection?.freeBytes ?? 0) - (previous.selection?.freeBytes ?? 0);
|
|
41
42
|
const held = ms > 0 && freeMs >= 0 && freeMs <= ms
|
|
42
43
|
? `; our selection held a peer back ${Math.round((1 - freeMs / ms) * 100)}% of the time` +
|
|
43
|
-
(freeMs > 0 ? `, the rest gave ${(freeBytes / freeMs
|
|
44
|
+
(freeMs > 0 ? `, the rest gave ${megabytesPerSecond(freeBytes / freeMs * 1000)}` : "") : "";
|
|
44
45
|
return loop + reads + held;
|
|
45
46
|
}
|
|
46
47
|
|
|
@@ -281,12 +282,12 @@ export class HostLoad {
|
|
|
281
282
|
// processor can be set against each kind of work (torrent-tv/meta#178).
|
|
282
283
|
const movedOf = (key) => Number.isFinite(now[key]) && Number.isFinite(previous[key]) && now[key] >= previous[key]
|
|
283
284
|
? (now[key] - previous[key]) / 1e6 : null;
|
|
284
|
-
const rateOf = (key) => movedOf(key) === null ? "n/a" :
|
|
285
|
+
const rateOf = (key) => movedOf(key) === null ? "n/a" : megabytesPerSecond(movedOf(key) * 1e6 / elapsedSec);
|
|
285
286
|
if (megabytes > 0 || Number.isFinite(limit) || movedOf("served") > 0 || movedOf("uploaded") > 0) {
|
|
286
287
|
logger.info(
|
|
287
|
-
`torrent: downloaded ${(megabytes / elapsedSec)
|
|
288
|
+
`torrent: downloaded ${megabytesPerSecond(megabytes * 1e6 / elapsedSec)}, sent to peers ${rateOf("uploaded")}, ` +
|
|
288
289
|
`handed to readers ${rateOf("served")} over ${elapsedSec.toFixed(1)}s, ` +
|
|
289
|
-
`limit ${Number.isFinite(limit) ?
|
|
290
|
+
`limit ${Number.isFinite(limit) ? megabytesPerSecond(limit) : "none"}; ` +
|
|
290
291
|
`its thread drew ${Math.round(cpuSeconds / elapsedSec * 100)}% of the machine` + threadSays(now, previous)
|
|
291
292
|
);
|
|
292
293
|
}
|
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
* answer.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
+
import { medianOf } from "../../utils/median.js";
|
|
19
|
+
|
|
18
20
|
/**
|
|
19
21
|
* How many recent readings a figure is taken from. The same reasoning as the
|
|
20
22
|
* other learned figures in this proxy: long enough that one reading does not
|
|
@@ -22,25 +24,6 @@
|
|
|
22
24
|
*/
|
|
23
25
|
const RECENT_READINGS = 20;
|
|
24
26
|
|
|
25
|
-
/**
|
|
26
|
-
* The middle of a set of readings, or null when there are none.
|
|
27
|
-
*
|
|
28
|
-
* Written here rather than borrowed from the general helper one level up: this
|
|
29
|
-
* layer states facts and imports nothing above itself, and four lines of
|
|
30
|
-
* arithmetic are not worth breaking that for.
|
|
31
|
-
*
|
|
32
|
-
* @param {number[]} values
|
|
33
|
-
* @returns {number | null}
|
|
34
|
-
*/
|
|
35
|
-
function middleOf(values) {
|
|
36
|
-
if (values.length === 0) {
|
|
37
|
-
return null;
|
|
38
|
-
}
|
|
39
|
-
const sorted = [...values].sort((left, right) => left - right);
|
|
40
|
-
const middle = Math.floor(sorted.length / 2);
|
|
41
|
-
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
42
|
-
}
|
|
43
|
-
|
|
44
27
|
export class RunCosts {
|
|
45
28
|
/** How long dying took, in milliseconds. @type {number[]} */
|
|
46
29
|
#dying = [];
|
|
@@ -145,7 +128,7 @@ export class RunCosts {
|
|
|
145
128
|
* @returns {{ seconds: number, measured: boolean } | null}
|
|
146
129
|
*/
|
|
147
130
|
openOf(address) {
|
|
148
|
-
const own =
|
|
131
|
+
const own = medianOf(this.#opens.get(address) ?? []);
|
|
149
132
|
if (own !== null) return { seconds: own, measured: true };
|
|
150
133
|
const startup = this.#atStartup?.firstByteWaitSec;
|
|
151
134
|
return Number.isFinite(startup) && startup > 0 ? { seconds: startup, measured: false } : null;
|
|
@@ -191,9 +174,9 @@ export class RunCosts {
|
|
|
191
174
|
// piece's encoding. Whoever uses it separates the two, because the piece
|
|
192
175
|
// costs more when encoders share the machine and the spawn does not.
|
|
193
176
|
return {
|
|
194
|
-
killCostSec: (
|
|
177
|
+
killCostSec: (medianOf(this.#dying) ?? 0) / 1000 || (this.#atStartup?.killCostSec ?? 0),
|
|
195
178
|
firstByteWaitSec:
|
|
196
|
-
(
|
|
179
|
+
(medianOf(this.#firstOutput) ?? 0) / 1000 || (this.#atStartup?.firstByteWaitSec ?? 0),
|
|
197
180
|
samples: Math.min(this.#dying.length, this.#firstOutput.length)
|
|
198
181
|
};
|
|
199
182
|
}
|
|
@@ -31,6 +31,7 @@ import { TextSubtitleTrack } from "./tracks/TextSubtitleTrack.js";
|
|
|
31
31
|
import { detectLanguage } from "./tracks/language-detect.js";
|
|
32
32
|
import { isUnavailable, strictReader } from "./container/unavailable.js";
|
|
33
33
|
import { logger } from "../../utils/logger.js";
|
|
34
|
+
import { megabytes } from "../../utils/units.js";
|
|
34
35
|
|
|
35
36
|
/**
|
|
36
37
|
* One file of one torrent, as much of it as this layer is allowed to know.
|
|
@@ -419,7 +420,7 @@ function reportWalk(source, state, stats, covered, indexed) {
|
|
|
419
420
|
`${stats.fromSearch ?? 0} found by searching the bytes, ${stats.rejectedCandidates ?? 0} candidate(s) refused, ` +
|
|
420
421
|
`${stats.pendingCandidates ?? 0} waiting for bytes, ${stats.contradictions ?? 0} withdrawn, ` +
|
|
421
422
|
`${stats.unreadable ?? 0} unreadable, ${stats.refusedElements ?? 0} block(s) over one read, ` +
|
|
422
|
-
`${
|
|
423
|
+
`${megabytes(stats.bytesWalked ?? 0)} read`
|
|
423
424
|
);
|
|
424
425
|
}
|
|
425
426
|
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* returns; where encoders go follows from those facts and is the plan's.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import { megabytesPerSecond } from "../../utils/units.js";
|
|
10
11
|
import { logger } from "../../utils/logger.js";
|
|
11
12
|
import { isOutputName, OutputSpec } from "../encode/output/index.js";
|
|
12
13
|
import { withSubtitleReadiness } from "./subtitle-readiness.js";
|
|
@@ -1254,7 +1255,7 @@ export class ViewerRequests {
|
|
|
1254
1255
|
`${operation.track} ${operation.operation} ${Number.isFinite(operation.speed) ? operation.speed.toFixed(2) : "?"}x`);
|
|
1255
1256
|
const downloads = (input.sources ?? []).map(source => {
|
|
1256
1257
|
const rate = this.#host.playbackReadiness.forecastRate(source.downloadRateReadings, now, 0, "time");
|
|
1257
|
-
return
|
|
1258
|
+
return megabytesPerSecond(rate);
|
|
1258
1259
|
});
|
|
1259
1260
|
logger.info(`playback held ${session.id} consumer=${consumerId}: delay ${seconds(delay)}s by ` +
|
|
1260
1261
|
(holding.kind === "position-not-held" ? "the position, which nothing buffered covers" :
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { EventEmitter } from "node:events";
|
|
12
12
|
import { writeJsonAtomic } from "../../utils/atomic-json.js";
|
|
13
13
|
import { logger } from "../../utils/logger.js";
|
|
14
|
+
import { megabytesPerSecond } from "../../utils/units.js";
|
|
14
15
|
import { KeyframeTables } from "../media/KeyframeTables.js";
|
|
15
16
|
import { matroskaIdOf } from "../media/tracks/codec-names.js";
|
|
16
17
|
import { bandOf, WaitLedger } from "../encode/OutputWaitLedger.js";
|
|
@@ -828,8 +829,8 @@ export function wireOutputs({
|
|
|
828
829
|
because = `${made}; the swarm's rate is not measured yet`;
|
|
829
830
|
} else {
|
|
830
831
|
held = swarm > needs;
|
|
831
|
-
because = `${made}; the swarm gives ${(swarm
|
|
832
|
-
`${held ? "more than" : "not more than"} the ${(needs
|
|
832
|
+
because = `${made}; the swarm gives ${megabytesPerSecond(swarm)}, ` +
|
|
833
|
+
`${held ? "more than" : "not more than"} the ${megabytesPerSecond(needs)} its film needs at ${asked.toFixed(2)}x`;
|
|
833
834
|
}
|
|
834
835
|
}
|
|
835
836
|
if (held === parts.speculativeHeld) return;
|
|
@@ -43,6 +43,7 @@
|
|
|
43
43
|
* left where it is: changing it is a decision about evidence, not about disk.
|
|
44
44
|
*/
|
|
45
45
|
|
|
46
|
+
import { megabytes } from "../../utils/units.js";
|
|
46
47
|
import { readdir, stat } from "node:fs/promises";
|
|
47
48
|
import path from "node:path";
|
|
48
49
|
|
|
@@ -193,10 +194,3 @@ export class Diagnostics {
|
|
|
193
194
|
}
|
|
194
195
|
}
|
|
195
196
|
|
|
196
|
-
/**
|
|
197
|
-
* @param {number} bytes
|
|
198
|
-
* @returns {string}
|
|
199
|
-
*/
|
|
200
|
-
function megabytes(bytes) {
|
|
201
|
-
return `${Math.round(Math.max(0, bytes) / (1024 * 1024))}MB`;
|
|
202
|
-
}
|
|
@@ -49,6 +49,7 @@
|
|
|
49
49
|
* is the one kind of number that is not ours to derive.
|
|
50
50
|
*/
|
|
51
51
|
|
|
52
|
+
import { mebibytes, megabytes } from "../../utils/units.js";
|
|
52
53
|
import { OtherDemand, divideAllowance } from "./allowance.js";
|
|
53
54
|
|
|
54
55
|
/**
|
|
@@ -242,8 +243,8 @@ export class MachineBudget {
|
|
|
242
243
|
// SAID, because a claimant working below what it needs is a fault of
|
|
243
244
|
// the machine and not of the code, and it is invisible otherwise.
|
|
244
245
|
this.#logger?.warn?.(
|
|
245
|
-
`budget: ${share.name} has ${
|
|
246
|
-
`below the ${
|
|
246
|
+
`budget: ${share.name} has ${printed(name, share.allowed)} of ${name}, ` +
|
|
247
|
+
`below the ${printed(name, claimants.find((one) => one.name === share.name)?.minimum ?? 0)} it needs`
|
|
247
248
|
);
|
|
248
249
|
}
|
|
249
250
|
}
|
|
@@ -297,18 +298,21 @@ export class MachineBudget {
|
|
|
297
298
|
const lines = [];
|
|
298
299
|
for (const [name, reading] of this.#last) {
|
|
299
300
|
const parts = reading.shares.map(
|
|
300
|
-
(share) => `${share.name} ${
|
|
301
|
+
(share) => `${share.name} ${printed(name, share.held)} of ${printed(name, share.allowed)}${share.short ? " (short)" : ""}`
|
|
301
302
|
);
|
|
302
|
-
lines.push(`${name}: ${
|
|
303
|
+
lines.push(`${name}: ${printed(name, reading.freeBytes)} free; ${parts.join(", ")}`);
|
|
303
304
|
}
|
|
304
305
|
return `budget — ${lines.join(" | ")}`;
|
|
305
306
|
}
|
|
306
307
|
}
|
|
307
308
|
|
|
308
309
|
/**
|
|
310
|
+
* Memory is printed in binary units under its own label, a disk (data) in decimal.
|
|
311
|
+
*
|
|
312
|
+
* @param {string} resource
|
|
309
313
|
* @param {number} bytes
|
|
310
314
|
* @returns {string}
|
|
311
315
|
*/
|
|
312
|
-
function
|
|
313
|
-
return
|
|
316
|
+
function printed(resource, bytes) {
|
|
317
|
+
return resource === "memory" ? mebibytes(bytes) : megabytes(bytes);
|
|
314
318
|
}
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
* (`machine-memory.js`); the cgroup is found the same way.
|
|
29
29
|
*/
|
|
30
30
|
|
|
31
|
+
import { clamp } from "../../utils/clamp.js";
|
|
31
32
|
import { readFileSync } from "node:fs";
|
|
32
33
|
import os from "node:os";
|
|
33
34
|
|
|
@@ -383,13 +384,3 @@ function statField(text, name) {
|
|
|
383
384
|
}
|
|
384
385
|
return null;
|
|
385
386
|
}
|
|
386
|
-
|
|
387
|
-
/**
|
|
388
|
-
* @param {number} value
|
|
389
|
-
* @param {number} low
|
|
390
|
-
* @param {number} high
|
|
391
|
-
* @returns {number}
|
|
392
|
-
*/
|
|
393
|
-
function clamp(value, low, high) {
|
|
394
|
-
return Math.min(high, Math.max(low, value));
|
|
395
|
-
}
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import { readdir, readFile, rm, statfs } from "node:fs/promises";
|
|
23
23
|
import { availableMemory } from "./machine-memory.js";
|
|
24
24
|
import os from "node:os";
|
|
25
|
+
import { megabytes, mebibytes } from "../../utils/units.js";
|
|
25
26
|
import v8 from "node:v8";
|
|
26
27
|
import path from "node:path";
|
|
27
28
|
|
|
@@ -217,16 +218,6 @@ async function readDiskFree(directory) {
|
|
|
217
218
|
return null;
|
|
218
219
|
}
|
|
219
220
|
|
|
220
|
-
/**
|
|
221
|
-
* Render a size the way a person reads one.
|
|
222
|
-
*
|
|
223
|
-
* @param {number} bytes
|
|
224
|
-
* @returns {string}
|
|
225
|
-
*/
|
|
226
|
-
function megabytes(bytes) {
|
|
227
|
-
return `${Math.round(bytes / (1024 * 1024))}MB`;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
221
|
/**
|
|
231
222
|
* One line saying what the process holds and what the machine has left.
|
|
232
223
|
*
|
|
@@ -282,27 +273,27 @@ export function describeMemory({
|
|
|
282
273
|
// grows, so a spilled piece frees a slot and no memory.
|
|
283
274
|
const storesPart = stores.length === 0
|
|
284
275
|
? "no torrent stores"
|
|
285
|
-
: `${stores.length} torrent store(s) holding ${
|
|
286
|
-
`committed ${
|
|
276
|
+
: `${stores.length} torrent store(s) holding ${mebibytes(storeResident)}, ` +
|
|
277
|
+
`committed ${mebibytes(storeCommitted)} of ${mebibytes(storeBudget)} allowed, ` +
|
|
287
278
|
`${megabytes(storeSpilled)} spilled to disk`;
|
|
288
279
|
const isolate =
|
|
289
|
-
`heap=${
|
|
290
|
-
`${usage.heapLimit ? ` of ${
|
|
291
|
-
`external=${
|
|
280
|
+
`heap=${mebibytes(usage.heapUsed)}/${mebibytes(usage.heapTotal)}` +
|
|
281
|
+
`${usage.heapLimit ? ` of ${mebibytes(usage.heapLimit)} allowed` : ""} ` +
|
|
282
|
+
`external=${mebibytes(usage.external)} arrayBuffers=${mebibytes(usage.arrayBuffers)}`;
|
|
292
283
|
const tail = extra ? `; ${extra}` : "";
|
|
293
284
|
if (scope === "thread") {
|
|
294
285
|
return `memory (${label || "thread"}): ${isolate}; ${storesPart}${tail}`;
|
|
295
286
|
}
|
|
296
287
|
const shape = mappings === null
|
|
297
288
|
? ""
|
|
298
|
-
: ` mappings=[heap ${
|
|
299
|
-
`${mappings.largeCount} anon ≥
|
|
300
|
-
`(largest ${
|
|
301
|
-
`${mappings.smallCount} anon <
|
|
302
|
-
`files ${
|
|
289
|
+
: ` mappings=[heap ${mebibytes(mappings.heapBytes)}, ` +
|
|
290
|
+
`${mappings.largeCount} anon ≥2MiB = ${mebibytes(mappings.largeBytes)} ` +
|
|
291
|
+
`(largest ${mebibytes(mappings.largestBytes)}), ` +
|
|
292
|
+
`${mappings.smallCount} anon <2MiB = ${mebibytes(mappings.smallBytes)}, ` +
|
|
293
|
+
`files ${mebibytes(mappings.fileBytes)}]`;
|
|
303
294
|
return (
|
|
304
|
-
`memory: rss=${
|
|
305
|
-
`${anonymousBytes === null ? "" : ` anon=${
|
|
295
|
+
`memory: rss=${mebibytes(usage.rss)} ${isolate}` +
|
|
296
|
+
`${anonymousBytes === null ? "" : ` anon=${mebibytes(anonymousBytes)}`}${shape}; ` +
|
|
306
297
|
`${storesPart}; ` +
|
|
307
298
|
describeAvailable(available) +
|
|
308
299
|
`${diskFreeBytes === null ? "" : `, ${megabytes(diskFreeBytes)} free on disk`}` +
|
|
@@ -326,8 +317,8 @@ function describeAvailable(available) {
|
|
|
326
317
|
: `${available.source} decides`;
|
|
327
318
|
const limit = available.limitBytes === null
|
|
328
319
|
? "no container limit"
|
|
329
|
-
: `container limit ${
|
|
330
|
-
return `machine has ${
|
|
320
|
+
: `container limit ${mebibytes(available.limitBytes)}`;
|
|
321
|
+
return `machine has ${mebibytes(available.bytes)} available (${decided}; ${limit})`;
|
|
331
322
|
}
|
|
332
323
|
|
|
333
324
|
/**
|
|
@@ -500,7 +491,7 @@ export function startMemoryReport({
|
|
|
500
491
|
// that names what is holding the memory, and it is why it is bounded by
|
|
501
492
|
// a floor, by a growth step and by how many are kept.
|
|
502
493
|
v8.writeHeapSnapshot(snapPath);
|
|
503
|
-
log(`memory: wrote heap snapshot of the ${label || scope} to ${snapPath} (${
|
|
494
|
+
log(`memory: wrote heap snapshot of the ${label || scope} to ${snapPath} (${mebibytes(watchedBytes)}, ${why})`);
|
|
504
495
|
} catch {
|
|
505
496
|
// silent-ok: no snapshot is worse than a snapshot, and much better than
|
|
506
497
|
// ending the series that leads to the next one.
|
|
@@ -628,7 +619,7 @@ export function startMemoryReport({
|
|
|
628
619
|
// line is, and at one reading a second an unconditional warning would be
|
|
629
620
|
// a line a second for as long as the process stayed large.
|
|
630
621
|
if (scope !== "thread" && anonymousBytes !== null && processMemory.rss > 800 * 1024 * 1024) {
|
|
631
|
-
log(`memory: high rss=${
|
|
622
|
+
log(`memory: high rss=${mebibytes(processMemory.rss)} anon=${mebibytes(anonymousBytes)} heap=${mebibytes(processMemory.heapUsed)} — watch for OOM`);
|
|
632
623
|
}
|
|
633
624
|
} catch {
|
|
634
625
|
// silent-ok: a reading that fails is not worth ending the series over.
|
|
@@ -41,6 +41,7 @@
|
|
|
41
41
|
* and nothing here disagrees.
|
|
42
42
|
*/
|
|
43
43
|
|
|
44
|
+
import { medianOf, upperMiddleOf } from "../../../utils/median.js";
|
|
44
45
|
import { divideAllowance, machineAllowanceBytes, OtherDemand } from "../allowance.js";
|
|
45
46
|
import { availableMemoryBytes as availableMemorySync } from "../machine-memory.js";
|
|
46
47
|
import { PieceLru } from "./piece-lru.js";
|
|
@@ -269,11 +270,7 @@ function median(values) {
|
|
|
269
270
|
if (values.length === 0) {
|
|
270
271
|
return null;
|
|
271
272
|
}
|
|
272
|
-
|
|
273
|
-
const middle = Math.floor(sorted.length / 2);
|
|
274
|
-
return sorted.length % 2 === 0
|
|
275
|
-
? Math.round((sorted[middle - 1] + sorted[middle]) / 2)
|
|
276
|
-
: sorted[middle];
|
|
273
|
+
return Math.round(medianOf(values));
|
|
277
274
|
}
|
|
278
275
|
const CLAIM_RETRY_MS = 50;
|
|
279
276
|
|
|
@@ -1101,8 +1098,10 @@ export class SharedPieceStore {
|
|
|
1101
1098
|
if (this.#writeDurations.length === 0 || this.#admittedAt.length < 2) {
|
|
1102
1099
|
return 0;
|
|
1103
1100
|
}
|
|
1104
|
-
|
|
1105
|
-
|
|
1101
|
+
// The upper middle, not the true median, on purpose: slack is a number of
|
|
1102
|
+
// pieces to keep in hand, so the slower of the two middle writes is the
|
|
1103
|
+
// safe side and a count stays an integer. Unchanged since before #294.
|
|
1104
|
+
const writeMs = upperMiddleOf(this.#writeDurations);
|
|
1106
1105
|
const spanMs = this.#admittedAt[this.#admittedAt.length - 1] - this.#admittedAt[0];
|
|
1107
1106
|
if (!(spanMs > 0)) {
|
|
1108
1107
|
return 0;
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
* beside it; nothing decides on it yet.
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
+
import { medianOf, scatterOf } from "../../utils/median.js";
|
|
25
26
|
import { readFileSync, readdirSync } from "node:fs";
|
|
26
27
|
|
|
27
28
|
/** Clock ticks per second of `/proc/<pid>/stat`, as in `encode/host-load.js`. */
|
|
@@ -269,13 +270,7 @@ export function describeRuns(runs) {
|
|
|
269
270
|
*/
|
|
270
271
|
function middleAndScatter(values) {
|
|
271
272
|
if (values.length === 0) return null;
|
|
272
|
-
|
|
273
|
-
const sorted = [...list].sort((a, b) => a - b);
|
|
274
|
-
const half = Math.floor(sorted.length / 2);
|
|
275
|
-
return sorted.length % 2 === 0 ? (sorted[half - 1] + sorted[half]) / 2 : sorted[half];
|
|
276
|
-
};
|
|
277
|
-
const middle = median(values);
|
|
278
|
-
return { middle, scatter: median(values.map((value) => Math.abs(value - middle))) };
|
|
273
|
+
return { middle: medianOf(values), scatter: scatterOf(values) };
|
|
279
274
|
}
|
|
280
275
|
|
|
281
276
|
/**
|
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
* what viewers actually do instead of from what a period felt like.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
import { medianOf } from "../../utils/median.js";
|
|
20
|
+
|
|
19
21
|
/** How many returns are kept. Enough to see a shape, few enough to say in a line. */
|
|
20
22
|
const KEPT = 200;
|
|
21
23
|
|
|
@@ -65,11 +67,10 @@ export class Returns {
|
|
|
65
67
|
return null;
|
|
66
68
|
}
|
|
67
69
|
const sorted = [...this.#ages].sort((left, right) => left - right);
|
|
68
|
-
const middle = Math.floor(sorted.length / 2);
|
|
69
70
|
return {
|
|
70
71
|
warm: this.#warm,
|
|
71
72
|
cold: this.#cold,
|
|
72
|
-
medianMs:
|
|
73
|
+
medianMs: medianOf(sorted),
|
|
73
74
|
longestMs: sorted[sorted.length - 1]
|
|
74
75
|
};
|
|
75
76
|
}
|
|
@@ -45,6 +45,7 @@ import { rmSync } from "node:fs";
|
|
|
45
45
|
import os from "node:os";
|
|
46
46
|
import path from "node:path";
|
|
47
47
|
import { writeFileAtomic } from "../../../utils/atomic-json.js";
|
|
48
|
+
import { megabytes } from "../../../utils/units.js";
|
|
48
49
|
|
|
49
50
|
/** Where every output's segments live. One root for the process. */
|
|
50
51
|
const DEFAULT_STORE_ROOT = path.join(os.tmpdir(), "torrent-tv-hls");
|
|
@@ -1388,7 +1389,7 @@ export class SegmentStore {
|
|
|
1388
1389
|
if (found.length > 0) {
|
|
1389
1390
|
this.#logger.info(
|
|
1390
1391
|
`segment-store startup sweep: ${found.length} directories left by a previous run, ` +
|
|
1391
|
-
`${totals.segments} segments, ${(totals.bytes
|
|
1392
|
+
`${totals.segments} segments, ${megabytes(totals.bytes)}, ` +
|
|
1392
1393
|
`${unidentified} of them unidentifiable — each one is an encoder that ended ` +
|
|
1393
1394
|
"without anything recording why"
|
|
1394
1395
|
);
|
|
@@ -55,6 +55,8 @@
|
|
|
55
55
|
* nothing smooths, weights or decays anything.
|
|
56
56
|
*/
|
|
57
57
|
|
|
58
|
+
import { medianOf } from "../../utils/median.js";
|
|
59
|
+
|
|
58
60
|
/**
|
|
59
61
|
* One measured interruption: how long a read waited, and when the wait ended.
|
|
60
62
|
*
|
|
@@ -106,7 +108,7 @@ export function requiredSpeedFrom(waits) {
|
|
|
106
108
|
if (intervals.length === 0) {
|
|
107
109
|
return null;
|
|
108
110
|
}
|
|
109
|
-
const medianIntervalSec =
|
|
111
|
+
const medianIntervalSec = medianOf(intervals);
|
|
110
112
|
if (!(medianIntervalSec > 0)) {
|
|
111
113
|
return null;
|
|
112
114
|
}
|
|
@@ -244,16 +246,6 @@ function usableWaits(waits) {
|
|
|
244
246
|
.sort((left, right) => left.at - right.at);
|
|
245
247
|
}
|
|
246
248
|
|
|
247
|
-
/**
|
|
248
|
-
* @param {number[]} values - Non-empty.
|
|
249
|
-
* @returns {number}
|
|
250
|
-
*/
|
|
251
|
-
function median(values) {
|
|
252
|
-
const sorted = [...values].sort((left, right) => left - right);
|
|
253
|
-
const middle = Math.floor(sorted.length / 2);
|
|
254
|
-
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
255
|
-
}
|
|
256
|
-
|
|
257
249
|
/**
|
|
258
250
|
* @param {unknown} value
|
|
259
251
|
* @returns {number}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* download.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { megabytes } from "../../utils/units.js";
|
|
11
12
|
import { IDLE_KEEP_MS, SWARM_HOLD_MS } from "../storage/keep.js";
|
|
12
13
|
import dns from "node:dns/promises";
|
|
13
14
|
import os from "node:os";
|
|
@@ -1658,14 +1659,14 @@ export class TorrentPool {
|
|
|
1658
1659
|
for (const zone of ordered) {
|
|
1659
1660
|
const level = levelOf(zone);
|
|
1660
1661
|
const byteCount = Math.max(0, Math.min(length - 1, zone.byteEnd) - zone.byteStart + 1);
|
|
1661
|
-
const held = byLevel.get(level) ?? { zones: 0,
|
|
1662
|
+
const held = byLevel.get(level) ?? { zones: 0, bytes: 0 };
|
|
1662
1663
|
held.zones += 1;
|
|
1663
|
-
held.
|
|
1664
|
+
held.bytes += byteCount;
|
|
1664
1665
|
byLevel.set(level, held);
|
|
1665
1666
|
}
|
|
1666
1667
|
const shape = [...byLevel.entries()]
|
|
1667
1668
|
.sort((left, right) => right[0] - left[0])
|
|
1668
|
-
.map(([level, held]) => `${urgencyName(level)} ${held.zones} zone(s) ${held.
|
|
1669
|
+
.map(([level, held]) => `${urgencyName(level)} ${held.zones} zone(s) ${megabytes(held.bytes)}`)
|
|
1669
1670
|
.join(", ");
|
|
1670
1671
|
// Something is wanted of this torrent, which may be news: a map published
|
|
1671
1672
|
// for a file of a torrent whose swarm was let go is what takes it back.
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
* with those bytes — not when they were sent, because nothing was sent.
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
|
+
import { medianOf } from "../../../utils/median.js";
|
|
23
24
|
import { pieceStoreOf } from "../piece-store-of.js";
|
|
24
25
|
import { urgencyName } from "../demand/index.js";
|
|
25
26
|
import { demandFor } from "../download/registry.js";
|
|
@@ -232,14 +233,10 @@ function describeWaitLevels(key) {
|
|
|
232
233
|
if (!byLevel || byLevel.size === 0) {
|
|
233
234
|
return null;
|
|
234
235
|
}
|
|
235
|
-
const middle = (values) => {
|
|
236
|
-
const sorted = [...values].sort((left, right) => left - right);
|
|
237
|
-
return sorted[Math.floor(sorted.length / 2)];
|
|
238
|
-
};
|
|
239
236
|
return [...byLevel.entries()]
|
|
240
237
|
.sort(([left], [right]) => left - right)
|
|
241
238
|
.map(([urgency, waits]) =>
|
|
242
|
-
`${urgencyName(urgency)} ${waits.length} waits median ${
|
|
239
|
+
`${urgencyName(urgency)} ${waits.length} waits median ${Math.round(medianOf(waits))}ms ` +
|
|
243
240
|
`worst ${Math.max(...waits)}ms`)
|
|
244
241
|
.join(", ");
|
|
245
242
|
}
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
// before WebTorrent can reach the native one. Two isolates using
|
|
21
21
|
// node-datachannel at once abort the process, and the torrent's wss trackers
|
|
22
22
|
// create peer connections of their own.
|
|
23
|
+
import { megabytes, mebibytes } from "../../../utils/units.js";
|
|
23
24
|
import { isUsableTorrentHandle, requireCurrentTorrent } from "./handle-state.js";
|
|
24
25
|
import "./install-webrtc-shim.js";
|
|
25
26
|
import { parentPort, workerData } from "node:worker_threads";
|
|
@@ -826,21 +827,21 @@ setInterval(() => {
|
|
|
826
827
|
if (revised.evicted > 0) {
|
|
827
828
|
log(
|
|
828
829
|
`piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
|
|
829
|
-
`${
|
|
830
|
+
`${mebibytes(revised.ceilingBytes)}, evicted ${revised.evicted} piece(s) to meet it` +
|
|
830
831
|
(revised.releasedBlocks > 0 ? `, gave back ${revised.releasedBlocks} block(s) of memory` : "") +
|
|
831
|
-
` — now ${
|
|
832
|
+
` — now ${mebibytes(revised.committedBytes)} committed`
|
|
832
833
|
);
|
|
833
834
|
} else if (revised.belowActiveDemand) {
|
|
834
835
|
log(
|
|
835
836
|
`piece-store "${revised.name.slice(0, 40)}": the machine's share is smaller than active read demand, ` +
|
|
836
|
-
`so the allowance is held at ${
|
|
837
|
+
`so the allowance is held at ${mebibytes(revised.ceilingBytes)} ` +
|
|
837
838
|
"— a store cannot finish a read if it cannot hold the pieces that read is using"
|
|
838
839
|
);
|
|
839
840
|
} else if (revised.committedBytes > revised.ceilingBytes) {
|
|
840
841
|
log(
|
|
841
842
|
`piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
|
|
842
|
-
`${
|
|
843
|
-
`${
|
|
843
|
+
`${mebibytes(revised.ceilingBytes)} and ` +
|
|
844
|
+
`${mebibytes(revised.committedBytes)} is committed — ` +
|
|
844
845
|
`all resident pieces are pinned, cannot shrink yet`
|
|
845
846
|
);
|
|
846
847
|
}
|
|
@@ -863,7 +864,7 @@ setInterval(() => {
|
|
|
863
864
|
if (reserveNow !== reserveBefore || reserveNow !== lastReserveBytes) {
|
|
864
865
|
lastReserveBytes = reserveNow;
|
|
865
866
|
log(
|
|
866
|
-
`piece-store: leaving ${
|
|
867
|
+
`piece-store: leaving ${mebibytes(reserveNow)} for everything else on this ` +
|
|
867
868
|
"machine — the largest fall in available memory this process has seen and did not cause"
|
|
868
869
|
);
|
|
869
870
|
}
|
|
@@ -882,11 +883,11 @@ setInterval(() => {
|
|
|
882
883
|
const fromMemoryShare = reads > 0 ? ((stats.fromMemory / reads) * 100).toFixed(1) : "—";
|
|
883
884
|
log(
|
|
884
885
|
`piece-store "${stats.name.slice(0, 40)}": resident=${stats.resident}/${stats.capacity} ` +
|
|
885
|
-
`(${
|
|
886
|
-
`${
|
|
887
|
-
`committed=${
|
|
886
|
+
`(${mebibytes(stats.residentBytes || 0)} of ` +
|
|
887
|
+
`${mebibytes(stats.budgetBytes || 0)} allowed) ` +
|
|
888
|
+
`committed=${mebibytes(stats.committedBytes || 0)} ` +
|
|
888
889
|
`blocks=${stats.blocksAllocated} (${stats.blocksFree} spare) ` +
|
|
889
|
-
`on-disk=${
|
|
890
|
+
`on-disk=${megabytes(stats.spilledBytes || 0)} ` +
|
|
890
891
|
`pinned=${stats.pinned} spilled=${stats.spilled} reads=${reads} (${fromMemoryShare}% from memory) ` +
|
|
891
892
|
`spills=${stats.spills} revivals=${stats.revivals}` +
|
|
892
893
|
(stats.blockedByPins > 0 ? ` no-block-for=${stats.blockedByPins}` : "") +
|
|
@@ -1206,7 +1207,7 @@ async function keepWholeFiles() {
|
|
|
1206
1207
|
});
|
|
1207
1208
|
if (kept) {
|
|
1208
1209
|
logger.info(
|
|
1209
|
-
`whole files: kept "${file.name}" (${
|
|
1210
|
+
`whole files: kept "${file.name}" (${megabytes(kept.length)}, ` +
|
|
1210
1211
|
`written in ${((performance.now() - startedAt) / 1000).toFixed(1)}s) — ` +
|
|
1211
1212
|
"it is a file now, and reading it needs no torrent"
|
|
1212
1213
|
);
|
package/utils/clamp.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The value, held between `low` and `high` (torrent-tv/meta#294: one clamp).
|
|
3
|
+
*
|
|
4
|
+
* @param {number} value
|
|
5
|
+
* @param {number} low
|
|
6
|
+
* @param {number} high
|
|
7
|
+
* @returns {number}
|
|
8
|
+
*/
|
|
9
|
+
export function clamp(value, low, high) {
|
|
10
|
+
return Math.min(high, Math.max(low, value));
|
|
11
|
+
}
|
package/utils/median.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The one median (torrent-tv/meta#294).
|
|
3
|
+
*
|
|
4
|
+
* Every place that needs the middle of a set of readings takes it from here, so
|
|
5
|
+
* that two logs saying "median" mean the same thing. Layers that may not import
|
|
6
|
+
* `utils/` (`viewer/`, `encode/output/`, `media/container/`) are handed the
|
|
7
|
+
* function instead.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The finite readings, ascending, as a new array.
|
|
12
|
+
*
|
|
13
|
+
* @param {number[]} values
|
|
14
|
+
* @returns {number[]}
|
|
15
|
+
*/
|
|
16
|
+
function sortedFinite(values) {
|
|
17
|
+
return (Array.isArray(values) ? values : []).filter((value) => Number.isFinite(value)).sort((left, right) => left - right);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The middle of a set of readings, or null when there are none. Readings that
|
|
22
|
+
* are not finite numbers are left out; on an even count the two middle
|
|
23
|
+
* readings are averaged.
|
|
24
|
+
*
|
|
25
|
+
* @param {number[]} values
|
|
26
|
+
* @returns {number | null}
|
|
27
|
+
*/
|
|
28
|
+
export function medianOf(values) {
|
|
29
|
+
const sorted = sortedFinite(values);
|
|
30
|
+
if (sorted.length === 0) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
const middle = Math.floor(sorted.length / 2);
|
|
34
|
+
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The element at index floor(n / 2) of the sorted finite readings: the upper of
|
|
39
|
+
* the two middle readings on an even count, never their mean, so a count stays
|
|
40
|
+
* an integer. Null when there are none.
|
|
41
|
+
*
|
|
42
|
+
* @param {number[]} values
|
|
43
|
+
* @returns {number | null}
|
|
44
|
+
*/
|
|
45
|
+
export function upperMiddleOf(values) {
|
|
46
|
+
const sorted = sortedFinite(values);
|
|
47
|
+
return sorted.length === 0 ? null : sorted[Math.floor(sorted.length / 2)];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* How far the readings sit from their own middle: the median of their
|
|
52
|
+
* distances to it. The median distance rather than the mean one, for the same
|
|
53
|
+
* reason the value itself is a median: a single disturbed reading describes the
|
|
54
|
+
* disturbance, not the host.
|
|
55
|
+
*
|
|
56
|
+
* @param {number[]} values
|
|
57
|
+
* @returns {number | null} Null when there is nothing to measure. Zero is a
|
|
58
|
+
* real answer: readings that all agree disagree by nothing.
|
|
59
|
+
*/
|
|
60
|
+
export function scatterOf(values) {
|
|
61
|
+
const middle = medianOf(values);
|
|
62
|
+
if (middle === null) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
return medianOf(sortedFinite(values).map((value) => Math.abs(value - middle)));
|
|
66
|
+
}
|
package/utils/units.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file One way to print bytes (torrent-tv/meta#294).
|
|
3
|
+
*
|
|
4
|
+
* Data and rates are printed in decimal units (`MB`, `MB/s`, 10^6 bytes);
|
|
5
|
+
* memory is printed in binary units under its own label (`MiB`, 2^20 bytes), so
|
|
6
|
+
* the same label never means two sizes.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const MEGABYTE = 1_000_000;
|
|
10
|
+
const MEBIBYTE = 1_048_576;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {number} bytes
|
|
14
|
+
* @returns {string} e.g. "123MB"; negative bytes read as 0.
|
|
15
|
+
*/
|
|
16
|
+
export function megabytes(bytes) {
|
|
17
|
+
return `${Math.round(Math.max(0, bytes) / MEGABYTE)}MB`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {number} bytes
|
|
22
|
+
* @returns {string} e.g. "123MiB"; negative bytes read as 0.
|
|
23
|
+
*/
|
|
24
|
+
export function mebibytes(bytes) {
|
|
25
|
+
return `${Math.round(Math.max(0, bytes) / MEBIBYTE)}MiB`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {number | null | undefined} bytesPerSecond
|
|
30
|
+
* @returns {string} e.g. "1.05 MB/s"; "? MB/s" when the rate is not a finite number.
|
|
31
|
+
*/
|
|
32
|
+
export function megabytesPerSecond(bytesPerSecond) {
|
|
33
|
+
return typeof bytesPerSecond === "number" && Number.isFinite(bytesPerSecond)
|
|
34
|
+
? `${(bytesPerSecond / MEGABYTE).toFixed(2)} MB/s` : "? MB/s";
|
|
35
|
+
}
|