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/s3.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// A small S3 client (AWS Signature Version 4) for staging job inputs and outputs.
|
|
2
|
+
// Works with AWS S3 and S3-compatible stores (MinIO, Ceph, Garage, ...). No dependencies.
|
|
3
|
+
|
|
4
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
5
|
+
import { createWriteStream } from 'node:fs';
|
|
6
|
+
import { open, readdir, stat } from 'node:fs/promises';
|
|
7
|
+
import { extname, join, relative, sep } from 'node:path';
|
|
8
|
+
import { get as httpGet } from 'node:http';
|
|
9
|
+
import { get as httpsGet } from 'node:https';
|
|
10
|
+
import { pipeline } from 'node:stream/promises';
|
|
11
|
+
|
|
12
|
+
const EMPTY_SHA256 = createHash('sha256').update('').digest('hex');
|
|
13
|
+
const UNSIGNED = 'UNSIGNED-PAYLOAD';
|
|
14
|
+
/** Files at or above this size are uploaded in parts. */
|
|
15
|
+
export const MULTIPART_THRESHOLD = 16 * 1024 * 1024;
|
|
16
|
+
const PART_SIZE = 16 * 1024 * 1024;
|
|
17
|
+
|
|
18
|
+
const CONTENT_TYPES = {
|
|
19
|
+
'.m3u8': 'application/vnd.apple.mpegurl',
|
|
20
|
+
'.mpd': 'application/dash+xml',
|
|
21
|
+
'.ts': 'video/mp2t',
|
|
22
|
+
'.m4s': 'video/iso.segment',
|
|
23
|
+
'.mp4': 'video/mp4',
|
|
24
|
+
'.m4a': 'audio/mp4',
|
|
25
|
+
'.mov': 'video/quicktime',
|
|
26
|
+
'.webm': 'video/webm',
|
|
27
|
+
'.mkv': 'video/x-matroska',
|
|
28
|
+
'.mp3': 'audio/mpeg',
|
|
29
|
+
'.aac': 'audio/aac',
|
|
30
|
+
'.wav': 'audio/wav',
|
|
31
|
+
'.ogg': 'audio/ogg',
|
|
32
|
+
'.opus': 'audio/ogg',
|
|
33
|
+
'.flac': 'audio/flac',
|
|
34
|
+
'.jpg': 'image/jpeg',
|
|
35
|
+
'.jpeg': 'image/jpeg',
|
|
36
|
+
'.png': 'image/png',
|
|
37
|
+
'.webp': 'image/webp',
|
|
38
|
+
'.gif': 'image/gif',
|
|
39
|
+
'.vtt': 'text/vtt',
|
|
40
|
+
'.srt': 'application/x-subrip',
|
|
41
|
+
'.ass': 'text/x-ssa',
|
|
42
|
+
'.json': 'application/json',
|
|
43
|
+
'.txt': 'text/plain',
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** A content type for a file name, by extension. */
|
|
47
|
+
export function contentTypeFor(name) {
|
|
48
|
+
return CONTENT_TYPES[extname(name).toLowerCase()] ?? 'application/octet-stream';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Reads S3 settings from the environment. Returns null when no credentials are set.
|
|
53
|
+
* AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION (or AWS_DEFAULT_REGION),
|
|
54
|
+
* FFFLEET_S3_ENDPOINT (for S3-compatible stores), FFFLEET_S3_PATH_STYLE=1 (MinIO and most others).
|
|
55
|
+
*/
|
|
56
|
+
export function s3ConfigFromEnv(env = process.env) {
|
|
57
|
+
if (!env.AWS_ACCESS_KEY_ID || !env.AWS_SECRET_ACCESS_KEY) return null;
|
|
58
|
+
return {
|
|
59
|
+
accessKeyId: env.AWS_ACCESS_KEY_ID,
|
|
60
|
+
secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
|
|
61
|
+
sessionToken: env.AWS_SESSION_TOKEN || undefined,
|
|
62
|
+
region: env.AWS_REGION || env.AWS_DEFAULT_REGION || 'us-east-1',
|
|
63
|
+
endpoint: env.FFFLEET_S3_ENDPOINT || undefined,
|
|
64
|
+
pathStyle: ['1', 'true', 'yes'].includes(String(env.FFFLEET_S3_PATH_STYLE ?? '').toLowerCase()),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Splits s3://bucket/key into its parts. */
|
|
69
|
+
export function parseS3Uri(uri) {
|
|
70
|
+
const url = new URL(uri);
|
|
71
|
+
return { bucket: url.hostname, key: decodeURIComponent(url.pathname.replace(/^\//, '')) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** RFC 3986 encoding as SigV4 wants it (encodeURIComponent leaves !'()* alone). */
|
|
75
|
+
function rfc3986(s) {
|
|
76
|
+
return encodeURIComponent(s).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const encodeKey = key => key.split('/').map(rfc3986).join('/');
|
|
80
|
+
const sha256 = data => createHash('sha256').update(data).digest('hex');
|
|
81
|
+
const hmac = (key, data) => createHmac('sha256', key).update(data).digest();
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Signs a request with AWS Signature Version 4. Exported for tests against AWS's published examples.
|
|
85
|
+
*
|
|
86
|
+
* @param {object} req
|
|
87
|
+
* @param {string} req.method
|
|
88
|
+
* @param {URL} req.url
|
|
89
|
+
* @param {Record<string, string>} req.headers Must include host and x-amz-date; every header given is signed.
|
|
90
|
+
* @param {string} req.payloadHash
|
|
91
|
+
* @param {{ accessKeyId: string, secretAccessKey: string, region: string }} creds
|
|
92
|
+
* @param {string} [service]
|
|
93
|
+
* @returns {string} the Authorization header value
|
|
94
|
+
*/
|
|
95
|
+
export function signV4({ method, url, headers, payloadHash }, creds, service = 's3') {
|
|
96
|
+
const amzDate = headers['x-amz-date'];
|
|
97
|
+
const date = amzDate.slice(0, 8);
|
|
98
|
+
const names = Object.keys(headers).map(h => h.toLowerCase()).sort();
|
|
99
|
+
const lower = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
|
|
100
|
+
const canonicalHeaders = names.map(n => `${n}:${String(lower[n]).trim().replace(/\s+/g, ' ')}\n`).join('');
|
|
101
|
+
const signedHeaders = names.join(';');
|
|
102
|
+
const query = [...url.searchParams.entries()]
|
|
103
|
+
.map(([k, v]) => [rfc3986(k), rfc3986(v)])
|
|
104
|
+
.sort(([a, av], [b, bv]) => (a < b ? -1 : a > b ? 1 : av < bv ? -1 : av > bv ? 1 : 0))
|
|
105
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
106
|
+
.join('&');
|
|
107
|
+
// url.pathname is already percent-encoded the way we built it.
|
|
108
|
+
const canonicalRequest = [method, url.pathname || '/', query, canonicalHeaders, signedHeaders, payloadHash].join('\n');
|
|
109
|
+
const scope = `${date}/${creds.region}/${service}/aws4_request`;
|
|
110
|
+
const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256(canonicalRequest)].join('\n');
|
|
111
|
+
const kDate = hmac(`AWS4${creds.secretAccessKey}`, date);
|
|
112
|
+
const kSigning = hmac(hmac(hmac(kDate, creds.region), service), 'aws4_request');
|
|
113
|
+
const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex');
|
|
114
|
+
return `AWS4-HMAC-SHA256 Credential=${creds.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* @param {object} config
|
|
119
|
+
* @param {string} config.accessKeyId
|
|
120
|
+
* @param {string} config.secretAccessKey
|
|
121
|
+
* @param {string} [config.sessionToken]
|
|
122
|
+
* @param {string} [config.region]
|
|
123
|
+
* @param {string} [config.endpoint] e.g. http://minio:9000; defaults to AWS for the region.
|
|
124
|
+
* @param {boolean} [config.pathStyle] bucket in the path instead of the host name.
|
|
125
|
+
* @param {typeof fetch} [config.fetch]
|
|
126
|
+
* @param {number} [config.partSize]
|
|
127
|
+
*/
|
|
128
|
+
export function createS3Client(config) {
|
|
129
|
+
const region = config.region ?? 'us-east-1';
|
|
130
|
+
const endpoint = new URL(config.endpoint ?? `https://s3.${region}.amazonaws.com`);
|
|
131
|
+
const pathStyle = config.pathStyle ?? !!config.endpoint;
|
|
132
|
+
const doFetch = config.fetch ?? globalThis.fetch;
|
|
133
|
+
const partSize = config.partSize ?? PART_SIZE;
|
|
134
|
+
const creds = { accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey, region };
|
|
135
|
+
|
|
136
|
+
function urlFor(bucket, key = '', query = {}) {
|
|
137
|
+
const base = endpoint.pathname.replace(/\/+$/, '');
|
|
138
|
+
const url = pathStyle
|
|
139
|
+
? new URL(`${endpoint.protocol}//${endpoint.host}${base}/${rfc3986(bucket)}/${encodeKey(key)}`)
|
|
140
|
+
: new URL(`${endpoint.protocol}//${bucket}.${endpoint.host}${base}/${encodeKey(key)}`);
|
|
141
|
+
for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
|
|
142
|
+
return url;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The URL and signed headers of a request. */
|
|
146
|
+
function sign(method, bucket, key, { query, headers = {} } = {}) {
|
|
147
|
+
const url = urlFor(bucket, key, query);
|
|
148
|
+
const amzDate = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
|
149
|
+
const signed = {
|
|
150
|
+
host: url.host,
|
|
151
|
+
'x-amz-date': amzDate,
|
|
152
|
+
'x-amz-content-sha256': UNSIGNED,
|
|
153
|
+
...(config.sessionToken ? { 'x-amz-security-token': config.sessionToken } : {}),
|
|
154
|
+
};
|
|
155
|
+
const authorization = signV4({ method, url, headers: signed, payloadHash: UNSIGNED }, creds);
|
|
156
|
+
const { host, ...sendHeaders } = signed;
|
|
157
|
+
return { url, headers: { ...sendHeaders, ...headers, authorization } };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function failure(method, bucket, key, status, text) {
|
|
161
|
+
const code = text.match(/<Code>([^<]+)<\/Code>/)?.[1];
|
|
162
|
+
const message = text.match(/<Message>([^<]+)<\/Message>/)?.[1];
|
|
163
|
+
const err = new Error(`S3 ${method} s3://${bucket}/${key} failed: HTTP ${status}${code ? ` ${code}` : ''}${message ? `: ${message}` : ''}`);
|
|
164
|
+
err.status = status;
|
|
165
|
+
err.s3Code = code;
|
|
166
|
+
return err;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function request(method, bucket, key, { query, headers = {}, body, signal } = {}) {
|
|
170
|
+
const { url, headers: signedHeaders } = sign(method, bucket, key, { query, headers });
|
|
171
|
+
const res = await doFetch(url, { method, headers: signedHeaders, body, signal, ...(body ? { duplex: 'half' } : {}) });
|
|
172
|
+
if (!res.ok) throw failure(method, bucket, key, res.status, await res.text().catch(() => ''));
|
|
173
|
+
return res;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Streams an object to a file with node:http(s) rather than fetch: undici (Node 24) can hit an internal
|
|
178
|
+
* assertion when a server closes the connection while a large body is paused by backpressure.
|
|
179
|
+
*/
|
|
180
|
+
function download(bucket, key, path, signal) {
|
|
181
|
+
const { url, headers } = sign('GET', bucket, key);
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
const req = (url.protocol === 'https:' ? httpsGet : httpGet)(url, { headers, signal }, res => {
|
|
184
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
185
|
+
const chunks = [];
|
|
186
|
+
res.on('data', c => chunks.push(c));
|
|
187
|
+
res.once('error', reject);
|
|
188
|
+
res.once('end', () => reject(failure('GET', bucket, key, res.statusCode, Buffer.concat(chunks).toString('utf8').slice(0, 4000))));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
pipeline(res, createWriteStream(path)).then(resolve, reject);
|
|
192
|
+
});
|
|
193
|
+
req.once('error', reject);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Reads and discards a response body: an unread body can trip an assertion in undici (Node 24) when the socket closes. */
|
|
198
|
+
const drain = res => res.arrayBuffer().catch(() => {});
|
|
199
|
+
|
|
200
|
+
async function putFile(bucket, key, path, { contentType, signal, forceMultipart = false } = {}) {
|
|
201
|
+
const size = (await stat(path)).size;
|
|
202
|
+
const type = contentType ?? contentTypeFor(path);
|
|
203
|
+
const fh = await open(path, 'r');
|
|
204
|
+
try {
|
|
205
|
+
if (!forceMultipart && size < Math.max(partSize, MULTIPART_THRESHOLD)) {
|
|
206
|
+
const body = size ? await fh.readFile() : Buffer.alloc(0);
|
|
207
|
+
await drain(await request('PUT', bucket, key, { headers: { 'content-type': type }, body, signal }));
|
|
208
|
+
return size;
|
|
209
|
+
}
|
|
210
|
+
const created = await (await request('POST', bucket, key, { query: { uploads: '' }, headers: { 'content-type': type }, signal })).text();
|
|
211
|
+
const uploadId = created.match(/<UploadId>([^<]+)<\/UploadId>/)?.[1];
|
|
212
|
+
if (!uploadId) throw new Error(`S3 did not return an UploadId for s3://${bucket}/${key}`);
|
|
213
|
+
try {
|
|
214
|
+
const parts = [];
|
|
215
|
+
const buf = Buffer.alloc(partSize);
|
|
216
|
+
for (let offset = 0, n = 1; offset < size; offset += partSize, n++) {
|
|
217
|
+
const { bytesRead } = await fh.read(buf, 0, Math.min(partSize, size - offset), offset);
|
|
218
|
+
const res = await request('PUT', bucket, key, {
|
|
219
|
+
query: { partNumber: String(n), uploadId },
|
|
220
|
+
body: Buffer.from(buf.subarray(0, bytesRead)),
|
|
221
|
+
signal,
|
|
222
|
+
});
|
|
223
|
+
parts.push(`<Part><PartNumber>${n}</PartNumber><ETag>${res.headers.get('etag')}</ETag></Part>`);
|
|
224
|
+
await drain(res);
|
|
225
|
+
}
|
|
226
|
+
const xml = `<CompleteMultipartUpload>${parts.join('')}</CompleteMultipartUpload>`;
|
|
227
|
+
const done = await request('POST', bucket, key, { query: { uploadId }, headers: { 'content-type': 'application/xml' }, body: xml, signal });
|
|
228
|
+
const text = await done.text();
|
|
229
|
+
// S3 can answer 200 with an error document.
|
|
230
|
+
if (/<Error>/.test(text)) throw new Error(`S3 multipart completion failed: ${text.match(/<Message>([^<]+)/)?.[1] ?? text.slice(0, 200)}`);
|
|
231
|
+
} catch (err) {
|
|
232
|
+
await request('DELETE', bucket, key, { query: { uploadId } }).catch(() => {});
|
|
233
|
+
throw err;
|
|
234
|
+
}
|
|
235
|
+
return size;
|
|
236
|
+
} finally {
|
|
237
|
+
await fh.close().catch(() => {});
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
/** Downloads an object to a local file. */
|
|
243
|
+
async getFile(bucket, key, path, { signal } = {}) {
|
|
244
|
+
await download(bucket, key, path, signal);
|
|
245
|
+
},
|
|
246
|
+
|
|
247
|
+
/** Size and ETag of an object, without downloading it. */
|
|
248
|
+
async head(bucket, key, { signal } = {}) {
|
|
249
|
+
const res = await request('HEAD', bucket, key, { signal });
|
|
250
|
+
return { size: Number(res.headers.get('content-length')), etag: res.headers.get('etag') };
|
|
251
|
+
},
|
|
252
|
+
|
|
253
|
+
/** Uploads a local file; large files go up in parts. Returns the size. */
|
|
254
|
+
putFile,
|
|
255
|
+
|
|
256
|
+
/** Uploads every file under `dir` to `prefix` + relative path. Returns the total size. */
|
|
257
|
+
async putDirectory(bucket, prefix, dir, { signal } = {}) {
|
|
258
|
+
let total = 0;
|
|
259
|
+
for (const file of await listFiles(dir)) {
|
|
260
|
+
const rel = relative(dir, file).split(sep).join('/');
|
|
261
|
+
total += await putFile(bucket, `${prefix}${rel}`, file, { signal });
|
|
262
|
+
}
|
|
263
|
+
return total;
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
async deleteObject(bucket, key, { signal } = {}) {
|
|
267
|
+
await request('DELETE', bucket, key, { signal });
|
|
268
|
+
},
|
|
269
|
+
|
|
270
|
+
/** Creates a bucket; succeeds if it already exists and is yours. */
|
|
271
|
+
async createBucket(bucket, { signal } = {}) {
|
|
272
|
+
try {
|
|
273
|
+
await request('PUT', bucket, '', { signal });
|
|
274
|
+
} catch (err) {
|
|
275
|
+
if (err.s3Code !== 'BucketAlreadyOwnedByYou') throw err;
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function listFiles(dir) {
|
|
282
|
+
const out = [];
|
|
283
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
284
|
+
const full = join(dir, entry.name);
|
|
285
|
+
if (entry.isDirectory()) out.push(...(await listFiles(full)));
|
|
286
|
+
else if (entry.isFile()) out.push(full);
|
|
287
|
+
}
|
|
288
|
+
return out.sort();
|
|
289
|
+
}
|
|
290
|
+
|
package/src/server.js
CHANGED
|
@@ -1,2 +1,8 @@
|
|
|
1
1
|
// Building blocks for fffleet-worker and fffleet-orchestrator. Not needed by applications.
|
|
2
|
-
export { createApiHandler, listen, close, checkBearer, send, sendError, readBody, readJson } from './http-api.js';
|
|
2
|
+
export { createApiHandler, allowed, listen, close, checkBearer, send, sendError, readBody, readJson } from './http-api.js';
|
|
3
|
+
export { getStream } from './http-stream.js';
|
|
4
|
+
export { Registry, jobMetrics, processMetrics, hostMetrics, procStats, METRICS_CONTENT_TYPE } from './metrics.js';
|
|
5
|
+
export {
|
|
6
|
+
SCOPES, hashSecret, verifySecret, generateSecret, loadSigningKey, createTokenSigner, createTokenVerifier,
|
|
7
|
+
createRemoteKeySet, createAuthenticator, createClientStore, issueToken, principal, bearerOf, OPEN,
|
|
8
|
+
} from './auth.js';
|
package/src/sse.js
CHANGED
|
@@ -45,7 +45,7 @@ export async function readSse(body, onEvent) {
|
|
|
45
45
|
*
|
|
46
46
|
* @param {object} opts
|
|
47
47
|
* @param {string} opts.url .../v1/jobs/:id/events
|
|
48
|
-
* @param {Record<string, string>} [opts.headers]
|
|
48
|
+
* @param {Record<string, string> | (() => Promise<Record<string, string>> | Record<string, string>)} [opts.headers] A function is called on every (re)connect, so tokens can be refreshed.
|
|
49
49
|
* @param {(event: import('./types.js').JobEvent) => void} opts.onEvent
|
|
50
50
|
* @param {AbortSignal} [opts.signal]
|
|
51
51
|
* @param {number} [opts.maxRetries]
|
|
@@ -60,8 +60,9 @@ export async function followJobEvents({ url, headers = {}, onEvent, signal, maxR
|
|
|
60
60
|
while (!finalEvent) {
|
|
61
61
|
signal?.throwIfAborted();
|
|
62
62
|
try {
|
|
63
|
+
const current = typeof headers === 'function' ? await headers() : headers;
|
|
63
64
|
const res = await f(url, {
|
|
64
|
-
headers: { accept: 'text/event-stream', ...
|
|
65
|
+
headers: { accept: 'text/event-stream', ...current, ...(lastSeq ? { 'last-event-id': String(lastSeq) } : {}) },
|
|
65
66
|
signal,
|
|
66
67
|
});
|
|
67
68
|
if (!res.ok || !res.body) {
|
package/src/types.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
* @property {Record<string, string>} labels
|
|
22
22
|
* @property {number | null} timeoutMs
|
|
23
23
|
* @property {boolean} stdin Keep ffmpeg's stdin open for POST /v1/jobs/:id/stdin.
|
|
24
|
+
* @property {boolean} stdout Hand ffmpeg's stdout (`pipe:1`) to GET /v1/jobs/:id/stdout. Stream jobs only; no `-progress` is reported then.
|
|
24
25
|
* @property {Endpoint[]} inputs
|
|
25
26
|
* @property {Endpoint[]} outputs
|
|
26
27
|
* @property {{ args: string[], durationMs: number | null }} [ffmpeg]
|