fffleet 2.6.0 → 2.8.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/index.d.ts CHANGED
@@ -10,6 +10,7 @@ export const FILE_SCHEMES: readonly string[];
10
10
  export const HTTP_SCHEMES: readonly string[];
11
11
  export const PASSTHROUGH_SCHEMES: readonly string[];
12
12
  export const OBJECT_SCHEMES: readonly string[];
13
+ export const MAX_VARIANTS: 16;
13
14
 
14
15
  export type JobKind = 'stream' | 'batch';
15
16
  export type JobState = 'queued' | 'assigned' | 'staging' | 'running' | 'uploading' | 'succeeded' | 'failed' | 'cancelled';
@@ -38,6 +39,14 @@ export interface JobSpecInput {
38
39
  class?: string;
39
40
  /** -1000..1000, higher runs first. */
40
41
  priority?: number;
42
+ /** Ordered worker IDs. The first eligible worker wins; unlisted workers are excluded. */
43
+ workerPreference?: string[];
44
+ /**
45
+ * Where-dependent versions of this spec (at most 16). After placement the first variant whose `when` fits the
46
+ * chosen worker replaces the base `ffmpeg`, `inputs`, `outputs` and type section and adds its `labels`.
47
+ * Placement itself (requires, class, workerPreference) uses the base spec.
48
+ */
49
+ variants?: SpecVariant[];
41
50
  owner?: string;
42
51
  /** Capabilities a worker must have, e.g. 'filter:ass', 'encoder:libx264', 'font:DejaVu Sans'. */
43
52
  requires?: string[];
@@ -57,6 +66,19 @@ export interface JobSpecInput {
57
66
  [section: string]: unknown;
58
67
  }
59
68
 
69
+ export interface SpecVariant {
70
+ /** Reported as `variant` on the job; 'variant-<index>' by default. */
71
+ name?: string;
72
+ /** `workers`: any of these worker IDs. `capabilities`: all of these. Both must hold when both are set. */
73
+ when: { workers?: string[]; capabilities?: string[] };
74
+ ffmpeg?: { args: string[]; durationMs?: number | null };
75
+ inputs?: Endpoint[];
76
+ outputs?: Endpoint[];
77
+ labels?: Record<string, string>;
78
+ /** The section of the spec's own type, for types other than ffmpeg. */
79
+ [section: string]: unknown;
80
+ }
81
+
60
82
  /** A validated spec with every default filled in (what parseSpec returns). */
61
83
  export interface JobSpec {
62
84
  contract: 1;
@@ -65,6 +87,11 @@ export interface JobSpec {
65
87
  type: string;
66
88
  class: string;
67
89
  priority: number;
90
+ /** Ordered worker IDs; when set, only listed workers may run the job. */
91
+ workerPreference?: string[];
92
+ variants?: (SpecVariant & { name: string })[];
93
+ /** Name of the variant applied, on the spec a worker runs. */
94
+ variant?: string;
68
95
  owner: string;
69
96
  requires: string[];
70
97
  labels: Record<string, string>;
@@ -106,6 +133,8 @@ export interface JobEvent {
106
133
  state: JobState;
107
134
  progress?: Progress;
108
135
  workerId?: string | null;
136
+ /** On 'assigned' (and 'queued' after a re-dispatch): the spec variant chosen for the worker, null for the base spec. */
137
+ variant?: string | null;
109
138
  exitCode?: number | null;
110
139
  error?: JobError;
111
140
  outputs?: OutputResult[];
@@ -119,9 +148,12 @@ export interface JobSnapshot {
119
148
  class: string;
120
149
  owner: string;
121
150
  priority: number;
151
+ workerPreference?: string[];
122
152
  labels: Record<string, string>;
123
153
  state: JobState;
124
154
  workerId: string | null;
155
+ /** The spec variant the job runs as, null for the base spec. */
156
+ variant: string | null;
125
157
  createdAt: string;
126
158
  startedAt: string | null;
127
159
  finishedAt: string | null;
@@ -156,6 +188,8 @@ export function validateSpec(input: unknown): { ok: true; spec: JobSpec } | { ok
156
188
  export function parseSpec(input: unknown): JobSpec;
157
189
  export function resolvePlaceholders(args: string[], values: { input: Record<string, string>; output: Record<string, string> }): string[];
158
190
  export function canonicalJson(value: unknown): string;
191
+ /** The spec to run on a worker: the first variant whose `when` fits, merged over the base (no `variants` left), or the base spec. */
192
+ export function resolveVariant(spec: JobSpec, worker?: { workerId?: string | null; capabilities?: Iterable<string> }): { spec: JobSpec; variant: string | null };
159
193
  /** Capabilities a job needs beyond `requires`: `type:<type>`, plus `scheme:s3` for s3: URIs. */
160
194
  export function implicitRequirements(spec: Pick<JobSpec, 'type' | 'inputs' | 'outputs'>): string[];
161
195
 
@@ -193,6 +227,8 @@ export interface JobManagerOptions {
193
227
  progressIntervalMs?: number;
194
228
  executors?: Record<string, Executor>;
195
229
  workerId?: string | null;
230
+ /** This runner's capabilities, used to pick a spec variant. */
231
+ capabilities?: () => Iterable<string>;
196
232
  fetch?: typeof fetch;
197
233
  /** S3 settings or a client; enables s3: URIs. */
198
234
  s3?: S3Config | S3Client | null;
@@ -243,6 +279,8 @@ export class JobHandle extends EventEmitter {
243
279
  /** The newest stderr lines ffmpeg wrote while the job runs (null until it writes any). */
244
280
  stderrTail: string | null;
245
281
  snapshot: JobSnapshot | null;
282
+ /** The spec variant chosen where the job runs (set by the 'assigned' event), null for the base spec. Read it before parsing stdout. */
283
+ variant: string | null;
246
284
  /** Resolves with the final snapshot whatever the outcome; check `state`. */
247
285
  readonly done: Promise<JobSnapshot>;
248
286
  cancel(): Promise<unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet",
3
- "version": "2.6.0",
3
+ "version": "2.8.0",
4
4
  "description": "Run ffmpeg jobs locally, on one worker or across a pool, through one client and one job contract",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/client.js CHANGED
@@ -24,6 +24,8 @@ export class JobHandle extends EventEmitter {
24
24
  this.snapshot = null;
25
25
  /** The newest stderr lines ffmpeg wrote while the job runs (null until it writes any). */
26
26
  this.stderrTail = null;
27
+ /** Name of the spec variant chosen where the job runs (known from the 'assigned' event), or null for the base spec. */
28
+ this.variant = null;
27
29
  let resolve, reject;
28
30
  /** @type {Promise<import('./types.js').JobSnapshot>} */
29
31
  this.done = new Promise((res, rej) => {
@@ -36,6 +38,7 @@ export class JobHandle extends EventEmitter {
36
38
  }
37
39
 
38
40
  _event(event) {
41
+ if (event.variant !== undefined) this.variant = event.variant;
39
42
  this.emit('event', event);
40
43
  if (event.progress) this.emit('progress', event.progress, event);
41
44
  if (event.stderrTail) {
@@ -128,6 +131,7 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
128
131
  const m = localManager();
129
132
  const { job } = m.submit(spec);
130
133
  const handle = new JobHandle(job.id, 'local');
134
+ handle.variant = job.variant ?? null;
131
135
  handle._cancel = async () => m.cancel(job.id);
132
136
  handle._write = data => m.writeStdin(job.id, data);
133
137
  handle._endStdin = () => m.closeStdin(job.id);
@@ -146,6 +150,7 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
146
150
  const job = await request('POST', '/v1/jobs', spec);
147
151
  const handle = new JobHandle(job.id, 'remote');
148
152
  handle.snapshot = job;
153
+ handle.variant = job.variant ?? null;
149
154
  const ac = new AbortController();
150
155
  controllers.add(ac);
151
156
  const enc = encodeURIComponent(job.id);
package/src/contract.js CHANGED
@@ -79,6 +79,15 @@ export function validateSpec(input) {
79
79
  const priority = s.priority ?? 0;
80
80
  if (!Number.isInteger(priority) || priority < -1000 || priority > 1000) err('priority', 'must be an integer from -1000 to 1000');
81
81
 
82
+ // Ordered worker IDs; when set, this list is also a placement allowlist.
83
+ const workerPreference = s.workerPreference;
84
+ if (workerPreference !== undefined && (!Array.isArray(workerPreference)
85
+ || workerPreference.length === 0
86
+ || workerPreference.some(id => typeof id !== 'string' || !id.trim() || id.length > 128)
87
+ || new Set(workerPreference).size !== workerPreference.length)) {
88
+ err('workerPreference', 'must be a non-empty array of unique worker IDs (1-128 characters each)');
89
+ }
90
+
82
91
  const owner = s.owner ?? '';
83
92
  if (typeof owner !== 'string' || owner.length > 256) err('owner', 'must be a string of at most 256 characters');
84
93
 
@@ -109,6 +118,10 @@ export function validateSpec(input) {
109
118
  const outputs = normalizeEndpoints(s.outputs, 'outputs', err);
110
119
  checkObjectEndpoints(s.kind, inputs, outputs, err);
111
120
 
121
+ // Set by a runner that applied a variant (see resolveVariant); a client does not send it.
122
+ const variant = s.variant;
123
+ if (variant !== undefined && (typeof variant !== 'string' || !NAME_RE.test(variant))) err('variant', 'must be 1-64 characters of A-Z a-z 0-9 _ -');
124
+
112
125
  let ffmpeg;
113
126
  if (type === 'ffmpeg') {
114
127
  const f = s.ffmpeg;
@@ -122,6 +135,8 @@ export function validateSpec(input) {
122
135
  }
123
136
  }
124
137
 
138
+ const variants = s.variants === undefined || errors.length ? undefined : normalizeVariants(s, type, err);
139
+
125
140
  if (errors.length) return { ok: false, errors };
126
141
 
127
142
  /** @type {any} */
@@ -132,6 +147,7 @@ export function validateSpec(input) {
132
147
  type,
133
148
  class: cls,
134
149
  priority,
150
+ ...(workerPreference !== undefined ? { workerPreference: [...workerPreference] } : {}),
135
151
  owner,
136
152
  requires: [...new Set(requires)].sort(),
137
153
  labels: { ...labels },
@@ -144,9 +160,97 @@ export function validateSpec(input) {
144
160
  if (redact.length) spec.redact = [...new Set(redact)];
145
161
  if (ffmpeg) spec.ffmpeg = ffmpeg;
146
162
  else if (s[type] !== undefined) spec[type] = s[type];
163
+ if (variant !== undefined) spec.variant = variant;
164
+ if (variants) spec.variants = variants;
147
165
  return { ok: true, spec };
148
166
  }
149
167
 
168
+ export const MAX_VARIANTS = 16;
169
+ const VARIANT_KEYS = new Set(['name', 'when', 'ffmpeg', 'inputs', 'outputs', 'labels']);
170
+
171
+ /** The spec a variant produces: its sections replace the base ones, its labels are added. */
172
+ function mergeVariant(base, v, type) {
173
+ const out = { ...base };
174
+ delete out.variants;
175
+ delete out.variant;
176
+ for (const k of ['ffmpeg', 'inputs', 'outputs']) if (v[k] !== undefined) out[k] = v[k];
177
+ if (type !== 'ffmpeg' && v[type] !== undefined) out[type] = v[type];
178
+ if (v.labels !== undefined) out.labels = { ...(base.labels ?? {}), ...v.labels };
179
+ return out;
180
+ }
181
+
182
+ /** Checks `variants` and that each one, merged over the base, is a valid spec. */
183
+ function normalizeVariants(s, type, err) {
184
+ const list = s.variants;
185
+ if (!Array.isArray(list) || list.length === 0 || list.length > MAX_VARIANTS) {
186
+ err('variants', `must be a non-empty array of at most ${MAX_VARIANTS} variants`);
187
+ return undefined;
188
+ }
189
+ const names = new Set();
190
+ return list.map((v, i) => {
191
+ const p = `variants[${i}]`;
192
+ if (!v || typeof v !== 'object' || Array.isArray(v)) {
193
+ err(p, 'must be an object');
194
+ return null;
195
+ }
196
+ for (const k of Object.keys(v)) {
197
+ if (!VARIANT_KEYS.has(k) && !(k === type && type !== 'ffmpeg')) err(`${p}.${k}`, `a variant may only set name, when, ffmpeg, inputs, outputs, labels${type !== 'ffmpeg' ? ` or ${type}` : ''}`);
198
+ }
199
+ const name = v.name ?? `variant-${i}`;
200
+ if (typeof name !== 'string' || !NAME_RE.test(name)) err(`${p}.name`, 'must be 1-64 characters of A-Z a-z 0-9 _ -');
201
+ else if (names.has(name)) err(`${p}.name`, `duplicate name "${name}"`);
202
+ names.add(name);
203
+
204
+ const w = v.when;
205
+ const when = {};
206
+ if (!w || typeof w !== 'object' || Array.isArray(w)) err(`${p}.when`, 'must be an object with workers and/or capabilities');
207
+ else {
208
+ for (const k of Object.keys(w)) if (k !== 'workers' && k !== 'capabilities') err(`${p}.when.${k}`, 'unknown condition (known: workers, capabilities)');
209
+ for (const k of ['workers', 'capabilities']) {
210
+ if (w[k] === undefined) continue;
211
+ const arr = w[k];
212
+ if (!Array.isArray(arr) || !arr.length || arr.some(x => typeof x !== 'string' || !x.trim() || x.length > 128)) {
213
+ err(`${p}.when.${k}`, 'must be a non-empty array of strings (1-128 characters each)');
214
+ } else when[k] = [...new Set(arr)];
215
+ }
216
+ if (w.workers === undefined && w.capabilities === undefined) err(`${p}.when`, 'needs workers and/or capabilities');
217
+ }
218
+
219
+ if (v.labels !== undefined && (!v.labels || typeof v.labels !== 'object' || Array.isArray(v.labels))) {
220
+ err(`${p}.labels`, 'must be an object of string values');
221
+ return null;
222
+ }
223
+ const merged = validateSpec(mergeVariant(s, v, type));
224
+ if (!merged.ok) for (const e of merged.errors) err(`${p}.${e.path}`, e.message);
225
+
226
+ const out = { name, when };
227
+ if (merged.ok) {
228
+ for (const k of ['ffmpeg', 'inputs', 'outputs']) if (v[k] !== undefined) out[k] = merged.spec[k];
229
+ if (type !== 'ffmpeg' && v[type] !== undefined) out[type] = v[type];
230
+ if (v.labels !== undefined) out.labels = { ...v.labels };
231
+ }
232
+ return out;
233
+ });
234
+ }
235
+
236
+ /**
237
+ * Picks the first variant whose `when` fits a worker and returns the spec to run there.
238
+ * `when.workers` matches any listed worker ID, `when.capabilities` needs all listed capabilities; both must hold when both are set.
239
+ * Without a matching variant the base spec is used. The returned spec has no `variants`; `variant` names the one applied.
240
+ * @param {import('./types.js').JobSpec} spec A validated spec.
241
+ * @param {{ workerId?: string | null, capabilities?: Iterable<string> }} worker
242
+ * @returns {{ spec: import('./types.js').JobSpec, variant: string | null }}
243
+ */
244
+ export function resolveVariant(spec, { workerId = null, capabilities = [] } = {}) {
245
+ if (!spec.variants) return { spec, variant: spec.variant ?? null };
246
+ const caps = capabilities instanceof Set ? capabilities : new Set(capabilities);
247
+ const v = spec.variants.find(x => (!x.when.workers || (workerId !== null && x.when.workers.includes(workerId)))
248
+ && (!x.when.capabilities || x.when.capabilities.every(c => caps.has(c))));
249
+ const resolved = /** @type {any} */ (mergeVariant(spec, v ?? {}, spec.type));
250
+ if (v) resolved.variant = v.name;
251
+ return { spec: resolved, variant: v ? v.name : null };
252
+ }
253
+
150
254
  /** Like validateSpec but throws a ContractError. */
151
255
  export function parseSpec(input) {
152
256
  const r = validateSpec(input);
package/src/index.js CHANGED
@@ -2,6 +2,7 @@ export { createFleet, JobHandle } from './client.js';
2
2
  export {
3
3
  CONTRACT_VERSION, KINDS, STATES, isFinal, validateSpec, parseSpec, ContractError,
4
4
  resolvePlaceholders, canonicalJson, implicitRequirements, FILE_SCHEMES, HTTP_SCHEMES, PASSTHROUGH_SCHEMES, OBJECT_SCHEMES,
5
+ resolveVariant, MAX_VARIANTS,
5
6
  } from './contract.js';
6
7
  export { JobManager, normalizeSlots, normalizeKinds, autoSlots } from './job-manager.js';
7
8
  export { JobRecord, FleetError, byPriority, pruneFinished } from './job-record.js';
@@ -4,7 +4,7 @@ import { EventEmitter } from 'node:events';
4
4
  import { mkdir, rm } from 'node:fs/promises';
5
5
  import { availableParallelism, tmpdir } from 'node:os';
6
6
  import { join } from 'node:path';
7
- import { KINDS, canonicalJson, implicitRequirements, parseSpec } from './contract.js';
7
+ import { KINDS, canonicalJson, implicitRequirements, parseSpec, resolveVariant } from './contract.js';
8
8
  import { createInputCache, parseSize } from './input-cache.js';
9
9
  import { createS3Client } from './s3.js';
10
10
  import { runFfmpegJob } from './executor.js';
@@ -34,6 +34,7 @@ export class JobManager extends EventEmitter {
34
34
  * @param {number} [opts.progressIntervalMs]
35
35
  * @param {Record<string, Function>} [opts.executors] type -> (spec, runtime) => Promise<result>
36
36
  * @param {string} [opts.workerId]
37
+ * @param {() => Iterable<string>} [opts.capabilities] This runner's capabilities, for picking a spec variant.
37
38
  * @param {typeof fetch} [opts.fetch]
38
39
  * @param {object | null} [opts.s3] S3 settings (see s3ConfigFromEnv) or a client; enables s3: URIs.
39
40
  * @param {{ dir: string, maxBytes?: number | string } | null} [opts.cache] Keeps staged s3: and http(s): inputs between jobs (least recently used removed above maxBytes, default 20 GB).
@@ -48,6 +49,7 @@ export class JobManager extends EventEmitter {
48
49
  progressIntervalMs = 1000,
49
50
  executors = {},
50
51
  workerId = null,
52
+ capabilities = () => [],
51
53
  fetch: fetchImpl,
52
54
  s3 = null,
53
55
  cache = null,
@@ -63,6 +65,7 @@ export class JobManager extends EventEmitter {
63
65
  this.progressIntervalMs = progressIntervalMs;
64
66
  this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, ...executors };
65
67
  this.workerId = workerId;
68
+ this.capabilities = capabilities;
66
69
  this.fetch = fetchImpl;
67
70
  this.cache = cache ? createInputCache({ dir: cache.dir, maxBytes: cache.maxBytes === undefined ? undefined : parseSize(cache.maxBytes) }) : null;
68
71
  this.s3 = !s3 ? null : typeof s3.getFile === 'function' ? s3 : createS3Client({ fetch: fetchImpl, ...s3 });
@@ -84,7 +87,9 @@ export class JobManager extends EventEmitter {
84
87
  */
85
88
  submit(input) {
86
89
  if (this.closed) throw new FleetError('SHUTTING_DOWN', 'job manager is closed', { status: 503 });
87
- const spec = parseSpec(input);
90
+ const parsed = parseSpec(input);
91
+ // A spec with variants runs as the variant that fits this runner (an orchestrator sends it already resolved).
92
+ const { spec } = resolveVariant(parsed, { workerId: this.workerId, capabilities: this.capabilities() });
88
93
  spec.id ??= `job_${randomUUID()}`;
89
94
 
90
95
  const existing = this.jobs.get(spec.id);
package/src/job-record.js CHANGED
@@ -30,6 +30,8 @@ export class JobRecord {
30
30
  this.id = spec.id;
31
31
  this.state = 'queued';
32
32
  this.workerId = null;
33
+ /** Name of the spec variant applied where the job runs, or null for the base spec. */
34
+ this.variant = spec.variant ?? null;
33
35
  this.createdAt = new Date().toISOString();
34
36
  this.order = ++order;
35
37
  this.startedAt = null;
@@ -59,7 +61,7 @@ export class JobRecord {
59
61
  */
60
62
  static restore(spec, saved) {
61
63
  const job = new JobRecord(spec);
62
- for (const key of ['state', 'workerId', 'createdAt', 'startedAt', 'finishedAt', 'progress', 'exitCode', 'error', 'outputs', 'stderrTail', 'seq']) {
64
+ for (const key of ['state', 'workerId', 'variant', 'createdAt', 'startedAt', 'finishedAt', 'progress', 'exitCode', 'error', 'outputs', 'stderrTail', 'seq']) {
63
65
  if (saved[key] !== undefined) job[key] = saved[key];
64
66
  }
65
67
  if (Array.isArray(saved.history) && saved.history.length) job.history = saved.history;
@@ -81,6 +83,7 @@ export class JobRecord {
81
83
  const now = new Date().toISOString();
82
84
  if (state === 'running' && !this.startedAt) this.startedAt = now;
83
85
  if (fields.workerId !== undefined) this.workerId = fields.workerId;
86
+ if (fields.variant !== undefined) this.variant = fields.variant;
84
87
  if (fields.progress) this.progress = fields.progress;
85
88
  if (fields.stderrTail !== undefined && !isFinal(state)) this.stderrTail = fields.stderrTail;
86
89
  this.state = state;
@@ -92,7 +95,7 @@ export class JobRecord {
92
95
  this.stderrTail = fields.stderrTail ?? null;
93
96
  }
94
97
  const event = { jobId: this.id, seq: ++this.seq, at: now, state };
95
- for (const key of ['progress', 'workerId', 'exitCode', 'error', 'outputs', 'stderrTail']) {
98
+ for (const key of ['progress', 'workerId', 'variant', 'exitCode', 'error', 'outputs', 'stderrTail']) {
96
99
  if (fields[key] !== undefined) event[key] = fields[key];
97
100
  }
98
101
  if (isFinal(state)) {
@@ -129,9 +132,11 @@ export class JobRecord {
129
132
  class: this.spec.class,
130
133
  owner: this.spec.owner,
131
134
  priority: this.spec.priority,
135
+ ...(this.spec.workerPreference ? { workerPreference: this.spec.workerPreference } : {}),
132
136
  labels: this.spec.labels,
133
137
  state: this.state,
134
138
  workerId: this.workerId,
139
+ variant: this.variant,
135
140
  createdAt: this.createdAt,
136
141
  startedAt: this.startedAt,
137
142
  finishedAt: this.finishedAt,
package/src/types.js CHANGED
@@ -16,6 +16,7 @@
16
16
  * @property {string} type Executor, 'ffmpeg' by default.
17
17
  * @property {string} class Slot pool on the worker, 'default' by default.
18
18
  * @property {number} priority Higher runs first.
19
+ * @property {string[]} [workerPreference] Ordered worker IDs; also restricts placement to listed workers.
19
20
  * @property {string} owner Opaque label of whoever submitted the job.
20
21
  * @property {string[]} requires Capabilities a worker must have, e.g. 'filter:ass'.
21
22
  * @property {Record<string, string>} labels