fffleet-orchestrator 0.0.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/README.md CHANGED
@@ -14,12 +14,16 @@ docker run -p 5000:5000 -e FFFLEET_TOKEN=... -e FFFLEET_WORKER_TOKEN=... ghcr.io
14
14
  | Variable | Default | |
15
15
  |---|---|---|
16
16
  | `PORT`, `HOST` | `5000`, `0.0.0.0` | |
17
- | `FFFLEET_TOKEN` | | Token clients send. |
17
+ | `FFFLEET_TOKEN` | | A static token with full access. |
18
+ | `FFFLEET_CLIENTS_FILE` | | Apps that may log in (`POST /v1/auth/token`). Add one with `fffleet-orchestrator add-client <id> --scope jobs`. |
19
+ | `FFFLEET_SIGNING_KEY_FILE` | | Ed25519 key for tokens, created when missing. Without it tokens end at a restart. |
20
+ | `FFFLEET_TOKEN_TTL_SECONDS` | `3600` | |
18
21
  | `FFFLEET_WORKER_TOKEN` | | Token workers register with. The orchestrator also sends it when it calls workers. |
19
22
  | `FFFLEET_HEARTBEAT_TIMEOUT_MS` | `15000` | |
20
23
  | `FFFLEET_MAX_QUEUED` | `1000` | Above this, submissions get 503. |
24
+ | `FFFLEET_CONFIG` | | YAML or JSON file with autoscaling pools (also `--config <file>`). See the [main README](https://github.com/jsilvanus/fffleet#autoscaling). |
21
25
 
22
- Extra routes: `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.
26
+ 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.
23
27
 
24
28
  State is kept in memory: a restart forgets the queue.
25
29
 
@@ -1,24 +1,83 @@
1
1
  #!/usr/bin/env node
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { SCOPES, generateSecret, hashSecret } from 'fffleet';
4
+ import { loadConfig } from '../src/config.js';
2
5
  import { createOrchestrator } from '../src/orchestrator.js';
3
6
 
4
7
  const env = process.env;
8
+ const log = msg => console.log(`[fffleet-orchestrator] ${msg}`);
9
+
10
+ if (process.argv[2] === 'add-client') {
11
+ await addClient(process.argv.slice(3));
12
+ process.exit(0);
13
+ }
14
+
15
+ let scaling = null;
16
+ const configPath = env.FFFLEET_CONFIG || (process.argv[2] === '--config' ? process.argv[3] : null);
17
+ if (configPath) {
18
+ try {
19
+ scaling = loadConfig(configPath);
20
+ } catch (err) {
21
+ console.error(`[fffleet-orchestrator] ${err.message}`);
22
+ process.exit(1);
23
+ }
24
+ }
5
25
 
6
26
  const orchestrator = createOrchestrator({
27
+ scaling,
7
28
  port: Number(env.PORT ?? 5000),
8
29
  host: env.HOST ?? '0.0.0.0',
9
30
  token: env.FFFLEET_TOKEN || null,
31
+ clients: env.FFFLEET_CLIENTS_FILE || null,
32
+ signingKeyFile: env.FFFLEET_SIGNING_KEY_FILE || null,
33
+ tokenTtlSeconds: Number(env.FFFLEET_TOKEN_TTL_SECONDS ?? 3600),
10
34
  workerToken: env.FFFLEET_WORKER_TOKEN || null,
11
35
  heartbeatTimeoutMs: Number(env.FFFLEET_HEARTBEAT_TIMEOUT_MS ?? 15000),
12
36
  maxQueued: Number(env.FFFLEET_MAX_QUEUED ?? 1000),
13
- log: msg => console.log(`[fffleet-orchestrator] ${msg}`),
37
+ log,
14
38
  });
15
39
 
16
40
  await orchestrator.start();
41
+ if (scaling && !env.FFFLEET_SIGNING_KEY_FILE && !scaling.autoscale.joinSecret && scaling.pools.some(p => p.provider !== 'process')) {
42
+ log('no FFFLEET_SIGNING_KEY_FILE or autoscale.joinSecret: workers started before a restart cannot rejoin and are removed after the boot timeout');
43
+ }
44
+ if (env.FFFLEET_CLIENTS_FILE && !env.FFFLEET_SIGNING_KEY_FILE) log('FFFLEET_SIGNING_KEY_FILE is not set: tokens stop working when the orchestrator restarts, and apps log in again');
17
45
 
18
46
  for (const sig of ['SIGINT', 'SIGTERM']) {
19
47
  process.once(sig, async () => {
20
- console.log(`[fffleet-orchestrator] ${sig}: stopping`);
48
+ log(`${sig}: stopping`);
21
49
  await orchestrator.stop();
22
50
  process.exit(0);
23
51
  });
24
52
  }
53
+
54
+ /**
55
+ * fffleet-orchestrator add-client <id> [--scope jobs,metrics] [--file clients.json]
56
+ * Adds (or replaces) an app in the clients file and prints its secret once.
57
+ */
58
+ async function addClient(args) {
59
+ const id = args[0];
60
+ const opt = name => {
61
+ const i = args.indexOf(`--${name}`);
62
+ return i >= 0 ? args[i + 1] : undefined;
63
+ };
64
+ const file = opt('file') ?? env.FFFLEET_CLIENTS_FILE;
65
+ const scopes = (opt('scope') ?? 'jobs').split(',').map(s => s.trim()).filter(Boolean);
66
+ if (!id || id.startsWith('--') || !file) {
67
+ console.error('usage: fffleet-orchestrator add-client <id> [--scope jobs,metrics,admin] [--file clients.json]\n(the file defaults to FFFLEET_CLIENTS_FILE)');
68
+ process.exit(2);
69
+ }
70
+ for (const s of scopes) {
71
+ if (!SCOPES.includes(s)) {
72
+ console.error(`unknown scope "${s}"; scopes are ${SCOPES.join(', ')}`);
73
+ process.exit(2);
74
+ }
75
+ }
76
+ const data = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { clients: [] };
77
+ data.clients = (data.clients ?? []).filter(c => c.id !== id);
78
+ const secret = generateSecret();
79
+ data.clients.push({ id, secretHash: await hashSecret(secret), scopes });
80
+ writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
81
+ console.log(`client ${id} (${scopes.join(', ')}) written to ${file}`);
82
+ console.log(`client secret (shown once): ${secret}`);
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet-orchestrator",
3
- "version": "0.0.0",
3
+ "version": "1.0.0",
4
4
  "description": "fffleet orchestrator: schedules ffmpeg jobs across a pool of fffleet workers",
5
5
  "type": "module",
6
6
  "main": "./src/orchestrator.js",
@@ -9,7 +9,7 @@
9
9
  "./package.json": "./package.json"
10
10
  },
11
11
  "bin": {
12
- "fffleet-orchestrator": "./bin/fffleet-orchestrator.js"
12
+ "fffleet-orchestrator": "bin/fffleet-orchestrator.js"
13
13
  },
14
14
  "files": [
15
15
  "src",
@@ -21,7 +21,7 @@
21
21
  "test": "node --test test/*.test.js"
22
22
  },
23
23
  "dependencies": {
24
- "fffleet": "^0.0.0"
24
+ "fffleet": "^1.0.0"
25
25
  },
26
26
  "keywords": [
27
27
  "ffmpeg",
@@ -44,5 +44,13 @@
44
44
  },
45
45
  "publishConfig": {
46
46
  "access": "public"
47
+ },
48
+ "peerDependencies": {
49
+ "fffleet-worker": "^1.0.0"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "fffleet-worker": {
53
+ "optional": true
54
+ }
47
55
  }
48
56
  }
@@ -0,0 +1,314 @@
1
+ import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { implicitRequirements } from 'fffleet';
3
+
4
+ /**
5
+ * Starts and stops workers to match demand.
6
+ *
7
+ * Pools are tried in the order they are configured, so a pool on this host listed before a cloud
8
+ * pool is filled first. A pool grows when a queued job has waited `scaleUpAfter` and no worker that
9
+ * could take it is on the way, and shrinks when a worker has been idle for `idleAfter`.
10
+ *
11
+ * Every instance it starts is labelled with this orchestrator's id, so after a restart it adopts the
12
+ * ones that register again and deletes the rest instead of leaking paid servers. Instances never see
13
+ * the shared worker token: each gets a join secret derived from the worker id with a key only the
14
+ * orchestrator holds, so a restart can recognise it again without storing anything.
15
+ *
16
+ * @param {object} opts
17
+ * @param {{ autoscale: any, pools: any[], publicUrl: string | null }} opts.config See normalizeConfig.
18
+ * @param {Record<string, any>} opts.providers pool name -> provider (create, destroy, list, close, billing).
19
+ * @param {{ queue(): any[], workers(): Iterable<any>, drain(id: string): void, forget(id: string): void, publicUrl(): string }} opts.view
20
+ * @param {Buffer | string} [opts.joinKey]
21
+ * @param {(msg: string) => void} [opts.log]
22
+ * @param {object} [opts.metrics] counters and gauges from the orchestrator's registry.
23
+ * @param {() => number} [opts.now]
24
+ */
25
+ export function createAutoscaler({ config, providers, view, joinKey = randomBytes(32), log = () => {}, metrics = null, now = Date.now }) {
26
+ const { autoscale } = config;
27
+ const pools = new Map(config.pools.map(p => [p.name, { ...p, observed: new Set(), failures: 0, backoffUntil: 0 }]));
28
+ /** @type {Map<string, { id: string, pool: string, providerId: string | null, state: 'creating' | 'booting' | 'ready' | 'draining' | 'removing', createdAt: number, idleSince: number | null, adopted?: boolean, destroyAttempts?: number }>} */
29
+ const instances = new Map();
30
+ let timer = null;
31
+ let ticking = false;
32
+ let stopped = false;
33
+
34
+ const joinSecret = workerId => createHmac('sha256', joinKey).update(`fffleet-worker:${workerId}`).digest('base64url');
35
+ const labels = (pool, workerId) => ({ 'fffleet.orchestrator': autoscale.id, 'fffleet.pool': pool.name, 'fffleet.worker': workerId });
36
+
37
+ const alive = pool => [...instances.values()].filter(i => i.pool === pool.name && i.state !== 'removing');
38
+ const count = (pool, ...states) => [...instances.values()].filter(i => i.pool === pool.name && states.includes(i.state)).length;
39
+ const totalAlive = () => [...instances.values()].filter(i => i.state !== 'removing').length;
40
+
41
+ /** What a worker of this pool can do: what the config declares plus what its running workers reported. */
42
+ function poolCaps(pool) {
43
+ return [...pool.capabilities, ...pool.observed];
44
+ }
45
+
46
+ function hasCap(caps, required) {
47
+ return caps.some(c => c === required || (c.endsWith('*') && required.startsWith(c.slice(0, -1))));
48
+ }
49
+
50
+ /** Whether a worker started from this pool could run the job. */
51
+ function canServe(pool, spec) {
52
+ if (!pool.kinds.includes(spec.kind)) return false;
53
+ const needs = [...implicitRequirements(spec), ...spec.requires].filter(r => !(r === 'type:ffmpeg' && spec.type === 'ffmpeg'));
54
+ const caps = poolCaps(pool);
55
+ return needs.every(r => hasCap(caps, r));
56
+ }
57
+
58
+ /** How many queued jobs one new worker of this pool is expected to absorb. */
59
+ function slotsPerWorker(pool) {
60
+ if (pool.slotsHint) return pool.slotsHint;
61
+ if (!pool.slotsAuto) return Math.max(1, pool.slotsResolved.default ?? Object.values(pool.slotsResolved)[0] ?? 1);
62
+ return 2;
63
+ }
64
+
65
+ async function create(pool) {
66
+ const workerId = `${pool.name}-${randomUUID().slice(0, 6)}`;
67
+ const inst = { id: workerId, pool: pool.name, provider: providers[pool.name], providerId: null, state: 'creating', createdAt: now(), idleSince: null };
68
+ instances.set(workerId, inst);
69
+ const secret = joinSecret(workerId);
70
+ const env = {
71
+ FFFLEET_WORKER_ID: workerId,
72
+ FFFLEET_ORCHESTRATOR_URL: view.publicUrl(),
73
+ FFFLEET_TOKEN: secret,
74
+ FFFLEET_WORKER_TOKEN: secret,
75
+ FFFLEET_SLOTS: pool.slots,
76
+ FFFLEET_KINDS: pool.kinds.join(','),
77
+ ...(pool.capabilities.some(c => !c.endsWith('*')) ? { FFFLEET_CAPABILITIES: pool.capabilities.filter(c => !c.endsWith('*')).join(',') } : {}),
78
+ ...pool.env,
79
+ };
80
+ try {
81
+ const made = await inst.provider.create({ workerId, pool, env, labels: labels(pool, workerId) });
82
+ inst.providerId = made.providerId;
83
+ inst.state = 'booting';
84
+ inst.createdAt = now();
85
+ metrics?.creates.inc({ pool: pool.name, result: 'ok' });
86
+ log(`autoscaler: started worker ${workerId} in pool ${pool.name}`);
87
+ } catch (err) {
88
+ instances.delete(workerId);
89
+ pool.failures++;
90
+ pool.backoffUntil = now() + Math.min(10 * 60000, 5000 * 2 ** Math.min(pool.failures, 7));
91
+ metrics?.creates.inc({ pool: pool.name, result: 'error' });
92
+ log(`autoscaler: could not start a worker in pool ${pool.name}: ${err.message}; retrying after ${Math.round((pool.backoffUntil - now()) / 1000)}s`);
93
+ }
94
+ }
95
+
96
+ async function destroy(inst, reason) {
97
+ if (inst.state !== 'removing') {
98
+ inst.state = 'removing';
99
+ inst.destroyReason = reason;
100
+ }
101
+ view.forget(inst.id);
102
+ try {
103
+ if (inst.providerId !== null) await inst.provider.destroy(inst.providerId);
104
+ instances.delete(inst.id);
105
+ metrics?.destroys.inc({ pool: inst.pool, reason });
106
+ log(`autoscaler: removed worker ${inst.id} (${reason})`);
107
+ } catch (err) {
108
+ inst.destroyAttempts = (inst.destroyAttempts ?? 0) + 1;
109
+ log(`autoscaler: could not remove worker ${inst.id} (attempt ${inst.destroyAttempts}): ${err.message}; will retry`);
110
+ }
111
+ }
112
+
113
+ /** Marks instances ready when their worker registers, and removes ones whose worker vanished. */
114
+ function sync() {
115
+ const known = new Map([...view.workers()].map(w => [w.id, w]));
116
+ for (const inst of [...instances.values()]) {
117
+ const w = known.get(inst.id);
118
+ const pool = pools.get(inst.pool);
119
+ if (inst.state === 'booting' && w) {
120
+ inst.state = 'ready';
121
+ inst.idleSince = now();
122
+ if (pool) {
123
+ pool.failures = 0;
124
+ for (const c of w.capabilities) pool.observed.add(c);
125
+ }
126
+ log(`autoscaler: worker ${inst.id} is up after ${Math.round((now() - inst.createdAt) / 1000)}s`);
127
+ } else if (inst.state === 'ready' && !w) {
128
+ inst.state = 'removing';
129
+ inst.destroyReason = 'lost';
130
+ } else if (inst.state === 'booting' && !w && now() - inst.createdAt > autoscale.bootTimeout) {
131
+ inst.state = 'removing';
132
+ inst.destroyReason = 'boot-timeout';
133
+ if (pool) {
134
+ pool.failures++;
135
+ pool.backoffUntil = now() + Math.min(10 * 60000, 5000 * 2 ** Math.min(pool.failures, 7));
136
+ }
137
+ log(`autoscaler: worker ${inst.id} did not register within ${Math.round(autoscale.bootTimeout / 1000)}s`);
138
+ } else if (!pool && inst.state !== 'removing') {
139
+ inst.state = 'removing';
140
+ inst.destroyReason = 'pool-removed';
141
+ }
142
+ }
143
+ }
144
+
145
+ async function scaleUp() {
146
+ const t = now();
147
+ const planned = new Map([...pools.keys()].map(n => [n, 0]));
148
+ const assigned = new Map([...pools.keys()].map(n => [n, 0]));
149
+ const room = pool => alive(pool).length + planned.get(pool.name) < pool.max
150
+ && totalAlive() + [...planned.values()].reduce((a, b) => a + b, 0) < autoscale.maxWorkers;
151
+
152
+ // Queued jobs that have waited go to the first pool that could run them. A worker that is
153
+ // already on the way covers its share of them; only the rest need new workers.
154
+ for (const job of view.queue()) {
155
+ if (job.waitedMs < autoscale.scaleUpAfter) continue;
156
+ for (const pool of pools.values()) {
157
+ if (!canServe(pool, job.spec) || t < pool.backoffUntil) continue;
158
+ const coverage = (count(pool, 'creating', 'booting') + planned.get(pool.name)) * slotsPerWorker(pool);
159
+ if (assigned.get(pool.name) < coverage) {
160
+ assigned.set(pool.name, assigned.get(pool.name) + 1);
161
+ break;
162
+ }
163
+ if (room(pool)) {
164
+ planned.set(pool.name, planned.get(pool.name) + 1);
165
+ assigned.set(pool.name, assigned.get(pool.name) + 1);
166
+ break;
167
+ }
168
+ }
169
+ }
170
+
171
+ const creating = [];
172
+ for (const pool of pools.values()) {
173
+ if (t < pool.backoffUntil) continue;
174
+ const missingMin = pool.min - alive(pool).length;
175
+ const toStart = Math.min(Math.max(planned.get(pool.name), missingMin), pool.maxConcurrentCreates);
176
+ for (let i = 0; i < toStart; i++) creating.push(create(pool));
177
+ }
178
+ await Promise.all(creating);
179
+ }
180
+
181
+ function billingAligned(inst, provider) {
182
+ const b = provider?.billing;
183
+ if (!b) return true;
184
+ const age = now() - inst.createdAt;
185
+ return age % b.alignMs >= b.alignMs - b.windowMs;
186
+ }
187
+
188
+ async function scaleDown() {
189
+ const known = new Map([...view.workers()].map(w => [w.id, w]));
190
+ const queue = view.queue();
191
+ const t = now();
192
+ for (const inst of [...instances.values()]) {
193
+ const pool = pools.get(inst.pool);
194
+ const w = known.get(inst.id);
195
+ if (!pool || !w) continue;
196
+ const idle = w.jobs.size === 0;
197
+ if (inst.state === 'draining') {
198
+ if (idle) await destroy(inst, 'idle');
199
+ continue;
200
+ }
201
+ if (inst.state !== 'ready') continue;
202
+ if (!idle || queue.some(j => canServe(pool, j.spec))) {
203
+ inst.idleSince = null;
204
+ continue;
205
+ }
206
+ inst.idleSince ??= t;
207
+ const idleAfter = pool.idleAfter ?? autoscale.idleAfter;
208
+ if (t - inst.idleSince < idleAfter || alive(pool).length <= pool.min) continue;
209
+ if (!billingAligned(inst, inst.provider)) continue;
210
+ inst.state = 'draining';
211
+ view.drain(inst.id);
212
+ log(`autoscaler: draining idle worker ${inst.id}`);
213
+ if (idle) await destroy(inst, 'idle');
214
+ }
215
+ }
216
+
217
+ async function retryRemovals() {
218
+ for (const inst of [...instances.values()]) if (inst.state === 'removing') await destroy(inst, inst.destroyReason ?? 'removed');
219
+ }
220
+
221
+ function report() {
222
+ if (!metrics) return;
223
+ metrics.instances.reset();
224
+ for (const pool of pools.values()) {
225
+ for (const state of ['creating', 'booting', 'ready', 'draining', 'removing']) metrics.instances.set({ pool: pool.name, state }, count(pool, state));
226
+ }
227
+ }
228
+
229
+ async function tick() {
230
+ if (ticking || stopped) return;
231
+ ticking = true;
232
+ try {
233
+ sync();
234
+ await retryRemovals();
235
+ await scaleUp();
236
+ await scaleDown();
237
+ report();
238
+ } catch (err) {
239
+ log(`autoscaler: tick failed: ${err.stack ?? err.message}`);
240
+ } finally {
241
+ ticking = false;
242
+ }
243
+ }
244
+
245
+ return {
246
+ /** Adopts instances that survived an orchestrator restart, then starts ticking. */
247
+ async start() {
248
+ for (const [name, provider] of Object.entries(providers)) {
249
+ let found = [];
250
+ try {
251
+ found = await provider.list(autoscale.id);
252
+ } catch (err) {
253
+ log(`autoscaler: could not list existing instances of pool ${name}: ${err.message}`);
254
+ }
255
+ for (const f of found) {
256
+ if (instances.has(f.workerId)) continue;
257
+ // A pool's workers belong to that pool even if the listing came from a shared provider.
258
+ instances.set(f.workerId, { id: f.workerId, pool: f.pool, provider, providerId: f.providerId, state: 'booting', createdAt: f.createdAt ?? now(), idleSince: null, adopted: true });
259
+ log(`autoscaler: found worker ${f.workerId} from before the restart in pool ${f.pool}`);
260
+ }
261
+ }
262
+ stopped = false;
263
+ await tick();
264
+ timer = setInterval(tick, autoscale.interval);
265
+ timer.unref?.();
266
+ },
267
+
268
+ tick,
269
+
270
+ /** Stops ticking. Workers are left running: they re-register with the next orchestrator. */
271
+ async stop() {
272
+ stopped = true;
273
+ clearInterval(timer);
274
+ for (const provider of new Set(Object.values(providers))) await provider.close?.();
275
+ },
276
+
277
+ /** Whether `secret` is the join secret of an instance this orchestrator started. */
278
+ acceptsJoin(workerId, secret) {
279
+ const inst = typeof workerId === 'string' ? instances.get(workerId) : null;
280
+ if (!inst || inst.state === 'removing' || typeof secret !== 'string') return false;
281
+ const want = Buffer.from(joinSecret(workerId));
282
+ const got = Buffer.from(secret);
283
+ return got.length === want.length && timingSafeEqual(got, want);
284
+ },
285
+
286
+ /** A process provider tells us its worker exited. */
287
+ exited(workerId) {
288
+ const inst = instances.get(workerId);
289
+ if (inst && inst.state !== 'removing') {
290
+ inst.state = 'removing';
291
+ inst.destroyReason = 'exited';
292
+ }
293
+ },
294
+
295
+ describe() {
296
+ return {
297
+ pools: [...pools.values()].map(p => ({
298
+ name: p.name,
299
+ provider: p.provider,
300
+ kinds: p.kinds,
301
+ slots: p.slots,
302
+ min: p.min,
303
+ max: p.max,
304
+ instances: alive(p).length,
305
+ backoffSeconds: Math.max(0, Math.ceil((p.backoffUntil - now()) / 1000)),
306
+ workers: [...instances.values()].filter(i => i.pool === p.name).map(i => ({ id: i.id, state: i.state, ageSeconds: Math.round((now() - i.createdAt) / 1000), providerId: i.providerId })),
307
+ })),
308
+ };
309
+ },
310
+
311
+ joinSecret,
312
+ canServe,
313
+ };
314
+ }
package/src/config.js ADDED
@@ -0,0 +1,155 @@
1
+ // The orchestrator's config file (YAML or JSON): where new workers may be started and how.
2
+
3
+ import { readFileSync } from 'node:fs';
4
+ import { KINDS, normalizeKinds, normalizeSlots } from 'fffleet';
5
+ import { parseYaml } from './yaml.js';
6
+
7
+ export const PROVIDERS = ['process', 'docker', 'hetzner'];
8
+ const DEFAULT_WORKER_IMAGE = 'ghcr.io/jsilvanus/fffleet-worker:latest';
9
+
10
+ const TOP_KEYS = ['publicUrl', 'autoscale', 'pools'];
11
+ const AUTOSCALE_KEYS = ['id', 'interval', 'scaleUpAfter', 'idleAfter', 'bootTimeout', 'maxWorkers', 'joinSecret'];
12
+ const POOL_KEYS = ['name', 'provider', 'min', 'max', 'kinds', 'slots', 'slotsHint', 'capabilities', 'env', 'maxConcurrentCreates', 'idleAfter', 'process', 'docker', 'hetzner'];
13
+ const PROVIDER_KEYS = {
14
+ process: ['command', 'cwd'],
15
+ docker: ['image', 'network', 'socket', 'port', 'cpus', 'memory', 'pull'],
16
+ hetzner: ['token', 'serverType', 'location', 'image', 'workerImage', 'sshKeys', 'network', 'firewalls', 'advertise', 'port', 'registry', 'alignToBillingHour', 'baseUrl', 'extraRunArgs'],
17
+ };
18
+
19
+ /** "5s", "10m", "1h", "250ms" or a number of milliseconds. */
20
+ export function parseDuration(value, where) {
21
+ if (typeof value === 'number' && value >= 0) return value;
22
+ const m = typeof value === 'string' ? value.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/) : null;
23
+ if (!m) throw new Error(`${where}: "${value}" is not a duration (use for example 500ms, 10s, 5m, 1h)`);
24
+ return Math.round(Number(m[1]) * { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 }[m[2]]);
25
+ }
26
+
27
+ /** Replaces ${NAME} with environment variables (an unset one is an error), anywhere in the document. */
28
+ export function interpolateEnv(value, env = process.env, where = 'config') {
29
+ if (typeof value === 'string') {
30
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_, name, fallback) => {
31
+ const v = env[name];
32
+ if (v !== undefined && v !== '') return v;
33
+ if (fallback !== undefined) return fallback;
34
+ throw new Error(`${where}: environment variable ${name} is not set`);
35
+ });
36
+ }
37
+ if (Array.isArray(value)) return value.map((v, i) => interpolateEnv(v, env, `${where}[${i}]`));
38
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, interpolateEnv(v, env, `${where}.${k}`)]));
39
+ return value;
40
+ }
41
+
42
+ function onlyKeys(obj, allowed, where) {
43
+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) throw new Error(`${where} must be a mapping`);
44
+ for (const k of Object.keys(obj)) {
45
+ if (!allowed.includes(k)) throw new Error(`${where}: unknown setting "${k}" (known: ${allowed.join(', ')})`);
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Checks a parsed config and fills in defaults. Throws an Error that names the offending setting.
51
+ * @returns {{ publicUrl: string | null, autoscale: object, pools: object[] }}
52
+ */
53
+ export function normalizeConfig(raw, env = process.env) {
54
+ const doc = interpolateEnv(raw ?? {}, env);
55
+ onlyKeys(doc, TOP_KEYS, 'config');
56
+ const as = doc.autoscale ?? {};
57
+ onlyKeys(as, AUTOSCALE_KEYS, 'autoscale');
58
+
59
+ const autoscale = {
60
+ id: String(as.id ?? 'default'),
61
+ interval: parseDuration(as.interval ?? '5s', 'autoscale.interval'),
62
+ scaleUpAfter: parseDuration(as.scaleUpAfter ?? '10s', 'autoscale.scaleUpAfter'),
63
+ idleAfter: parseDuration(as.idleAfter ?? '5m', 'autoscale.idleAfter'),
64
+ bootTimeout: parseDuration(as.bootTimeout ?? '5m', 'autoscale.bootTimeout'),
65
+ maxWorkers: as.maxWorkers === undefined ? Infinity : Number(as.maxWorkers),
66
+ joinSecret: as.joinSecret ? String(as.joinSecret) : null,
67
+ };
68
+ if (!/^[A-Za-z0-9_.-]{1,40}$/.test(autoscale.id)) throw new Error('autoscale.id may use letters, digits, ".", "_" and "-" (40 characters at most)');
69
+ if (autoscale.interval < 100) throw new Error('autoscale.interval must be at least 100ms');
70
+ if (!(autoscale.maxWorkers >= 1)) throw new Error('autoscale.maxWorkers must be at least 1');
71
+
72
+ if (!Array.isArray(doc.pools) || !doc.pools.length) throw new Error('pools must list at least one pool');
73
+ const names = new Set();
74
+ const pools = doc.pools.map((p, i) => {
75
+ const where = `pools[${i}]`;
76
+ onlyKeys(p, POOL_KEYS, where);
77
+ if (typeof p.name !== 'string' || !/^[a-z0-9][a-z0-9-]{0,30}$/.test(p.name)) throw new Error(`${where}.name must be lowercase letters, digits and "-" (for example "batch-cloud")`);
78
+ if (names.has(p.name)) throw new Error(`${where}.name "${p.name}" is used twice`);
79
+ names.add(p.name);
80
+ if (!PROVIDERS.includes(p.provider)) throw new Error(`${where}.provider must be one of ${PROVIDERS.join(', ')}`);
81
+
82
+ const min = p.min === undefined ? 0 : Number(p.min);
83
+ const max = p.max === undefined ? Math.max(min, 1) : Number(p.max);
84
+ if (!Number.isInteger(min) || min < 0) throw new Error(`${where}.min must be a whole number, 0 or more`);
85
+ if (!Number.isInteger(max) || max < min) throw new Error(`${where}.max must be a whole number, not below min (0 retires a pool: its workers are removed when idle)`);
86
+
87
+ let kinds;
88
+ try {
89
+ kinds = normalizeKinds(p.kinds);
90
+ } catch (err) {
91
+ throw new Error(`${where}.kinds: ${err.message}`);
92
+ }
93
+ const slotsSpec = p.slots ?? 'auto';
94
+ let slots;
95
+ try {
96
+ slots = normalizeSlots(typeof slotsSpec === 'object' ? slotsSpec : String(slotsSpec), { kinds, cpus: 4 });
97
+ } catch (err) {
98
+ throw new Error(`${where}.slots: ${err.message}`);
99
+ }
100
+ const slotsText = typeof slotsSpec === 'object' ? Object.entries(slotsSpec).map(([k, v]) => `${k}=${v}`).join(',') : String(slotsSpec);
101
+ const isAuto = typeof slotsSpec === 'string' && slotsSpec.trim().startsWith('auto');
102
+
103
+ const provider = p[p.provider] ?? {};
104
+ onlyKeys(provider, PROVIDER_KEYS[p.provider], `${where}.${p.provider}`);
105
+ const wrongBlock = PROVIDERS.find(other => other !== p.provider && p[other] !== undefined);
106
+ if (wrongBlock) throw new Error(`${where}: has a "${wrongBlock}" block but its provider is ${p.provider}`);
107
+ if (p.provider === 'hetzner') {
108
+ for (const required of ['token', 'serverType']) if (!provider[required]) throw new Error(`${where}.hetzner.${required} is required`);
109
+ }
110
+ if (p.provider === 'docker' && !provider.network) throw new Error(`${where}.docker.network is required (the Docker network the orchestrator and the workers share)`);
111
+
112
+ const capabilities = (p.capabilities ?? []).map(String);
113
+ const poolEnv = Object.fromEntries(Object.entries(p.env ?? {}).map(([k, v]) => [k, String(v)]));
114
+ if (poolEnv.AWS_ACCESS_KEY_ID && poolEnv.AWS_SECRET_ACCESS_KEY && !capabilities.includes('scheme:s3')) capabilities.push('scheme:s3');
115
+
116
+ return {
117
+ name: p.name,
118
+ provider: p.provider,
119
+ min,
120
+ max,
121
+ kinds,
122
+ slots: slotsText,
123
+ slotsResolved: slots,
124
+ slotsAuto: isAuto,
125
+ slotsHint: p.slotsHint === undefined ? null : Number(p.slotsHint),
126
+ capabilities,
127
+ env: poolEnv,
128
+ maxConcurrentCreates: Number(p.maxConcurrentCreates ?? 2),
129
+ idleAfter: p.idleAfter === undefined ? null : parseDuration(p.idleAfter, `${where}.idleAfter`),
130
+ options: { workerImage: DEFAULT_WORKER_IMAGE, ...provider },
131
+ };
132
+ });
133
+
134
+ const publicUrl = doc.publicUrl ? String(doc.publicUrl).replace(/\/+$/, '') : null;
135
+ if (!publicUrl && pools.some(p => p.provider !== 'process')) throw new Error('publicUrl is required when a pool uses the docker or hetzner provider (the address new workers use to reach this orchestrator)');
136
+ return { publicUrl, autoscale, pools };
137
+ }
138
+
139
+ /** Reads and checks a config file; `.json` is parsed as JSON, anything else as YAML. */
140
+ export function loadConfig(path, env = process.env) {
141
+ const text = readFileSync(path, 'utf8');
142
+ let raw;
143
+ try {
144
+ raw = path.endsWith('.json') ? JSON.parse(text) : parseYaml(text);
145
+ } catch (err) {
146
+ throw new Error(`${path}: ${err.message}`);
147
+ }
148
+ try {
149
+ return normalizeConfig(raw, env);
150
+ } catch (err) {
151
+ throw new Error(`${path}: ${err.message}`);
152
+ }
153
+ }
154
+
155
+ export { KINDS };