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/metrics.js ADDED
@@ -0,0 +1,227 @@
1
+ // Prometheus metrics in the text exposition format (0.0.4). No dependencies.
2
+
3
+ import { readFile, statfs } from 'node:fs/promises';
4
+ import { cpus, freemem, loadavg, totalmem } from 'node:os';
5
+
6
+ export const METRICS_CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
7
+ const DURATION_BUCKETS = [0.1, 0.5, 1, 5, 15, 60, 300, 900, 3600, 14400];
8
+
9
+ const escapeLabel = v => String(v).replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"');
10
+ const formatValue = v => (Number.isNaN(v) ? 'NaN' : v === Infinity ? '+Inf' : v === -Infinity ? '-Inf' : String(v));
11
+
12
+ function labelString(names, values, extra = '') {
13
+ const parts = names.map((n, i) => `${n}="${escapeLabel(values[i] ?? '')}"`);
14
+ if (extra) parts.push(extra);
15
+ return parts.length ? `{${parts.join(',')}}` : '';
16
+ }
17
+
18
+ class Metric {
19
+ constructor(type, name, help, labelNames = []) {
20
+ this.type = type;
21
+ this.name = name;
22
+ this.help = help;
23
+ this.labelNames = labelNames;
24
+ /** @type {Map<string, { values: string[], value: any }>} */
25
+ this.series = new Map();
26
+ }
27
+
28
+ slot(labels = {}) {
29
+ const values = this.labelNames.map(n => String(labels[n] ?? ''));
30
+ const key = values.join('\u0000');
31
+ let s = this.series.get(key);
32
+ if (!s) {
33
+ s = { values, value: this.initial() };
34
+ this.series.set(key, s);
35
+ }
36
+ return s;
37
+ }
38
+
39
+ initial() {
40
+ return 0;
41
+ }
42
+
43
+ /** Drops every series (gauges that are rebuilt on each scrape). */
44
+ reset() {
45
+ this.series.clear();
46
+ }
47
+
48
+ render() {
49
+ const lines = [`# HELP ${this.name} ${this.help}`, `# TYPE ${this.name} ${this.type}`];
50
+ for (const s of this.series.values()) lines.push(...this.renderSeries(s));
51
+ return lines.join('\n');
52
+ }
53
+
54
+ renderSeries(s) {
55
+ return [`${this.name}${labelString(this.labelNames, s.values)} ${formatValue(s.value)}`];
56
+ }
57
+ }
58
+
59
+ class Counter extends Metric {
60
+ inc(labels, n = 1) {
61
+ this.slot(labels).value += n;
62
+ }
63
+ }
64
+
65
+ class Gauge extends Metric {
66
+ set(labels, v) {
67
+ this.slot(labels).value = v;
68
+ }
69
+
70
+ inc(labels, n = 1) {
71
+ this.slot(labels).value += n;
72
+ }
73
+ }
74
+
75
+ class Histogram extends Metric {
76
+ constructor(name, help, labelNames, buckets = DURATION_BUCKETS) {
77
+ super('histogram', name, help, labelNames);
78
+ this.buckets = [...buckets].sort((a, b) => a - b);
79
+ }
80
+
81
+ initial() {
82
+ return { counts: new Array(this.buckets.length).fill(0), sum: 0, count: 0 };
83
+ }
84
+
85
+ observe(labels, v) {
86
+ const h = this.slot(labels).value;
87
+ for (let i = 0; i < this.buckets.length; i++) if (v <= this.buckets[i]) h.counts[i]++;
88
+ h.sum += v;
89
+ h.count++;
90
+ }
91
+
92
+ renderSeries(s) {
93
+ const h = s.value;
94
+ const lines = this.buckets.map((b, i) => `${this.name}_bucket${labelString(this.labelNames, s.values, `le="${b}"`)} ${h.counts[i]}`);
95
+ lines.push(`${this.name}_bucket${labelString(this.labelNames, s.values, 'le="+Inf"')} ${h.count}`);
96
+ lines.push(`${this.name}_sum${labelString(this.labelNames, s.values)} ${h.sum}`);
97
+ lines.push(`${this.name}_count${labelString(this.labelNames, s.values)} ${h.count}`);
98
+ return lines;
99
+ }
100
+ }
101
+
102
+ /** A set of metrics plus collectors that refresh gauges right before each scrape. */
103
+ export class Registry {
104
+ constructor() {
105
+ /** @type {Metric[]} */
106
+ this.metrics = [];
107
+ /** @type {(() => void | Promise<void>)[]} */
108
+ this.collectors = [];
109
+ }
110
+
111
+ counter(name, help, labelNames) {
112
+ return this.add(new Counter('counter', name, help, labelNames));
113
+ }
114
+
115
+ gauge(name, help, labelNames) {
116
+ return this.add(new Gauge('gauge', name, help, labelNames));
117
+ }
118
+
119
+ histogram(name, help, labelNames, buckets) {
120
+ return this.add(new Histogram(name, help, labelNames, buckets));
121
+ }
122
+
123
+ add(metric) {
124
+ this.metrics.push(metric);
125
+ return metric;
126
+ }
127
+
128
+ collect(fn) {
129
+ this.collectors.push(fn);
130
+ }
131
+
132
+ async render() {
133
+ for (const fn of this.collectors) await fn();
134
+ return `${this.metrics.map(m => m.render()).join('\n')}\n`;
135
+ }
136
+ }
137
+
138
+ const seconds = (from, to) => (Date.parse(to) - Date.parse(from)) / 1000;
139
+
140
+ /**
141
+ * Job metrics shared by the orchestrator and the worker. Call `track(record)` once per new job.
142
+ * @param {Registry} registry
143
+ * @param {() => Iterable<import('./job-record.js').JobRecord>} records The jobs currently known.
144
+ */
145
+ export function jobMetrics(registry, records) {
146
+ const submitted = registry.counter('fffleet_jobs_submitted_total', 'Jobs accepted.', ['owner', 'class', 'kind']);
147
+ const finished = registry.counter('fffleet_jobs_finished_total', 'Jobs that ended, by final state and error code.', ['owner', 'class', 'kind', 'state', 'code']);
148
+ const wait = registry.histogram('fffleet_job_wait_seconds', 'Time from submit until ffmpeg started.', ['class']);
149
+ const duration = registry.histogram('fffleet_job_run_seconds', 'Time from start until the job ended.', ['class', 'kind', 'state']);
150
+ const current = registry.gauge('fffleet_jobs', 'Unfinished jobs by state.', ['owner', 'class', 'state']);
151
+ registry.collect(() => {
152
+ current.reset();
153
+ for (const r of records()) if (!r.final) current.inc({ owner: r.spec.owner, class: r.spec.class, state: r.state });
154
+ });
155
+ return {
156
+ track(record) {
157
+ const { owner, kind } = record.spec;
158
+ const cls = record.spec.class;
159
+ submitted.inc({ owner, class: cls, kind });
160
+ let started = false;
161
+ record.subscribe(record.seq, e => {
162
+ if (e.state === 'running' && !started && record.startedAt) {
163
+ started = true;
164
+ wait.observe({ class: cls }, seconds(record.createdAt, record.startedAt));
165
+ }
166
+ if (['succeeded', 'failed', 'cancelled'].includes(e.state)) {
167
+ finished.inc({ owner, class: cls, kind, state: e.state, code: e.error?.code ?? '' });
168
+ if (record.startedAt) duration.observe({ class: cls, kind, state: e.state }, seconds(record.startedAt, record.finishedAt));
169
+ }
170
+ });
171
+ },
172
+ };
173
+ }
174
+
175
+ /** process_* metrics of this Node process. */
176
+ export function processMetrics(registry) {
177
+ const cpu = registry.gauge('process_cpu_seconds_total', 'User and system CPU time of this process.');
178
+ const rss = registry.gauge('process_resident_memory_bytes', 'Resident memory of this process.');
179
+ const start = registry.gauge('process_start_time_seconds', 'Start time of this process since the Unix epoch.');
180
+ const startedAt = Date.now() / 1000 - process.uptime();
181
+ cpu.type = 'counter';
182
+ registry.collect(() => {
183
+ const u = process.cpuUsage();
184
+ cpu.set({}, (u.user + u.system) / 1e6);
185
+ rss.set({}, process.memoryUsage.rss());
186
+ start.set({}, Math.round(startedAt));
187
+ });
188
+ }
189
+
190
+ /** Host metrics a worker reports: CPUs, load, memory and free space under `dir`. */
191
+ export function hostMetrics(registry, dir) {
192
+ const ncpu = registry.gauge('fffleet_host_cpus', 'CPUs on this host.');
193
+ const load = registry.gauge('fffleet_host_load1', 'One-minute load average.');
194
+ const memTotal = registry.gauge('fffleet_host_memory_total_bytes', 'Memory on this host.');
195
+ const memFree = registry.gauge('fffleet_host_memory_available_bytes', 'Memory available on this host.');
196
+ const disk = registry.gauge('fffleet_workdir_free_bytes', 'Free space in the work directory.');
197
+ registry.collect(async () => {
198
+ ncpu.set({}, cpus().length);
199
+ load.set({}, loadavg()[0]);
200
+ memTotal.set({}, totalmem());
201
+ memFree.set({}, freemem());
202
+ disk.reset();
203
+ if (dir) {
204
+ try {
205
+ const s = await statfs(dir);
206
+ disk.set({}, s.bavail * s.bsize);
207
+ } catch {
208
+ // The work directory may not exist until the first job.
209
+ }
210
+ }
211
+ });
212
+ }
213
+
214
+ const CLK_TCK = 100;
215
+ const PAGE_SIZE = 4096;
216
+
217
+ /** CPU seconds and resident bytes of a process, from /proc (Linux only; null elsewhere). */
218
+ export async function procStats(pid) {
219
+ try {
220
+ const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
221
+ // Fields after the parenthesised command name; utime and stime are fields 14 and 15, rss is 24.
222
+ const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
223
+ return { cpuSeconds: (Number(f[11]) + Number(f[12])) / CLK_TCK, rssBytes: Number(f[21]) * PAGE_SIZE };
224
+ } catch {
225
+ return null;
226
+ }
227
+ }
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,7 @@
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 { Registry, jobMetrics, processMetrics, hostMetrics, procStats, METRICS_CONTENT_TYPE } from './metrics.js';
4
+ export {
5
+ SCOPES, hashSecret, verifySecret, generateSecret, loadSigningKey, createTokenSigner, createTokenVerifier,
6
+ createRemoteKeySet, createAuthenticator, createClientStore, issueToken, principal, bearerOf, OPEN,
7
+ } 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', ...headers, ...(lastSeq ? { 'last-event-id': String(lastSeq) } : {}) },
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) {