fffleet 1.0.0 → 2.1.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
@@ -26,6 +26,8 @@ await job.cancel();
26
26
  const final = await job.done; // final snapshot: state, error, outputs, exitCode, stderrTail
27
27
  ```
28
28
 
29
+ While a job runs, `job.on('stderr', tail => ...)` and `job.stderrTail` give ffmpeg's newest stderr lines, which is how you diagnose a stream job that never exits.
30
+
29
31
  `job.where` is `'local'` or `'remote'`. `fleet.capabilities()` reports slots and capabilities.
30
32
 
31
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.
package/index.d.ts CHANGED
@@ -45,6 +45,8 @@ export interface JobSpecInput {
45
45
  timeoutMs?: number | null;
46
46
  /** Keep ffmpeg's stdin open for writes through the API. */
47
47
  stdin?: boolean;
48
+ /** Stream jobs only: ffmpeg's `pipe:1` is readable through `job.stdout()`. No `-progress` is reported. */
49
+ stdout?: boolean;
48
50
  inputs?: Endpoint[];
49
51
  outputs?: Endpoint[];
50
52
  ffmpeg?: { args: string[]; durationMs?: number | null };
@@ -140,7 +142,10 @@ export interface ExecutorRuntime {
140
142
  signal: AbortSignal;
141
143
  setState(state: JobState, extra?: object): void;
142
144
  progress(progress: Progress): void;
145
+ /** Reports the newest stderr lines while the job runs (called often; the manager throttles). */
146
+ stderr?(tail: string): void;
143
147
  attachStdin(stdin: Writable | null): void;
148
+ attachStdout?(stdout: import('node:stream').Readable): void;
144
149
  ffmpegPath?: string;
145
150
  fetch?: typeof fetch;
146
151
  s3?: S3Client | null;
@@ -212,14 +217,21 @@ export class JobHandle extends EventEmitter {
212
217
  readonly id: string;
213
218
  readonly where: 'local' | 'remote';
214
219
  state: JobState;
220
+ /** The newest stderr lines ffmpeg wrote while the job runs (null until it writes any). */
221
+ stderrTail: string | null;
215
222
  snapshot: JobSnapshot | null;
216
223
  /** Resolves with the final snapshot whatever the outcome; check `state`. */
217
224
  readonly done: Promise<JobSnapshot>;
218
225
  cancel(): Promise<unknown>;
219
226
  write(data: Buffer | string): Promise<{ bytes: number }>;
227
+ /** Closes ffmpeg's stdin (EOF) after the last write. */
228
+ endStdin(): Promise<{ closed: boolean }>;
229
+ /** ffmpeg's stdout as a Readable (the job must have been submitted with `stdout: true`). */
230
+ stdout(): Promise<import('node:stream').Readable>;
220
231
  on(event: 'event', listener: (event: JobEvent) => void): this;
221
232
  on(event: 'state', listener: (state: JobState, event: JobEvent) => void): this;
222
233
  on(event: 'progress', listener: (progress: Progress, event: JobEvent) => void): this;
234
+ on(event: 'stderr', listener: (stderrTail: string, event: JobEvent) => void): this;
223
235
  on(event: string | symbol, listener: (...args: any[]) => void): this;
224
236
  }
225
237
 
@@ -275,6 +287,8 @@ export function followJobEvents(opts: {
275
287
 
276
288
  export class JobRecord {
277
289
  constructor(spec: JobSpec & { id: string });
290
+ /** Rebuilds a record from saved fields (state, history, order, ...). */
291
+ static restore(spec: JobSpec & { id: string }, saved: Record<string, unknown>): JobRecord;
278
292
  readonly id: string;
279
293
  readonly final: boolean;
280
294
  state: JobState;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet",
3
- "version": "1.0.0",
3
+ "version": "2.1.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/server.d.ts CHANGED
@@ -41,6 +41,7 @@ export function close(server: Server): Promise<void>;
41
41
  export function checkBearer(req: IncomingMessage, token: string | null): boolean;
42
42
  export function send(res: ServerResponse, status: number, body: unknown, headers?: Record<string, string>): void;
43
43
  export function sendError(res: ServerResponse, err: unknown): void;
44
+ export function getStream(url: string, opts?: { headers?: Record<string, string>; signal?: AbortSignal }): Promise<import('node:http').IncomingMessage>;
44
45
  export function readBody(req: IncomingMessage, limit: number): Promise<Buffer>;
45
46
  export function readJson(req: IncomingMessage): Promise<unknown>;
46
47
 
package/src/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { getStream } from './http-stream.js';
2
3
  import { EventEmitter } from 'node:events';
3
4
  import { isFinal, parseSpec } from './contract.js';
4
5
  import { detectCapabilities } from './capabilities.js';
@@ -9,7 +10,7 @@ import { followJobEvents } from './sse.js';
9
10
 
10
11
  /**
11
12
  * A handle to one submitted job, local or remote.
12
- * Events: 'event' (every JobEvent), 'state' (state, event), 'progress' (progress, event).
13
+ * Events: 'event' (every JobEvent), 'state' (state, event), 'progress' (progress, event), 'stderr' (newest ffmpeg stderr lines, event).
13
14
  * `done` resolves with the final snapshot whatever the outcome; check `state`.
14
15
  */
15
16
  export class JobHandle extends EventEmitter {
@@ -21,6 +22,8 @@ export class JobHandle extends EventEmitter {
21
22
  this.state = 'queued';
22
23
  /** @type {import('./types.js').JobSnapshot | null} */
23
24
  this.snapshot = null;
25
+ /** The newest stderr lines ffmpeg wrote while the job runs (null until it writes any). */
26
+ this.stderrTail = null;
24
27
  let resolve, reject;
25
28
  /** @type {Promise<import('./types.js').JobSnapshot>} */
26
29
  this.done = new Promise((res, rej) => {
@@ -35,6 +38,10 @@ export class JobHandle extends EventEmitter {
35
38
  _event(event) {
36
39
  this.emit('event', event);
37
40
  if (event.progress) this.emit('progress', event.progress, event);
41
+ if (event.stderrTail) {
42
+ this.stderrTail = event.stderrTail;
43
+ this.emit('stderr', event.stderrTail, event);
44
+ }
38
45
  if (event.state !== this.state) {
39
46
  this.state = event.state;
40
47
  this.emit('state', event.state, event);
@@ -46,6 +53,19 @@ export class JobHandle extends EventEmitter {
46
53
  return this._cancel();
47
54
  }
48
55
 
56
+ /**
57
+ * Opens ffmpeg's stdout (spec.stdout must be true) as a Readable. One reader per job; it ends with the job.
58
+ * @returns {Promise<import('node:stream').Readable>}
59
+ */
60
+ stdout() {
61
+ return this._stdout();
62
+ }
63
+
64
+ /** Closes the job's stdin (EOF for ffmpeg), after the last write. */
65
+ endStdin() {
66
+ return this._endStdin();
67
+ }
68
+
49
69
  /** Writes to the job's stdin (spec.stdin must be true). */
50
70
  write(data) {
51
71
  return this._write(typeof data === 'string' ? Buffer.from(data) : data);
@@ -104,6 +124,8 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
104
124
  const handle = new JobHandle(job.id, 'local');
105
125
  handle._cancel = async () => m.cancel(job.id);
106
126
  handle._write = data => m.writeStdin(job.id, data);
127
+ handle._endStdin = () => m.closeStdin(job.id);
128
+ handle._stdout = async () => m.openStdout(job.id);
107
129
  m.subscribe(job.id, 0, event => {
108
130
  handle._event(event);
109
131
  if (isFinal(event.state)) {
@@ -123,6 +145,8 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
123
145
  const enc = encodeURIComponent(job.id);
124
146
  handle._cancel = () => request('DELETE', `/v1/jobs/${enc}`);
125
147
  handle._write = data => request('POST', `/v1/jobs/${enc}/stdin`, data, { 'content-type': 'application/octet-stream' });
148
+ handle._endStdin = () => request('POST', `/v1/jobs/${enc}/stdin/close`);
149
+ handle._stdout = async () => getStream(`${base}/v1/jobs/${enc}/stdout`, { headers: await authHeaders(), signal: ac.signal });
126
150
  followJobEvents({ url: `${base}/v1/jobs/${enc}/events`, headers: authHeaders, signal: ac.signal, fetch: f, onEvent: e => handle._event(e) })
127
151
  .then(async () => {
128
152
  handle.snapshot = await request('GET', `/v1/jobs/${enc}`).catch(() => handle.snapshot);
package/src/contract.js CHANGED
@@ -88,6 +88,10 @@ export function validateSpec(input) {
88
88
  const stdin = s.stdin ?? false;
89
89
  if (typeof stdin !== 'boolean') err('stdin', 'must be a boolean');
90
90
 
91
+ const stdout = s.stdout ?? false;
92
+ if (typeof stdout !== 'boolean') err('stdout', 'must be a boolean');
93
+ else if (stdout && s.kind !== 'stream') err('stdout', 'is only allowed for stream jobs');
94
+
91
95
  const requires = s.requires ?? [];
92
96
  if (!Array.isArray(requires) || requires.some(r => typeof r !== 'string' || !r)) err('requires', 'must be an array of capability strings');
93
97
 
@@ -128,6 +132,7 @@ export function validateSpec(input) {
128
132
  labels: { ...labels },
129
133
  timeoutMs,
130
134
  stdin,
135
+ stdout,
131
136
  inputs,
132
137
  outputs,
133
138
  };
package/src/executor.js CHANGED
@@ -85,7 +85,7 @@ export async function runFfmpegJob(spec, rt) {
85
85
  rt.signal.throwIfAborted();
86
86
 
87
87
  const args = [
88
- '-hide_banner', '-nostats', '-loglevel', 'warning', '-progress', 'pipe:1',
88
+ '-hide_banner', '-nostats', '-loglevel', 'warning', ...(spec.stdout ? [] : ['-progress', 'pipe:1']),
89
89
  ...(spec.stdin ? [] : ['-nostdin']),
90
90
  ...(batch ? ['-y'] : []),
91
91
  ...resolvePlaceholders(spec.ffmpeg.args, values),
@@ -232,11 +232,16 @@ function runProcess(cmd, args, spec, rt) {
232
232
  rt.progress(progress);
233
233
  }, { durationMs: spec.ffmpeg.durationMs });
234
234
 
235
- child.stdout.setEncoding('utf8');
236
- child.stdout.on('data', parse);
235
+ if (spec.stdout) {
236
+ rt.attachStdout?.(child.stdout);
237
+ } else {
238
+ child.stdout.setEncoding('utf8');
239
+ child.stdout.on('data', parse);
240
+ }
237
241
  child.stderr.setEncoding('utf8');
238
242
  child.stderr.on('data', d => {
239
243
  tail = (tail + d).slice(-STDERR_TAIL_BYTES);
244
+ rt.stderr?.(tail.trim());
240
245
  });
241
246
  if (child.stdin) {
242
247
  child.stdin.on('error', () => {});
@@ -244,6 +249,13 @@ function runProcess(cmd, args, spec, rt) {
244
249
  }
245
250
 
246
251
  const onAbort = () => {
252
+ if (process.platform === 'win32') {
253
+ // SIGTERM is TerminateProcess here, which stops only the process we started. An ffmpeg started
254
+ // through a launcher shim (Chocolatey, Scoop) would keep running with our pipes open and the
255
+ // job would never end, so stop the whole tree.
256
+ killTree(child);
257
+ return;
258
+ }
247
259
  child.kill('SIGTERM');
248
260
  killTimer = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);
249
261
  killTimer.unref?.();
@@ -269,3 +281,12 @@ function runProcess(cmd, args, spec, rt) {
269
281
  });
270
282
  });
271
283
  }
284
+
285
+ /** Windows: ends a process and everything it started. Falls back to killing just the child. */
286
+ function killTree(child) {
287
+ try {
288
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).once('error', () => child.kill());
289
+ } catch {
290
+ child.kill();
291
+ }
292
+ }
package/src/http-api.js CHANGED
@@ -15,6 +15,8 @@ const SSE_KEEPALIVE_MS = 15000;
15
15
  * @property {() => any[]} list
16
16
  * @property {(id: string) => any | Promise<any>} cancel
17
17
  * @property {(id: string, data: Buffer) => Promise<any>} writeStdin
18
+ * @property {(id: string) => Promise<any>} closeStdin
19
+ * @property {(id: string) => import('node:stream').Readable | Promise<import('node:stream').Readable>} openStdout
18
20
  * @property {(id: string, afterSeq: number, fn: (e: any) => void) => () => void} subscribe
19
21
  * @property {() => any} capabilities
20
22
  */
@@ -61,7 +63,7 @@ export function createApiHandler({ backend, token = null, authenticate = createA
61
63
  if (req.method === 'GET') return send(res, 200, { jobs: backend.list().filter(mine) });
62
64
  }
63
65
 
64
- const m = url.pathname.match(/^\/v1\/jobs\/([^/]+)(\/events|\/stdin)?$/);
66
+ const m = url.pathname.match(/^\/v1\/jobs\/([^/]+)(\/events|\/stdin|\/stdin\/close|\/stdout)?$/);
65
67
  if (m) {
66
68
  const id = decodeURIComponent(m[1]);
67
69
  // Someone else's job answers 404, the same as a job that does not exist.
@@ -72,6 +74,14 @@ export function createApiHandler({ backend, token = null, authenticate = createA
72
74
  return job ? send(res, 202, job) : notFound(res, id);
73
75
  }
74
76
  if (m[2] === '/events' && req.method === 'GET') return streamEvents(req, res, url, backend, id);
77
+ if (m[2] === '/stdin/close' && req.method === 'POST') return send(res, 200, { ok: true, ...(await backend.closeStdin(id)) });
78
+ if (m[2] === '/stdout' && req.method === 'GET') {
79
+ const stream = await backend.openStdout(id);
80
+ res.writeHead(200, { 'content-type': 'application/octet-stream', 'cache-control': 'no-cache', 'x-accel-buffering': 'no' });
81
+ res.on('close', () => stream.unpipe?.(res));
82
+ stream.pipe(res);
83
+ return;
84
+ }
75
85
  if (m[2] === '/stdin' && req.method === 'POST') {
76
86
  const data = await readBody(req, STDIN_LIMIT);
77
87
  return send(res, 200, { ok: true, ...(await backend.writeStdin(id, data)) });
@@ -0,0 +1,29 @@
1
+ import { request as httpRequest } from 'node:http';
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { FleetError } from './job-record.js';
4
+
5
+ /**
6
+ * GET a long-lived binary response as a Readable (node:http, not fetch: a body that is read
7
+ * slowly or ended by the server must not trip fetch's body handling).
8
+ *
9
+ * @param {string} url
10
+ * @param {{ headers?: Record<string, string>, signal?: AbortSignal }} [opts]
11
+ * @returns {Promise<import('node:http').IncomingMessage>}
12
+ */
13
+ export function getStream(url, { headers = {}, signal } = {}) {
14
+ return new Promise((resolve, reject) => {
15
+ const request = url.startsWith('https:') ? httpsRequest : httpRequest;
16
+ const req = request(url, { method: 'GET', headers, signal }, res => {
17
+ if (res.statusCode === 200) return resolve(res);
18
+ const chunks = [];
19
+ res.on('data', c => chunks.push(c));
20
+ res.on('end', () => {
21
+ let body = null;
22
+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { /* not JSON */ }
23
+ reject(new FleetError(body?.error?.code ?? 'HTTP_ERROR', body?.error?.message ?? `HTTP ${res.statusCode}`, { status: res.statusCode }));
24
+ });
25
+ });
26
+ req.once('error', reject);
27
+ req.end();
28
+ });
29
+ }
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { PassThrough } from 'node:stream';
2
3
  import { EventEmitter } from 'node:events';
3
4
  import { mkdir, rm } from 'node:fs/promises';
4
5
  import { availableParallelism, tmpdir } from 'node:os';
@@ -111,6 +112,7 @@ export class JobManager extends EventEmitter {
111
112
 
112
113
  pruneFinished(this.jobs, this.keepFinished);
113
114
  const record = new JobRecord(spec);
115
+ if (spec.stdout) record.stdoutPipe = new PassThrough();
114
116
  this.jobs.set(spec.id, record);
115
117
  this.queue.push(record);
116
118
  this.queue.sort(byPriority);
@@ -147,6 +149,7 @@ export class JobManager extends EventEmitter {
147
149
  if (idx >= 0) {
148
150
  this.queue.splice(idx, 1);
149
151
  record.push({ state: 'cancelled', error: { code: 'CANCELLED', message: 'cancelled before it started' } });
152
+ record.stdoutPipe?.end();
150
153
  return record.snapshot();
151
154
  }
152
155
  record.run?.abort.abort(new FleetError('CANCELLED', 'cancelled'));
@@ -164,6 +167,30 @@ export class JobManager extends EventEmitter {
164
167
  return { bytes: Buffer.byteLength(data) };
165
168
  }
166
169
 
170
+ /** Closes a running job's stdin (EOF to ffmpeg), e.g. after sending a whole input. */
171
+ async closeStdin(id) {
172
+ const record = this.jobs.get(id);
173
+ if (!record) throw new FleetError('NOT_FOUND', `job ${id} not found`, { status: 404 });
174
+ if (!record.spec.stdin) throw new FleetError('NO_STDIN', 'job was not started with stdin: true', { status: 409 });
175
+ const stdin = record.run?.stdin;
176
+ if (!stdin || record.final) throw new FleetError('NOT_RUNNING', 'job is not running', { status: 409 });
177
+ await new Promise(resolve => stdin.end(resolve));
178
+ return { closed: true };
179
+ }
180
+
181
+ /**
182
+ * Opens a stdout job's output as a Readable (one reader per job; it ends when the job does).
183
+ * Until a reader is attached ffmpeg stalls once the pipe's buffer is full.
184
+ */
185
+ openStdout(id) {
186
+ const record = this.jobs.get(id);
187
+ if (!record) throw new FleetError('NOT_FOUND', `job ${id} not found`, { status: 404 });
188
+ if (!record.stdoutPipe) throw new FleetError('NO_STDOUT', 'job was not started with stdout: true', { status: 409 });
189
+ if (record.stdoutOpened) throw new FleetError('STDOUT_TAKEN', 'stdout already has a reader', { status: 409 });
190
+ record.stdoutOpened = true;
191
+ return record.stdoutPipe;
192
+ }
193
+
167
194
  stats() {
168
195
  const pools = Object.fromEntries(Object.keys(this.slots).map(k => [k, { total: this.slots[k], used: this.used[k] }]));
169
196
  return { pools, queued: this.queue.length, running: Object.values(this.used).reduce((a, b) => a + b, 0) };
@@ -197,6 +224,7 @@ export class JobManager extends EventEmitter {
197
224
  }
198
225
 
199
226
  let lastProgressAt = 0;
227
+ let lastStderrAt = 0;
200
228
  const workDir = join(this.workRoot, record.id.replace(/[^A-Za-z0-9._-]/g, '_'));
201
229
  const runtime = {
202
230
  workDir,
@@ -218,9 +246,22 @@ export class JobManager extends EventEmitter {
218
246
  lastProgressAt = now;
219
247
  if (!abort.signal.aborted) record.push({ progress: p });
220
248
  },
249
+ // The newest stderr lines of a running job, so a failing stream job can be diagnosed before it ends.
250
+ stderr: tail => {
251
+ const now = Date.now();
252
+ if (now - lastStderrAt < this.progressIntervalMs) {
253
+ record.stderrTail = tail;
254
+ return;
255
+ }
256
+ lastStderrAt = now;
257
+ if (!abort.signal.aborted) record.push({ stderrTail: tail });
258
+ },
221
259
  attachStdin: s => {
222
260
  run.stdin = s;
223
261
  },
262
+ attachStdout: s => {
263
+ if (record.stdoutPipe) s.pipe(record.stdoutPipe, { end: false });
264
+ },
224
265
  transfer: (direction, scheme, bytes) => {
225
266
  if (bytes > 0) this.emit('transfer', { direction, scheme, bytes });
226
267
  },
@@ -244,6 +285,7 @@ export class JobManager extends EventEmitter {
244
285
  });
245
286
  } finally {
246
287
  clearTimeout(timer);
288
+ record.stdoutPipe?.end();
247
289
  run.stdin = null;
248
290
  run.pid = null;
249
291
  this.used[pool]--;
package/src/job-record.js CHANGED
@@ -51,6 +51,25 @@ export class JobRecord {
51
51
  return isFinal(this.state);
52
52
  }
53
53
 
54
+ /**
55
+ * Rebuilds a record from a saved one (an orchestrator restoring its jobs after a restart).
56
+ * Subscribers start from the saved history.
57
+ * @param {import('./types.js').JobSpec & { id: string }} spec
58
+ * @param {Record<string, any>} saved
59
+ */
60
+ static restore(spec, saved) {
61
+ const job = new JobRecord(spec);
62
+ for (const key of ['state', 'workerId', 'createdAt', 'startedAt', 'finishedAt', 'progress', 'exitCode', 'error', 'outputs', 'stderrTail', 'seq']) {
63
+ if (saved[key] !== undefined) job[key] = saved[key];
64
+ }
65
+ if (Array.isArray(saved.history) && saved.history.length) job.history = saved.history;
66
+ if (Number.isInteger(saved.order)) {
67
+ job.order = saved.order;
68
+ order = Math.max(order, saved.order);
69
+ }
70
+ return job;
71
+ }
72
+
54
73
  /**
55
74
  * Appends an event. A state change or a final result updates the snapshot too.
56
75
  * Events after the final one are ignored, so a job is final exactly once.
@@ -63,6 +82,7 @@ export class JobRecord {
63
82
  if (state === 'running' && !this.startedAt) this.startedAt = now;
64
83
  if (fields.workerId !== undefined) this.workerId = fields.workerId;
65
84
  if (fields.progress) this.progress = fields.progress;
85
+ if (fields.stderrTail !== undefined && !isFinal(state)) this.stderrTail = fields.stderrTail;
66
86
  this.state = state;
67
87
  if (isFinal(state)) {
68
88
  this.finishedAt = now;
package/src/server.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Building blocks for fffleet-worker and fffleet-orchestrator. Not needed by applications.
2
2
  export { createApiHandler, allowed, listen, close, checkBearer, send, sendError, readBody, readJson } from './http-api.js';
3
+ export { getStream } from './http-stream.js';
3
4
  export { Registry, jobMetrics, processMetrics, hostMetrics, procStats, METRICS_CONTENT_TYPE } from './metrics.js';
4
5
  export {
5
6
  SCOPES, hashSecret, verifySecret, generateSecret, loadSigningKey, createTokenSigner, createTokenVerifier,
package/src/types.js CHANGED
@@ -21,6 +21,7 @@
21
21
  * @property {Record<string, string>} labels
22
22
  * @property {number | null} timeoutMs
23
23
  * @property {boolean} stdin Keep ffmpeg's stdin open for POST /v1/jobs/:id/stdin.
24
+ * @property {boolean} stdout Hand ffmpeg's stdout (`pipe:1`) to GET /v1/jobs/:id/stdout. Stream jobs only; no `-progress` is reported then.
24
25
  * @property {Endpoint[]} inputs
25
26
  * @property {Endpoint[]} outputs
26
27
  * @property {{ args: string[], durationMs: number | null }} [ffmpeg]