fffleet 2.2.0 → 2.4.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/README.md CHANGED
@@ -32,4 +32,6 @@ While a job runs, `job.on('stderr', tail => ...)` and `job.stderrTail` give ffmp
32
32
 
33
33
  The job contract, routes and error codes are documented in the [repository README](https://github.com/jsilvanus/fffleet#the-job-contract-v1). The building blocks (`JobManager`, `validateSpec`, `followJobEvents`, …) are exported too. `fffleet/server` holds the HTTP API that the worker and the orchestrator use.
34
34
 
35
+ See also the [integration guide](https://github.com/jsilvanus/fffleet/blob/main/docs/integration-guide.md).
36
+
35
37
  License: EUPL-1.2
package/index.d.ts CHANGED
@@ -291,6 +291,22 @@ export function createProgressParser(
291
291
  export function detectCapabilities(ffmpegPath?: string): Promise<string[]>;
292
292
  export function satisfies(capabilities: Iterable<string>, requires: string[]): boolean;
293
293
 
294
+ export interface Probe {
295
+ host: string;
296
+ port: number;
297
+ alias: string | null;
298
+ /** `net:<host>:<port>`, plus `net:<alias>` or, for a host name without an alias, `net:<host>`. */
299
+ capabilities: string[];
300
+ }
301
+ /** Parses `[alias=]host:port[,...]`; throws on a malformed entry. */
302
+ export function parseProbes(input: string | string[] | undefined): Probe[];
303
+ export function canConnect(host: string, port: number, timeoutMs?: number): Promise<boolean>;
304
+ /** The `net:` capabilities of the probes that connect right now. */
305
+ export function probeCapabilities(
306
+ probes: Probe[],
307
+ opts?: { timeoutMs?: number; connect?: (host: string, port: number, timeoutMs: number) => Promise<boolean> },
308
+ ): Promise<string[]>;
309
+
294
310
  export function readSse(
295
311
  body: ReadableStream<Uint8Array>,
296
312
  onEvent: (msg: { id: string | null; event: string; data: string }) => void,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "Run ffmpeg jobs locally, on one worker or across a pool, through one client and one job contract",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/client.js CHANGED
@@ -108,7 +108,13 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
108
108
  signal: AbortSignal.timeout(requestTimeoutMs),
109
109
  });
110
110
  const text = await res.text();
111
- const json = text ? JSON.parse(text) : null;
111
+ let json = null;
112
+ try {
113
+ json = text ? JSON.parse(text) : null;
114
+ } catch {
115
+ // A proxy's HTML error page: report the status, do not blame the JSON.
116
+ if (res.ok) throw new FleetError('BAD_RESPONSE', `${method} ${path} answered with something that is not JSON`, { status: res.status });
117
+ }
112
118
  // An expired or revoked token: log in again once.
113
119
  if (res.status === 401 && login && attempt === 0) continue;
114
120
  if (!res.ok) {
package/src/executor.js CHANGED
@@ -84,11 +84,18 @@ export async function runFfmpegJob(spec, rt) {
84
84
 
85
85
  rt.signal.throwIfAborted();
86
86
 
87
+ let resolved;
88
+ try {
89
+ resolved = resolvePlaceholders(spec.ffmpeg.args, values);
90
+ } catch (err) {
91
+ // For example {{inputdir:x}} on a live input, which has no directory.
92
+ throw new FleetError('INVALID_SPEC', err.message, { status: 422 });
93
+ }
87
94
  const args = [
88
95
  '-hide_banner', '-nostats', '-loglevel', 'warning', ...(spec.stdout ? [] : ['-progress', 'pipe:1']),
89
96
  ...(spec.stdin ? [] : ['-nostdin']),
90
97
  ...(batch ? ['-y'] : []),
91
- ...resolvePlaceholders(spec.ffmpeg.args, values),
98
+ ...resolved,
92
99
  ];
93
100
  const { exitCode, stderrTail } = await runProcess(rt.ffmpegPath ?? 'ffmpeg', args, spec, rt);
94
101
 
package/src/index.js CHANGED
@@ -9,6 +9,7 @@ export { runFfmpegJob } from './executor.js';
9
9
  export { runFfprobeJob } from './ffprobe.js';
10
10
  export { createProgressParser } from './progress.js';
11
11
  export { detectCapabilities, satisfies } from './capabilities.js';
12
+ export { canConnect, parseProbes, probeCapabilities } from './probe.js';
12
13
  export { readSse, followJobEvents } from './sse.js';
13
14
  export { createS3Client, s3ConfigFromEnv, parseS3Uri, contentTypeFor, signV4 } from './s3.js';
14
15
  export { SCOPES, hashSecret, verifySecret, generateSecret, createTokenProvider } from './auth.js';
package/src/probe.js ADDED
@@ -0,0 +1,66 @@
1
+ import { connect, isIP } from 'node:net';
2
+
3
+ /**
4
+ * Network reachability probes. A worker given `mediamtx=10.1.2.3:8554` tries a TCP connect to it and, while that
5
+ * works, advertises `net:10.1.2.3:8554` and `net:mediamtx`, so a job with `requires: ['net:mediamtx']` only goes
6
+ * to workers that can reach the host from where they run. A host name without an alias (a docker service name)
7
+ * is advertised as `net:<name>` too.
8
+ */
9
+
10
+ const ALIAS_RE = /^[A-Za-z0-9._-]{1,64}$/;
11
+
12
+ /**
13
+ * Parses `[alias=]host:port[,...]` (an optional `tcp://` prefix is accepted; IPv6 as `[::1]:8554`).
14
+ * Hosts are lower-cased. Throws on a malformed entry, so a typo does not silently disable a probe.
15
+ *
16
+ * @param {string | string[] | undefined} input
17
+ * @returns {{ host: string, port: number, alias: string | null, capabilities: string[] }[]}
18
+ */
19
+ export function parseProbes(input) {
20
+ const entries = Array.isArray(input) ? input : String(input ?? '').split(',');
21
+ return entries.map(e => String(e).trim()).filter(Boolean).map(entry => {
22
+ let rest = entry;
23
+ let alias = null;
24
+ const eq = rest.indexOf('=');
25
+ if (eq !== -1) {
26
+ alias = rest.slice(0, eq).trim();
27
+ rest = rest.slice(eq + 1).trim();
28
+ if (!ALIAS_RE.test(alias)) throw new Error(`probe "${entry}": alias must be 1-64 characters of A-Z a-z 0-9 . _ -`);
29
+ }
30
+ rest = rest.replace(/^tcp:\/\//i, '');
31
+ const m = rest.match(/^(\[[0-9a-fA-F:.]+\]|[^:\s/\[\]]+):(\d{1,5})$/);
32
+ const port = m ? Number(m[2]) : 0;
33
+ if (!m || port < 1 || port > 65535) throw new Error(`probe "${entry}": expected [alias=]host:port`);
34
+ const host = m[1].toLowerCase();
35
+ // A name (a docker service, a DNS name) is also advertised on its own; an IP only with its port.
36
+ const bare = !alias && !isIP(host.replace(/^\[|\]$/g, '')) ? [`net:${host}`] : [];
37
+ const capabilities = [`net:${host}:${port}`, ...(alias ? [`net:${alias}`] : bare)];
38
+ return { host, port, alias, capabilities };
39
+ });
40
+ }
41
+
42
+ /** True when a TCP connection to host:port opens within `timeoutMs`. */
43
+ export function canConnect(host, port, timeoutMs = 3000) {
44
+ return new Promise(resolve => {
45
+ const socket = connect({ host: host.replace(/^\[|\]$/g, ''), port });
46
+ const done = ok => {
47
+ socket.destroy();
48
+ resolve(ok);
49
+ };
50
+ socket.setTimeout(timeoutMs, () => done(false));
51
+ socket.once('connect', () => done(true));
52
+ socket.once('error', () => done(false));
53
+ });
54
+ }
55
+
56
+ /**
57
+ * The `net:` capabilities of the probes that currently connect.
58
+ *
59
+ * @param {ReturnType<typeof parseProbes>} probes
60
+ * @param {{ timeoutMs?: number, connect?: (host: string, port: number, timeoutMs: number) => Promise<boolean> }} [opts]
61
+ * @returns {Promise<string[]>}
62
+ */
63
+ export async function probeCapabilities(probes, { timeoutMs = 3000, connect: tryConnect = canConnect } = {}) {
64
+ const results = await Promise.all(probes.map(async p => ((await tryConnect(p.host, p.port, timeoutMs)) ? p.capabilities : [])));
65
+ return [...new Set(results.flat())].sort();
66
+ }