fffleet 0.0.0-stage → 0.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/LICENSE +190 -0
- package/README.md +32 -2
- package/index.d.ts +255 -0
- package/package.json +52 -4
- package/server.d.ts +29 -0
- package/src/capabilities.js +49 -0
- package/src/client.js +159 -0
- package/src/contract.js +201 -0
- package/src/executor.js +200 -0
- package/src/http-api.js +166 -0
- package/src/index.js +11 -0
- package/src/job-manager.js +240 -0
- package/src/job-record.js +148 -0
- package/src/progress.js +48 -0
- package/src/server.js +2 -0
- package/src/sse.js +95 -0
- package/src/types.js +76 -0
package/src/client.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
import { isFinal, parseSpec } from './contract.js';
|
|
4
|
+
import { detectCapabilities } from './capabilities.js';
|
|
5
|
+
import { JobManager } from './job-manager.js';
|
|
6
|
+
import { FleetError } from './job-record.js';
|
|
7
|
+
import { followJobEvents } from './sse.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A handle to one submitted job, local or remote.
|
|
11
|
+
* Events: 'event' (every JobEvent), 'state' (state, event), 'progress' (progress, event).
|
|
12
|
+
* `done` resolves with the final snapshot whatever the outcome; check `state`.
|
|
13
|
+
*/
|
|
14
|
+
export class JobHandle extends EventEmitter {
|
|
15
|
+
constructor(id, where) {
|
|
16
|
+
super();
|
|
17
|
+
this.id = id;
|
|
18
|
+
/** 'local' or 'remote' */
|
|
19
|
+
this.where = where;
|
|
20
|
+
this.state = 'queued';
|
|
21
|
+
/** @type {import('./types.js').JobSnapshot | null} */
|
|
22
|
+
this.snapshot = null;
|
|
23
|
+
let resolve, reject;
|
|
24
|
+
/** @type {Promise<import('./types.js').JobSnapshot>} */
|
|
25
|
+
this.done = new Promise((res, rej) => {
|
|
26
|
+
resolve = res;
|
|
27
|
+
reject = rej;
|
|
28
|
+
});
|
|
29
|
+
this.done.catch(() => {});
|
|
30
|
+
this._resolve = resolve;
|
|
31
|
+
this._reject = reject;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
_event(event) {
|
|
35
|
+
this.emit('event', event);
|
|
36
|
+
if (event.progress) this.emit('progress', event.progress, event);
|
|
37
|
+
if (event.state !== this.state) {
|
|
38
|
+
this.state = event.state;
|
|
39
|
+
this.emit('state', event.state, event);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Cancels or stops the job. */
|
|
44
|
+
cancel() {
|
|
45
|
+
return this._cancel();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Writes to the job's stdin (spec.stdin must be true). */
|
|
49
|
+
write(data) {
|
|
50
|
+
return this._write(typeof data === 'string' ? Buffer.from(data) : data);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Creates a client. With no `url` every job runs on this machine. With a `url` (a worker or an
|
|
56
|
+
* orchestrator, same API) jobs go there; if it cannot be reached and `fallback` is 'local',
|
|
57
|
+
* the job runs here instead.
|
|
58
|
+
*
|
|
59
|
+
* @param {object} [opts]
|
|
60
|
+
* @param {string} [opts.url]
|
|
61
|
+
* @param {string} [opts.token]
|
|
62
|
+
* @param {'local' | 'none'} [opts.fallback]
|
|
63
|
+
* @param {ConstructorParameters<typeof JobManager>[0]} [opts.local] Options for the local runner.
|
|
64
|
+
* @param {typeof fetch} [opts.fetch]
|
|
65
|
+
* @param {number} [opts.requestTimeoutMs]
|
|
66
|
+
*/
|
|
67
|
+
export function createFleet({ url, token, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
|
|
68
|
+
const base = url ? url.replace(/\/+$/, '') : null;
|
|
69
|
+
const headers = token ? { authorization: `Bearer ${token}` } : {};
|
|
70
|
+
let manager = null;
|
|
71
|
+
const localManager = () => (manager ??= new JobManager(local));
|
|
72
|
+
const controllers = new Set();
|
|
73
|
+
|
|
74
|
+
async function request(method, path, body, extraHeaders = {}) {
|
|
75
|
+
const res = await f(`${base}${path}`, {
|
|
76
|
+
method,
|
|
77
|
+
headers: { ...headers, ...(body !== undefined && !Buffer.isBuffer(body) ? { 'content-type': 'application/json' } : {}), ...extraHeaders },
|
|
78
|
+
body: body === undefined ? undefined : Buffer.isBuffer(body) ? body : JSON.stringify(body),
|
|
79
|
+
signal: AbortSignal.timeout(requestTimeoutMs),
|
|
80
|
+
});
|
|
81
|
+
const text = await res.text();
|
|
82
|
+
const json = text ? JSON.parse(text) : null;
|
|
83
|
+
if (!res.ok) {
|
|
84
|
+
throw new FleetError(json?.error?.code ?? 'HTTP_ERROR', json?.error?.message ?? `HTTP ${res.status}`, { status: res.status, details: json?.error?.details });
|
|
85
|
+
}
|
|
86
|
+
return json;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function submitLocal(spec) {
|
|
90
|
+
const m = localManager();
|
|
91
|
+
const { job } = m.submit(spec);
|
|
92
|
+
const handle = new JobHandle(job.id, 'local');
|
|
93
|
+
handle._cancel = async () => m.cancel(job.id);
|
|
94
|
+
handle._write = data => m.writeStdin(job.id, data);
|
|
95
|
+
m.subscribe(job.id, 0, event => {
|
|
96
|
+
handle._event(event);
|
|
97
|
+
if (isFinal(event.state)) {
|
|
98
|
+
handle.snapshot = m.get(job.id);
|
|
99
|
+
handle._resolve(handle.snapshot);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
return handle;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function submitRemote(spec) {
|
|
106
|
+
const job = await request('POST', '/v1/jobs', spec);
|
|
107
|
+
const handle = new JobHandle(job.id, 'remote');
|
|
108
|
+
handle.snapshot = job;
|
|
109
|
+
const ac = new AbortController();
|
|
110
|
+
controllers.add(ac);
|
|
111
|
+
const enc = encodeURIComponent(job.id);
|
|
112
|
+
handle._cancel = () => request('DELETE', `/v1/jobs/${enc}`);
|
|
113
|
+
handle._write = data => request('POST', `/v1/jobs/${enc}/stdin`, data, { 'content-type': 'application/octet-stream' });
|
|
114
|
+
followJobEvents({ url: `${base}/v1/jobs/${enc}/events`, headers, signal: ac.signal, fetch: f, onEvent: e => handle._event(e) })
|
|
115
|
+
.then(async () => {
|
|
116
|
+
handle.snapshot = await request('GET', `/v1/jobs/${enc}`).catch(() => handle.snapshot);
|
|
117
|
+
handle._resolve(handle.snapshot);
|
|
118
|
+
})
|
|
119
|
+
.catch(err => handle._reject(err))
|
|
120
|
+
.finally(() => controllers.delete(ac));
|
|
121
|
+
return handle;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
/** 'local' when no url is configured, else 'remote'. */
|
|
126
|
+
mode: base ? 'remote' : 'local',
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Submits a job and returns its handle.
|
|
130
|
+
* @param {Partial<import('./types.js').JobSpec>} input
|
|
131
|
+
* @returns {Promise<JobHandle>}
|
|
132
|
+
*/
|
|
133
|
+
async submit(input) {
|
|
134
|
+
const spec = parseSpec(input);
|
|
135
|
+
// Choose the id here so a retry or a local fallback never runs the same job twice.
|
|
136
|
+
spec.id ??= `job_${randomUUID()}`;
|
|
137
|
+
if (!base) return submitLocal(spec);
|
|
138
|
+
try {
|
|
139
|
+
return await submitRemote(spec);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
const unreachable = !(err instanceof FleetError) || err.status === 503 || err.status === 502;
|
|
142
|
+
if (fallback === 'local' && unreachable) return submitLocal(spec);
|
|
143
|
+
throw err;
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
/** Capabilities of the remote side, or of this machine's runner in local mode. */
|
|
148
|
+
async capabilities() {
|
|
149
|
+
if (!base) return { slots: localManager().stats().pools, capabilities: await detectCapabilities(local.ffmpegPath) };
|
|
150
|
+
return request('GET', '/v1/capabilities');
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
/** Stops following remote jobs and cancels local ones. */
|
|
154
|
+
async close() {
|
|
155
|
+
for (const ac of controllers) ac.abort();
|
|
156
|
+
if (manager) await manager.close();
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
package/src/contract.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Job contract v1: the spec a client submits and the states a job moves through.
|
|
2
|
+
// The same rules are applied by the local runner, the worker and the orchestrator.
|
|
3
|
+
|
|
4
|
+
export const CONTRACT_VERSION = 1;
|
|
5
|
+
|
|
6
|
+
export const KINDS = Object.freeze(['stream', 'batch']);
|
|
7
|
+
|
|
8
|
+
export const STATES = Object.freeze([
|
|
9
|
+
'queued', 'assigned', 'staging', 'running', 'uploading', 'succeeded', 'failed', 'cancelled',
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
const FINAL = new Set(['succeeded', 'failed', 'cancelled']);
|
|
13
|
+
|
|
14
|
+
/** @param {string} state */
|
|
15
|
+
export function isFinal(state) {
|
|
16
|
+
return FINAL.has(state);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Schemes a worker can stage or write itself. */
|
|
20
|
+
export const FILE_SCHEMES = Object.freeze(['file:']);
|
|
21
|
+
/** Fetched before a batch job starts, uploaded (HTTP PUT) after it ends; passed through for streams. */
|
|
22
|
+
export const HTTP_SCHEMES = Object.freeze(['http:', 'https:']);
|
|
23
|
+
/** Handed to ffmpeg as they are (live sources and destinations). */
|
|
24
|
+
export const PASSTHROUGH_SCHEMES = Object.freeze(['rtmp:', 'rtmps:', 'srt:', 'udp:', 'tcp:', 'rtsp:', 'rtp:']);
|
|
25
|
+
|
|
26
|
+
const ALL_SCHEMES = new Set([...FILE_SCHEMES, ...HTTP_SCHEMES, ...PASSTHROUGH_SCHEMES]);
|
|
27
|
+
|
|
28
|
+
const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
29
|
+
const NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
30
|
+
const CLASS_RE = /^[a-z0-9_-]{1,32}$/;
|
|
31
|
+
const PLACEHOLDER_RE = /\{\{(input|output):([^}]*)\}\}/g;
|
|
32
|
+
|
|
33
|
+
export class ContractError extends Error {
|
|
34
|
+
/** @param {{ path: string, message: string }[]} errors */
|
|
35
|
+
constructor(errors) {
|
|
36
|
+
super(`invalid job spec: ${errors.map(e => `${e.path}: ${e.message}`).join('; ')}`);
|
|
37
|
+
this.name = 'ContractError';
|
|
38
|
+
this.code = 'INVALID_SPEC';
|
|
39
|
+
this.status = 422;
|
|
40
|
+
this.errors = errors;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Validates a job spec and returns it with defaults filled in.
|
|
46
|
+
* Unknown top-level fields are dropped so idempotency checks compare like with like.
|
|
47
|
+
*
|
|
48
|
+
* @param {unknown} input
|
|
49
|
+
* @returns {{ ok: true, spec: import('./types.js').JobSpec } | { ok: false, errors: { path: string, message: string }[] }}
|
|
50
|
+
*/
|
|
51
|
+
export function validateSpec(input) {
|
|
52
|
+
const errors = [];
|
|
53
|
+
const err = (path, message) => errors.push({ path, message });
|
|
54
|
+
|
|
55
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
56
|
+
return { ok: false, errors: [{ path: '', message: 'spec must be an object' }] };
|
|
57
|
+
}
|
|
58
|
+
const s = /** @type {Record<string, any>} */ (input);
|
|
59
|
+
|
|
60
|
+
const contract = s.contract ?? CONTRACT_VERSION;
|
|
61
|
+
if (contract !== CONTRACT_VERSION) err('contract', `unsupported contract version ${contract}; this build speaks ${CONTRACT_VERSION}`);
|
|
62
|
+
|
|
63
|
+
if (s.id !== undefined && (typeof s.id !== 'string' || !ID_RE.test(s.id))) {
|
|
64
|
+
err('id', 'must be 1-128 characters of A-Z a-z 0-9 . _ : -');
|
|
65
|
+
}
|
|
66
|
+
if (!KINDS.includes(s.kind)) err('kind', `must be one of ${KINDS.join(', ')}`);
|
|
67
|
+
|
|
68
|
+
const type = s.type ?? 'ffmpeg';
|
|
69
|
+
if (typeof type !== 'string' || !NAME_RE.test(type)) err('type', 'must be a short name such as "ffmpeg"');
|
|
70
|
+
|
|
71
|
+
const cls = s.class ?? 'default';
|
|
72
|
+
if (typeof cls !== 'string' || !CLASS_RE.test(cls)) err('class', 'must be 1-32 characters of a-z 0-9 _ -');
|
|
73
|
+
|
|
74
|
+
const priority = s.priority ?? 0;
|
|
75
|
+
if (!Number.isInteger(priority) || priority < -1000 || priority > 1000) err('priority', 'must be an integer from -1000 to 1000');
|
|
76
|
+
|
|
77
|
+
const owner = s.owner ?? '';
|
|
78
|
+
if (typeof owner !== 'string' || owner.length > 256) err('owner', 'must be a string of at most 256 characters');
|
|
79
|
+
|
|
80
|
+
const timeoutMs = s.timeoutMs ?? null;
|
|
81
|
+
if (timeoutMs !== null && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) err('timeoutMs', 'must be a positive integer');
|
|
82
|
+
|
|
83
|
+
const stdin = s.stdin ?? false;
|
|
84
|
+
if (typeof stdin !== 'boolean') err('stdin', 'must be a boolean');
|
|
85
|
+
|
|
86
|
+
const requires = s.requires ?? [];
|
|
87
|
+
if (!Array.isArray(requires) || requires.some(r => typeof r !== 'string' || !r)) err('requires', 'must be an array of capability strings');
|
|
88
|
+
|
|
89
|
+
const labels = s.labels ?? {};
|
|
90
|
+
if (typeof labels !== 'object' || Array.isArray(labels) || Object.values(labels).some(v => typeof v !== 'string')) {
|
|
91
|
+
err('labels', 'must be an object of string values');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const inputs = normalizeEndpoints(s.inputs, 'inputs', err);
|
|
95
|
+
const outputs = normalizeEndpoints(s.outputs, 'outputs', err);
|
|
96
|
+
|
|
97
|
+
let ffmpeg;
|
|
98
|
+
if (type === 'ffmpeg') {
|
|
99
|
+
const f = s.ffmpeg;
|
|
100
|
+
if (!f || typeof f !== 'object' || !Array.isArray(f.args) || f.args.length === 0 || f.args.some(a => typeof a !== 'string')) {
|
|
101
|
+
err('ffmpeg.args', 'must be a non-empty array of strings');
|
|
102
|
+
} else {
|
|
103
|
+
const durationMs = f.durationMs ?? null;
|
|
104
|
+
if (durationMs !== null && (!Number.isFinite(durationMs) || durationMs <= 0)) err('ffmpeg.durationMs', 'must be a positive number');
|
|
105
|
+
ffmpeg = { args: [...f.args], durationMs };
|
|
106
|
+
checkPlaceholders(f.args, inputs, outputs, err);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (errors.length) return { ok: false, errors };
|
|
111
|
+
|
|
112
|
+
/** @type {any} */
|
|
113
|
+
const spec = {
|
|
114
|
+
contract,
|
|
115
|
+
id: s.id,
|
|
116
|
+
kind: s.kind,
|
|
117
|
+
type,
|
|
118
|
+
class: cls,
|
|
119
|
+
priority,
|
|
120
|
+
owner,
|
|
121
|
+
requires: [...new Set(requires)].sort(),
|
|
122
|
+
labels: { ...labels },
|
|
123
|
+
timeoutMs,
|
|
124
|
+
stdin,
|
|
125
|
+
inputs,
|
|
126
|
+
outputs,
|
|
127
|
+
};
|
|
128
|
+
if (ffmpeg) spec.ffmpeg = ffmpeg;
|
|
129
|
+
else if (s[type] !== undefined) spec[type] = s[type];
|
|
130
|
+
return { ok: true, spec };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Like validateSpec but throws a ContractError. */
|
|
134
|
+
export function parseSpec(input) {
|
|
135
|
+
const r = validateSpec(input);
|
|
136
|
+
if (!r.ok) throw new ContractError(r.errors);
|
|
137
|
+
return r.spec;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function normalizeEndpoints(list, path, err) {
|
|
141
|
+
if (list === undefined) return [];
|
|
142
|
+
if (!Array.isArray(list)) {
|
|
143
|
+
err(path, 'must be an array');
|
|
144
|
+
return [];
|
|
145
|
+
}
|
|
146
|
+
const seen = new Set();
|
|
147
|
+
return list.map((e, i) => {
|
|
148
|
+
const p = `${path}[${i}]`;
|
|
149
|
+
if (!e || typeof e !== 'object') {
|
|
150
|
+
err(p, 'must be an object');
|
|
151
|
+
return {};
|
|
152
|
+
}
|
|
153
|
+
if (typeof e.name !== 'string' || !NAME_RE.test(e.name)) err(`${p}.name`, 'must be 1-64 characters of A-Z a-z 0-9 _ -');
|
|
154
|
+
else if (seen.has(e.name)) err(`${p}.name`, `duplicate name "${e.name}"`);
|
|
155
|
+
seen.add(e.name);
|
|
156
|
+
let url;
|
|
157
|
+
try {
|
|
158
|
+
url = new URL(e.uri);
|
|
159
|
+
} catch {
|
|
160
|
+
err(`${p}.uri`, 'must be an absolute URI');
|
|
161
|
+
}
|
|
162
|
+
if (url && !ALL_SCHEMES.has(url.protocol)) err(`${p}.uri`, `scheme ${url.protocol} is not supported`);
|
|
163
|
+
const out = { name: e.name, uri: e.uri };
|
|
164
|
+
if (e.contentType !== undefined) {
|
|
165
|
+
if (typeof e.contentType !== 'string') err(`${p}.contentType`, 'must be a string');
|
|
166
|
+
else out.contentType = e.contentType;
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function checkPlaceholders(args, inputs, outputs, err) {
|
|
173
|
+
const names = { input: new Set(inputs.map(i => i.name)), output: new Set(outputs.map(o => o.name)) };
|
|
174
|
+
args.forEach((arg, i) => {
|
|
175
|
+
for (const m of arg.matchAll(PLACEHOLDER_RE)) {
|
|
176
|
+
if (!names[m[1]].has(m[2])) err(`ffmpeg.args[${i}]`, `${m[0]} names no ${m[1]}`);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Replaces {{input:name}} and {{output:name}} in every argument.
|
|
183
|
+
* @param {string[]} args
|
|
184
|
+
* @param {{ input: Record<string, string>, output: Record<string, string> }} values
|
|
185
|
+
*/
|
|
186
|
+
export function resolvePlaceholders(args, values) {
|
|
187
|
+
return args.map(arg => arg.replace(PLACEHOLDER_RE, (whole, kind, name) => {
|
|
188
|
+
const v = values[kind][name];
|
|
189
|
+
if (v === undefined) throw new Error(`unresolved placeholder ${whole}`);
|
|
190
|
+
return v;
|
|
191
|
+
}));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** JSON with sorted keys, used to compare two specs for idempotent submission. */
|
|
195
|
+
export function canonicalJson(value) {
|
|
196
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
|
197
|
+
if (value && typeof value === 'object') {
|
|
198
|
+
return `{${Object.keys(value).filter(k => value[k] !== undefined).sort().map(k => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
|
|
199
|
+
}
|
|
200
|
+
return JSON.stringify(value ?? null);
|
|
201
|
+
}
|
package/src/executor.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createWriteStream } from 'node:fs';
|
|
3
|
+
import { mkdir, open, stat } from 'node:fs/promises';
|
|
4
|
+
import { dirname, extname, join } from 'node:path';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { HTTP_SCHEMES, resolvePlaceholders } from './contract.js';
|
|
9
|
+
import { FleetError } from './job-record.js';
|
|
10
|
+
import { createProgressParser } from './progress.js';
|
|
11
|
+
|
|
12
|
+
const STDERR_TAIL_BYTES = 8 * 1024;
|
|
13
|
+
const KILL_GRACE_MS = 5000;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {object} ExecutorRuntime
|
|
17
|
+
* @property {string} workDir Private scratch directory for this job.
|
|
18
|
+
* @property {AbortSignal} signal Aborted on cancel or timeout; `signal.reason` is a FleetError.
|
|
19
|
+
* @property {(state: string, extra?: object) => void} setState
|
|
20
|
+
* @property {(progress: object) => void} progress
|
|
21
|
+
* @property {(stdin: import('node:stream').Writable | null) => void} attachStdin
|
|
22
|
+
* @property {string} [ffmpegPath]
|
|
23
|
+
* @property {typeof fetch} [fetch]
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Runs one ffmpeg job: stages inputs, resolves placeholders, runs ffmpeg with progress reporting,
|
|
28
|
+
* then uploads outputs. Resolves with the final result or throws a FleetError.
|
|
29
|
+
*
|
|
30
|
+
* @param {import('./types.js').JobSpec & { id: string }} spec
|
|
31
|
+
* @param {ExecutorRuntime} rt
|
|
32
|
+
* @returns {Promise<{ exitCode: number, outputs: import('./types.js').OutputResult[], stderrTail: string | null }>}
|
|
33
|
+
*/
|
|
34
|
+
export async function runFfmpegJob(spec, rt) {
|
|
35
|
+
const doFetch = rt.fetch ?? globalThis.fetch;
|
|
36
|
+
const batch = spec.kind === 'batch';
|
|
37
|
+
const values = { input: {}, output: {} };
|
|
38
|
+
|
|
39
|
+
const needsStaging = batch && spec.inputs.some(i => HTTP_SCHEMES.includes(new URL(i.uri).protocol));
|
|
40
|
+
if (needsStaging) rt.setState('staging');
|
|
41
|
+
for (const input of spec.inputs) {
|
|
42
|
+
values.input[input.name] = await stageInput(input, { batch, rt, doFetch });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @type {{ name: string, uri: string, local: string | null, upload: boolean, contentType?: string }[]} */
|
|
46
|
+
const outputs = [];
|
|
47
|
+
for (const output of spec.outputs) {
|
|
48
|
+
const url = new URL(output.uri);
|
|
49
|
+
if (url.protocol === 'file:') {
|
|
50
|
+
const path = fileURLToPath(url);
|
|
51
|
+
await mkdir(dirname(path), { recursive: true });
|
|
52
|
+
outputs.push({ name: output.name, uri: output.uri, local: path, upload: false });
|
|
53
|
+
values.output[output.name] = path;
|
|
54
|
+
} else if (batch && HTTP_SCHEMES.includes(url.protocol)) {
|
|
55
|
+
const path = join(rt.workDir, 'out', `${output.name}${extname(url.pathname)}`);
|
|
56
|
+
await mkdir(dirname(path), { recursive: true });
|
|
57
|
+
outputs.push({ name: output.name, uri: output.uri, local: path, upload: true, contentType: output.contentType });
|
|
58
|
+
values.output[output.name] = path;
|
|
59
|
+
} else {
|
|
60
|
+
outputs.push({ name: output.name, uri: output.uri, local: null, upload: false });
|
|
61
|
+
values.output[output.name] = output.uri;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
rt.signal.throwIfAborted();
|
|
66
|
+
|
|
67
|
+
const args = [
|
|
68
|
+
'-hide_banner', '-nostats', '-loglevel', 'warning', '-progress', 'pipe:1',
|
|
69
|
+
...(spec.stdin ? [] : ['-nostdin']),
|
|
70
|
+
...(batch ? ['-y'] : []),
|
|
71
|
+
...resolvePlaceholders(spec.ffmpeg.args, values),
|
|
72
|
+
];
|
|
73
|
+
const { exitCode, stderrTail } = await runProcess(rt.ffmpegPath ?? 'ffmpeg', args, spec, rt);
|
|
74
|
+
|
|
75
|
+
rt.signal.throwIfAborted();
|
|
76
|
+
if (exitCode !== 0) {
|
|
77
|
+
throw new FleetError('FFMPEG_EXIT', `ffmpeg exited with code ${exitCode}`, { details: { exitCode, stderrTail } });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const results = [];
|
|
81
|
+
if (outputs.some(o => o.upload)) rt.setState('uploading');
|
|
82
|
+
for (const o of outputs) {
|
|
83
|
+
let bytes = null;
|
|
84
|
+
if (o.local) {
|
|
85
|
+
try {
|
|
86
|
+
bytes = (await stat(o.local)).size;
|
|
87
|
+
} catch {
|
|
88
|
+
if (batch) throw new FleetError('OUTPUT_MISSING', `ffmpeg did not write output "${o.name}"`, { details: { exitCode, stderrTail } });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (o.upload) await uploadOutput(o, { rt, doFetch });
|
|
92
|
+
results.push({ name: o.name, uri: o.uri, bytes });
|
|
93
|
+
}
|
|
94
|
+
return { exitCode, outputs: results, stderrTail };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function stageInput(input, { batch, rt, doFetch }) {
|
|
98
|
+
const url = new URL(input.uri);
|
|
99
|
+
if (url.protocol === 'file:') {
|
|
100
|
+
const path = fileURLToPath(url);
|
|
101
|
+
if (batch) {
|
|
102
|
+
try {
|
|
103
|
+
await stat(path);
|
|
104
|
+
} catch {
|
|
105
|
+
throw new FleetError('INPUT_FAILED', `input "${input.name}" not found at ${path}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return path;
|
|
109
|
+
}
|
|
110
|
+
if (!batch || !HTTP_SCHEMES.includes(url.protocol)) return input.uri;
|
|
111
|
+
|
|
112
|
+
const path = join(rt.workDir, 'in', `${input.name}${extname(url.pathname)}`);
|
|
113
|
+
await mkdir(dirname(path), { recursive: true });
|
|
114
|
+
let res;
|
|
115
|
+
try {
|
|
116
|
+
res = await doFetch(input.uri, { signal: rt.signal });
|
|
117
|
+
} catch (err) {
|
|
118
|
+
if (rt.signal.aborted) throw rt.signal.reason;
|
|
119
|
+
throw new FleetError('INPUT_FAILED', `could not fetch input "${input.name}": ${err.message}`);
|
|
120
|
+
}
|
|
121
|
+
if (!res.ok || !res.body) throw new FleetError('INPUT_FAILED', `could not fetch input "${input.name}": HTTP ${res.status}`);
|
|
122
|
+
await pipeline(Readable.fromWeb(res.body), createWriteStream(path));
|
|
123
|
+
return path;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function uploadOutput(o, { rt, doFetch }) {
|
|
127
|
+
const size = (await stat(o.local)).size;
|
|
128
|
+
const fh = await open(o.local, 'r');
|
|
129
|
+
try {
|
|
130
|
+
const res = await doFetch(o.uri, {
|
|
131
|
+
method: 'PUT',
|
|
132
|
+
headers: { 'content-type': o.contentType ?? 'application/octet-stream', 'content-length': String(size) },
|
|
133
|
+
body: Readable.toWeb(fh.createReadStream()),
|
|
134
|
+
duplex: 'half',
|
|
135
|
+
signal: rt.signal,
|
|
136
|
+
});
|
|
137
|
+
if (!res.ok) throw new FleetError('UPLOAD_FAILED', `upload of output "${o.name}" failed: HTTP ${res.status}`);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if (err instanceof FleetError) throw err;
|
|
140
|
+
if (rt.signal.aborted) throw rt.signal.reason;
|
|
141
|
+
throw new FleetError('UPLOAD_FAILED', `upload of output "${o.name}" failed: ${err.message}`);
|
|
142
|
+
} finally {
|
|
143
|
+
await fh.close().catch(() => {});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function runProcess(cmd, args, spec, rt) {
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
let child;
|
|
150
|
+
try {
|
|
151
|
+
child = spawn(cmd, args, { stdio: [spec.stdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
|
|
152
|
+
} catch (err) {
|
|
153
|
+
reject(new FleetError('SPAWN_FAILED', `could not start ${cmd}: ${err.message}`));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
let tail = '';
|
|
157
|
+
let killTimer = null;
|
|
158
|
+
let started = false;
|
|
159
|
+
const parse = createProgressParser(p => {
|
|
160
|
+
const { end, ...progress } = p;
|
|
161
|
+
rt.progress(progress);
|
|
162
|
+
}, { durationMs: spec.ffmpeg.durationMs });
|
|
163
|
+
|
|
164
|
+
child.stdout.setEncoding('utf8');
|
|
165
|
+
child.stdout.on('data', parse);
|
|
166
|
+
child.stderr.setEncoding('utf8');
|
|
167
|
+
child.stderr.on('data', d => {
|
|
168
|
+
tail = (tail + d).slice(-STDERR_TAIL_BYTES);
|
|
169
|
+
});
|
|
170
|
+
if (child.stdin) {
|
|
171
|
+
child.stdin.on('error', () => {});
|
|
172
|
+
rt.attachStdin(child.stdin);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const onAbort = () => {
|
|
176
|
+
child.kill('SIGTERM');
|
|
177
|
+
killTimer = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);
|
|
178
|
+
killTimer.unref?.();
|
|
179
|
+
};
|
|
180
|
+
rt.signal.addEventListener('abort', onAbort, { once: true });
|
|
181
|
+
|
|
182
|
+
child.once('spawn', () => {
|
|
183
|
+
started = true;
|
|
184
|
+
rt.setState('running', { pid: child.pid });
|
|
185
|
+
});
|
|
186
|
+
child.once('error', err => {
|
|
187
|
+
if (!started) {
|
|
188
|
+
rt.signal.removeEventListener('abort', onAbort);
|
|
189
|
+
reject(new FleetError('SPAWN_FAILED', `could not start ${cmd}: ${err.message}`));
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
child.once('close', (code, signal) => {
|
|
193
|
+
clearTimeout(killTimer);
|
|
194
|
+
rt.signal.removeEventListener('abort', onAbort);
|
|
195
|
+
rt.attachStdin(null);
|
|
196
|
+
if (!started) return;
|
|
197
|
+
resolve({ exitCode: code ?? (signal ? 128 : 1), stderrTail: tail.trim() || null });
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
}
|