fffleet 2.1.1 → 2.3.1

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
@@ -50,6 +50,8 @@ export interface JobSpecInput {
50
50
  inputs?: Endpoint[];
51
51
  outputs?: Endpoint[];
52
52
  ffmpeg?: { args: string[]; durationMs?: number | null };
53
+ /** For `type: 'ffprobe'`: which sections to print (default format and streams). */
54
+ ffprobe?: { show?: ('format' | 'streams' | 'chapters' | 'programs')[] };
53
55
  [section: string]: unknown;
54
56
  }
55
57
 
@@ -91,6 +93,8 @@ export interface OutputResult {
91
93
  name: string;
92
94
  uri: string;
93
95
  bytes: number | null;
96
+ /** Small results returned inline instead of written to an endpoint, e.g. an ffprobe job's JSON (`uri: 'inline:'`). */
97
+ data?: unknown;
94
98
  }
95
99
 
96
100
  export interface JobEvent {
@@ -228,6 +232,7 @@ export function normalizeKinds(kinds?: JobKind[] | string): JobKind[];
228
232
  /** Slot pools sized from the CPU count: batch only cores/2, stream only cores, both: default cores/2 plus stream cores/4. */
229
233
  export function autoSlots(opts?: { cpus?: number; kinds?: JobKind[]; coresPerSlot?: number }): Record<string, number>;
230
234
  export function runFfmpegJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime): Promise<Required<ExecutorResult>>;
235
+ export function runFfprobeJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime & { ffprobePath?: string }): Promise<Required<ExecutorResult>>;
231
236
 
232
237
  export class JobHandle extends EventEmitter {
233
238
  readonly id: string;
@@ -286,6 +291,22 @@ export function createProgressParser(
286
291
  export function detectCapabilities(ffmpegPath?: string): Promise<string[]>;
287
292
  export function satisfies(capabilities: Iterable<string>, requires: string[]): boolean;
288
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
+
289
310
  export function readSse(
290
311
  body: ReadableStream<Uint8Array>,
291
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.1.1",
3
+ "version": "2.3.1",
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",
@@ -1,11 +1,12 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
+ import { siblingProbe } from './ffprobe.js';
3
4
 
4
5
  const run = promisify(execFile);
5
6
 
6
7
  /**
7
8
  * Lists what this machine can do, as capability strings matched against a spec's `requires`:
8
- * `type:ffmpeg`, `ffmpeg:<major.minor>`, `filter:<name>`, `encoder:<name>`, `font:<family>`.
9
+ * `type:ffmpeg`, `type:ffprobe`, `ffmpeg:<major.minor>`, `filter:<name>`, `encoder:<name>`, `font:<family>`.
9
10
  * Missing tools simply contribute nothing.
10
11
  *
11
12
  * @param {string} [ffmpegPath]
@@ -24,6 +25,7 @@ export async function detectCapabilities(ffmpegPath = 'ffmpeg') {
24
25
  const version = await out(ffmpegPath, ['-hide_banner', '-version']);
25
26
  const v = version.match(/ffmpeg version n?(\d+)\.(\d+)/);
26
27
  if (version) caps.add('type:ffmpeg');
28
+ if (await out(siblingProbe(ffmpegPath), ['-hide_banner', '-version'])) caps.add('type:ffprobe');
27
29
  if (v) caps.add(`ffmpeg:${v[1]}.${v[2]}`);
28
30
 
29
31
  // " T.. ass V->V Render ASS subtitles..."
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/ffprobe.js ADDED
@@ -0,0 +1,88 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import { dirname, extname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { HTTP_SCHEMES } from './contract.js';
6
+ import { FleetError } from './job-record.js';
7
+ import { parseS3Uri } from './s3.js';
8
+
9
+ const SHOW = ['format', 'streams', 'chapters', 'programs'];
10
+ const MAX_RESULT_BYTES = 1024 * 1024;
11
+ const DEFAULT_TIMEOUT_MS = 60_000;
12
+
13
+ /**
14
+ * Runs ffprobe on the job's single input and returns its JSON in the result.
15
+ *
16
+ * Spec: `type: 'ffprobe'`, `kind: 'batch'`, one input (file:, http(s): or s3:), no outputs, and an
17
+ * optional `ffprobe: { show?: ('format' | 'streams' | 'chapters' | 'programs')[] }` (default
18
+ * `['format', 'streams']`). http(s): inputs are read by ffprobe directly (it fetches only what it
19
+ * needs); s3: inputs are staged to the scratch directory first.
20
+ *
21
+ * Result: one output `{ name: 'probe', uri: 'inline:', bytes, data }` where `data` is ffprobe's JSON.
22
+ *
23
+ * @param {import('./types.js').JobSpec & { id: string, ffprobe?: { show?: string[] } }} spec
24
+ * @param {import('./executor.js').ExecutorRuntime & { ffprobePath?: string }} rt
25
+ */
26
+ export async function runFfprobeJob(spec, rt) {
27
+ if (spec.inputs.length !== 1) throw new FleetError('INVALID_SPEC', 'an ffprobe job takes exactly one input', { status: 422 });
28
+ if (spec.outputs.length) throw new FleetError('INVALID_SPEC', 'an ffprobe job takes no outputs; the result is returned inline', { status: 422 });
29
+ const show = spec.ffprobe?.show ?? ['format', 'streams'];
30
+ if (!Array.isArray(show) || !show.length || show.some(s => !SHOW.includes(s))) {
31
+ throw new FleetError('INVALID_SPEC', `ffprobe.show must list some of ${SHOW.join(', ')}`, { status: 422 });
32
+ }
33
+
34
+ const input = spec.inputs[0];
35
+ const url = new URL(input.uri);
36
+ let target = input.uri;
37
+ if (url.protocol === 'file:') {
38
+ target = fileURLToPath(url);
39
+ } else if (url.protocol === 's3:') {
40
+ if (!rt.s3) throw new FleetError('UNSUPPORTED_SCHEME', 'this runner has no S3 credentials for s3: URIs');
41
+ const { bucket, key } = parseS3Uri(input.uri);
42
+ target = join(rt.workDir, 'in', input.name, `file${extname(key)}`);
43
+ await mkdir(dirname(target), { recursive: true });
44
+ rt.setState('staging');
45
+ try {
46
+ await rt.s3.getFile(bucket, key, target, { signal: rt.signal });
47
+ } catch (err) {
48
+ if (rt.signal.aborted) throw rt.signal.reason;
49
+ throw new FleetError('INPUT_FAILED', `could not fetch input "${input.name}": ${err.message}`);
50
+ }
51
+ } else if (!HTTP_SCHEMES.includes(url.protocol)) {
52
+ throw new FleetError('UNSUPPORTED_SCHEME', `ffprobe cannot read ${url.protocol} inputs`);
53
+ }
54
+
55
+ const args = ['-v', 'error', '-print_format', 'json', ...show.map(s => `-show_${s}`), target];
56
+ rt.setState('running');
57
+ const stdout = await runFfprobe(rt.ffprobePath ?? siblingProbe(rt.ffmpegPath), args, spec.timeoutMs ?? DEFAULT_TIMEOUT_MS, rt);
58
+
59
+ let data;
60
+ try {
61
+ data = JSON.parse(stdout);
62
+ } catch {
63
+ throw new FleetError('FFPROBE_OUTPUT', 'ffprobe printed output that is not JSON');
64
+ }
65
+ return { exitCode: 0, outputs: [{ name: 'probe', uri: 'inline:', bytes: Buffer.byteLength(stdout), data }], stderrTail: null };
66
+ }
67
+
68
+ /** `/opt/ffmpeg/bin/ffmpeg` -> `/opt/ffmpeg/bin/ffprobe`; plain `ffmpeg` -> `ffprobe`. */
69
+ export function siblingProbe(ffmpegPath) {
70
+ if (!ffmpegPath) return 'ffprobe';
71
+ return ffmpegPath.replace(/ffmpeg(\.exe)?$/i, 'ffprobe$1');
72
+ }
73
+
74
+ function runFfprobe(cmd, args, timeoutMs, rt) {
75
+ return new Promise((resolve, reject) => {
76
+ const child = execFile(cmd, args, { maxBuffer: MAX_RESULT_BYTES, timeout: timeoutMs, signal: rt.signal }, (err, stdout, stderr) => {
77
+ if (rt.signal.aborted) return reject(rt.signal.reason);
78
+ if (err) {
79
+ if (err.code === 'ENOENT') return reject(new FleetError('SPAWN_FAILED', `could not start ${cmd}: ${err.message}`));
80
+ if (err.killed) return reject(new FleetError('TIMEOUT', `ffprobe did not finish within ${timeoutMs} ms`));
81
+ const tail = String(stderr).trim().slice(-2048) || null;
82
+ return reject(new FleetError('FFPROBE_EXIT', `ffprobe exited with code ${err.code}`, { details: { exitCode: typeof err.code === 'number' ? err.code : null, stderrTail: tail } }));
83
+ }
84
+ resolve(stdout);
85
+ });
86
+ child.stdin?.end();
87
+ });
88
+ }
package/src/index.js CHANGED
@@ -6,8 +6,10 @@ export {
6
6
  export { JobManager, normalizeSlots, normalizeKinds, autoSlots } from './job-manager.js';
7
7
  export { JobRecord, FleetError, byPriority, pruneFinished } from './job-record.js';
8
8
  export { runFfmpegJob } from './executor.js';
9
+ export { runFfprobeJob } from './ffprobe.js';
9
10
  export { createProgressParser } from './progress.js';
10
11
  export { detectCapabilities, satisfies } from './capabilities.js';
12
+ export { canConnect, parseProbes, probeCapabilities } from './probe.js';
11
13
  export { readSse, followJobEvents } from './sse.js';
12
14
  export { createS3Client, s3ConfigFromEnv, parseS3Uri, contentTypeFor, signV4 } from './s3.js';
13
15
  export { SCOPES, hashSecret, verifySecret, generateSecret, createTokenProvider } from './auth.js';
@@ -8,6 +8,7 @@ import { KINDS, canonicalJson, implicitRequirements, parseSpec } from './contrac
8
8
  import { createInputCache, parseSize } from './input-cache.js';
9
9
  import { createS3Client } from './s3.js';
10
10
  import { runFfmpegJob } from './executor.js';
11
+ import { runFfprobeJob } from './ffprobe.js';
11
12
  import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.js';
12
13
 
13
14
  /**
@@ -60,7 +61,7 @@ export class JobManager extends EventEmitter {
60
61
  this.maxQueued = maxQueued;
61
62
  this.keepFinished = keepFinished;
62
63
  this.progressIntervalMs = progressIntervalMs;
63
- this.executors = { ffmpeg: runFfmpegJob, ...executors };
64
+ this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, ...executors };
64
65
  this.workerId = workerId;
65
66
  this.fetch = fetchImpl;
66
67
  this.cache = cache ? createInputCache({ dir: cache.dir, maxBytes: cache.maxBytes === undefined ? undefined : parseSize(cache.maxBytes) }) : null;
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
+ }
package/src/types.js CHANGED
@@ -41,6 +41,7 @@
41
41
  * @property {string} name
42
42
  * @property {string} uri
43
43
  * @property {number | null} bytes
44
+ * @property {unknown} [data] Small result returned inline (an ffprobe job's JSON, `uri: 'inline:'`).
44
45
  *
45
46
  * @typedef {object} JobEvent
46
47
  * @property {string} jobId