fffleet 1.0.0 → 2.0.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/index.d.ts +7 -0
- package/package.json +1 -1
- package/server.d.ts +1 -0
- package/src/client.js +18 -0
- package/src/contract.js +5 -0
- package/src/executor.js +7 -3
- package/src/http-api.js +11 -1
- package/src/http-stream.js +29 -0
- package/src/job-manager.js +31 -0
- package/src/server.js +1 -0
- package/src/types.js +1 -0
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 };
|
|
@@ -141,6 +143,7 @@ export interface ExecutorRuntime {
|
|
|
141
143
|
setState(state: JobState, extra?: object): void;
|
|
142
144
|
progress(progress: Progress): void;
|
|
143
145
|
attachStdin(stdin: Writable | null): void;
|
|
146
|
+
attachStdout?(stdout: import('node:stream').Readable): void;
|
|
144
147
|
ffmpegPath?: string;
|
|
145
148
|
fetch?: typeof fetch;
|
|
146
149
|
s3?: S3Client | null;
|
|
@@ -217,6 +220,10 @@ export class JobHandle extends EventEmitter {
|
|
|
217
220
|
readonly done: Promise<JobSnapshot>;
|
|
218
221
|
cancel(): Promise<unknown>;
|
|
219
222
|
write(data: Buffer | string): Promise<{ bytes: number }>;
|
|
223
|
+
/** Closes ffmpeg's stdin (EOF) after the last write. */
|
|
224
|
+
endStdin(): Promise<{ closed: boolean }>;
|
|
225
|
+
/** ffmpeg's stdout as a Readable (the job must have been submitted with `stdout: true`). */
|
|
226
|
+
stdout(): Promise<import('node:stream').Readable>;
|
|
220
227
|
on(event: 'event', listener: (event: JobEvent) => void): this;
|
|
221
228
|
on(event: 'state', listener: (state: JobState, event: JobEvent) => void): this;
|
|
222
229
|
on(event: 'progress', listener: (progress: Progress, event: JobEvent) => void): this;
|
package/package.json
CHANGED
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';
|
|
@@ -46,6 +47,19 @@ export class JobHandle extends EventEmitter {
|
|
|
46
47
|
return this._cancel();
|
|
47
48
|
}
|
|
48
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Opens ffmpeg's stdout (spec.stdout must be true) as a Readable. One reader per job; it ends with the job.
|
|
52
|
+
* @returns {Promise<import('node:stream').Readable>}
|
|
53
|
+
*/
|
|
54
|
+
stdout() {
|
|
55
|
+
return this._stdout();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Closes the job's stdin (EOF for ffmpeg), after the last write. */
|
|
59
|
+
endStdin() {
|
|
60
|
+
return this._endStdin();
|
|
61
|
+
}
|
|
62
|
+
|
|
49
63
|
/** Writes to the job's stdin (spec.stdin must be true). */
|
|
50
64
|
write(data) {
|
|
51
65
|
return this._write(typeof data === 'string' ? Buffer.from(data) : data);
|
|
@@ -104,6 +118,8 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
|
|
|
104
118
|
const handle = new JobHandle(job.id, 'local');
|
|
105
119
|
handle._cancel = async () => m.cancel(job.id);
|
|
106
120
|
handle._write = data => m.writeStdin(job.id, data);
|
|
121
|
+
handle._endStdin = () => m.closeStdin(job.id);
|
|
122
|
+
handle._stdout = async () => m.openStdout(job.id);
|
|
107
123
|
m.subscribe(job.id, 0, event => {
|
|
108
124
|
handle._event(event);
|
|
109
125
|
if (isFinal(event.state)) {
|
|
@@ -123,6 +139,8 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
|
|
|
123
139
|
const enc = encodeURIComponent(job.id);
|
|
124
140
|
handle._cancel = () => request('DELETE', `/v1/jobs/${enc}`);
|
|
125
141
|
handle._write = data => request('POST', `/v1/jobs/${enc}/stdin`, data, { 'content-type': 'application/octet-stream' });
|
|
142
|
+
handle._endStdin = () => request('POST', `/v1/jobs/${enc}/stdin/close`);
|
|
143
|
+
handle._stdout = async () => getStream(`${base}/v1/jobs/${enc}/stdout`, { headers: await authHeaders(), signal: ac.signal });
|
|
126
144
|
followJobEvents({ url: `${base}/v1/jobs/${enc}/events`, headers: authHeaders, signal: ac.signal, fetch: f, onEvent: e => handle._event(e) })
|
|
127
145
|
.then(async () => {
|
|
128
146
|
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,8 +232,12 @@ function runProcess(cmd, args, spec, rt) {
|
|
|
232
232
|
rt.progress(progress);
|
|
233
233
|
}, { durationMs: spec.ffmpeg.durationMs });
|
|
234
234
|
|
|
235
|
-
|
|
236
|
-
|
|
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);
|
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
|
+
}
|
package/src/job-manager.js
CHANGED
|
@@ -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) };
|
|
@@ -221,6 +248,9 @@ export class JobManager extends EventEmitter {
|
|
|
221
248
|
attachStdin: s => {
|
|
222
249
|
run.stdin = s;
|
|
223
250
|
},
|
|
251
|
+
attachStdout: s => {
|
|
252
|
+
if (record.stdoutPipe) s.pipe(record.stdoutPipe, { end: false });
|
|
253
|
+
},
|
|
224
254
|
transfer: (direction, scheme, bytes) => {
|
|
225
255
|
if (bytes > 0) this.emit('transfer', { direction, scheme, bytes });
|
|
226
256
|
},
|
|
@@ -244,6 +274,7 @@ export class JobManager extends EventEmitter {
|
|
|
244
274
|
});
|
|
245
275
|
} finally {
|
|
246
276
|
clearTimeout(timer);
|
|
277
|
+
record.stdoutPipe?.end();
|
|
247
278
|
run.stdin = null;
|
|
248
279
|
run.pid = null;
|
|
249
280
|
this.used[pool]--;
|
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]
|