@torrent-tv/proxy 2.87.0 → 2.87.2

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.
@@ -33,6 +33,14 @@ import { contentionPenalty } from "./contention.js";
33
33
  import { SegmentDemand } from "./SegmentDemand.js";
34
34
  import { runStateOf } from "./encode-run-state.js";
35
35
 
36
+ /**
37
+ * @typedef {Object} SegmentCoverage
38
+ * @property {(address: string) => number[]} provenNumbers
39
+ * @property {(address: string, index: number) => void} announce
40
+ * @property {(address: string) => number} filesHeld
41
+ * @property {(address: string, startedAt: number) => number} clearUpAfter
42
+ */
43
+
36
44
  /**
37
45
  * How long nothing is placed on an output whose input has just gone, and the
38
46
  * ceiling that doubling reaches.
@@ -58,6 +66,9 @@ export class EncodeOrchestrator {
58
66
  /** Output address to what has been made of it. @type {Map<string, CoverageMap>} */
59
67
  #coverage = new Map();
60
68
 
69
+ /** @type {SegmentCoverage | null} */
70
+ #segmentCoverage = null;
71
+
61
72
  /** Output address to the runs on it. @type {Map<string, import("../encode/EncodeRun.js").EncodeRun[]>} */
62
73
  #runs = new Map();
63
74
 
@@ -148,6 +159,7 @@ export class EncodeOrchestrator {
148
159
  * HANDED IN: what anybody waited for belongs to the priority layer, and
149
160
  * this one may be asked about encoders with no ledger, no clock and no
150
161
  * viewer anywhere. Absent, the line simply does not carry it.
162
+ * @param {SegmentCoverage | null} [params.segmentCoverage]
151
163
  */
152
164
  constructor({
153
165
  maxRunsFor,
@@ -156,7 +168,7 @@ export class EncodeOrchestrator {
156
168
  contentionPenalties = null,
157
169
  refetchSecPerFilmSecond = () => 0,
158
170
  startingSpeedFor = () => 0,
159
- segmentStore = null,
171
+ segmentCoverage = null,
160
172
  planSoon = null,
161
173
  describeWaits = null,
162
174
  admission = null,
@@ -169,11 +181,9 @@ export class EncodeOrchestrator {
169
181
  // is about one output, and then only the per-output limit binds.
170
182
  this.admission = admission && typeof admission.placesFor === "function" ? admission : null;
171
183
  this.#describeWaits = typeof describeWaits === "function" ? describeWaits : () => "";
172
- // The store of produced segments — the layer below this one. It is asked to
173
- // clean up after a run that ended other than by reaching the end of its
174
- // stretch, which is the one thing an ending must not leave behind: a file
175
- // under a name that promises a whole segment.
176
- this.segmentStore = segmentStore;
184
+ // Only the segment facts and operations this planner needs cross the
185
+ // storage boundary; the concrete storage remains in the server assembly.
186
+ this.#segmentCoverage = segmentCoverage;
177
187
  this.maxRunsFor = maxRunsFor;
178
188
  // Seconds of swarm time per second of film: what re-encoding material that
179
189
  // already exists costs the download, over and above the encoder's own time.
@@ -238,8 +248,8 @@ export class EncodeOrchestrator {
238
248
  */
239
249
  #upToDateCoverage(address) {
240
250
  const coverage = this.coverageOf(address);
241
- if (this.segmentStore) {
242
- coverage.setReady(this.segmentStore.provenNumbers(address));
251
+ if (this.#segmentCoverage) {
252
+ coverage.setReady(this.#segmentCoverage.provenNumbers(address));
243
253
  }
244
254
  return coverage;
245
255
  }
@@ -549,9 +559,9 @@ export class EncodeOrchestrator {
549
559
  // Nothing is told to the store: by the time this is called the piece is
550
560
  // ALREADY under its served name, because the rename is what closing it
551
561
  // means. A statement kept beside the disk would be a second owner of one
552
- // fact, which is what item 87 removed from the coverage map.
562
+ // fact, which removed the stale second owner from the coverage map.
553
563
  this.coverageOf(address).markReady(index);
554
- this.segmentStore?.announce?.(address, index);
564
+ this.#segmentCoverage?.announce?.(address, index);
555
565
  for (const run of this.runsOn(address)) {
556
566
  run.noteProduced(index);
557
567
  }
@@ -805,7 +815,7 @@ export class EncodeOrchestrator {
805
815
  this.#lastUnmet.delete(address);
806
816
  } else if (this.#lastUnmet.get(address) !== wanting) {
807
817
  this.#lastUnmet.set(address, wanting);
808
- const held = this.segmentStore ? this.segmentStore.filesHeld(address) : -1;
818
+ const held = this.#segmentCoverage ? this.#segmentCoverage.filesHeld(address) : -1;
809
819
  this.logger.warn(
810
820
  `encode: #${wanting} of ${address} is wanted and NO ENCODER IS MAKING IT — ` +
811
821
  `ready=${coverage.stats().ready} of ${coverage.segmentCount} ` +
@@ -1009,7 +1019,7 @@ export class EncodeOrchestrator {
1009
1019
  // is a name match: no stretch to search and no bytes to judge. Done for
1010
1020
  // every ending, the normal one included, since a run that finished cleanly
1011
1021
  // has nothing under a working name and the sweep then removes nothing.
1012
- this.segmentStore?.clearUpAfter(ended.address, ended.from);
1022
+ this.#segmentCoverage?.clearUpAfter(ended.address, ended.from);
1013
1023
  this.coverageOf(ended.address).release(ended.run);
1014
1024
  const remaining = this.runsOn(ended.address).filter((run) => run !== ended.run);
1015
1025
  if (remaining.length === 0) {
@@ -1182,7 +1192,7 @@ export class EncodeOrchestrator {
1182
1192
  // different statements: files with nothing proving them closed reads as a
1183
1193
  // reporting fault, no files at all reads as an output yet to be made, and
1184
1194
  // the difference decides where to look.
1185
- const held = this.segmentStore ? this.segmentStore.filesHeld(address) : -1;
1195
+ const held = this.#segmentCoverage ? this.#segmentCoverage.filesHeld(address) : -1;
1186
1196
  // AND WHETHER THE MAP IS BEING SERVED IN ITS OWN ORDER. The zones say
1187
1197
  // what matters most; this says what the viewer actually waited for, by
1188
1198
  // band. Waits at `now` are the ones that cost a spinner, and until this
@@ -15,6 +15,14 @@ import { ENCODE_EXIT } from "./encode-exit.js";
15
15
  import { EncodeRun } from "./EncodeRun.js";
16
16
  import { computeOutputDimensions } from "./args.js";
17
17
  import { buildRunCommand, trueStartOf } from "./run-command.js";
18
+
19
+ /**
20
+ * @typedef {Object} SegmentFiles
21
+ * @property {(address: string) => string} pathFor
22
+ * @property {(address: string) => Buffer | null} initOf
23
+ * @property {(address: string) => string} directoryFor
24
+ * @property {(address: string, makingName: string, format: object) => string | null} publish
25
+ */
18
26
  // How far the accounting of a backward restart looks for work about to be done
19
27
  // twice. It runs on the restart path and a session an hour in has thousands of
20
28
  // segments; the figure is for a comparison, not an inventory.
@@ -147,7 +155,9 @@ export class EncodeRuns {
147
155
  #planScheduled = false;
148
156
 
149
157
  /**
150
- * @param {object} host - `logger`, `viewerSecondsOn`, `noteRunStarting`, `inputOf`, `producedNumbers`, `servesAudioSeparately`, `disposeSession`, `contentionPenalties`, `encodeCost`, `encodeOrchestrator`, `encoders`, `ffmpegBin`, `outputTimes`, `outputs`, `priority`, `segmentDurationSec`, `segmentStore`, `videoEncoder`
158
+ * @param {object} host - `logger`, `viewerSecondsOn`, `noteRunStarting`, `inputOf`, `producedNumbers`, `servesAudioSeparately`, `disposeSession`, `contentionPenalties`, `encodeCost`, `encodeOrchestrator`, `encoders`, `ffmpegBin`, `outputTimes`, `outputs`, `priority`, `segmentDurationSec`, `segmentFiles`, `videoEncoder`
159
+ * @param {SegmentFiles} host.segmentFiles - The storage operations used to
160
+ * write and inspect output files.
151
161
  */
152
162
  constructor(host) {
153
163
  this.#host = host;
@@ -542,7 +552,7 @@ export class EncodeRuns {
542
552
  * @returns {void}
543
553
  */
544
554
  noteRunProducedSegment(session, filePath) {
545
- if (typeof filePath !== "string" || path.dirname(filePath) !== this.#host.segmentStore.pathFor(session.outputKey ?? "")) {
555
+ if (typeof filePath !== "string" || path.dirname(filePath) !== this.#host.segmentFiles.pathFor(session.outputKey ?? "")) {
546
556
  return;
547
557
  }
548
558
  const index = session.segmentFormat.segmentIndexFromName(path.basename(filePath));
@@ -580,7 +590,7 @@ export class EncodeRuns {
580
590
  * @returns {void}
581
591
  */
582
592
  #warnIfRunLeavesTheInitBehind(session) {
583
- const initBytes = this.#host.segmentStore.initOf(session.outputKey ?? "");
593
+ const initBytes = this.#host.segmentFiles.initOf(session.outputKey ?? "");
584
594
  if (!session.spec.transcodesVideo || !initBytes || initBytes.length === 0) {
585
595
  return; // nothing served yet, or nothing being encoded
586
596
  }
@@ -804,7 +814,7 @@ export class EncodeRuns {
804
814
  totalSeconds: Number(session.file.durationSeconds) || null,
805
815
  spawn: (spawnArgs) =>
806
816
  spawn(this.#host.ffmpegBin, spawnArgs, {
807
- cwd: this.#host.segmentStore.directoryFor(session.outputKey ?? ""),
817
+ cwd: this.#host.segmentFiles.directoryFor(session.outputKey ?? ""),
808
818
  // A fourth channel: the encoder names every piece it has CLOSED on it,
809
819
  // which is the only proof a piece is whole.
810
820
  stdio: ["ignore", "pipe", "pipe", "pipe"]
@@ -821,7 +831,7 @@ export class EncodeRuns {
821
831
  // Why this encoder exists, recorded with its argument list. It used to be
822
832
  // handed to a separate `start` call; there is no separate call now.
823
833
  because,
824
- onClosed: (name) => this.#host.segmentStore.publish(session.outputKey ?? "", name, session.segmentFormat),
834
+ onClosed: (name) => this.#host.segmentFiles.publish(session.outputKey ?? "", name, session.segmentFormat),
825
835
  onEnded: (ended) => this.noteRunEnded(session, run, ended)
826
836
  });
827
837
  // THE ONE FAULT THAT IS OTHERWISE SILENT, asked before this run produces a
@@ -28,6 +28,14 @@ import { rungForVisiblePicture } from "./quality/visible-rung.js";
28
28
  import { audioLoadOf, linkAnswerFigures as linkFiguresOf } from "./quality/link-budget.js";
29
29
  import { AUDIO_TRANSCODE_KBPS } from "./args.js";
30
30
 
31
+ /**
32
+ * @typedef {Object} SegmentOutputFiles
33
+ * @property {() => string[]} addresses
34
+ * @property {(address: string, index: number) => boolean} isClosed
35
+ * @property {(address: string) => number | null} lastReadAt
36
+ * @property {(address: string) => string} directoryFor
37
+ * @property {(address: string, format: object) => void} useFormat
38
+ */
31
39
 
32
40
  /** Own package version, stamped onto output-start log lines. */
33
41
  const PROXY_VERSION = createRequire(import.meta.url)("../../package.json").version;
@@ -37,7 +45,9 @@ export class OutputOpening {
37
45
  #host;
38
46
 
39
47
  /**
40
- * @param {object} host - `logger`, `probeMediaInfo`, `probeKeyframeTimes`, `enabled`, `segmentFormat`, `renditions`, `sourceFiles`, `getCachedMediaInfo`, `localBaseUrl`, `tonemapSupported`, `videoEncoder`, `hostLoad`, `keyframeTables`, `timelines`, `segmentDurationSec`, `softwarePresetBenchmark`, `decodeCostModel`, `encodeCost`, `outputs`, `segmentStore`, `hostTimings`, `returns`, `encodeRuns`
48
+ * @param {object} host - `logger`, `probeMediaInfo`, `probeKeyframeTimes`, `enabled`, `segmentFormat`, `renditions`, `sourceFiles`, `getCachedMediaInfo`, `localBaseUrl`, `tonemapSupported`, `videoEncoder`, `hostLoad`, `keyframeTables`, `timelines`, `segmentDurationSec`, `softwarePresetBenchmark`, `decodeCostModel`, `encodeCost`, `outputs`, `segmentOutputFiles`, `hostTimings`, `returns`, `encodeRuns`
49
+ * @param {SegmentOutputFiles} host.segmentOutputFiles - The storage
50
+ * operations needed while selecting or opening an output.
41
51
  */
42
52
  constructor(host) {
43
53
  this.#host = host;
@@ -586,8 +596,8 @@ export class OutputOpening {
586
596
  serving: {
587
597
  mode: servingMode ?? (forceExactSize ? "manual" : "auto"),
588
598
  linkMbps: viewerLinkMbps,
589
- keys: [...this.#host.outputs.values()].map((other) => other.outputKey).concat(this.#host.segmentStore.addresses()),
590
- readyAt: (key) => this.#host.segmentStore.isClosed(key, timeline.indexForTime(Math.max(0, startPositionSeconds))),
599
+ keys: [...this.#host.outputs.values()].map((other) => other.outputKey).concat(this.#host.segmentOutputFiles.addresses()),
600
+ readyAt: (key) => this.#host.segmentOutputFiles.isClosed(key, timeline.indexForTime(Math.max(0, startPositionSeconds))),
591
601
  observedPeakMbps: (candidate) => this.#host.observedPeakMbps?.(candidate) ?? null
592
602
  }
593
603
  });
@@ -679,9 +689,9 @@ export class OutputOpening {
679
689
  // A RETURN, if this output was held before — and its age, which is the one
680
690
  // term of the keeping period that nothing measures. Read BEFORE the
681
691
  // directory is claimed, since claiming it is what marks it read.
682
- this.#host.returns.note({ lastReadAt: this.#host.segmentStore.lastReadAt(spec.toKey()), now: Date.now() });
683
- this.#host.segmentStore.directoryFor(spec.toKey());
684
- this.#host.segmentStore.useFormat(spec.toKey(), segmentFormat);
692
+ this.#host.returns.note({ lastReadAt: this.#host.segmentOutputFiles.lastReadAt(spec.toKey()), now: Date.now() });
693
+ this.#host.segmentOutputFiles.directoryFor(spec.toKey());
694
+ this.#host.segmentOutputFiles.useFormat(spec.toKey(), segmentFormat);
685
695
  this.#host.hostTimings.noteOutputCreated(session, createEntryMs);
686
696
  this.#host.encodeRuns.setReadWindow(session, readWindowBytes);
687
697
  this.#host.encodeCost.notePredictionFor(session, output.encodeHeight);
@@ -59,6 +59,8 @@ const BUDGET_DOWNLOAD_OK_FACTOR = 1.0;
59
59
  // segments (the newest file on disk may still be written and is excluded).
60
60
  const LINK_OBSERVED_SEGMENTS = 5;
61
61
 
62
+ /** @typedef {{ pathOf: (address: string, index: number) => string | null }} SegmentPathLookup */
63
+
62
64
  export class QualityController {
63
65
  /** What this reads and asks of the rest of the proxy, and nothing else. @type {object} */
64
66
  #host;
@@ -70,7 +72,9 @@ export class QualityController {
70
72
  #judging = new Set();
71
73
 
72
74
  /**
73
- * @param {object} host - `isLive`, `liveConsumers`, `liveRunsOf`, `producedNumbers`, `reportHostLoad`, `runStateOf`, `sampleDownloadRates`, `encodeCost`, `getSourceStats`, `outputs`, `qualityOffer`, `segmentDurationSec`, `segmentStore`, `videoEncoder`, `prepareSameHeightSwitch`, `sameHeightSwitchPending`, `sameHeightSwitchDirection`, `cancelSameHeightSwitch`, `heightReadyFor`, `bufferOf`, `visiblePictureOf`, `expectedFirstSegmentMs`
75
+ * @param {object} host - `isLive`, `liveConsumers`, `liveRunsOf`, `producedNumbers`, `reportHostLoad`, `runStateOf`, `sampleDownloadRates`, `encodeCost`, `getSourceStats`, `outputs`, `qualityOffer`, `segmentDurationSec`, `segmentPaths`, `videoEncoder`, `prepareSameHeightSwitch`, `sameHeightSwitchPending`, `sameHeightSwitchDirection`, `cancelSameHeightSwitch`, `heightReadyFor`, `bufferOf`, `visiblePictureOf`, `expectedFirstSegmentMs`
76
+ * @param {SegmentPathLookup} host.segmentPaths - Lookup for completed
77
+ * segment paths needed by quality decisions.
74
78
  */
75
79
  constructor(host) {
76
80
  this.#host = host;
@@ -751,7 +755,7 @@ export class QualityController {
751
755
  let bytes = 0;
752
756
  try {
753
757
  for (const index of completed) {
754
- const segmentPath = this.#host.segmentStore.pathOf(session.outputKey ?? "", index);
758
+ const segmentPath = this.#host.segmentPaths.pathOf(session.outputKey ?? "", index);
755
759
  if (!segmentPath) {
756
760
  break;
757
761
  }
@@ -0,0 +1,38 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const ID_FILE = "proxy-identity.json";
6
+
7
+ /**
8
+ * Resolve this installation's registry id. Without a state directory the id
9
+ * remains ephemeral; with one, the id survives process restarts.
10
+ *
11
+ * @param {{ stateDir?: string, explicitId?: string, makeId?: () => string }} options
12
+ * @returns {string}
13
+ */
14
+ export function installationId({ stateDir, explicitId, makeId = randomUUID } = {}) {
15
+ const requestedId = typeof explicitId === "string" ? explicitId.trim() : "";
16
+ if (!stateDir) {
17
+ return requestedId || makeId();
18
+ }
19
+
20
+ const file = path.join(stateDir, ID_FILE);
21
+ let savedId = "";
22
+ if (existsSync(file)) {
23
+ const saved = JSON.parse(readFileSync(file, "utf8"));
24
+ savedId = typeof saved?.id === "string" ? saved.id.trim() : "";
25
+ if (!savedId) {
26
+ throw new Error(`Invalid proxy identity file: ${file}`);
27
+ }
28
+ }
29
+
30
+ const id = requestedId || savedId || makeId();
31
+ if (id !== savedId) {
32
+ mkdirSync(stateDir, { recursive: true });
33
+ const temporary = `${file}.${process.pid}.tmp`;
34
+ writeFileSync(temporary, `${JSON.stringify({ id })}\n`, { mode: 0o600 });
35
+ renameSync(temporary, file);
36
+ }
37
+ return id;
38
+ }
@@ -272,6 +272,13 @@ export class Container {
272
272
  declared,
273
273
  "subtitle",
274
274
  (track) => ({
275
+ // Matroska applies `eng` when Language is absent, and ffmpeg reports
276
+ // that default as if the file had stated it. Preserve only an explicit
277
+ // container value; otherwise let cue-text detection decide later.
278
+ language: track.declaresLanguage === true
279
+ ? (track.languageBcp47 || track.language || "")
280
+ : "",
281
+ declaresLanguage: track.declaresLanguage === true,
275
282
  isDefault: track.isDefault === true,
276
283
  declaresDefault: track.declaresDefault === true,
277
284
  // Read from the file rather than guessed from the track's name. Both
@@ -538,6 +538,7 @@ export class MatroskaContainer extends Container {
538
538
  // RFC 9559 LanguageBCP47 MUST — when present, Language ignored
539
539
  const resolvedLang = languageBcp47 || language;
540
540
  const bcpTag = languageBcp47;
541
+ const declaresLanguage = resolvedLang.length > 0;
541
542
 
542
543
  if (typeNum === 1) {
543
544
  videoDeclaredIndex += 1;
@@ -547,6 +548,7 @@ export class MatroskaContainer extends Container {
547
548
  codecId,
548
549
  language: resolvedLang,
549
550
  languageBcp47: bcpTag,
551
+ declaresLanguage,
550
552
  name,
551
553
  isEnabled,
552
554
  isDefault,
@@ -565,6 +567,7 @@ export class MatroskaContainer extends Container {
565
567
  codecId,
566
568
  language: resolvedLang,
567
569
  languageBcp47: bcpTag,
570
+ declaresLanguage,
568
571
  name,
569
572
  isEnabled,
570
573
  isDefault,
@@ -597,6 +600,7 @@ export class MatroskaContainer extends Container {
597
600
  codecId,
598
601
  language: resolvedLang,
599
602
  languageBcp47: bcpTag,
603
+ declaresLanguage,
600
604
  name,
601
605
  isEnabled: finalEnabled,
602
606
  isDefault: finalDefault,
@@ -615,6 +619,7 @@ export class MatroskaContainer extends Container {
615
619
  codecId,
616
620
  language: resolvedLang,
617
621
  languageBcp47: bcpTag,
622
+ declaresLanguage,
618
623
  name,
619
624
  isEnabled: finalEnabled,
620
625
  isDefault: finalDefault,
@@ -634,6 +639,7 @@ export class MatroskaContainer extends Container {
634
639
  codecId,
635
640
  language: resolvedLang,
636
641
  languageBcp47: bcpTag,
642
+ declaresLanguage,
637
643
  name,
638
644
  isEnabled,
639
645
  isDefault,
@@ -1047,11 +1053,13 @@ async function readSubtitlePlan(readRange, fileSize) {
1047
1053
  // `language` here stays the three-letter code, because this list exists to
1048
1054
  // be lined up against ffmpeg's banner, which prints that code. The RFC 5646
1049
1055
  // tag rides beside it for whoever displays the track.
1056
+ const declaresLanguage = languageBcp47.length > 0 || language.length > 0;
1050
1057
  declared.push({
1051
1058
  trackNumber,
1052
1059
  codecId,
1053
1060
  language,
1054
1061
  languageBcp47,
1062
+ declaresLanguage,
1055
1063
  name,
1056
1064
  isDefault,
1057
1065
  declaresDefault,
@@ -1071,6 +1079,7 @@ async function readSubtitlePlan(readRange, fileSize) {
1071
1079
  // three-letter code MUST be ignored.
1072
1080
  language: languageBcp47 || language,
1073
1081
  languageBcp47,
1082
+ declaresLanguage,
1074
1083
  name,
1075
1084
  isDefault,
1076
1085
  isForced,
@@ -25,6 +25,7 @@ export class ContainerTrack {
25
25
  * @param {string} params.codecId - Matroska CodecID or MP4 sample entry type (e.g. "S_TEXT/UTF8", "avc1", "mp4a").
26
26
  * @param {string} params.language - Three-letter code or packed mdhd code; empty when absent. For Matroska, when LanguageBCP47 is present this is the BCP47 value ignored per MUST — caller stores both, but `language` here is the resolved one.
27
27
  * @param {string} params.languageBcp47 - RFC 5646 tag from LanguageBCP47 / elng, or "".
28
+ * @param {boolean} params.declaresLanguage - Whether the file explicitly supplies a language rather than relying on a container default.
28
29
  * @param {string} params.name - Track Name / title, or "".
29
30
  * @param {boolean} params.isEnabled - FlagEnabled / tkhd track_enabled. Default true per both specs. Matroska zero-length element means default, not disabled.
30
31
  * @param {boolean} params.isDefault - FlagDefault / tkhd? For MP4, derived from handler default? For Matroska, after applying default 1.
@@ -39,6 +40,7 @@ export class ContainerTrack {
39
40
  codecId,
40
41
  language,
41
42
  languageBcp47,
43
+ declaresLanguage,
42
44
  name,
43
45
  isEnabled,
44
46
  isDefault,
@@ -52,6 +54,7 @@ export class ContainerTrack {
52
54
  this.codecId = codecId ?? "";
53
55
  this.language = language ?? "";
54
56
  this.languageBcp47 = languageBcp47 ?? "";
57
+ this.declaresLanguage = declaresLanguage === true;
55
58
  this.name = name ?? "";
56
59
  this.isEnabled = isEnabled !== false;
57
60
  this.isDefault = isDefault === true;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Shared HTTP responses used by more than one route.
3
+ */
4
+ /**
5
+ * The answer given when no output suits this viewer: nothing this proxy holds
6
+ * or could produce is admitted by their link. Machine-readable, because the
7
+ * page has to explain it to the viewer and offer what they can do; the
8
+ * figures are the ones the decision was made on.
9
+ *
10
+ * 409 and not a 5xx: nothing is wrong with the proxy, and repeating the same
11
+ * request against the same link gives the same answer.
12
+ *
13
+ * @param {import("fastify").FastifyReply} reply
14
+ * @param {{ reason: string, figures: object | null, wantedKey?: string }} details
15
+ * @returns {import("fastify").FastifyReply}
16
+ */
17
+ export function replyOutputUnavailable(reply, details) {
18
+ return reply.code(409).send({
19
+ error: `No output suits this viewer: ${details?.reason ?? "unknown"}.`,
20
+ outcome: "output-unavailable",
21
+ reason: details?.reason ?? "",
22
+ figures: details?.figures ?? null
23
+ });
24
+ }
25
+
26
+ /**
27
+ * The answer given when this machine cannot take the output asked for: nothing
28
+ * it has shown it can encode fits, or it has no place for one more encoder.
29
+ * The page answers it by asking the rest of the pool before anything plays.
30
+ *
31
+ * @param {import("fastify").FastifyReply} reply
32
+ * @param {{ reason: string, figures?: object | null }} details
33
+ * @returns {import("fastify").FastifyReply}
34
+ */
35
+ export function replyNoCapacity(reply, details) {
36
+ return reply.code(409).send({
37
+ error: `This proxy cannot take this video now: ${details?.reason ?? "unknown"}.`,
38
+ outcome: "no-capacity",
39
+ reason: details?.reason ?? "",
40
+ figures: details?.figures ?? null
41
+ });
42
+ }
43
+
44
+ /**
45
+ * The answer given when an address this viewer was already given cannot be
46
+ * given again without risking a piece under a header it may not match. The
47
+ * page answers it by starting a new viewing where the picture is — which is
48
+ * why it is not a "retry": the same request would be answered the same way.
49
+ *
50
+ * @param {import("fastify").FastifyReply} reply
51
+ * @param {{ reason: string }} details
52
+ * @returns {import("fastify").FastifyReply}
53
+ */
54
+ export function replyAssignmentLost(reply, details) {
55
+ return reply.code(409).send({
56
+ error: `This part was answered by an output that has gone: ${details?.reason ?? "unknown"}.`,
57
+ outcome: "assignment-lost",
58
+ reason: details?.reason ?? ""
59
+ });
60
+ }