fffleet-worker 2.3.1 → 2.4.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
@@ -34,6 +34,20 @@ The worker detects `type:ffmpeg`, `ffmpeg:<version>`, `filter:*`, `encoder:*` an
34
34
 
35
35
  The Docker image is Debian's ffmpeg build, with x264, x265, vpx, aom, lame, opus, libass and freetype, plus DejaVu fonts.
36
36
 
37
+ ## Download jobs (yt-dlp)
38
+
39
+ `FFFLEET_EXECUTORS=fffleet-worker/executors/download` (or the `fffleet-worker-ytdlp` image, which has it and yt-dlp) adds job type `download`; the worker then claims `type:download`. `YTDLP_PATH` overrides the yt-dlp binary.
40
+
41
+ ```js
42
+ { type: 'download',
43
+ download: { url: 'https://…', format: 'bv*+ba/b', extraArgs: ['--limit-rate', '5M'] }, // url must be http(s)
44
+ inputs: [{ name: 'cookies', uri: 's3://bucket/tmp/cookies.txt' }], // optional Netscape cookies.txt
45
+ outputs: [{ name: 'video', uri: 's3://bucket/out/video.mp4' },
46
+ { name: 'cookies-out', uri: 's3://bucket/tmp/cookies-out.txt' }] } // optional
47
+ ```
48
+
49
+ **Credentials are a cookies.txt passed as an input**, so they travel like any other file (`s3:`, `http(s):` or `file:`) and never appear in the job spec, logs or errors. Stage the cookie file in a private object, and delete it when the job ends. yt-dlp rewrites its cookie file, so the executor works on a copy in the job's work directory; `cookies-out` is uploaded only when yt-dlp changed it, so you can store the refreshed cookies. `extraArgs` refuses options that run commands or touch other files (`--exec`, `--output`, `--cookies`, config and plugin options). Progress comes from yt-dlp's percentages and cancelling the job stops yt-dlp.
50
+
37
51
  Programmatic use: `import { createWorker } from 'fffleet-worker'`. Pass `executors` to add job types other than ffmpeg.
38
52
 
39
53
  `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.
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "fffleet-worker",
3
- "version": "2.3.1",
3
+ "version": "2.4.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",
7
7
  "exports": {
8
8
  ".": "./src/worker.js",
9
- "./package.json": "./package.json"
9
+ "./package.json": "./package.json",
10
+ "./executors/download": "./src/executors/download.js"
10
11
  },
11
12
  "bin": {
12
13
  "fffleet-worker": "bin/fffleet-worker.js"
@@ -21,7 +22,7 @@
21
22
  "test": "node --test test/*.test.js"
22
23
  },
23
24
  "dependencies": {
24
- "fffleet": "^2.3.1"
25
+ "fffleet": "^2.4.0"
25
26
  },
26
27
  "keywords": [
27
28
  "ffmpeg",
@@ -0,0 +1,230 @@
1
+ // Built-in executor for yt-dlp downloads (job type "download").
2
+ //
3
+ // Enable it on a worker with FFFLEET_EXECUTORS=fffleet-worker/executors/download (yt-dlp must be on the PATH, or set
4
+ // YTDLP_PATH). The worker image `fffleet-worker-ytdlp` has both.
5
+ //
6
+ // Spec: spec.download = { url, format?, extraArgs? } (url is http(s); format is a yt-dlp format selector)
7
+ // Inputs: "cookies" (optional) Netscape cookies.txt; s3:, http(s): or file:. Copied into the work directory, because
8
+ // yt-dlp rewrites the cookie file it is given.
9
+ // Outputs: "video" the downloaded mp4 (s3:, file: or http(s) PUT)
10
+ // "cookies-out" (opt.) the cookie file after the run, uploaded only when yt-dlp changed it
11
+ //
12
+ // Cookie contents are never logged and never put into errors: error text is built from yt-dlp's stderr after cookie
13
+ // values, the cookie file path and cookie-shaped lines are removed.
14
+ import { spawn } from "node:child_process";
15
+ import { createHash } from "node:crypto";
16
+ import { copyFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
17
+ import { dirname, join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ const DEFAULT_FORMAT = "bv*+ba/b";
21
+ const KILL_GRACE_MS = 5000;
22
+ const TAIL_CHARS = 2000;
23
+ // Options that would let a job spec run commands, read other files or move the output elsewhere.
24
+ const FORBIDDEN_ARGS = /^(?:-o|-a|-P|--output|--paths|--exec(?:-before-download)?|--config(?:-location|-locations)?|--plugin-dirs|--batch-file|--cookies|--cookies-from-browser|--load-info-json|--netrc-cmd|--ffmpeg-location|--no-config|--write-.*|--print-to-file)(?:=|$)/;
25
+
26
+ function fail(code, message, details) {
27
+ const err = new Error(message);
28
+ err.code = code;
29
+ if (details !== undefined) err.details = details;
30
+ return err;
31
+ }
32
+
33
+ function parseS3(uri) {
34
+ const m = /^s3:\/\/([^/]+)\/(.+)$/.exec(uri);
35
+ if (!m) throw fail("BAD_SPEC", `not an s3://bucket/key URI: ${uri}`);
36
+ return { bucket: m[1], key: m[2] };
37
+ }
38
+
39
+ function endpoint(list, name) {
40
+ return Array.isArray(list) ? list.find(e => e.name === name) : undefined;
41
+ }
42
+
43
+ export function readPayload(spec) {
44
+ const d = spec.download;
45
+ if (!d || typeof d !== "object" || typeof d.url !== "string") throw fail("BAD_SPEC", "spec.download.url is required");
46
+ let url;
47
+ try { url = new URL(d.url); } catch { throw fail("BAD_SPEC", "spec.download.url is not a URL"); }
48
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw fail("BAD_SPEC", "spec.download.url must be http(s)");
49
+ const extraArgs = d.extraArgs ?? [];
50
+ if (!Array.isArray(extraArgs) || extraArgs.some(a => typeof a !== "string")) throw fail("BAD_SPEC", "spec.download.extraArgs must be an array of strings");
51
+ const bad = extraArgs.find(a => FORBIDDEN_ARGS.test(a));
52
+ if (bad) throw fail("BAD_SPEC", `yt-dlp option not allowed in extraArgs: ${bad.split("=")[0]}`);
53
+ const format = typeof d.format === "string" && d.format ? d.format : DEFAULT_FORMAT;
54
+ return { url: url.href, format, extraArgs };
55
+ }
56
+
57
+ async function stageCookies(input, dest, rt) {
58
+ await mkdir(dirname(dest), { recursive: true });
59
+ const url = new URL(input.uri);
60
+ try {
61
+ if (url.protocol === "s3:") {
62
+ if (!rt.s3) throw fail("UNSUPPORTED_SCHEME", "this runner has no S3 credentials for s3: URIs");
63
+ const { bucket, key } = parseS3(input.uri);
64
+ await rt.s3.getFile(bucket, key, dest, { signal: rt.signal });
65
+ } else if (url.protocol === "file:") {
66
+ await copyFile(fileURLToPath(url), dest);
67
+ } else if (url.protocol === "http:" || url.protocol === "https:") {
68
+ const res = await (rt.fetch ?? globalThis.fetch)(input.uri, { signal: rt.signal });
69
+ if (!res.ok) throw fail("INPUT_FAILED", `HTTP ${res.status}`);
70
+ await writeFile(dest, Buffer.from(await res.arrayBuffer()));
71
+ } else {
72
+ throw fail("UNSUPPORTED_SCHEME", `unsupported scheme ${url.protocol}`);
73
+ }
74
+ } catch (err) {
75
+ if (rt.signal.aborted) throw rt.signal.reason;
76
+ // Only the endpoint name, never the URI (it may carry a signature) or file contents.
77
+ throw fail(err.code ?? "INPUT_FAILED", `could not fetch input "${input.name}": ${err.message}`);
78
+ }
79
+ }
80
+
81
+ async function deliver(output, file, rt, contentType) {
82
+ const url = new URL(output.uri);
83
+ if (url.protocol === "s3:") {
84
+ if (!rt.s3) throw fail("UNSUPPORTED_SCHEME", "this runner has no S3 credentials for s3: URIs");
85
+ const { bucket, key } = parseS3(output.uri);
86
+ await rt.s3.putFile(bucket, key, file, { contentType, signal: rt.signal });
87
+ } else if (url.protocol === "file:") {
88
+ const target = fileURLToPath(url);
89
+ await mkdir(dirname(target), { recursive: true });
90
+ await copyFile(file, target);
91
+ } else if (url.protocol === "http:" || url.protocol === "https:") {
92
+ const body = await readFile(file);
93
+ const res = await (rt.fetch ?? globalThis.fetch)(output.uri, { method: "PUT", headers: { "content-type": contentType ?? "application/octet-stream" }, body, signal: rt.signal });
94
+ if (!res.ok) throw fail("UPLOAD_FAILED", `upload of output "${output.name}" failed: HTTP ${res.status}`);
95
+ } else {
96
+ throw fail("UNSUPPORTED_SCHEME", `unsupported scheme ${url.protocol}`);
97
+ }
98
+ }
99
+
100
+ const sha = buf => createHash("sha256").update(buf).digest("hex");
101
+
102
+ /** Removes everything that could reveal cookies from yt-dlp's output before it goes into an error. */
103
+ export function scrub(text, { cookiePath, secrets = [] }) {
104
+ let out = text;
105
+ if (cookiePath) out = out.split(cookiePath).join("<cookies>");
106
+ for (const s of secrets) out = out.split(s).join("[redacted]");
107
+ return out
108
+ .split("\n")
109
+ .filter(line => (line.match(/\t/g) ?? []).length < 5) // Netscape cookie lines have 6 or 7 tab-separated fields.
110
+ .join("\n");
111
+ }
112
+
113
+ /** Cookie values and names long enough to be worth masking. */
114
+ function cookieSecrets(text) {
115
+ const secrets = new Set();
116
+ for (const line of text.split(/\r?\n/)) {
117
+ const f = line.replace(/^#HttpOnly_/, "").split("\t");
118
+ if (f.length >= 7) for (const v of [f[5], f[6]]) if (v && v.length >= 6) secrets.add(v.trim());
119
+ }
120
+ return [...secrets].sort((a, b) => b.length - a.length);
121
+ }
122
+
123
+ const PROGRESS_RE = /\[download\]\s+(\d+(?:\.\d+)?)%/;
124
+
125
+ function runYtDlp(command, args, rt, onLine) {
126
+ return new Promise((resolve, reject) => {
127
+ let child;
128
+ try {
129
+ child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], env: process.env });
130
+ } catch (err) {
131
+ reject(fail("YTDLP_SPAWN", `could not start yt-dlp: ${err.message}`));
132
+ return;
133
+ }
134
+ let stderr = "";
135
+ let buffered = "";
136
+ let killTimer;
137
+ const kill = () => {
138
+ child.kill("SIGTERM");
139
+ killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
140
+ killTimer.unref?.();
141
+ };
142
+ const onAbort = () => kill();
143
+ if (rt.signal.aborted) kill();
144
+ else rt.signal.addEventListener("abort", onAbort, { once: true });
145
+ child.stdout.on("data", chunk => {
146
+ buffered += chunk.toString();
147
+ const lines = buffered.split(/\r?\n|\r/);
148
+ buffered = lines.pop() ?? "";
149
+ for (const line of lines) onLine(line);
150
+ });
151
+ child.stderr.on("data", chunk => { stderr = (stderr + chunk.toString()).slice(-16 * 1024); });
152
+ child.on("error", err => {
153
+ clearTimeout(killTimer);
154
+ rt.signal.removeEventListener("abort", onAbort);
155
+ reject(fail("YTDLP_SPAWN", `could not start yt-dlp: ${err.code === "ENOENT" ? "yt-dlp is not installed on this worker" : err.message}`));
156
+ });
157
+ child.on("close", (code, signal) => {
158
+ clearTimeout(killTimer);
159
+ rt.signal.removeEventListener("abort", onAbort);
160
+ if (buffered) onLine(buffered);
161
+ resolve({ code, signal, stderr });
162
+ });
163
+ });
164
+ }
165
+
166
+ export async function runDownload(spec, rt) {
167
+ const { url, format, extraArgs } = readPayload(spec);
168
+ const videoOut = endpoint(spec.outputs, "video");
169
+ if (!videoOut) throw fail("BAD_SPEC", 'output "video" is required');
170
+ const cookiesIn = endpoint(spec.inputs, "cookies");
171
+ const cookiesOut = endpoint(spec.outputs, "cookies-out");
172
+
173
+ const videoPath = join(rt.workDir, "out", "video.mp4");
174
+ await mkdir(dirname(videoPath), { recursive: true });
175
+
176
+ let cookiePath;
177
+ let cookieHash;
178
+ let secrets = [];
179
+ if (cookiesIn) {
180
+ rt.setState("staging");
181
+ cookiePath = join(rt.workDir, "cookies", "cookies.txt");
182
+ await stageCookies(cookiesIn, cookiePath, rt);
183
+ const bytes = await readFile(cookiePath);
184
+ cookieHash = sha(bytes);
185
+ secrets = cookieSecrets(bytes.toString("utf8"));
186
+ }
187
+ rt.signal.throwIfAborted();
188
+
189
+ const args = [
190
+ "--no-playlist", "--format", format, "--merge-output-format", "mp4", "--newline", "--progress", "--no-colors",
191
+ ...(cookiePath ? ["--cookies", cookiePath] : []),
192
+ ...extraArgs,
193
+ "--output", videoPath,
194
+ "--", url,
195
+ ];
196
+ rt.setState("running");
197
+ const { code, signal, stderr } = await runYtDlp(process.env.YTDLP_PATH || "yt-dlp", args, rt, line => {
198
+ const m = PROGRESS_RE.exec(line);
199
+ if (m) rt.progress({ pct: Math.max(0, Math.min(100, Number(m[1]))), outTimeMs: null, speed: null, fps: null, frame: null });
200
+ });
201
+
202
+ if (rt.signal.aborted) throw rt.signal.reason ?? fail("CANCELLED", "cancelled");
203
+ if (code !== 0) {
204
+ const tail = scrub(stderr, { cookiePath, secrets }).trim().slice(-TAIL_CHARS);
205
+ const how = code === null ? `was killed by ${signal}` : `exited with code ${code}`;
206
+ throw fail("YTDLP_EXIT", `yt-dlp ${how}${tail ? `: ${tail}` : ""}`, { exitCode: code });
207
+ }
208
+
209
+ let size;
210
+ try { size = (await stat(videoPath)).size; } catch { size = 0; }
211
+ if (!size) throw fail("OUTPUT_MISSING", "yt-dlp finished but wrote no video file");
212
+
213
+ rt.setState("uploading");
214
+ const results = [];
215
+ await deliver(videoOut, videoPath, rt, "video/mp4");
216
+ results.push({ name: "video", uri: videoOut.uri, bytes: size });
217
+
218
+ if (cookiesOut && cookiePath) {
219
+ let after;
220
+ try { after = await readFile(cookiePath); } catch { after = null; }
221
+ // Upload only a changed file: an unchanged one means nothing to write back.
222
+ if (after && sha(after) !== cookieHash) {
223
+ await deliver(cookiesOut, cookiePath, rt, "text/plain");
224
+ results.push({ name: "cookies-out", uri: cookiesOut.uri, bytes: after.length });
225
+ }
226
+ }
227
+ return { exitCode: 0, outputs: results, stderrTail: null };
228
+ }
229
+
230
+ export default { type: "download", run: runDownload };