fffleet-worker 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 CHANGED
@@ -10,8 +10,10 @@ docker run -p 5100:5100 -e FFFLEET_TOKEN=secret ghcr.io/jsilvanus/fffleet-worker
10
10
  | Variable | Default | |
11
11
  |---|---|---|
12
12
  | `PORT`, `HOST` | `5100`, `0.0.0.0` | |
13
- | `FFFLEET_TOKEN` | `FFFLEET_WORKER_TOKEN` | Bearer token callers must send. With neither set the API is open. |
14
- | `FFFLEET_SLOTS` | `default=2` | Slot pools, e.g. `default=2,stream=1`. |
13
+ | `FFFLEET_TOKEN` | `FFFLEET_WORKER_TOKEN` | Bearer token callers must send (full access, and what the orchestrator uses). With neither set the API is open. |
14
+ | `FFFLEET_KEYS_URL` | the orchestrator's `/v1/auth/keys` when a token and an orchestrator are set | Also accept tokens the orchestrator issued, with their scopes. |
15
+ | `FFFLEET_SLOTS` | `default=2` | Slot pools, e.g. `default=2,stream=1`, or `auto` (from the CPU count) / `auto:4` (4 cores per slot). |
16
+ | `FFFLEET_KINDS` | `batch,stream` | Job kinds this worker takes. Others get 422 `UNSUPPORTED_KIND`, and the orchestrator does not send them. |
15
17
  | `FFFLEET_CAPABILITIES` | | Extra capabilities, comma separated, e.g. `mount:/media,site:hel1`. |
16
18
  | `FFFLEET_ORCHESTRATOR_URL` | | Register and heartbeat here. |
17
19
  | `FFFLEET_WORKER_TOKEN` | | Token for the orchestrator. |
@@ -19,7 +21,12 @@ docker run -p 5100:5100 -e FFFLEET_TOKEN=secret ghcr.io/jsilvanus/fffleet-worker
19
21
  | `FFFLEET_WORKER_ID` | `worker-<hostname>` | |
20
22
  | `FFFLEET_HEARTBEAT_MS` | `5000` | |
21
23
  | `FFFLEET_WORK_DIR` | `$TMPDIR/fffleet` | Scratch space for staged inputs and outputs. |
24
+ | `FFFLEET_CACHE_DIR` | | Keep staged `s3://` and `http(s)://` inputs here between jobs (hard-linked, checked against the object's ETag). Off when unset. |
25
+ | `FFFLEET_EXECUTORS` | | Comma-separated modules (package names or paths) that add job types. Each default-exports `{ type, run(spec, runtime) }` or an array of them. The worker then claims `type:<type>`. |
26
+ | `FFFLEET_CACHE_MAX_SIZE` | `20GB` | Least recently used inputs are removed above this. |
22
27
  | `FFMPEG_PATH` | `ffmpeg` | |
28
+ | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | | Enable `s3://` inputs and outputs and the `scheme:s3` capability. Also `AWS_SESSION_TOKEN`, `AWS_REGION`. |
29
+ | `FFFLEET_S3_ENDPOINT`, `FFFLEET_S3_PATH_STYLE` | AWS, off | For S3-compatible stores, e.g. `http://minio:9000` and `1`. |
23
30
 
24
31
  The worker detects `type:ffmpeg`, `ffmpeg:<version>`, `filter:*`, `encoder:*` and `font:*` capabilities at start-up.
25
32
 
@@ -27,4 +34,6 @@ The Docker image is Debian's ffmpeg build, with x264, x265, vpx, aom, lame, opus
27
34
 
28
35
  Programmatic use: `import { createWorker } from 'fffleet-worker'`. Pass `executors` to add job types other than ffmpeg.
29
36
 
37
+ `GET /metrics` (Prometheus text format, `metrics` scope or the static token) reports slots, running jobs with their encoding speed and fps, ffmpeg CPU and memory, bytes staged and uploaded, and host load and memory.
38
+
30
39
  License: EUPL-1.2
@@ -1,23 +1,45 @@
1
1
  #!/usr/bin/env node
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { s3ConfigFromEnv } from 'fffleet';
2
5
  import { createWorker } from '../src/worker.js';
3
6
 
4
7
  const env = process.env;
5
8
  const list = v => (v ? v.split(',').map(s => s.trim()).filter(Boolean) : []);
6
9
 
10
+ // Extra job types: FFFLEET_EXECUTORS lists modules (package names or paths) that default-export
11
+ // { type, run(spec, runtime) } or an array of them. Workers with them claim type:<type>.
12
+ const executors = {};
13
+ for (const ref of list(env.FFFLEET_EXECUTORS)) {
14
+ const specifier = ref.startsWith('.') || isAbsolute(ref) ? pathToFileURL(resolve(ref)).href : ref;
15
+ const mod = await import(specifier);
16
+ for (const e of [mod.default].flat()) {
17
+ if (!e || typeof e.type !== 'string' || typeof e.run !== 'function') throw new Error(`${ref}: default export must be { type, run } or an array of them`);
18
+ executors[e.type] = e.run;
19
+ }
20
+ }
21
+
7
22
  const worker = createWorker({
23
+ executors,
8
24
  id: env.FFFLEET_WORKER_ID || undefined,
9
25
  port: Number(env.PORT ?? 5100),
10
26
  host: env.HOST ?? '0.0.0.0',
11
27
  // Behind an orchestrator the worker usually accepts the same token it registers with.
12
28
  token: env.FFFLEET_TOKEN || env.FFFLEET_WORKER_TOKEN || null,
13
29
  slots: env.FFFLEET_SLOTS || 'default=2',
30
+ kinds: env.FFFLEET_KINDS || undefined,
14
31
  ffmpegPath: env.FFMPEG_PATH || 'ffmpeg',
32
+ // An orchestrator's /v1/auth/keys: apps and Prometheus can then use the tokens it issued on this worker too.
33
+ // Only when a static token is set; a worker with no token stays open, as before.
34
+ keysUrl: env.FFFLEET_KEYS_URL || ((env.FFFLEET_TOKEN || env.FFFLEET_WORKER_TOKEN) && env.FFFLEET_ORCHESTRATOR_URL ? `${env.FFFLEET_ORCHESTRATOR_URL.replace(/\/+$/, '')}/v1/auth/keys` : null),
15
35
  workRoot: env.FFFLEET_WORK_DIR || undefined,
16
36
  extraCapabilities: list(env.FFFLEET_CAPABILITIES),
17
37
  orchestratorUrl: env.FFFLEET_ORCHESTRATOR_URL || null,
18
38
  orchestratorToken: env.FFFLEET_WORKER_TOKEN || null,
19
39
  advertiseUrl: env.FFFLEET_ADVERTISE_URL || null,
20
40
  heartbeatMs: Number(env.FFFLEET_HEARTBEAT_MS ?? 5000),
41
+ s3: s3ConfigFromEnv(env),
42
+ cache: env.FFFLEET_CACHE_DIR ? { dir: env.FFFLEET_CACHE_DIR, maxBytes: env.FFFLEET_CACHE_MAX_SIZE || undefined } : null,
21
43
  log: msg => console.log(`[fffleet-worker] ${msg}`),
22
44
  });
23
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet-worker",
3
- "version": "0.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "fffleet worker daemon: runs ffmpeg jobs and serves the fffleet job API",
5
5
  "type": "module",
6
6
  "main": "./src/worker.js",
@@ -21,7 +21,7 @@
21
21
  "test": "node --test test/*.test.js"
22
22
  },
23
23
  "dependencies": {
24
- "fffleet": "^0.1.0"
24
+ "fffleet": "^2.0.0"
25
25
  },
26
26
  "keywords": [
27
27
  "ffmpeg",
package/src/worker.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { hostname } from 'node:os';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { JobManager, detectCapabilities } from 'fffleet';
4
- import { close, createApiHandler, listen } from 'fffleet/server';
4
+ import {
5
+ Registry, close, createApiHandler, createAuthenticator, createRemoteKeySet, createTokenVerifier,
6
+ hostMetrics, jobMetrics, listen, procStats, processMetrics,
7
+ } from 'fffleet/server';
5
8
 
6
9
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
7
10
 
@@ -13,8 +16,11 @@ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.u
13
16
  * @param {string} [opts.id]
14
17
  * @param {number} [opts.port]
15
18
  * @param {string} [opts.host]
16
- * @param {string | null} [opts.token] Required from callers (the orchestrator or a client).
17
- * @param {Record<string, number> | string} [opts.slots]
19
+ * @param {string | null} [opts.token] Static token that is granted full access (the orchestrator sends it).
20
+ * @param {string | null} [opts.keysUrl] An orchestrator's /v1/auth/keys: tokens it issued are accepted too, with their scopes.
21
+ * @param {Record<string, number> | string} [opts.slots] Pools, or 'auto' / 'auto:<cores per job>' to size them from the CPU count.
22
+ * @param {{ dir: string, maxBytes?: number | string } | null} [opts.cache] Keeps staged s3:/http inputs between jobs.
23
+ * @param {('batch' | 'stream')[] | string} [opts.kinds] Job kinds this worker takes; both by default. A batch-only and a stream-only worker keep long streams from starving encodes.
18
24
  * @param {string} [opts.ffmpegPath]
19
25
  * @param {string} [opts.workRoot]
20
26
  * @param {string[]} [opts.extraCapabilities] Added to the detected ones, e.g. 'mount:/data/media'.
@@ -24,6 +30,7 @@ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.u
24
30
  * @param {number} [opts.heartbeatMs]
25
31
  * @param {number} [opts.progressIntervalMs]
26
32
  * @param {Record<string, Function>} [opts.executors] Extra job types: type -> (spec, runtime) => Promise<result>.
33
+ * @param {object | null} [opts.s3] S3 settings (see s3ConfigFromEnv); adds the scheme:s3 capability.
27
34
  * @param {(msg: string) => void} [opts.log]
28
35
  */
29
36
  export function createWorker({
@@ -31,7 +38,9 @@ export function createWorker({
31
38
  port = 5100,
32
39
  host = '0.0.0.0',
33
40
  token = null,
41
+ keysUrl = null,
34
42
  slots = { default: 2 },
43
+ kinds = undefined,
35
44
  ffmpegPath = 'ffmpeg',
36
45
  workRoot,
37
46
  extraCapabilities = [],
@@ -41,30 +50,77 @@ export function createWorker({
41
50
  heartbeatMs = 5000,
42
51
  progressIntervalMs = 1000,
43
52
  executors = {},
53
+ s3 = null,
54
+ cache = null,
44
55
  log = () => {},
45
56
  } = {}) {
46
- const manager = new JobManager({ slots, ffmpegPath, workRoot, workerId: id, progressIntervalMs, executors });
57
+ const manager = new JobManager({ slots, kinds, ffmpegPath, workRoot, workerId: id, progressIntervalMs, executors, s3, cache });
47
58
  let capabilities = [];
48
59
  let server = null;
49
60
  let url = null;
50
61
  let heartbeat = null;
51
62
  let registered = false;
52
63
 
64
+ const authenticate = createAuthenticator({
65
+ token,
66
+ verify: keysUrl ? createTokenVerifier({ getKey: createRemoteKeySet(keysUrl) }) : null,
67
+ open: !token && !keysUrl,
68
+ });
69
+
70
+ const registry = new Registry();
71
+ processMetrics(registry);
72
+ hostMetrics(registry, manager.workRoot);
73
+ const jobStats = jobMetrics(registry, () => manager.jobs.values());
74
+ manager.on('job', record => jobStats.track(record));
75
+ const slotsTotal = registry.gauge('fffleet_slots', 'Slots per pool.', ['pool']);
76
+ const slotsUsed = registry.gauge('fffleet_slots_used', 'Slots in use per pool.', ['pool']);
77
+ const queued = registry.gauge('fffleet_queue_length', 'Jobs waiting for a slot on this worker.');
78
+ const speed = registry.gauge('fffleet_job_speed', 'Encoding speed of a running job as a multiple of real time.', ['job', 'owner', 'class']);
79
+ const fps = registry.gauge('fffleet_job_fps', 'Frames per second of a running job.', ['job', 'owner', 'class']);
80
+ const procCpu = registry.gauge('fffleet_ffmpeg_cpu_seconds', 'CPU time used so far by a running ffmpeg process (Linux).', ['job']);
81
+ const procRss = registry.gauge('fffleet_ffmpeg_resident_memory_bytes', 'Resident memory of a running ffmpeg process (Linux).', ['job']);
82
+ const transferred = registry.counter('fffleet_transfer_bytes_total', 'Bytes staged in and uploaded out of this worker.', ['direction', 'scheme']);
83
+ const info = registry.gauge('fffleet_build_info', 'Version of this fffleet process.', ['role', 'version', 'worker']);
84
+ info.set({ role: 'worker', version: VERSION, worker: id }, 1);
85
+ manager.on('transfer', t => transferred.inc({ direction: t.direction, scheme: t.scheme }, t.bytes));
86
+ registry.collect(async () => {
87
+ for (const g of [slotsTotal, slotsUsed, speed, fps, procCpu, procRss]) g.reset();
88
+ const stats = manager.stats();
89
+ for (const [pool, p] of Object.entries(stats.pools)) {
90
+ slotsTotal.set({ pool }, p.total);
91
+ slotsUsed.set({ pool }, p.used);
92
+ }
93
+ queued.set({}, stats.queued);
94
+ for (const r of manager.jobs.values()) {
95
+ if (r.state !== 'running') continue;
96
+ const l = { job: r.id, owner: r.spec.owner, class: r.spec.class };
97
+ if (r.progress?.speed != null) speed.set(l, r.progress.speed);
98
+ if (r.progress?.fps != null) fps.set(l, r.progress.fps);
99
+ const ps = r.run?.pid ? await procStats(r.run.pid) : null;
100
+ if (ps) {
101
+ procCpu.set({ job: r.id }, ps.cpuSeconds);
102
+ procRss.set({ job: r.id }, ps.rssBytes);
103
+ }
104
+ }
105
+ });
106
+
53
107
  const backend = {
54
108
  submit: spec => manager.submit(spec),
55
109
  get: jobId => manager.get(jobId),
56
110
  list: () => manager.list(),
57
111
  cancel: jobId => manager.cancel(jobId),
58
112
  writeStdin: (jobId, data) => manager.writeStdin(jobId, data),
113
+ closeStdin: jobId => manager.closeStdin(jobId),
114
+ openStdout: jobId => manager.openStdout(jobId),
59
115
  subscribe: (jobId, after, fn) => manager.subscribe(jobId, after, fn),
60
- capabilities: () => ({ id, version: VERSION, slots: manager.stats().pools, queued: manager.stats().queued, capabilities }),
116
+ capabilities: () => ({ id, version: VERSION, kinds: manager.kinds, slots: manager.stats().pools, queued: manager.stats().queued, capabilities }),
61
117
  };
62
118
 
63
119
  async function register() {
64
120
  const res = await fetch(`${orchestratorUrl.replace(/\/+$/, '')}/v1/workers/register`, {
65
121
  method: 'POST',
66
122
  headers: { 'content-type': 'application/json', ...(orchestratorToken ? { authorization: `Bearer ${orchestratorToken}` } : {}) },
67
- body: JSON.stringify({ id, url: advertiseUrl ?? url, slots: manager.slots, capabilities, version: VERSION, active: manager.activeIds() }),
123
+ body: JSON.stringify({ id, url: advertiseUrl ?? url, slots: manager.slots, kinds: manager.kinds, capabilities, version: VERSION, active: manager.activeIds() }),
68
124
  signal: AbortSignal.timeout(5000),
69
125
  });
70
126
  if (!res.ok) throw new Error(`register returned HTTP ${res.status}`);
@@ -82,6 +138,7 @@ export function createWorker({
82
138
  return {
83
139
  id,
84
140
  manager,
141
+ registry,
85
142
  get url() {
86
143
  return url;
87
144
  },
@@ -92,9 +149,10 @@ export function createWorker({
92
149
  async start() {
93
150
  // type:ffmpeg comes from detection, so a machine without ffmpeg does not claim it.
94
151
  const types = Object.keys(manager.executors).filter(t => t !== 'ffmpeg').map(t => `type:${t}`);
95
- capabilities = [...new Set([...(await detectCapabilities(ffmpegPath)), ...types, ...extraCapabilities])].sort();
96
- ({ server, url } = await listen(createApiHandler({ backend, token }), { port, host }));
97
- log(`fffleet-worker ${id} listening on ${url} with slots ${JSON.stringify(manager.slots)}`);
152
+ const schemes = manager.s3 ? ['scheme:s3'] : [];
153
+ capabilities = [...new Set([...(await detectCapabilities(ffmpegPath)), ...types, ...schemes, ...extraCapabilities])].sort();
154
+ ({ server, url } = await listen(createApiHandler({ backend, authenticate, metrics: () => registry.render() }), { port, host }));
155
+ log(`fffleet-worker ${id} listening on ${url} with slots ${JSON.stringify(manager.slots)} for ${manager.kinds.join(' and ')} jobs`);
98
156
  if (orchestratorUrl) {
99
157
  await register().catch(err => log(`first registration failed, retrying: ${err.message}`));
100
158
  heartbeat = setInterval(beat, heartbeatMs);