fffleet-orchestrator 2.0.0 → 2.1.1

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
@@ -21,10 +21,19 @@ docker run -p 5000:5000 -e FFFLEET_TOKEN=... -e FFFLEET_WORKER_TOKEN=... ghcr.io
21
21
  | `FFFLEET_WORKER_TOKEN` | | Token workers register with. The orchestrator also sends it when it calls workers. |
22
22
  | `FFFLEET_HEARTBEAT_TIMEOUT_MS` | `15000` | |
23
23
  | `FFFLEET_MAX_QUEUED` | `1000` | Above this, submissions get 503. |
24
+ | `FFFLEET_STATE_FILE` | | SQLite file that keeps jobs across restarts (needs Node 22.13 or later; the Docker image has it). Without it a restart forgets the queue. |
25
+ | `FFFLEET_ADOPT_GRACE_MS` | `30000` | After a restart, how long a running job waits for its worker to report it before it fails with `ORCHESTRATOR_RESTARTED`. |
24
26
  | `FFFLEET_CONFIG` | | YAML or JSON file with autoscaling pools (also `--config <file>`). See the [main README](https://github.com/jsilvanus/fffleet#autoscaling). |
25
27
 
26
28
  Extra routes: `GET /v1/pools` lists the autoscaling pools. `GET /v1/workers` lists the pool. `POST /v1/workers/:id/drain` stops new work going to a worker, for example before you shut it down (both need `admin`). `GET /metrics` is the fleet view for Prometheus, and `GET /v1/sd/prometheus` lists the workers as scrape targets. Logins, scopes and per-app job ownership are described in the [main README](https://github.com/jsilvanus/fffleet#logins-many-apps-one-orchestrator). With neither `FFFLEET_TOKEN` nor a clients file the API is open, and the orchestrator says so at startup.
27
29
 
28
- State is kept in memory: a restart forgets the queue.
30
+ **Restarts.** Without `FFFLEET_STATE_FILE` the orchestrator keeps jobs in memory and a restart forgets them (workers keep running theirs). With it, jobs are saved as they change and come back after a restart:
31
+
32
+ - queued jobs go back in the queue, in the same order;
33
+ - running batch jobs are picked up again when their worker reports them in its next heartbeat; if it does not within `FFFLEET_ADOPT_GRACE_MS` (or finished while the orchestrator was down), the job fails with `ORCHESTRATOR_RESTARTED` and the client decides whether to submit it again (outputs may be half written, so jobs are not rerun for you);
34
+ - stream jobs fail with `ORCHESTRATOR_RESTARTED`, because the client's connection to them is gone;
35
+ - finished jobs stay available for status and idempotency, up to the newest 1000.
36
+
37
+ Keep the file on a volume that survives the container. Use one orchestrator per state file.
29
38
 
30
39
  License: EUPL-1.2
@@ -34,6 +34,8 @@ const orchestrator = createOrchestrator({
34
34
  workerToken: env.FFFLEET_WORKER_TOKEN || null,
35
35
  heartbeatTimeoutMs: Number(env.FFFLEET_HEARTBEAT_TIMEOUT_MS ?? 15000),
36
36
  maxQueued: Number(env.FFFLEET_MAX_QUEUED ?? 1000),
37
+ stateFile: env.FFFLEET_STATE_FILE || null,
38
+ adoptGraceMs: Number(env.FFFLEET_ADOPT_GRACE_MS ?? 30000),
37
39
  log,
38
40
  });
39
41
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet-orchestrator",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "fffleet orchestrator: schedules ffmpeg jobs across a pool of fffleet workers",
5
5
  "type": "module",
6
6
  "main": "./src/orchestrator.js",
@@ -21,7 +21,7 @@
21
21
  "test": "node --test test/*.test.js"
22
22
  },
23
23
  "dependencies": {
24
- "fffleet": "^2.0.0"
24
+ "fffleet": "^2.1.1"
25
25
  },
26
26
  "keywords": [
27
27
  "ffmpeg",
@@ -44,13 +44,5 @@
44
44
  },
45
45
  "publishConfig": {
46
46
  "access": "public"
47
- },
48
- "peerDependencies": {
49
- "fffleet-worker": "^2.0.0"
50
- },
51
- "peerDependenciesMeta": {
52
- "fffleet-worker": {
53
- "optional": true
54
- }
55
47
  }
56
48
  }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Where the orchestrator keeps its jobs between restarts. A store needs four methods:
3
+ *
4
+ * save(job) write or replace one job (JobRecord)
5
+ * loadAll() every saved job, oldest first, as `{ spec, state, history, ... }`
6
+ * prune(keep) forget the oldest finished jobs beyond `keep`
7
+ * close()
8
+ *
9
+ * The built-in one is a SQLite file through `node:sqlite`, loaded only when asked for (Node 22.13 or later).
10
+ */
11
+
12
+ const FIELDS = ['state', 'workerId', 'createdAt', 'startedAt', 'finishedAt', 'progress', 'exitCode', 'error', 'outputs', 'stderrTail', 'seq', 'order', 'history'];
13
+ const SCHEMA_VERSION = 1;
14
+
15
+ /** @param {string} file */
16
+ export async function openSqliteJobStore(file) {
17
+ let DatabaseSync;
18
+ try {
19
+ ({ DatabaseSync } = await import('node:sqlite'));
20
+ } catch (err) {
21
+ throw new Error(`a state file needs node:sqlite (Node 22.13 or later): ${err.message}`);
22
+ }
23
+ const db = new DatabaseSync(file);
24
+ db.exec('PRAGMA journal_mode = WAL');
25
+ db.exec('PRAGMA synchronous = NORMAL');
26
+ const version = db.prepare('PRAGMA user_version').get().user_version;
27
+ if (version > SCHEMA_VERSION) {
28
+ db.close();
29
+ throw new Error(`state file ${file} was written by a newer fffleet (schema ${version}, this one knows ${SCHEMA_VERSION})`);
30
+ }
31
+ db.exec('CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, ord INTEGER NOT NULL, final INTEGER NOT NULL, data TEXT NOT NULL)');
32
+ db.exec('CREATE INDEX IF NOT EXISTS jobs_final_ord ON jobs (final, ord)');
33
+ db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
34
+
35
+ const upsert = db.prepare(
36
+ 'INSERT INTO jobs (id, ord, final, data) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET final = excluded.final, data = excluded.data',
37
+ );
38
+ const all = db.prepare('SELECT data FROM jobs ORDER BY ord');
39
+ const prune = db.prepare('DELETE FROM jobs WHERE final = 1 AND ord <= (SELECT ord FROM jobs WHERE final = 1 ORDER BY ord DESC LIMIT 1 OFFSET ?)');
40
+
41
+ return {
42
+ save(job) {
43
+ const data = { spec: job.spec };
44
+ for (const key of FIELDS) data[key] = job[key];
45
+ upsert.run(job.id, job.order, job.final ? 1 : 0, JSON.stringify(data));
46
+ },
47
+ loadAll() {
48
+ const out = [];
49
+ for (const row of all.all()) {
50
+ try {
51
+ out.push(JSON.parse(row.data));
52
+ } catch {
53
+ // A damaged row is skipped; the rest of the jobs still come back.
54
+ }
55
+ }
56
+ return out;
57
+ },
58
+ prune(keep) {
59
+ prune.run(Math.max(0, keep));
60
+ },
61
+ close() {
62
+ db.close();
63
+ },
64
+ };
65
+ }
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { createAutoscaler } from './autoscaler.js';
3
3
  import { createProviders } from './providers/index.js';
4
+ import { openSqliteJobStore } from './job-store.js';
4
5
  import { randomUUID } from 'node:crypto';
5
6
  import { FleetError, JobRecord, byPriority, canonicalJson, followJobEvents, implicitRequirements, normalizeKinds, normalizeSlots, parseSpec, pruneFinished, satisfies } from 'fffleet';
6
7
  import {
@@ -16,7 +17,10 @@ const REDISPATCH_DELAY_MS = 500;
16
17
  * to a worker with a free slot in the job's class and the capabilities it requires, relays the
17
18
  * worker's events, and fails jobs whose worker stops sending heartbeats.
18
19
  *
19
- * State is in memory: a restart forgets queued and running jobs (workers keep running theirs).
20
+ * Jobs are kept in memory. With `stateFile` (or a `store`) they are also saved, and a restart brings them back:
21
+ * queued jobs go back in the queue, running batch jobs are picked up again when their worker reports them
22
+ * (or fail with ORCHESTRATOR_RESTARTED after `adoptGraceMs`), and stream jobs fail, since the client's
23
+ * connection to them is gone.
20
24
  *
21
25
  * @param {object} [opts]
22
26
  * @param {number} [opts.port]
@@ -35,6 +39,9 @@ const REDISPATCH_DELAY_MS = 500;
35
39
  * @param {number} [opts.maxQueued]
36
40
  * @param {number} [opts.keepFinished] Finished jobs remembered for status and idempotency.
37
41
  * @param {number} [opts.lostJobGraceMs] How long a dispatched job may be missing from a heartbeat.
42
+ * @param {string | null} [opts.stateFile] SQLite file to save jobs in (needs Node 22.13+). Without it a restart forgets the jobs.
43
+ * @param {{ save(job: JobRecord): void, loadAll(): object[], prune(keep: number): void, close(): void } | null} [opts.store] A job store of your own, instead of `stateFile`.
44
+ * @param {number} [opts.adoptGraceMs] After a restart, how long a running job waits for its worker to report it.
38
45
  * @param {number} [opts.dispatchCooldownMs] How long a worker that answered a dispatch with 5xx gets no new jobs.
39
46
  * @param {(msg: string) => void} [opts.log]
40
47
  */
@@ -56,6 +63,9 @@ export function createOrchestrator({
56
63
  keepFinished = 1000,
57
64
  lostJobGraceMs = 10000,
58
65
  dispatchCooldownMs = 5000,
66
+ stateFile = null,
67
+ store = null,
68
+ adoptGraceMs = 30000,
59
69
  log = () => {},
60
70
  } = {}) {
61
71
  /** @type {Map<string, Worker>} */
@@ -64,6 +74,10 @@ export function createOrchestrator({
64
74
  const jobs = new Map();
65
75
  /** @type {Job[]} */
66
76
  const queue = [];
77
+ /** Jobs restored as running, waiting for their worker to report them. */
78
+ const adopting = new Map();
79
+ let jobStore = store;
80
+ const lastSaved = new WeakMap();
67
81
  let server = null;
68
82
  let url = null;
69
83
  let sweeper = null;
@@ -173,6 +187,67 @@ export function createOrchestrator({
173
187
  pumpTimer.unref?.();
174
188
  }
175
189
 
190
+ function persist(job, event = null) {
191
+ if (!jobStore) return;
192
+ // Progress arrives every second or so per job; the state changes are what a restart needs.
193
+ const now = Date.now();
194
+ if (event && !job.final && event.progress && event.state === lastSaved.get(job)?.state && now - (lastSaved.get(job)?.at ?? 0) < 1000) return;
195
+ try {
196
+ jobStore.save(job);
197
+ lastSaved.set(job, { state: job.state, at: now });
198
+ } catch (err) {
199
+ log(`could not save job ${job.id}: ${err.message}`);
200
+ }
201
+ }
202
+
203
+ function track(job) {
204
+ job.emitter.on('event', e => persist(job, e));
205
+ persist(job);
206
+ }
207
+
208
+ function restore() {
209
+ const now = Date.now();
210
+ let queued = 0;
211
+ let running = 0;
212
+ let finished = 0;
213
+ for (const saved of jobStore.loadAll()) {
214
+ if (!saved?.spec?.id || jobs.has(saved.spec.id)) continue;
215
+ const job = /** @type {Job} */ (JobRecord.restore(saved.spec, saved));
216
+ jobs.set(job.id, job);
217
+ if (job.final) {
218
+ finished++;
219
+ track(job);
220
+ continue;
221
+ }
222
+ jobStats.track(job);
223
+ track(job);
224
+ if (job.state === 'queued') {
225
+ enqueue(job);
226
+ queued++;
227
+ } else if (job.spec.kind === 'stream') {
228
+ job.push({ state: 'failed', error: { code: 'ORCHESTRATOR_RESTARTED', message: 'the orchestrator restarted; a stream job cannot be picked up again' } });
229
+ } else {
230
+ adopting.set(job.id, { job, deadline: now + adoptGraceMs });
231
+ running++;
232
+ }
233
+ }
234
+ log(`restored ${queued} queued, ${running} running and ${finished} finished jobs from the state file`);
235
+ }
236
+
237
+ /** A restored job whose worker reported it again: attach to it like a fresh dispatch that already succeeded. */
238
+ function adopt(job, worker) {
239
+ const pool = poolFor(worker, job.spec.class);
240
+ worker.used[pool] = (worker.used[pool] ?? 0) + 1;
241
+ worker.jobs.add(job.id);
242
+ job.worker = worker;
243
+ job.pool = pool;
244
+ job.released = false;
245
+ job.assignedAt = Date.now();
246
+ log(`job ${job.id} picked up again on worker ${worker.id}`);
247
+ follow(job, worker);
248
+ if (job.cancelWanted) backend.cancel(job.id);
249
+ }
250
+
176
251
  function enqueue(job) {
177
252
  queue.push(job);
178
253
  queue.sort(byPriority);
@@ -241,6 +316,7 @@ export function createOrchestrator({
241
316
  state: e.state === 'queued' ? job.state : e.state,
242
317
  workerId: worker.id,
243
318
  ...(e.progress ? { progress: e.progress } : {}),
319
+ ...(e.stderrTail && !['succeeded', 'failed', 'cancelled'].includes(e.state) ? { stderrTail: e.stderrTail } : {}),
244
320
  ...(['succeeded', 'failed', 'cancelled'].includes(e.state)
245
321
  ? { exitCode: e.exitCode ?? null, error: e.error, outputs: e.outputs ?? [], stderrTail: e.stderrTail ?? null }
246
322
  : {}),
@@ -318,12 +394,28 @@ export function createOrchestrator({
318
394
  release(job, false);
319
395
  }
320
396
  }
397
+ if (adopting.size && Array.isArray(body.active)) {
398
+ for (const id of body.active) {
399
+ const entry = adopting.get(id);
400
+ if (!entry || entry.job.workerId !== worker.id) continue;
401
+ adopting.delete(id);
402
+ adopt(entry.job, worker);
403
+ }
404
+ }
321
405
  schedulePump();
322
406
  return { ok: true, heartbeatTimeoutMs };
323
407
  }
324
408
 
325
409
  function sweep() {
326
410
  const now = Date.now();
411
+ for (const [id, entry] of adopting) {
412
+ if (now < entry.deadline) continue;
413
+ adopting.delete(id);
414
+ const { job } = entry;
415
+ job.push(job.cancelWanted
416
+ ? { state: 'cancelled', error: { code: 'CANCELLED', message: 'cancelled (the orchestrator restarted and the worker did not report the job)' } }
417
+ : { state: 'failed', error: { code: 'ORCHESTRATOR_RESTARTED', message: `the orchestrator restarted and worker ${job.workerId ?? '?'} did not report the job within ${adoptGraceMs} ms` } });
418
+ }
327
419
  for (const worker of [...workers.values()]) {
328
420
  if (now - worker.lastSeen > heartbeatTimeoutMs) {
329
421
  m.workersLost.inc();
@@ -346,9 +438,11 @@ export function createOrchestrator({
346
438
  }
347
439
  if (queue.length >= maxQueued) throw new FleetError('QUEUE_FULL', 'queue is full', { status: 503 });
348
440
  pruneFinished(jobs, keepFinished);
441
+ jobStore?.prune(keepFinished);
349
442
  const job = /** @type {Job} */ (new JobRecord(spec));
350
443
  jobs.set(spec.id, job);
351
444
  jobStats.track(job);
445
+ track(job);
352
446
  enqueue(job);
353
447
  pump();
354
448
  return { created: true, queued: queue.includes(job), job: job.snapshot() };
@@ -370,6 +464,11 @@ export function createOrchestrator({
370
464
  job.push({ state: 'cancelled', error: { code: 'CANCELLED', message: 'cancelled before it started' } });
371
465
  return job.snapshot();
372
466
  }
467
+ if (adopting.has(id) && !job.worker) {
468
+ // Restored as running but its worker has not reported yet: cancel it when it does.
469
+ job.cancelWanted = true;
470
+ return job.snapshot();
471
+ }
373
472
  const worker = job.worker;
374
473
  try {
375
474
  const res = await fetch(`${worker.url}/v1/jobs/${encodeURIComponent(id)}`, { method: 'DELETE', headers: workerHeaders(worker), signal: AbortSignal.timeout(5000) });
@@ -519,6 +618,8 @@ export function createOrchestrator({
519
618
  return url;
520
619
  },
521
620
  async start() {
621
+ if (!jobStore && stateFile) jobStore = await openSqliteJobStore(stateFile);
622
+ if (jobStore) restore();
522
623
  ({ server, url } = await listen(createApiHandler({ backend, authenticate, metrics: () => registry.render(), extraRoutes }), { port, host }));
523
624
  if (!token && !clientStore) log('no FFFLEET_TOKEN and no clients file: the job API is open to anyone who can reach it');
524
625
  sweeper = setInterval(sweep, sweepMs);
@@ -557,6 +658,7 @@ export function createOrchestrator({
557
658
  clearTimeout(pumpTimer);
558
659
  for (const job of jobs.values()) job.follow?.abort();
559
660
  if (server) await close(server);
661
+ jobStore?.close();
560
662
  },
561
663
  };
562
664
  }