fffleet 0.1.0 → 1.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/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 */
@@ -93,6 +98,7 @@ export function validateSpec(input) {
93
98
 
94
99
  const inputs = normalizeEndpoints(s.inputs, 'inputs', err);
95
100
  const outputs = normalizeEndpoints(s.outputs, 'outputs', err);
101
+ checkObjectEndpoints(s.kind, inputs, outputs, err);
96
102
 
97
103
  let ffmpeg;
98
104
  if (type === 'ffmpeg') {
@@ -169,8 +175,46 @@ function normalizeEndpoints(list, path, err) {
169
175
  });
170
176
  }
171
177
 
178
+ function checkObjectEndpoints(kind, inputs, outputs, err) {
179
+ const check = (list, path, isOutput) => list.forEach((e, i) => {
180
+ let url;
181
+ try {
182
+ url = new URL(e.uri);
183
+ } catch {
184
+ return;
185
+ }
186
+ if (url.protocol !== 's3:') return;
187
+ const p = `${path}[${i}].uri`;
188
+ if (kind === 'stream') err(p, 's3: is only supported for batch jobs');
189
+ if (!url.hostname) err(p, 's3: URIs need a bucket: s3://bucket/key');
190
+ const key = url.pathname.replace(/^\//, '');
191
+ const rootFolder = isOutput && url.pathname === '/';
192
+ if (!key && !rootFolder) err(p, 's3: URIs need a key: s3://bucket/key');
193
+ else if (key.endsWith('/') && !isOutput) err(p, 'an input must name one object, not a folder');
194
+ });
195
+ check(inputs, 'inputs', false);
196
+ check(outputs, 'outputs', true);
197
+ }
198
+
199
+ /**
200
+ * Capabilities a job needs beyond its `requires`: `type:<type>`, plus `scheme:s3` when it uses s3: URIs.
201
+ * @param {{ type: string, inputs: { uri: string }[], outputs: { uri: string }[] }} spec
202
+ */
203
+ export function implicitRequirements(spec) {
204
+ const reqs = [`type:${spec.type}`];
205
+ const schemes = new Set([...spec.inputs, ...spec.outputs].map(e => {
206
+ try {
207
+ return new URL(e.uri).protocol;
208
+ } catch {
209
+ return null;
210
+ }
211
+ }));
212
+ for (const scheme of OBJECT_SCHEMES) if (schemes.has(scheme)) reqs.push(`scheme:${scheme.slice(0, -1)}`);
213
+ return reqs;
214
+ }
215
+
172
216
  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)) };
217
+ 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
218
  args.forEach((arg, i) => {
175
219
  for (const m of arg.matchAll(PLACEHOLDER_RE)) {
176
220
  if (!names[m[1]].has(m[2])) err(`ffmpeg.args[${i}]`, `${m[0]} names no ${m[1]}`);
@@ -179,13 +223,13 @@ function checkPlaceholders(args, inputs, outputs, err) {
179
223
  }
180
224
 
181
225
  /**
182
- * Replaces {{input:name}} and {{output:name}} in every argument.
226
+ * Replaces {{input:name}}, {{inputdir:name}} (the directory holding that input) and {{output:name}} in every argument.
183
227
  * @param {string[]} args
184
- * @param {{ input: Record<string, string>, output: Record<string, string> }} values
228
+ * @param {{ input: Record<string, string>, output: Record<string, string>, inputdir?: Record<string, string> }} values
185
229
  */
186
230
  export function resolvePlaceholders(args, values) {
187
231
  return args.map(arg => arg.replace(PLACEHOLDER_RE, (whole, kind, name) => {
188
- const v = values[kind][name];
232
+ const v = values[kind]?.[name];
189
233
  if (v === undefined) throw new Error(`unresolved placeholder ${whole}`);
190
234
  return v;
191
235
  }));
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
- const needsStaging = batch && spec.inputs.some(i => HTTP_SCHEMES.includes(new URL(i.uri).protocol));
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
- values.input[input.name] = await stageInput(input, { batch, rt, doFetch });
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: true, contentType: output.contentType });
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 });
@@ -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
- if (batch) throw new FleetError('OUTPUT_MISSING', `ffmpeg did not write output "${o.name}"`, { details: { exitCode, stderrTail } });
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', `${input.name}${extname(url.pathname)}`);
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
- return path;
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 }) {
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;
@@ -21,36 +22,51 @@ const SSE_KEEPALIVE_MS = 15000;
21
22
  /**
22
23
  * The consumer API (contract v1), served identically by a worker and the orchestrator.
23
24
  *
25
+ * Every route except /v1/health needs a principal (see auth.js). Job routes need the `jobs`
26
+ * scope, /metrics needs `metrics`. A principal without `admin` only sees its own jobs, and the
27
+ * jobs it submits are owned by it whatever `owner` the spec names.
28
+ *
24
29
  * @param {object} opts
25
30
  * @param {JobBackend} opts.backend
26
- * @param {string | null} [opts.token] Bearer token required on every route except /v1/health.
27
- * @param {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse, url: URL) => Promise<boolean> | boolean} [opts.extraRoutes]
31
+ * @param {string | null} [opts.token] A static admin token; ignored when `authenticate` is given.
32
+ * @param {(req: import('node:http').IncomingMessage) => Promise<import('./auth.js').Principal | null>} [opts.authenticate]
33
+ * @param {(() => Promise<string>) | null} [opts.metrics] Renders the Prometheus text for GET /metrics.
34
+ * @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
35
  */
29
- export function createApiHandler({ backend, token = null, extraRoutes }) {
36
+ export function createApiHandler({ backend, token = null, authenticate = createAuthenticator({ token }), metrics = null, extraRoutes }) {
30
37
  return async (req, res) => {
31
38
  const url = new URL(req.url ?? '/', 'http://localhost');
32
39
  try {
33
40
  if (req.method === 'GET' && url.pathname === '/v1/health') return send(res, 200, { ok: true });
34
- if (extraRoutes && (await extraRoutes(req, res, url))) return;
35
- if (!checkBearer(req, token)) return send(res, 401, { error: { code: 'UNAUTHORIZED', message: 'missing or wrong bearer token' } });
41
+ const who = await authenticate(req);
42
+ if (extraRoutes && (await extraRoutes(req, res, url, who))) return;
43
+ if (metrics && req.method === 'GET' && url.pathname === '/metrics') {
44
+ if (!allowed(res, who, 'metrics')) return;
45
+ const text = await metrics();
46
+ res.writeHead(200, { 'content-type': METRICS_CONTENT_TYPE });
47
+ return res.end(text);
48
+ }
49
+ if (!allowed(res, who, 'jobs')) return;
50
+ const mine = job => job && (who.admin || job.owner === who.sub) ? job : null;
36
51
 
37
52
  if (url.pathname === '/v1/capabilities' && req.method === 'GET') return send(res, 200, await backend.capabilities());
38
53
  if (url.pathname === '/v1/jobs') {
39
54
  if (req.method === 'POST') {
40
- const { created, queued, job } = await backend.submit(await readJson(req));
55
+ const input = await readJson(req);
56
+ if (!who.admin && input && typeof input === 'object' && !Array.isArray(input)) input.owner = who.sub;
57
+ const { created, queued, job } = await backend.submit(input);
41
58
  // 201: took a slot (or was handed to a worker) now; 202: waiting in the queue; 200: already known.
42
59
  return send(res, created ? ((queued ?? job.state === 'queued') ? 202 : 201) : 200, job);
43
60
  }
44
- if (req.method === 'GET') return send(res, 200, { jobs: backend.list() });
61
+ if (req.method === 'GET') return send(res, 200, { jobs: backend.list().filter(mine) });
45
62
  }
46
63
 
47
64
  const m = url.pathname.match(/^\/v1\/jobs\/([^/]+)(\/events|\/stdin)?$/);
48
65
  if (m) {
49
66
  const id = decodeURIComponent(m[1]);
50
- if (!m[2] && req.method === 'GET') {
51
- const job = backend.get(id);
52
- return job ? send(res, 200, job) : notFound(res, id);
53
- }
67
+ // Someone else's job answers 404, the same as a job that does not exist.
68
+ if (!mine(backend.get(id))) return notFound(res, id);
69
+ if (!m[2] && req.method === 'GET') return send(res, 200, backend.get(id));
54
70
  if (!m[2] && req.method === 'DELETE') {
55
71
  const job = await backend.cancel(id);
56
72
  return job ? send(res, 202, job) : notFound(res, id);
@@ -68,6 +84,19 @@ export function createApiHandler({ backend, token = null, extraRoutes }) {
68
84
  };
69
85
  }
70
86
 
87
+ /** Sends 401 (no or bad credentials) or 403 (missing scope) and returns false, or returns true. */
88
+ export function allowed(res, who, scope) {
89
+ if (!who) {
90
+ send(res, 401, { error: { code: 'UNAUTHORIZED', message: 'missing or invalid bearer token' } }, { 'www-authenticate': 'Bearer realm="fffleet"' });
91
+ return false;
92
+ }
93
+ if (!who.scopes.has(scope)) {
94
+ send(res, 403, { error: { code: 'FORBIDDEN', message: `this token lacks the "${scope}" scope` } });
95
+ return false;
96
+ }
97
+ return true;
98
+ }
99
+
71
100
  /** Starts an HTTP server on host:port (port 0 picks a free port). */
72
101
  export function listen(handler, { port = 0, host = '127.0.0.1' } = {}) {
73
102
  const server = createServer(handler);
@@ -123,9 +152,7 @@ function streamEvents(req, res, url, backend, id) {
123
152
  export function checkBearer(req, token) {
124
153
  if (!token) return true;
125
154
  const header = req.headers.authorization ?? '';
126
- const given = Buffer.from(header.startsWith('Bearer ') ? header.slice(7) : '');
127
- const want = Buffer.from(token);
128
- return given.length === want.length && timingSafeEqual(given, want);
155
+ return sameSecret(header.startsWith('Bearer ') ? header.slice(7) : '', token);
129
156
  }
130
157
 
131
158
  export function send(res, status, body, headers = {}) {
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';
@@ -0,0 +1,104 @@
1
+ // A worker-side cache of staged inputs, so a large source is downloaded once and not for every job.
2
+
3
+ import { createHash, randomBytes } from 'node:crypto';
4
+ import { copyFile, link, mkdir, readFile, readdir, rename, rm, stat, utimes, writeFile } from 'node:fs/promises';
5
+ import { dirname, join } from 'node:path';
6
+
7
+ /** "500", "20MB", "50GB" (decimal units) as a number of bytes. */
8
+ export function parseSize(value) {
9
+ if (typeof value === 'number') return value;
10
+ const m = String(value).trim().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/i);
11
+ if (!m) throw new Error(`invalid size "${value}" (use for example 500MB or 50GB)`);
12
+ const unit = { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12 }[(m[2] ?? 'b').toLowerCase()];
13
+ return Math.round(Number(m[1]) * unit);
14
+ }
15
+
16
+ /**
17
+ * @param {object} opts
18
+ * @param {string} opts.dir Where cached files live.
19
+ * @param {number} [opts.maxBytes] Least recently used files are removed above this. Default 20 GB.
20
+ */
21
+ export function createInputCache({ dir, maxBytes = 20e9 }) {
22
+ const hashOf = key => createHash('sha256').update(key).digest('hex').slice(0, 40);
23
+ const stats = { hits: 0, misses: 0 };
24
+
25
+ async function place(entry, target) {
26
+ await mkdir(dirname(target), { recursive: true });
27
+ await rm(target, { force: true });
28
+ try {
29
+ await link(entry, target);
30
+ } catch {
31
+ await copyFile(entry, target); // another file system, or no hard links
32
+ }
33
+ }
34
+
35
+ async function evict(keep) {
36
+ let names;
37
+ try {
38
+ names = (await readdir(dir)).filter(n => n.endsWith('.json'));
39
+ } catch {
40
+ return;
41
+ }
42
+ const entries = [];
43
+ let total = 0;
44
+ for (const n of names) {
45
+ const base = n.slice(0, -5);
46
+ try {
47
+ const [m, f] = await Promise.all([stat(join(dir, n)), stat(join(dir, `${base}.bin`))]);
48
+ entries.push({ base, used: m.mtimeMs, size: f.size });
49
+ total += f.size;
50
+ } catch {
51
+ // half-written or already removed
52
+ }
53
+ }
54
+ entries.sort((a, b) => a.used - b.used);
55
+ for (const e of entries) {
56
+ if (total <= maxBytes) break;
57
+ if (e.base === keep) continue;
58
+ await rm(join(dir, `${e.base}.bin`), { force: true });
59
+ await rm(join(dir, `${e.base}.json`), { force: true });
60
+ total -= e.size;
61
+ }
62
+ }
63
+
64
+ return {
65
+ stats,
66
+
67
+ /**
68
+ * Puts the file for `key` at `target`: from the cache when its `validator` (an ETag or similar) still
69
+ * matches, else by calling `download(path)` and keeping the result. Hard-links, so no copy is made.
70
+ * @returns {Promise<'hit' | 'miss'>}
71
+ */
72
+ async stage({ key, validator, target, download }) {
73
+ const base = hashOf(key);
74
+ const entry = join(dir, `${base}.bin`);
75
+ const metaPath = join(dir, `${base}.json`);
76
+ await mkdir(dir, { recursive: true });
77
+ try {
78
+ const meta = JSON.parse(await readFile(metaPath, 'utf8'));
79
+ if (meta.validator === validator && (await stat(entry)).size === meta.size) {
80
+ const now = new Date();
81
+ await utimes(metaPath, now, now).catch(() => {});
82
+ await place(entry, target);
83
+ stats.hits++;
84
+ return 'hit';
85
+ }
86
+ } catch {
87
+ // not cached yet
88
+ }
89
+ const part = join(dir, `${base}.${randomBytes(4).toString('hex')}.part`);
90
+ try {
91
+ await download(part);
92
+ const { size } = await stat(part);
93
+ await rename(part, entry);
94
+ await writeFile(metaPath, JSON.stringify({ key, validator, size }));
95
+ } finally {
96
+ await rm(part, { force: true });
97
+ }
98
+ await place(entry, target);
99
+ stats.misses++;
100
+ await evict(base);
101
+ return 'miss';
102
+ },
103
+ };
104
+ }
@@ -1,8 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { EventEmitter } from 'node:events';
2
3
  import { mkdir, rm } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
+ import { availableParallelism, tmpdir } from 'node:os';
4
5
  import { join } from 'node:path';
5
- import { canonicalJson, parseSpec } from './contract.js';
6
+ import { KINDS, canonicalJson, implicitRequirements, parseSpec } from './contract.js';
7
+ import { createInputCache, parseSize } from './input-cache.js';
8
+ import { createS3Client } from './s3.js';
6
9
  import { runFfmpegJob } from './executor.js';
7
10
  import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.js';
8
11
 
@@ -13,11 +16,15 @@ import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.j
13
16
  *
14
17
  * Slots: `{ default: 2, stream: 1 }` means two jobs of any class plus one extra slot
15
18
  * reserved for class "stream". A class without its own pool uses "default".
19
+ *
20
+ * Events: 'job' (record) for every new job, 'transfer' ({ direction: 'in' | 'out', scheme, bytes })
21
+ * after an input is staged or an output uploaded.
16
22
  */
17
- export class JobManager {
23
+ export class JobManager extends EventEmitter {
18
24
  /**
19
25
  * @param {object} [opts]
20
- * @param {Record<string, number>} [opts.slots]
26
+ * @param {Record<string, number> | string} [opts.slots] Pools, or 'auto' / 'auto:<cores per job>' to size them from this machine's CPUs.
27
+ * @param {('batch' | 'stream')[]} [opts.kinds] Job kinds this runner accepts (both by default).
21
28
  * @param {string} [opts.workRoot]
22
29
  * @param {string} [opts.ffmpegPath]
23
30
  * @param {number} [opts.maxQueued]
@@ -26,9 +33,12 @@ export class JobManager {
26
33
  * @param {Record<string, Function>} [opts.executors] type -> (spec, runtime) => Promise<result>
27
34
  * @param {string} [opts.workerId]
28
35
  * @param {typeof fetch} [opts.fetch]
36
+ * @param {object | null} [opts.s3] S3 settings (see s3ConfigFromEnv) or a client; enables s3: URIs.
37
+ * @param {{ dir: string, maxBytes?: number | string } | null} [opts.cache] Keeps staged s3: and http(s): inputs between jobs (least recently used removed above maxBytes, default 20 GB).
29
38
  */
30
39
  constructor({
31
40
  slots = { default: 2 },
41
+ kinds = KINDS,
32
42
  workRoot = join(tmpdir(), 'fffleet'),
33
43
  ffmpegPath = 'ffmpeg',
34
44
  maxQueued = 1000,
@@ -37,8 +47,12 @@ export class JobManager {
37
47
  executors = {},
38
48
  workerId = null,
39
49
  fetch: fetchImpl,
50
+ s3 = null,
51
+ cache = null,
40
52
  } = {}) {
41
- this.slots = normalizeSlots(slots);
53
+ super();
54
+ this.kinds = normalizeKinds(kinds);
55
+ this.slots = normalizeSlots(slots, { kinds: this.kinds });
42
56
  this.used = Object.fromEntries(Object.keys(this.slots).map(k => [k, 0]));
43
57
  this.workRoot = workRoot;
44
58
  this.ffmpegPath = ffmpegPath;
@@ -48,6 +62,8 @@ export class JobManager {
48
62
  this.executors = { ffmpeg: runFfmpegJob, ...executors };
49
63
  this.workerId = workerId;
50
64
  this.fetch = fetchImpl;
65
+ this.cache = cache ? createInputCache({ dir: cache.dir, maxBytes: cache.maxBytes === undefined ? undefined : parseSize(cache.maxBytes) }) : null;
66
+ this.s3 = !s3 ? null : typeof s3.getFile === 'function' ? s3 : createS3Client({ fetch: fetchImpl, ...s3 });
51
67
  /** @type {Map<string, JobRecord & { run?: any }>} */
52
68
  this.jobs = new Map();
53
69
  /** @type {JobRecord[]} */
@@ -76,9 +92,15 @@ export class JobManager {
76
92
  }
77
93
  return { created: false, job: existing.snapshot() };
78
94
  }
95
+ if (!this.kinds.includes(spec.kind)) {
96
+ throw new FleetError('UNSUPPORTED_KIND', `this runner only takes ${this.kinds.join(' and ')} jobs`, { status: 422 });
97
+ }
79
98
  if (!this.executors[spec.type]) {
80
99
  throw new FleetError('UNSUPPORTED_TYPE', `no executor for job type "${spec.type}"`, { status: 422 });
81
100
  }
101
+ if (!this.s3 && implicitRequirements(spec).includes('scheme:s3')) {
102
+ throw new FleetError('UNSUPPORTED_SCHEME', 's3: URIs need S3 credentials on this runner', { status: 422 });
103
+ }
82
104
  const pool = this.poolFor(spec.class);
83
105
  if (this.slots[pool] === undefined || this.slots[pool] === 0) {
84
106
  throw new FleetError('NO_SLOTS', `no slot pool for class "${spec.class}"`, { status: 422 });
@@ -92,6 +114,7 @@ export class JobManager {
92
114
  this.jobs.set(spec.id, record);
93
115
  this.queue.push(record);
94
116
  this.queue.sort(byPriority);
117
+ this.emit('job', record);
95
118
  this.pump();
96
119
  return { created: true, queued: this.queue.includes(record), job: record.snapshot() };
97
120
  }
@@ -166,7 +189,7 @@ export class JobManager {
166
189
 
167
190
  start(record, pool) {
168
191
  const abort = new AbortController();
169
- const run = { abort, stdin: null, done: null };
192
+ const run = { abort, stdin: null, done: null, pid: null };
170
193
  record.run = run;
171
194
  let timer = null;
172
195
  if (record.spec.timeoutMs) {
@@ -180,7 +203,10 @@ export class JobManager {
180
203
  signal: abort.signal,
181
204
  ffmpegPath: this.ffmpegPath,
182
205
  fetch: this.fetch,
183
- setState: state => {
206
+ s3: this.s3,
207
+ cache: this.cache,
208
+ setState: (state, extra) => {
209
+ if (extra?.pid) run.pid = extra.pid;
184
210
  if (!abort.signal.aborted) record.push({ state, ...(this.workerId ? { workerId: this.workerId } : {}) });
185
211
  },
186
212
  progress: p => {
@@ -195,6 +221,9 @@ export class JobManager {
195
221
  attachStdin: s => {
196
222
  run.stdin = s;
197
223
  },
224
+ transfer: (direction, scheme, bytes) => {
225
+ if (bytes > 0) this.emit('transfer', { direction, scheme, bytes });
226
+ },
198
227
  };
199
228
 
200
229
  run.done = (async () => {
@@ -216,6 +245,7 @@ export class JobManager {
216
245
  } finally {
217
246
  clearTimeout(timer);
218
247
  run.stdin = null;
248
+ run.pid = null;
219
249
  this.used[pool]--;
220
250
  await rm(workDir, { recursive: true, force: true }).catch(() => {});
221
251
  if (!this.closed) this.pump();
@@ -224,8 +254,44 @@ export class JobManager {
224
254
  }
225
255
  }
226
256
 
227
- /** Parses "default=2,stream=1" or an object into { pool: count }. */
228
- export function normalizeSlots(slots) {
257
+ /** Parses "batch", "stream", "batch,stream" or an array into a list of job kinds. */
258
+ export function normalizeKinds(kinds) {
259
+ const list = (typeof kinds === 'string' ? kinds.split(',') : kinds ?? []).map(k => String(k).trim()).filter(Boolean);
260
+ if (!list.length) return [...KINDS];
261
+ for (const k of list) if (!KINDS.includes(k)) throw new Error(`invalid job kind "${k}"; kinds are ${KINDS.join(' and ')}`);
262
+ return [...new Set(list)];
263
+ }
264
+
265
+ /**
266
+ * Slot pools sized from the CPU count. A batch job (an encode) is assumed to use about two cores,
267
+ * a stream job (a relay or a light live encode) about one; `auto:N` sets the cores per slot.
268
+ *
269
+ * - batch and stream: `default` for batch work plus a separate `stream` pool of a quarter of the cores.
270
+ * - batch only: `default` = cores / 2.
271
+ * - stream only: `default` = cores.
272
+ *
273
+ * @param {{ cpus?: number, kinds?: string[], coresPerSlot?: number }} [opts]
274
+ */
275
+ export function autoSlots({ cpus = availableParallelism(), kinds = KINDS, coresPerSlot } = {}) {
276
+ const streamOnly = kinds.length === 1 && kinds[0] === 'stream';
277
+ const per = coresPerSlot ?? (streamOnly ? 1 : 2);
278
+ const slots = { default: Math.max(1, Math.floor(cpus / per)) };
279
+ if (kinds.includes('batch') && kinds.includes('stream') && coresPerSlot === undefined) slots.stream = Math.max(1, Math.floor(cpus / 4));
280
+ return slots;
281
+ }
282
+
283
+ /**
284
+ * Parses "default=2,stream=1", "auto", "auto:1" or an object into { pool: count }.
285
+ * @param {string | Record<string, number | string>} slots
286
+ * @param {{ kinds?: string[], cpus?: number }} [opts] used by "auto"
287
+ */
288
+ export function normalizeSlots(slots, { kinds = KINDS, cpus } = {}) {
289
+ const auto = typeof slots === 'string' ? slots.trim().match(/^auto(?::(\d+(?:\.\d+)?))?$/) : null;
290
+ if (auto) {
291
+ const coresPerSlot = auto[1] === undefined ? undefined : Number(auto[1]);
292
+ if (coresPerSlot !== undefined && !(coresPerSlot > 0)) throw new Error(`invalid slots "${slots}": cores per slot must be above 0`);
293
+ return autoSlots({ kinds, cpus, coresPerSlot });
294
+ }
229
295
  const obj = typeof slots === 'string'
230
296
  ? Object.fromEntries(slots.split(',').map(s => s.trim()).filter(Boolean).map(s => s.split('=').map(x => x.trim())))
231
297
  : slots;