fffleet 0.1.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/README.md +1 -1
- package/index.d.ts +95 -4
- package/package.json +1 -1
- package/server.d.ts +66 -2
- package/src/auth.js +304 -0
- package/src/client.js +45 -15
- package/src/contract.js +55 -6
- package/src/executor.js +89 -14
- package/src/http-api.js +53 -16
- package/src/http-stream.js +29 -0
- package/src/index.js +5 -2
- package/src/input-cache.js +104 -0
- package/src/job-manager.js +106 -9
- package/src/metrics.js +227 -0
- package/src/s3.js +290 -0
- package/src/server.js +7 -1
- package/src/sse.js +3 -2
- package/src/types.js +1 -0
package/src/client.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
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';
|
|
5
6
|
import { JobManager } from './job-manager.js';
|
|
6
7
|
import { FleetError } from './job-record.js';
|
|
8
|
+
import { createTokenProvider } from './auth.js';
|
|
7
9
|
import { followJobEvents } from './sse.js';
|
|
8
10
|
|
|
9
11
|
/**
|
|
@@ -45,6 +47,19 @@ export class JobHandle extends EventEmitter {
|
|
|
45
47
|
return this._cancel();
|
|
46
48
|
}
|
|
47
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
|
+
|
|
48
63
|
/** Writes to the job's stdin (spec.stdin must be true). */
|
|
49
64
|
write(data) {
|
|
50
65
|
return this._write(typeof data === 'string' ? Buffer.from(data) : data);
|
|
@@ -58,32 +73,43 @@ export class JobHandle extends EventEmitter {
|
|
|
58
73
|
*
|
|
59
74
|
* @param {object} [opts]
|
|
60
75
|
* @param {string} [opts.url]
|
|
61
|
-
* @param {string} [opts.token]
|
|
76
|
+
* @param {string} [opts.token] A static bearer token.
|
|
77
|
+
* @param {string} [opts.clientId] With clientSecret: log in at the orchestrator (POST /v1/auth/token) instead of using a static token.
|
|
78
|
+
* @param {string} [opts.clientSecret]
|
|
79
|
+
* @param {string} [opts.scope] Narrow the token to some of the client's scopes, e.g. 'jobs'.
|
|
62
80
|
* @param {'local' | 'none'} [opts.fallback]
|
|
63
81
|
* @param {ConstructorParameters<typeof JobManager>[0]} [opts.local] Options for the local runner.
|
|
64
82
|
* @param {typeof fetch} [opts.fetch]
|
|
65
83
|
* @param {number} [opts.requestTimeoutMs]
|
|
66
84
|
*/
|
|
67
|
-
export function createFleet({ url, token, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
|
|
85
|
+
export function createFleet({ url, token, clientId, clientSecret, scope, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
|
|
68
86
|
const base = url ? url.replace(/\/+$/, '') : null;
|
|
69
|
-
const
|
|
87
|
+
const login = base && clientId && clientSecret ? createTokenProvider({ url: base, clientId, clientSecret, scope, fetch: f, timeoutMs: requestTimeoutMs }) : null;
|
|
88
|
+
const authHeaders = async (refresh = false) => {
|
|
89
|
+
if (login) return { authorization: `Bearer ${await login.get({ refresh })}` };
|
|
90
|
+
return token ? { authorization: `Bearer ${token}` } : {};
|
|
91
|
+
};
|
|
70
92
|
let manager = null;
|
|
71
93
|
const localManager = () => (manager ??= new JobManager(local));
|
|
72
94
|
const controllers = new Set();
|
|
73
95
|
|
|
74
96
|
async function request(method, path, body, extraHeaders = {}) {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
97
|
+
for (let attempt = 0; ; attempt++) {
|
|
98
|
+
const res = await f(`${base}${path}`, {
|
|
99
|
+
method,
|
|
100
|
+
headers: { ...(await authHeaders(attempt > 0)), ...(body !== undefined && !Buffer.isBuffer(body) ? { 'content-type': 'application/json' } : {}), ...extraHeaders },
|
|
101
|
+
body: body === undefined ? undefined : Buffer.isBuffer(body) ? body : JSON.stringify(body),
|
|
102
|
+
signal: AbortSignal.timeout(requestTimeoutMs),
|
|
103
|
+
});
|
|
104
|
+
const text = await res.text();
|
|
105
|
+
const json = text ? JSON.parse(text) : null;
|
|
106
|
+
// An expired or revoked token: log in again once.
|
|
107
|
+
if (res.status === 401 && login && attempt === 0) continue;
|
|
108
|
+
if (!res.ok) {
|
|
109
|
+
throw new FleetError(json?.error?.code ?? 'HTTP_ERROR', json?.error?.message ?? `HTTP ${res.status}`, { status: res.status, details: json?.error?.details });
|
|
110
|
+
}
|
|
111
|
+
return json;
|
|
85
112
|
}
|
|
86
|
-
return json;
|
|
87
113
|
}
|
|
88
114
|
|
|
89
115
|
function submitLocal(spec) {
|
|
@@ -92,6 +118,8 @@ export function createFleet({ url, token, fallback = 'local', local = {}, fetch:
|
|
|
92
118
|
const handle = new JobHandle(job.id, 'local');
|
|
93
119
|
handle._cancel = async () => m.cancel(job.id);
|
|
94
120
|
handle._write = data => m.writeStdin(job.id, data);
|
|
121
|
+
handle._endStdin = () => m.closeStdin(job.id);
|
|
122
|
+
handle._stdout = async () => m.openStdout(job.id);
|
|
95
123
|
m.subscribe(job.id, 0, event => {
|
|
96
124
|
handle._event(event);
|
|
97
125
|
if (isFinal(event.state)) {
|
|
@@ -111,7 +139,9 @@ export function createFleet({ url, token, fallback = 'local', local = {}, fetch:
|
|
|
111
139
|
const enc = encodeURIComponent(job.id);
|
|
112
140
|
handle._cancel = () => request('DELETE', `/v1/jobs/${enc}`);
|
|
113
141
|
handle._write = data => request('POST', `/v1/jobs/${enc}/stdin`, data, { 'content-type': 'application/octet-stream' });
|
|
114
|
-
|
|
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 });
|
|
144
|
+
followJobEvents({ url: `${base}/v1/jobs/${enc}/events`, headers: authHeaders, signal: ac.signal, fetch: f, onEvent: e => handle._event(e) })
|
|
115
145
|
.then(async () => {
|
|
116
146
|
handle.snapshot = await request('GET', `/v1/jobs/${enc}`).catch(() => handle.snapshot);
|
|
117
147
|
handle._resolve(handle.snapshot);
|
package/src/contract.js
CHANGED
|
@@ -22,13 +22,18 @@ export const FILE_SCHEMES = Object.freeze(['file:']);
|
|
|
22
22
|
export const HTTP_SCHEMES = Object.freeze(['http:', 'https:']);
|
|
23
23
|
/** Handed to ffmpeg as they are (live sources and destinations). */
|
|
24
24
|
export const PASSTHROUGH_SCHEMES = Object.freeze(['rtmp:', 'rtmps:', 'srt:', 'udp:', 'tcp:', 'rtsp:', 'rtp:']);
|
|
25
|
+
/**
|
|
26
|
+
* Object storage, staged by a worker that holds the credentials (batch jobs only).
|
|
27
|
+
* s3://bucket/key is one object; s3://bucket/prefix/ (trailing slash) is an output folder.
|
|
28
|
+
*/
|
|
29
|
+
export const OBJECT_SCHEMES = Object.freeze(['s3:']);
|
|
25
30
|
|
|
26
|
-
const ALL_SCHEMES = new Set([...FILE_SCHEMES, ...HTTP_SCHEMES, ...PASSTHROUGH_SCHEMES]);
|
|
31
|
+
const ALL_SCHEMES = new Set([...FILE_SCHEMES, ...HTTP_SCHEMES, ...PASSTHROUGH_SCHEMES, ...OBJECT_SCHEMES]);
|
|
27
32
|
|
|
28
33
|
const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
29
34
|
const NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
30
35
|
const CLASS_RE = /^[a-z0-9_-]{1,32}$/;
|
|
31
|
-
const PLACEHOLDER_RE = /\{\{(input|output):([^}]*)\}\}/g;
|
|
36
|
+
const PLACEHOLDER_RE = /\{\{(input|inputdir|output):([^}]*)\}\}/g;
|
|
32
37
|
|
|
33
38
|
export class ContractError extends Error {
|
|
34
39
|
/** @param {{ path: string, message: string }[]} errors */
|
|
@@ -83,6 +88,10 @@ export function validateSpec(input) {
|
|
|
83
88
|
const stdin = s.stdin ?? false;
|
|
84
89
|
if (typeof stdin !== 'boolean') err('stdin', 'must be a boolean');
|
|
85
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
|
+
|
|
86
95
|
const requires = s.requires ?? [];
|
|
87
96
|
if (!Array.isArray(requires) || requires.some(r => typeof r !== 'string' || !r)) err('requires', 'must be an array of capability strings');
|
|
88
97
|
|
|
@@ -93,6 +102,7 @@ export function validateSpec(input) {
|
|
|
93
102
|
|
|
94
103
|
const inputs = normalizeEndpoints(s.inputs, 'inputs', err);
|
|
95
104
|
const outputs = normalizeEndpoints(s.outputs, 'outputs', err);
|
|
105
|
+
checkObjectEndpoints(s.kind, inputs, outputs, err);
|
|
96
106
|
|
|
97
107
|
let ffmpeg;
|
|
98
108
|
if (type === 'ffmpeg') {
|
|
@@ -122,6 +132,7 @@ export function validateSpec(input) {
|
|
|
122
132
|
labels: { ...labels },
|
|
123
133
|
timeoutMs,
|
|
124
134
|
stdin,
|
|
135
|
+
stdout,
|
|
125
136
|
inputs,
|
|
126
137
|
outputs,
|
|
127
138
|
};
|
|
@@ -169,8 +180,46 @@ function normalizeEndpoints(list, path, err) {
|
|
|
169
180
|
});
|
|
170
181
|
}
|
|
171
182
|
|
|
183
|
+
function checkObjectEndpoints(kind, inputs, outputs, err) {
|
|
184
|
+
const check = (list, path, isOutput) => list.forEach((e, i) => {
|
|
185
|
+
let url;
|
|
186
|
+
try {
|
|
187
|
+
url = new URL(e.uri);
|
|
188
|
+
} catch {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (url.protocol !== 's3:') return;
|
|
192
|
+
const p = `${path}[${i}].uri`;
|
|
193
|
+
if (kind === 'stream') err(p, 's3: is only supported for batch jobs');
|
|
194
|
+
if (!url.hostname) err(p, 's3: URIs need a bucket: s3://bucket/key');
|
|
195
|
+
const key = url.pathname.replace(/^\//, '');
|
|
196
|
+
const rootFolder = isOutput && url.pathname === '/';
|
|
197
|
+
if (!key && !rootFolder) err(p, 's3: URIs need a key: s3://bucket/key');
|
|
198
|
+
else if (key.endsWith('/') && !isOutput) err(p, 'an input must name one object, not a folder');
|
|
199
|
+
});
|
|
200
|
+
check(inputs, 'inputs', false);
|
|
201
|
+
check(outputs, 'outputs', true);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Capabilities a job needs beyond its `requires`: `type:<type>`, plus `scheme:s3` when it uses s3: URIs.
|
|
206
|
+
* @param {{ type: string, inputs: { uri: string }[], outputs: { uri: string }[] }} spec
|
|
207
|
+
*/
|
|
208
|
+
export function implicitRequirements(spec) {
|
|
209
|
+
const reqs = [`type:${spec.type}`];
|
|
210
|
+
const schemes = new Set([...spec.inputs, ...spec.outputs].map(e => {
|
|
211
|
+
try {
|
|
212
|
+
return new URL(e.uri).protocol;
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
}));
|
|
217
|
+
for (const scheme of OBJECT_SCHEMES) if (schemes.has(scheme)) reqs.push(`scheme:${scheme.slice(0, -1)}`);
|
|
218
|
+
return reqs;
|
|
219
|
+
}
|
|
220
|
+
|
|
172
221
|
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)) };
|
|
222
|
+
const names = { input: new Set(inputs.map(i => i.name)), inputdir: new Set(inputs.map(i => i.name)), output: new Set(outputs.map(o => o.name)) };
|
|
174
223
|
args.forEach((arg, i) => {
|
|
175
224
|
for (const m of arg.matchAll(PLACEHOLDER_RE)) {
|
|
176
225
|
if (!names[m[1]].has(m[2])) err(`ffmpeg.args[${i}]`, `${m[0]} names no ${m[1]}`);
|
|
@@ -179,13 +228,13 @@ function checkPlaceholders(args, inputs, outputs, err) {
|
|
|
179
228
|
}
|
|
180
229
|
|
|
181
230
|
/**
|
|
182
|
-
* Replaces {{input:name}} and {{output:name}} in every argument.
|
|
231
|
+
* Replaces {{input:name}}, {{inputdir:name}} (the directory holding that input) and {{output:name}} in every argument.
|
|
183
232
|
* @param {string[]} args
|
|
184
|
-
* @param {{ input: Record<string, string>, output: Record<string, string> }} values
|
|
233
|
+
* @param {{ input: Record<string, string>, output: Record<string, string>, inputdir?: Record<string, string> }} values
|
|
185
234
|
*/
|
|
186
235
|
export function resolvePlaceholders(args, values) {
|
|
187
236
|
return args.map(arg => arg.replace(PLACEHOLDER_RE, (whole, kind, name) => {
|
|
188
|
-
const v = values[kind][name];
|
|
237
|
+
const v = values[kind]?.[name];
|
|
189
238
|
if (v === undefined) throw new Error(`unresolved placeholder ${whole}`);
|
|
190
239
|
return v;
|
|
191
240
|
}));
|
package/src/executor.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createWriteStream } from 'node:fs';
|
|
3
|
-
import { mkdir, open, stat } from 'node:fs/promises';
|
|
3
|
+
import { mkdir, open, readdir, stat } from 'node:fs/promises';
|
|
4
4
|
import { dirname, extname, join } from 'node:path';
|
|
5
5
|
import { Readable } from 'node:stream';
|
|
6
6
|
import { pipeline } from 'node:stream/promises';
|
|
@@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
8
8
|
import { HTTP_SCHEMES, resolvePlaceholders } from './contract.js';
|
|
9
9
|
import { FleetError } from './job-record.js';
|
|
10
10
|
import { createProgressParser } from './progress.js';
|
|
11
|
+
import { parseS3Uri } from './s3.js';
|
|
11
12
|
|
|
12
13
|
const STDERR_TAIL_BYTES = 8 * 1024;
|
|
13
14
|
const KILL_GRACE_MS = 5000;
|
|
@@ -19,8 +20,11 @@ const KILL_GRACE_MS = 5000;
|
|
|
19
20
|
* @property {(state: string, extra?: object) => void} setState
|
|
20
21
|
* @property {(progress: object) => void} progress
|
|
21
22
|
* @property {(stdin: import('node:stream').Writable | null) => void} attachStdin
|
|
23
|
+
* @property {(direction: 'in' | 'out', scheme: string, bytes: number) => void} [transfer] Counts staged and uploaded bytes.
|
|
22
24
|
* @property {string} [ffmpegPath]
|
|
23
25
|
* @property {typeof fetch} [fetch]
|
|
26
|
+
* @property {ReturnType<typeof import('./s3.js').createS3Client> | null} [s3] Needed for s3: URIs.
|
|
27
|
+
* @property {ReturnType<typeof import('./input-cache.js').createInputCache> | null} [cache] Reuses staged s3: and http(s): inputs between jobs.
|
|
24
28
|
*/
|
|
25
29
|
|
|
26
30
|
/**
|
|
@@ -34,15 +38,23 @@ const KILL_GRACE_MS = 5000;
|
|
|
34
38
|
export async function runFfmpegJob(spec, rt) {
|
|
35
39
|
const doFetch = rt.fetch ?? globalThis.fetch;
|
|
36
40
|
const batch = spec.kind === 'batch';
|
|
37
|
-
const values = { input: {}, output: {} };
|
|
41
|
+
const values = { input: {}, inputdir: {}, output: {} };
|
|
42
|
+
const scheme = e => new URL(e.uri).protocol;
|
|
38
43
|
|
|
39
|
-
|
|
44
|
+
if (!rt.s3 && [...spec.inputs, ...spec.outputs].some(e => scheme(e) === 's3:')) {
|
|
45
|
+
throw new FleetError('UNSUPPORTED_SCHEME', 'this runner has no S3 credentials for s3: URIs');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const needsStaging = batch && spec.inputs.some(i => HTTP_SCHEMES.includes(scheme(i)) || scheme(i) === 's3:');
|
|
40
49
|
if (needsStaging) rt.setState('staging');
|
|
41
50
|
for (const input of spec.inputs) {
|
|
42
|
-
|
|
51
|
+
const local = await stageInput(input, { batch, rt, doFetch });
|
|
52
|
+
values.input[input.name] = local;
|
|
53
|
+
if (local !== input.uri) values.inputdir[input.name] = dirname(local);
|
|
54
|
+
if (local !== input.uri && scheme(input) !== 'file:') rt.transfer?.('in', scheme(input).slice(0, -1), (await stat(local)).size);
|
|
43
55
|
}
|
|
44
56
|
|
|
45
|
-
/** @type {{ name: string, uri: string, local: string | null, upload: boolean, contentType?: string }[]} */
|
|
57
|
+
/** @type {{ name: string, uri: string, local: string | null, upload: false | 'http' | 's3', folder?: boolean, contentType?: string }[]} */
|
|
46
58
|
const outputs = [];
|
|
47
59
|
for (const output of spec.outputs) {
|
|
48
60
|
const url = new URL(output.uri);
|
|
@@ -54,7 +66,15 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
54
66
|
} else if (batch && HTTP_SCHEMES.includes(url.protocol)) {
|
|
55
67
|
const path = join(rt.workDir, 'out', `${output.name}${extname(url.pathname)}`);
|
|
56
68
|
await mkdir(dirname(path), { recursive: true });
|
|
57
|
-
outputs.push({ name: output.name, uri: output.uri, local: path, upload:
|
|
69
|
+
outputs.push({ name: output.name, uri: output.uri, local: path, upload: 'http', contentType: output.contentType });
|
|
70
|
+
values.output[output.name] = path;
|
|
71
|
+
} else if (url.protocol === 's3:') {
|
|
72
|
+
const { key } = parseS3Uri(output.uri);
|
|
73
|
+
const folder = key === '' || key.endsWith('/');
|
|
74
|
+
// A folder output is a directory ffmpeg writes into, e.g. {{output:hls}}/index.m3u8.
|
|
75
|
+
const path = join(rt.workDir, 'out', folder ? output.name : `${output.name}${extname(key)}`);
|
|
76
|
+
await mkdir(folder ? path : dirname(path), { recursive: true });
|
|
77
|
+
outputs.push({ name: output.name, uri: output.uri, local: path, upload: 's3', folder, contentType: output.contentType });
|
|
58
78
|
values.output[output.name] = path;
|
|
59
79
|
} else {
|
|
60
80
|
outputs.push({ name: output.name, uri: output.uri, local: null, upload: false });
|
|
@@ -65,7 +85,7 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
65
85
|
rt.signal.throwIfAborted();
|
|
66
86
|
|
|
67
87
|
const args = [
|
|
68
|
-
'-hide_banner', '-nostats', '-loglevel', 'warning', '-progress', 'pipe:1',
|
|
88
|
+
'-hide_banner', '-nostats', '-loglevel', 'warning', ...(spec.stdout ? [] : ['-progress', 'pipe:1']),
|
|
69
89
|
...(spec.stdin ? [] : ['-nostdin']),
|
|
70
90
|
...(batch ? ['-y'] : []),
|
|
71
91
|
...resolvePlaceholders(spec.ffmpeg.args, values),
|
|
@@ -83,12 +103,15 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
83
103
|
let bytes = null;
|
|
84
104
|
if (o.local) {
|
|
85
105
|
try {
|
|
86
|
-
bytes = (await stat(o.local)).size;
|
|
106
|
+
bytes = o.folder ? ((await readdir(o.local)).length ? 0 : null) : (await stat(o.local)).size;
|
|
87
107
|
} catch {
|
|
88
|
-
|
|
108
|
+
bytes = null;
|
|
89
109
|
}
|
|
110
|
+
if (bytes === null && batch) throw new FleetError('OUTPUT_MISSING', `ffmpeg did not write output "${o.name}"`, { details: { exitCode, stderrTail } });
|
|
90
111
|
}
|
|
91
|
-
if (o.upload) await uploadOutput(o, { rt, doFetch });
|
|
112
|
+
if (o.upload === 'http') await uploadOutput(o, { rt, doFetch });
|
|
113
|
+
if (o.upload === 's3') bytes = await uploadS3Output(o, rt);
|
|
114
|
+
if (o.upload) rt.transfer?.('out', scheme(o).slice(0, -1), bytes ?? 0);
|
|
92
115
|
results.push({ name: o.name, uri: o.uri, bytes });
|
|
93
116
|
}
|
|
94
117
|
return { exitCode, outputs: results, stderrTail };
|
|
@@ -107,10 +130,47 @@ async function stageInput(input, { batch, rt, doFetch }) {
|
|
|
107
130
|
}
|
|
108
131
|
return path;
|
|
109
132
|
}
|
|
133
|
+
if (batch && url.protocol === 's3:') {
|
|
134
|
+
const { bucket, key } = parseS3Uri(input.uri);
|
|
135
|
+
// Each input gets its own directory, so {{inputdir:name}} holds only that file (for example a font for ass fontsdir).
|
|
136
|
+
const path = join(rt.workDir, 'in', input.name, `file${extname(key)}`);
|
|
137
|
+
await mkdir(dirname(path), { recursive: true });
|
|
138
|
+
try {
|
|
139
|
+
const head = rt.cache ? await rt.s3.head(bucket, key, { signal: rt.signal }).catch(() => null) : null;
|
|
140
|
+
if (head?.etag) {
|
|
141
|
+
await rt.cache.stage({ key: input.uri, validator: head.etag, target: path, download: p => rt.s3.getFile(bucket, key, p, { signal: rt.signal }) });
|
|
142
|
+
} else {
|
|
143
|
+
await rt.s3.getFile(bucket, key, path, { signal: rt.signal });
|
|
144
|
+
}
|
|
145
|
+
} catch (err) {
|
|
146
|
+
if (rt.signal.aborted) throw rt.signal.reason;
|
|
147
|
+
throw new FleetError('INPUT_FAILED', `could not fetch input "${input.name}": ${err.message}`);
|
|
148
|
+
}
|
|
149
|
+
return path;
|
|
150
|
+
}
|
|
110
151
|
if (!batch || !HTTP_SCHEMES.includes(url.protocol)) return input.uri;
|
|
111
152
|
|
|
112
|
-
const path = join(rt.workDir, 'in',
|
|
153
|
+
const path = join(rt.workDir, 'in', input.name, `file${extname(url.pathname)}`);
|
|
113
154
|
await mkdir(dirname(path), { recursive: true });
|
|
155
|
+
if (rt.cache) {
|
|
156
|
+
const head = await doFetch(input.uri, { method: 'HEAD', signal: rt.signal }).catch(() => null);
|
|
157
|
+
const validator = head?.ok ? head.headers.get('etag') ?? (head.headers.get('last-modified') && head.headers.get('content-length') ? `${head.headers.get('last-modified')}|${head.headers.get('content-length')}` : null) : null;
|
|
158
|
+
if (validator) {
|
|
159
|
+
try {
|
|
160
|
+
await rt.cache.stage({ key: input.uri, validator, target: path, download: p => downloadHttp(input, p, { rt, doFetch }) });
|
|
161
|
+
} catch (err) {
|
|
162
|
+
if (err instanceof FleetError) throw err;
|
|
163
|
+
if (rt.signal.aborted) throw rt.signal.reason;
|
|
164
|
+
throw new FleetError('INPUT_FAILED', `could not fetch input "${input.name}": ${err.message}`);
|
|
165
|
+
}
|
|
166
|
+
return path;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
await downloadHttp(input, path, { rt, doFetch });
|
|
170
|
+
return path;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function downloadHttp(input, path, { rt, doFetch }) {
|
|
114
174
|
let res;
|
|
115
175
|
try {
|
|
116
176
|
res = await doFetch(input.uri, { signal: rt.signal });
|
|
@@ -120,7 +180,18 @@ async function stageInput(input, { batch, rt, doFetch }) {
|
|
|
120
180
|
}
|
|
121
181
|
if (!res.ok || !res.body) throw new FleetError('INPUT_FAILED', `could not fetch input "${input.name}": HTTP ${res.status}`);
|
|
122
182
|
await pipeline(Readable.fromWeb(res.body), createWriteStream(path));
|
|
123
|
-
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function uploadS3Output(o, rt) {
|
|
186
|
+
const { bucket, key } = parseS3Uri(o.uri);
|
|
187
|
+
try {
|
|
188
|
+
return o.folder
|
|
189
|
+
? await rt.s3.putDirectory(bucket, key, o.local, { signal: rt.signal })
|
|
190
|
+
: await rt.s3.putFile(bucket, key, o.local, { contentType: o.contentType, signal: rt.signal });
|
|
191
|
+
} catch (err) {
|
|
192
|
+
if (rt.signal.aborted) throw rt.signal.reason;
|
|
193
|
+
throw new FleetError('UPLOAD_FAILED', `upload of output "${o.name}" failed: ${err.message}`);
|
|
194
|
+
}
|
|
124
195
|
}
|
|
125
196
|
|
|
126
197
|
async function uploadOutput(o, { rt, doFetch }) {
|
|
@@ -161,8 +232,12 @@ function runProcess(cmd, args, spec, rt) {
|
|
|
161
232
|
rt.progress(progress);
|
|
162
233
|
}, { durationMs: spec.ffmpeg.durationMs });
|
|
163
234
|
|
|
164
|
-
|
|
165
|
-
|
|
235
|
+
if (spec.stdout) {
|
|
236
|
+
rt.attachStdout?.(child.stdout);
|
|
237
|
+
} else {
|
|
238
|
+
child.stdout.setEncoding('utf8');
|
|
239
|
+
child.stdout.on('data', parse);
|
|
240
|
+
}
|
|
166
241
|
child.stderr.setEncoding('utf8');
|
|
167
242
|
child.stderr.on('data', d => {
|
|
168
243
|
tail = (tail + d).slice(-STDERR_TAIL_BYTES);
|
package/src/http-api.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { timingSafeEqual } from 'node:crypto';
|
|
2
1
|
import { createServer } from 'node:http';
|
|
2
|
+
import { createAuthenticator, sameSecret } from './auth.js';
|
|
3
3
|
import { FleetError } from './job-record.js';
|
|
4
|
+
import { METRICS_CONTENT_TYPE } from './metrics.js';
|
|
4
5
|
|
|
5
6
|
const JSON_LIMIT = 1024 * 1024;
|
|
6
7
|
const STDIN_LIMIT = 1024 * 1024;
|
|
@@ -14,6 +15,8 @@ const SSE_KEEPALIVE_MS = 15000;
|
|
|
14
15
|
* @property {() => any[]} list
|
|
15
16
|
* @property {(id: string) => any | Promise<any>} cancel
|
|
16
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
|
|
17
20
|
* @property {(id: string, afterSeq: number, fn: (e: any) => void) => () => void} subscribe
|
|
18
21
|
* @property {() => any} capabilities
|
|
19
22
|
*/
|
|
@@ -21,41 +24,64 @@ const SSE_KEEPALIVE_MS = 15000;
|
|
|
21
24
|
/**
|
|
22
25
|
* The consumer API (contract v1), served identically by a worker and the orchestrator.
|
|
23
26
|
*
|
|
27
|
+
* Every route except /v1/health needs a principal (see auth.js). Job routes need the `jobs`
|
|
28
|
+
* scope, /metrics needs `metrics`. A principal without `admin` only sees its own jobs, and the
|
|
29
|
+
* jobs it submits are owned by it whatever `owner` the spec names.
|
|
30
|
+
*
|
|
24
31
|
* @param {object} opts
|
|
25
32
|
* @param {JobBackend} opts.backend
|
|
26
|
-
* @param {string | null} [opts.token]
|
|
27
|
-
* @param {(req: import('node:http').IncomingMessage
|
|
33
|
+
* @param {string | null} [opts.token] A static admin token; ignored when `authenticate` is given.
|
|
34
|
+
* @param {(req: import('node:http').IncomingMessage) => Promise<import('./auth.js').Principal | null>} [opts.authenticate]
|
|
35
|
+
* @param {(() => Promise<string>) | null} [opts.metrics] Renders the Prometheus text for GET /metrics.
|
|
36
|
+
* @param {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse, url: URL, principal: import('./auth.js').Principal | null) => Promise<boolean> | boolean} [opts.extraRoutes]
|
|
28
37
|
*/
|
|
29
|
-
export function createApiHandler({ backend, token = null, extraRoutes }) {
|
|
38
|
+
export function createApiHandler({ backend, token = null, authenticate = createAuthenticator({ token }), metrics = null, extraRoutes }) {
|
|
30
39
|
return async (req, res) => {
|
|
31
40
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
32
41
|
try {
|
|
33
42
|
if (req.method === 'GET' && url.pathname === '/v1/health') return send(res, 200, { ok: true });
|
|
34
|
-
|
|
35
|
-
if (
|
|
43
|
+
const who = await authenticate(req);
|
|
44
|
+
if (extraRoutes && (await extraRoutes(req, res, url, who))) return;
|
|
45
|
+
if (metrics && req.method === 'GET' && url.pathname === '/metrics') {
|
|
46
|
+
if (!allowed(res, who, 'metrics')) return;
|
|
47
|
+
const text = await metrics();
|
|
48
|
+
res.writeHead(200, { 'content-type': METRICS_CONTENT_TYPE });
|
|
49
|
+
return res.end(text);
|
|
50
|
+
}
|
|
51
|
+
if (!allowed(res, who, 'jobs')) return;
|
|
52
|
+
const mine = job => job && (who.admin || job.owner === who.sub) ? job : null;
|
|
36
53
|
|
|
37
54
|
if (url.pathname === '/v1/capabilities' && req.method === 'GET') return send(res, 200, await backend.capabilities());
|
|
38
55
|
if (url.pathname === '/v1/jobs') {
|
|
39
56
|
if (req.method === 'POST') {
|
|
40
|
-
const
|
|
57
|
+
const input = await readJson(req);
|
|
58
|
+
if (!who.admin && input && typeof input === 'object' && !Array.isArray(input)) input.owner = who.sub;
|
|
59
|
+
const { created, queued, job } = await backend.submit(input);
|
|
41
60
|
// 201: took a slot (or was handed to a worker) now; 202: waiting in the queue; 200: already known.
|
|
42
61
|
return send(res, created ? ((queued ?? job.state === 'queued') ? 202 : 201) : 200, job);
|
|
43
62
|
}
|
|
44
|
-
if (req.method === 'GET') return send(res, 200, { jobs: backend.list() });
|
|
63
|
+
if (req.method === 'GET') return send(res, 200, { jobs: backend.list().filter(mine) });
|
|
45
64
|
}
|
|
46
65
|
|
|
47
|
-
const m = url.pathname.match(/^\/v1\/jobs\/([^/]+)(\/events|\/stdin)?$/);
|
|
66
|
+
const m = url.pathname.match(/^\/v1\/jobs\/([^/]+)(\/events|\/stdin|\/stdin\/close|\/stdout)?$/);
|
|
48
67
|
if (m) {
|
|
49
68
|
const id = decodeURIComponent(m[1]);
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
69
|
+
// Someone else's job answers 404, the same as a job that does not exist.
|
|
70
|
+
if (!mine(backend.get(id))) return notFound(res, id);
|
|
71
|
+
if (!m[2] && req.method === 'GET') return send(res, 200, backend.get(id));
|
|
54
72
|
if (!m[2] && req.method === 'DELETE') {
|
|
55
73
|
const job = await backend.cancel(id);
|
|
56
74
|
return job ? send(res, 202, job) : notFound(res, id);
|
|
57
75
|
}
|
|
58
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
|
+
}
|
|
59
85
|
if (m[2] === '/stdin' && req.method === 'POST') {
|
|
60
86
|
const data = await readBody(req, STDIN_LIMIT);
|
|
61
87
|
return send(res, 200, { ok: true, ...(await backend.writeStdin(id, data)) });
|
|
@@ -68,6 +94,19 @@ export function createApiHandler({ backend, token = null, extraRoutes }) {
|
|
|
68
94
|
};
|
|
69
95
|
}
|
|
70
96
|
|
|
97
|
+
/** Sends 401 (no or bad credentials) or 403 (missing scope) and returns false, or returns true. */
|
|
98
|
+
export function allowed(res, who, scope) {
|
|
99
|
+
if (!who) {
|
|
100
|
+
send(res, 401, { error: { code: 'UNAUTHORIZED', message: 'missing or invalid bearer token' } }, { 'www-authenticate': 'Bearer realm="fffleet"' });
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
if (!who.scopes.has(scope)) {
|
|
104
|
+
send(res, 403, { error: { code: 'FORBIDDEN', message: `this token lacks the "${scope}" scope` } });
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
|
|
71
110
|
/** Starts an HTTP server on host:port (port 0 picks a free port). */
|
|
72
111
|
export function listen(handler, { port = 0, host = '127.0.0.1' } = {}) {
|
|
73
112
|
const server = createServer(handler);
|
|
@@ -123,9 +162,7 @@ function streamEvents(req, res, url, backend, id) {
|
|
|
123
162
|
export function checkBearer(req, token) {
|
|
124
163
|
if (!token) return true;
|
|
125
164
|
const header = req.headers.authorization ?? '';
|
|
126
|
-
|
|
127
|
-
const want = Buffer.from(token);
|
|
128
|
-
return given.length === want.length && timingSafeEqual(given, want);
|
|
165
|
+
return sameSecret(header.startsWith('Bearer ') ? header.slice(7) : '', token);
|
|
129
166
|
}
|
|
130
167
|
|
|
131
168
|
export function send(res, status, body, headers = {}) {
|
|
@@ -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/index.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
export { createFleet, JobHandle } from './client.js';
|
|
2
2
|
export {
|
|
3
3
|
CONTRACT_VERSION, KINDS, STATES, isFinal, validateSpec, parseSpec, ContractError,
|
|
4
|
-
resolvePlaceholders, canonicalJson, FILE_SCHEMES, HTTP_SCHEMES, PASSTHROUGH_SCHEMES,
|
|
4
|
+
resolvePlaceholders, canonicalJson, implicitRequirements, FILE_SCHEMES, HTTP_SCHEMES, PASSTHROUGH_SCHEMES, OBJECT_SCHEMES,
|
|
5
5
|
} from './contract.js';
|
|
6
|
-
export { JobManager, normalizeSlots } from './job-manager.js';
|
|
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
9
|
export { createProgressParser } from './progress.js';
|
|
10
10
|
export { detectCapabilities, satisfies } from './capabilities.js';
|
|
11
11
|
export { readSse, followJobEvents } from './sse.js';
|
|
12
|
+
export { createS3Client, s3ConfigFromEnv, parseS3Uri, contentTypeFor, signV4 } from './s3.js';
|
|
13
|
+
export { SCOPES, hashSecret, verifySecret, generateSecret, createTokenProvider } from './auth.js';
|
|
14
|
+
export { createInputCache, parseSize } from './input-cache.js';
|