fffleet-worker 0.0.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/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,11 @@ 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_CACHE_MAX_SIZE` | `20GB` | Least recently used inputs are removed above this. |
22
26
  | `FFMPEG_PATH` | `ffmpeg` | |
27
+ | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | | Enable `s3://` inputs and outputs and the `scheme:s3` capability. Also `AWS_SESSION_TOKEN`, `AWS_REGION`. |
28
+ | `FFFLEET_S3_ENDPOINT`, `FFFLEET_S3_PATH_STYLE` | AWS, off | For S3-compatible stores, e.g. `http://minio:9000` and `1`. |
23
29
 
24
30
  The worker detects `type:ffmpeg`, `ffmpeg:<version>`, `filter:*`, `encoder:*` and `font:*` capabilities at start-up.
25
31
 
@@ -27,4 +33,6 @@ The Docker image is Debian's ffmpeg build, with x264, x265, vpx, aom, lame, opus
27
33
 
28
34
  Programmatic use: `import { createWorker } from 'fffleet-worker'`. Pass `executors` to add job types other than ffmpeg.
29
35
 
36
+ `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.
37
+
30
38
  License: EUPL-1.2
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { s3ConfigFromEnv } from 'fffleet';
2
3
  import { createWorker } from '../src/worker.js';
3
4
 
4
5
  const env = process.env;
@@ -11,13 +12,19 @@ const worker = createWorker({
11
12
  // Behind an orchestrator the worker usually accepts the same token it registers with.
12
13
  token: env.FFFLEET_TOKEN || env.FFFLEET_WORKER_TOKEN || null,
13
14
  slots: env.FFFLEET_SLOTS || 'default=2',
15
+ kinds: env.FFFLEET_KINDS || undefined,
14
16
  ffmpegPath: env.FFMPEG_PATH || 'ffmpeg',
17
+ // An orchestrator's /v1/auth/keys: apps and Prometheus can then use the tokens it issued on this worker too.
18
+ // Only when a static token is set; a worker with no token stays open, as before.
19
+ 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
20
  workRoot: env.FFFLEET_WORK_DIR || undefined,
16
21
  extraCapabilities: list(env.FFFLEET_CAPABILITIES),
17
22
  orchestratorUrl: env.FFFLEET_ORCHESTRATOR_URL || null,
18
23
  orchestratorToken: env.FFFLEET_WORKER_TOKEN || null,
19
24
  advertiseUrl: env.FFFLEET_ADVERTISE_URL || null,
20
25
  heartbeatMs: Number(env.FFFLEET_HEARTBEAT_MS ?? 5000),
26
+ s3: s3ConfigFromEnv(env),
27
+ cache: env.FFFLEET_CACHE_DIR ? { dir: env.FFFLEET_CACHE_DIR, maxBytes: env.FFFLEET_CACHE_MAX_SIZE || undefined } : null,
21
28
  log: msg => console.log(`[fffleet-worker] ${msg}`),
22
29
  });
23
30
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet-worker",
3
- "version": "0.0.0",
3
+ "version": "1.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",
@@ -9,7 +9,7 @@
9
9
  "./package.json": "./package.json"
10
10
  },
11
11
  "bin": {
12
- "fffleet-worker": "./bin/fffleet-worker.js"
12
+ "fffleet-worker": "bin/fffleet-worker.js"
13
13
  },
14
14
  "files": [
15
15
  "src",
@@ -21,7 +21,7 @@
21
21
  "test": "node --test test/*.test.js"
22
22
  },
23
23
  "dependencies": {
24
- "fffleet": "^0.0.0"
24
+ "fffleet": "^1.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,15 +50,60 @@ 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),
@@ -57,14 +111,14 @@ export function createWorker({
57
111
  cancel: jobId => manager.cancel(jobId),
58
112
  writeStdin: (jobId, data) => manager.writeStdin(jobId, data),
59
113
  subscribe: (jobId, after, fn) => manager.subscribe(jobId, after, fn),
60
- capabilities: () => ({ id, version: VERSION, slots: manager.stats().pools, queued: manager.stats().queued, capabilities }),
114
+ capabilities: () => ({ id, version: VERSION, kinds: manager.kinds, slots: manager.stats().pools, queued: manager.stats().queued, capabilities }),
61
115
  };
62
116
 
63
117
  async function register() {
64
118
  const res = await fetch(`${orchestratorUrl.replace(/\/+$/, '')}/v1/workers/register`, {
65
119
  method: 'POST',
66
120
  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() }),
121
+ body: JSON.stringify({ id, url: advertiseUrl ?? url, slots: manager.slots, kinds: manager.kinds, capabilities, version: VERSION, active: manager.activeIds() }),
68
122
  signal: AbortSignal.timeout(5000),
69
123
  });
70
124
  if (!res.ok) throw new Error(`register returned HTTP ${res.status}`);
@@ -82,6 +136,7 @@ export function createWorker({
82
136
  return {
83
137
  id,
84
138
  manager,
139
+ registry,
85
140
  get url() {
86
141
  return url;
87
142
  },
@@ -92,9 +147,10 @@ export function createWorker({
92
147
  async start() {
93
148
  // type:ffmpeg comes from detection, so a machine without ffmpeg does not claim it.
94
149
  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)}`);
150
+ const schemes = manager.s3 ? ['scheme:s3'] : [];
151
+ capabilities = [...new Set([...(await detectCapabilities(ffmpegPath)), ...types, ...schemes, ...extraCapabilities])].sort();
152
+ ({ server, url } = await listen(createApiHandler({ backend, authenticate, metrics: () => registry.render() }), { port, host }));
153
+ log(`fffleet-worker ${id} listening on ${url} with slots ${JSON.stringify(manager.slots)} for ${manager.kinds.join(' and ')} jobs`);
98
154
  if (orchestratorUrl) {
99
155
  await register().catch(err => log(`first registration failed, retrying: ${err.message}`));
100
156
  heartbeat = setInterval(beat, heartbeatMs);