@torrent-tv/proxy 2.21.1 → 2.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,18 @@
1
+ ## 2.23.0
2
+
3
+ - **New**: The encoder run is a transition table, and the table is the specification rather than a description of code written elsewhere. `services/encode-run-state.js` declares eight states, ten events named for what happened, two superstates and the answers each state gives — whether the input is being read, whether the process can be signalled, what a missing segment gets, what the browser is told, whether a restart is allowed. What it buys is not tidiness: five field failures in a row were empty cells — a pair of state and event nobody had considered — and a table makes an empty cell visible before a release. The edges that must NEVER exist are data too, each naming the release it cost: the 2.9.93 sawtooth where any segment request released a suspended encoder, and the 2.9.93 dead-run shortcut where the handle pointed at a corpse and every later seek was waved through as already covered.
4
+ - **New**: Every transition a real run makes is logged as state, event and target (`run-state <id> STARTING --FIRST_SEGMENT--> PRODUCING`), and a pair the table does not declare is logged as a refusal instead of being obeyed. Nothing READS the state yet — the fields it will replace keep their current writes — because whether the model matches reality is a measurement to take in the field, not an assumption to build on. This release exists to take it.
5
+ - **New**: The picture in `docs/encode-run-state.md` is rendered FROM the table (`npm run graph`), and a test regenerates it and compares, so a drawing that disagrees with the code cannot be committed.
6
+ - **Fix**: The ffmpeg a seek kills is no longer handled as the session's own run dying — and this was found by writing the table down, before it shipped. The exit handler decides whether an exit is its own by comparing against `session.ffmpeg`, and during a restart that field still names the process being killed, because the replacement is spawned a few hundred lines later. So every seek and every quality switch ran the failure branch for its predecessor: a spurious `failed` for the moment between the kill and the spawn, which a segment request landing in that window is answered 500 for; a fast-failure tally against a target that never failed; and on any host with a hardware encoder, the runtime safety net firing on each seek — the proxy downgraded itself to libx264 permanently and started an extra run at the OLD index, which took the generation and made the real restart abort. A process is now marked superseded BEFORE it is signalled.
7
+ - **Fix**: Losing the torrent's data no longer condemns a working hardware encoder. The hardware-failure fallback was asked of every non-zero exit, including a run that died because its input went away — which says nothing about the encoder. What an exit means is now classified in one place (`services/encode-exit.js`, tested by its four field cases) and the fallback is asked only of a genuine encoder failure.
8
+
9
+ - **Fix**: What the torrent costs this machine can actually be measured now. The reading is taken when no encoder is RUNNING, and a SUSPENDED encoder was being counted as one — so on a host with two sessions parked by the look-ahead cap the moment never arrived: measured 2026-08-15, four minutes of `encoders=0 running +2 suspended` in which the price could have been taken and was not. A suspended encoder costs nothing, which is exactly why that moment is the right one.
10
+
11
+ ## 2.22.0
12
+
13
+ - **Fix**: What a rung is OFFERED on is the startup measurement again, not the figure learned from a live session. The startup one is taken on a quiet machine against known clips and does not move; the learned one moves with whatever else the box was doing that second, and three field sessions in a row show the price of that: decoding learned at 0.87x, then at 1.34-1.57x, against calibration's 2.6x — each reading refusing another rung until the offer held a single height and the quality menu vanished with it.
14
+ - **New**: A live reading keeps the one thing it is authority on — itself. A rung that has actually been seen running below realtime, with the machine to itself, is withdrawn on that evidence whatever any prediction says. A rung nobody has run is judged by the startup measurement like any other, because a measurement of one rung is not a prediction about the rest.
15
+
1
16
  ## 2.21.1
2
17
 
3
18
  - **Fix**: A cost is learned only from an encoder that had the machine to itself. Beside another encoder a reading already contains that other work, and the budget then ADDS the same work again when it predicts — so the price of a file grew with every reading. Measured in the field 2026-08-15: copying, whose truth is 7.9x, was learned as 2.03x; decoding, whose calibration clips say 2.6x, as 0.87x. Every re-encoded rung was then refused (`not offering 720p=0.56x … 240p=0.66x`), the offer collapsed to the one copied height, and the viewer lost the quality menu entirely.
@@ -0,0 +1,96 @@
1
+ <!-- GENERATED from services/encode-run-state.js by scripts/render-run-graph.js.
2
+ Do not edit by hand: change the table and run `npm run graph`. -->
3
+
4
+ # The encoder run — states and transitions
5
+
6
+ One run of one ffmpeg inside one transcode session. The table this is drawn
7
+ from is executed by `services/hls-session-manager.js`; every transition a real
8
+ run makes is logged as state, event and target, so a run that takes an edge
9
+ absent here is a violation the log names.
10
+
11
+ ```mermaid
12
+ stateDiagram-v2
13
+ state RUN {
14
+ [*] --> IDLE
15
+ state WORKING {
16
+ state ALIVE {
17
+ STARTING
18
+ PRODUCING
19
+ SUSPENDED
20
+ }
21
+ RETRY_WAIT
22
+ }
23
+ IDLE
24
+ STOPPED
25
+ ENDED_COMPLETE
26
+ ENDED_FAILED
27
+ }
28
+
29
+ RUN --> STARTING : SPAWNED
30
+ WORKING --> STOPPED : STOP_ORDERED
31
+ ALIVE --> SUSPENDED : SUSPEND_ORDERED
32
+ ALIVE --> ENDED_COMPLETE : EXITED_COMPLETE
33
+ ALIVE --> ENDED_FAILED : EXITED_SHORT
34
+ ALIVE --> RETRY_WAIT : EXITED_INPUT_LOST
35
+ ALIVE --> ENDED_FAILED : EXITED_FAILED
36
+ STARTING --> PRODUCING : FIRST_SEGMENT
37
+ SUSPENDED --> PRODUCING : RESUME_ORDERED
38
+ RETRY_WAIT --> IDLE : RETRY_DUE
39
+ ```
40
+
41
+ ## States
42
+
43
+ | state | means |
44
+ |---|---|
45
+ | `IDLE` | No process, and one is expected — before the first run, or after a retry timer fired. |
46
+ | `STARTING` | Spawned; this run has produced nothing servable yet. |
47
+ | `PRODUCING` | This run has produced at least one servable segment. |
48
+ | `SUSPENDED` | SIGSTOP delivered, process alive — and nothing is reading the input. |
49
+ | `RETRY_WAIT` | The input went away; a restart is timed. Requests are held, not refused. |
50
+ | `STOPPED` | Stopped on purpose with no replacement — a rung the viewer switched away from. |
51
+ | `ENDED_COMPLETE` | Ran through the last segment of the file. Nothing is owed. |
52
+ | `ENDED_FAILED` | Terminal for this target: requests are answered as failures. |
53
+
54
+ ## Events
55
+
56
+ | event | means |
57
+ |---|---|
58
+ | `SPAWNED` | A process was spawned for this session. |
59
+ | `FIRST_SEGMENT` | The first servable segment of this run was served. |
60
+ | `SUSPEND_ORDERED` | SIGSTOP was delivered. |
61
+ | `RESUME_ORDERED` | SIGCONT was sent. |
62
+ | `STOP_ORDERED` | The run was stopped with no replacement. |
63
+ | `EXITED_COMPLETE` | Exit 0, having produced through the last segment. |
64
+ | `EXITED_SHORT` | Exit 0, short of the last segment — the input dried up. |
65
+ | `EXITED_INPUT_LOST` | Died because the input was not there. Recoverable. |
66
+ | `EXITED_FAILED` | Died for any other reason, or could not be spawned. |
67
+ | `RETRY_DUE` | The input-retry timer fired. |
68
+
69
+ ## What each state answers
70
+
71
+ Outputs depend on the state alone — computed here by calling the same
72
+ functions the session manager calls.
73
+
74
+ | state | reads its input | can be signalled | a missing segment | on the wire | may restart |
75
+ |---|---|---|---|---|---|
76
+ | `IDLE` | no | no | hold | `starting` | yes |
77
+ | `STARTING` | yes | yes | hold | `running` | yes |
78
+ | `PRODUCING` | yes | yes | hold | `running` | yes |
79
+ | `SUSPENDED` | no | yes | hold | `running` | yes |
80
+ | `RETRY_WAIT` | no | no | hold | `starting` | yes |
81
+ | `STOPPED` | no | no | hold | `running` | yes |
82
+ | `ENDED_COMPLETE` | no | no | hold | `ready` | no |
83
+ | `ENDED_FAILED` | no | no | fail | `failed` | yes |
84
+
85
+ ## Edges that must never exist
86
+
87
+ The machine's real content: a near-complete digraph asserts nothing.
88
+
89
+ | from | event | must not reach | because |
90
+ |---|---|---|---|
91
+ | `SUSPENDED` | `FIRST_SEGMENT` | `PRODUCING` | a segment request must not release a suspended encoder — 2.9.93, where any request did, and the run sawtoothed from 155 s to 922 s ahead of the viewer in three minutes |
92
+ | `ENDED_FAILED` | `FIRST_SEGMENT` | `PRODUCING` | a dead run is not a producing one — 2.9.93, where the handle pointed at a corpse and every later seek was waved through as already covered, so the session answered 500 for ever |
93
+ | `ENDED_FAILED` | `RESUME_ORDERED` | `PRODUCING` | there is no process to continue; only a spawn leads out of a failure |
94
+ | `IDLE` | `FIRST_SEGMENT` | `PRODUCING` | nothing produces before a process exists |
95
+ | `RETRY_WAIT` | `FIRST_SEGMENT` | `PRODUCING` | a run waiting for its input back has no process; only a spawn resumes production |
96
+ | `STOPPED` | `RESUME_ORDERED` | `PRODUCING` | a rung the viewer switched away from must not be revived by its own held requests — the host has one encoder's worth of capacity and the rung on screen needs it |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.21.1",
3
+ "version": "2.23.0",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -20,6 +20,7 @@
20
20
  "start": "node ./bin/cli.js",
21
21
  "dev": "node --inspect=0 --experimental-network-inspection ./bin/cli.js",
22
22
  "test": "npm run lint && node --test",
23
+ "graph": "node scripts/render-run-graph.js",
23
24
  "lint": "biome lint ."
24
25
  },
25
26
  "dependencies": {
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file Render the encoder-run table as a document, FROM the table.
4
+ *
5
+ * The picture is not drawn beside the code — it is produced from the same data
6
+ * the code executes, so it cannot describe a machine that no longer exists. A
7
+ * test regenerates it and compares, which is what makes "the table is the
8
+ * single source" enforceable rather than a promise.
9
+ *
10
+ * Run it with `npm run graph`.
11
+ */
12
+
13
+ import { writeFileSync } from "node:fs";
14
+ import path from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ import {
18
+ ABSENT_EDGE_INVARIANTS,
19
+ ENCODE_RUN_EVENT,
20
+ ENCODE_RUN_STATE,
21
+ EVENT_MEANING,
22
+ INITIAL_RUN_STATE,
23
+ STATE_MEANING,
24
+ answerForMissingSegment,
25
+ declaredContainment,
26
+ declaredEdges,
27
+ isInputBeingRead,
28
+ mayRestart,
29
+ processCanBeSignalled,
30
+ wireState
31
+ } from "../services/encode-run-state.js";
32
+
33
+ /** Where the rendered document lives. */
34
+ export const GRAPH_DOC_PATH = path.join(
35
+ path.dirname(fileURLToPath(import.meta.url)),
36
+ "..",
37
+ "docs",
38
+ "encode-run-state.md"
39
+ );
40
+
41
+ const ALL_STATES = Object.values(ENCODE_RUN_STATE);
42
+ const ALL_EVENTS = Object.values(ENCODE_RUN_EVENT);
43
+
44
+ /**
45
+ * Children of each node of the containment tree, in declaration order.
46
+ *
47
+ * @returns {{ root: string, childrenOf: Map<string, string[]> }}
48
+ */
49
+ function containmentTree() {
50
+ const childrenOf = new Map();
51
+ let root = null;
52
+ for (const { state, parent } of declaredContainment()) {
53
+ if (parent === null) {
54
+ root = state;
55
+ continue;
56
+ }
57
+ if (!childrenOf.has(parent)) {
58
+ childrenOf.set(parent, []);
59
+ }
60
+ childrenOf.get(parent).push(state);
61
+ }
62
+ return { root, childrenOf };
63
+ }
64
+
65
+ /**
66
+ * One composite block, and everything nested inside it.
67
+ *
68
+ * @param {string} node
69
+ * @param {Map<string, string[]>} childrenOf
70
+ * @param {number} depth
71
+ * @returns {string[]} Lines, already indented.
72
+ */
73
+ function renderBlock(node, childrenOf, depth) {
74
+ const pad = " ".repeat(depth);
75
+ const children = childrenOf.get(node) ?? [];
76
+ if (children.length === 0) {
77
+ return [`${pad}${node}`];
78
+ }
79
+ const lines = [`${pad}state ${node} {`];
80
+ if (children.includes(INITIAL_RUN_STATE)) {
81
+ lines.push(`${pad} [*] --> ${INITIAL_RUN_STATE}`);
82
+ }
83
+ for (const child of children) {
84
+ lines.push(...renderBlock(child, childrenOf, depth + 1));
85
+ }
86
+ lines.push(`${pad}}`);
87
+ return lines;
88
+ }
89
+
90
+ /**
91
+ * The whole document.
92
+ *
93
+ * @returns {string}
94
+ */
95
+ export function renderRunGraphMarkdown() {
96
+ const { root, childrenOf } = containmentTree();
97
+ const lines = [];
98
+
99
+ lines.push(
100
+ "<!-- GENERATED from services/encode-run-state.js by scripts/render-run-graph.js.",
101
+ " Do not edit by hand: change the table and run `npm run graph`. -->",
102
+ "",
103
+ "# The encoder run — states and transitions",
104
+ "",
105
+ "One run of one ffmpeg inside one transcode session. The table this is drawn",
106
+ "from is executed by `services/hls-session-manager.js`; every transition a real",
107
+ "run makes is logged as state, event and target, so a run that takes an edge",
108
+ "absent here is a violation the log names.",
109
+ "",
110
+ "```mermaid",
111
+ "stateDiagram-v2"
112
+ );
113
+ lines.push(...renderBlock(root, childrenOf, 1));
114
+ lines.push("");
115
+ for (const edge of declaredEdges()) {
116
+ lines.push(` ${edge.from} --> ${edge.to} : ${edge.event}`);
117
+ }
118
+ lines.push("```", "");
119
+
120
+ lines.push("## States", "", "| state | means |", "|---|---|");
121
+ for (const state of ALL_STATES) {
122
+ lines.push(`| \`${state}\` | ${STATE_MEANING[state]} |`);
123
+ }
124
+ lines.push("");
125
+
126
+ lines.push("## Events", "", "| event | means |", "|---|---|");
127
+ for (const event of ALL_EVENTS) {
128
+ lines.push(`| \`${event}\` | ${EVENT_MEANING[event]} |`);
129
+ }
130
+ lines.push("");
131
+
132
+ lines.push(
133
+ "## What each state answers",
134
+ "",
135
+ "Outputs depend on the state alone — computed here by calling the same",
136
+ "functions the session manager calls.",
137
+ "",
138
+ "| state | reads its input | can be signalled | a missing segment | on the wire | may restart |",
139
+ "|---|---|---|---|---|---|"
140
+ );
141
+ for (const state of ALL_STATES) {
142
+ lines.push(
143
+ `| \`${state}\` | ${isInputBeingRead(state) ? "yes" : "no"} | ` +
144
+ `${processCanBeSignalled(state) ? "yes" : "no"} | ${answerForMissingSegment(state)} | ` +
145
+ `\`${wireState(state)}\` | ${mayRestart(state) ? "yes" : "no"} |`
146
+ );
147
+ }
148
+ lines.push("");
149
+
150
+ lines.push(
151
+ "## Edges that must never exist",
152
+ "",
153
+ "The machine's real content: a near-complete digraph asserts nothing.",
154
+ "",
155
+ "| from | event | must not reach | because |",
156
+ "|---|---|---|---|"
157
+ );
158
+ for (const invariant of ABSENT_EDGE_INVARIANTS) {
159
+ lines.push(
160
+ `| \`${invariant.from}\` | \`${invariant.event}\` | \`${invariant.mustNotReach}\` | ${invariant.because} |`
161
+ );
162
+ }
163
+ lines.push("");
164
+
165
+ return `${lines.join("\n")}`;
166
+ }
167
+
168
+ // Written only when this file is the program being run, so importing it from a
169
+ // test cannot rewrite the very file the test is about to compare against.
170
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
171
+ writeFileSync(GRAPH_DOC_PATH, renderRunGraphMarkdown(), "utf8");
172
+ process.stdout.write(`wrote ${GRAPH_DOC_PATH}\n`);
173
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @file What an ffmpeg exit MEANS — as a pure classification, so the four
3
+ * possibilities can be exercised without spawning anything.
4
+ *
5
+ * The exit handler is where two of this project's most expensive failures
6
+ * lived, and both were classification faults rather than logic faults:
7
+ *
8
+ * - 2.9.104: ffmpeg exits 0 when it reaches the end of the file AND when its
9
+ * input simply stops delivering bytes — over HTTP the two look identical to
10
+ * it. A run that had made 188 segments of 624 reported itself complete, the
11
+ * player consumed what was on disk and froze on the first segment nobody
12
+ * was making. The difference is not in the exit code; it is in how far the
13
+ * run got against the playlist we published.
14
+ * - The predecessor a seek kills exits with a signal and used to be handled
15
+ * as the session's own run dying. Which is why "was this process already
16
+ * replaced" is the FIRST question here rather than a check somewhere in the
17
+ * caller: an exit that belongs to a superseded run means nothing at all,
18
+ * and reading it as a failure downgraded a hardware encoder for good.
19
+ *
20
+ * Nothing here touches a session, a process or a clock. The caller decides what
21
+ * to DO about each answer.
22
+ */
23
+
24
+ /**
25
+ * What this exit says about the run.
26
+ *
27
+ * @readonly
28
+ */
29
+ export const ENCODE_EXIT = Object.freeze({
30
+ /** The process was already replaced or the session is gone: it says nothing. */
31
+ IGNORED: "ignored",
32
+ /** Reached the end of the file. */
33
+ COMPLETE: "complete",
34
+ /** Claimed success, stopped short of the last segment — the input dried up. */
35
+ SHORT: "short",
36
+ /** The input was not there. Recoverable: the data can come back. */
37
+ INPUT_LOST: "input-lost",
38
+ /** Anything else. Terminal for this target until something restarts it. */
39
+ FAILED: "failed"
40
+ });
41
+
42
+ /**
43
+ * Classify one exit.
44
+ *
45
+ * `inputUnavailable` is decided by the caller from ffmpeg's own message, and it
46
+ * is asked BEFORE the hardware-encoder question deliberately: a run that died
47
+ * because its torrent data went away says nothing whatever about the encoder,
48
+ * and treating it as an encoder failure is how a host with NVENC came to
49
+ * downgrade itself to software over a missing piece.
50
+ *
51
+ * @param {object} facts
52
+ * @param {boolean} [facts.superseded] - This process was replaced or the
53
+ * session disposed before the exit arrived.
54
+ * @param {number | null} [facts.code] - Exit code, null when killed by a signal.
55
+ * @param {number | null} [facts.producedThrough] - Highest segment index this
56
+ * session has on disk, or null when that could not be read.
57
+ * @param {number | null} [facts.lastSegmentIndex] - Index of the file's last
58
+ * segment according to the published playlist, or null when unknown.
59
+ * @param {boolean} [facts.inputUnavailable] - The error names a missing input.
60
+ * @returns {string} One of {@link ENCODE_EXIT}.
61
+ */
62
+ export function classifyEncodeExit({
63
+ superseded = false,
64
+ code = null,
65
+ producedThrough = null,
66
+ lastSegmentIndex = null,
67
+ inputUnavailable = false
68
+ } = {}) {
69
+ if (superseded) {
70
+ return ENCODE_EXIT.IGNORED;
71
+ }
72
+ if (code === 0) {
73
+ const stoppedShort =
74
+ lastSegmentIndex !== null &&
75
+ producedThrough !== null &&
76
+ producedThrough < lastSegmentIndex;
77
+ return stoppedShort ? ENCODE_EXIT.SHORT : ENCODE_EXIT.COMPLETE;
78
+ }
79
+ return inputUnavailable ? ENCODE_EXIT.INPUT_LOST : ENCODE_EXIT.FAILED;
80
+ }