fffleet-orchestrator 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.
@@ -1,7 +1,12 @@
1
1
  import { readFileSync } from 'node:fs';
2
+ import { createAutoscaler } from './autoscaler.js';
3
+ import { createProviders } from './providers/index.js';
2
4
  import { randomUUID } from 'node:crypto';
3
- import { FleetError, JobRecord, byPriority, canonicalJson, followJobEvents, normalizeSlots, parseSpec, pruneFinished, satisfies } from 'fffleet';
4
- import { checkBearer, close, createApiHandler, listen, readJson, send, sendError } from 'fffleet/server';
5
+ import { FleetError, JobRecord, byPriority, canonicalJson, followJobEvents, implicitRequirements, normalizeKinds, normalizeSlots, parseSpec, pruneFinished, satisfies } from 'fffleet';
6
+ import {
7
+ Registry, allowed, checkBearer, close, createApiHandler, createAuthenticator, createClientStore, createTokenSigner, createTokenVerifier,
8
+ bearerOf, getStream, issueToken, jobMetrics, listen, loadSigningKey, processMetrics, readBody, readJson, send, sendError,
9
+ } from 'fffleet/server';
5
10
 
6
11
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
7
12
  const REDISPATCH_DELAY_MS = 500;
@@ -16,7 +21,14 @@ const REDISPATCH_DELAY_MS = 500;
16
21
  * @param {object} [opts]
17
22
  * @param {number} [opts.port]
18
23
  * @param {string} [opts.host]
19
- * @param {string | null} [opts.token] Bearer token for clients.
24
+ * @param {string | null} [opts.token] Static bearer token with full (admin) access.
25
+ * @param {string | object[] | null} [opts.clients] Apps that may log in: a clients file path, or a list of { id, secretHash, scopes }.
26
+ * @param {import('node:crypto').KeyObject | string | null} [opts.signingKey] Ed25519 key for tokens (KeyObject or PEM).
27
+ * @param {string | null} [opts.signingKeyFile] Where the signing key is kept; created when missing. Without it tokens die with the process.
28
+ * @param {number} [opts.tokenTtlSeconds]
29
+ * @param {{ publicUrl: string | null, autoscale: object, pools: object[] } | null} [opts.scaling] Where to start more workers (see loadConfig). Without it the pool is whatever registers.
30
+ * @param {Record<string, object>} [opts.providers] Provider instances by pool name, replacing the built-in ones (tests).
31
+ * @param {Buffer | string | null} [opts.joinKey] Key the workers' join secrets derive from. Default: the signing key's file contents, else random.
20
32
  * @param {string | null} [opts.workerToken] Bearer token workers register with; also sent to workers.
21
33
  * @param {number} [opts.heartbeatTimeoutMs] A worker silent this long is dropped and its jobs fail.
22
34
  * @param {number} [opts.sweepMs]
@@ -30,6 +42,13 @@ export function createOrchestrator({
30
42
  port = 5000,
31
43
  host = '0.0.0.0',
32
44
  token = null,
45
+ clients = null,
46
+ signingKey = null,
47
+ signingKeyFile = null,
48
+ tokenTtlSeconds = 3600,
49
+ scaling = null,
50
+ providers: providerOverrides = {},
51
+ joinKey = null,
33
52
  workerToken = null,
34
53
  heartbeatTimeoutMs = 15000,
35
54
  sweepMs = 1000,
@@ -50,13 +69,73 @@ export function createOrchestrator({
50
69
  let sweeper = null;
51
70
  let pumpTimer = null;
52
71
 
72
+ // The key the workers' join secrets derive from: stable across restarts only when the signing key is a file.
73
+ const signingKeyBytes = () => {
74
+ try {
75
+ return signingKeyFile ? readFileSync(signingKeyFile) : null;
76
+ } catch {
77
+ return null;
78
+ }
79
+ };
80
+ const clientStore = createClientStore(clients);
81
+ const signer = createTokenSigner({ privateKey: signingKey ?? loadSigningKey(signingKeyFile), ttlSeconds: tokenTtlSeconds });
82
+ const authenticate = createAuthenticator({
83
+ token,
84
+ verify: clientStore ? createTokenVerifier({ getKey: kid => (kid === signer.kid ? signer.publicKey : null) }) : null,
85
+ isActive: sub => clientStore?.has(sub) ?? false,
86
+ });
87
+
88
+ let autoscaler = null;
89
+ const registry = new Registry();
90
+ processMetrics(registry);
91
+ const jobStats = jobMetrics(registry, () => jobs.values());
92
+ const m = {
93
+ info: registry.gauge('fffleet_build_info', 'Version of this fffleet process.', ['role', 'version']),
94
+ workerSlots: registry.gauge('fffleet_worker_slots', 'Slots per worker and pool.', ['worker', 'pool']),
95
+ workerUsed: registry.gauge('fffleet_worker_slots_used', 'Slots in use per worker and pool.', ['worker', 'pool']),
96
+ workerAge: registry.gauge('fffleet_worker_heartbeat_age_seconds', 'Seconds since the worker last registered or sent a heartbeat.', ['worker']),
97
+ workerDraining: registry.gauge('fffleet_worker_draining', '1 while the worker is drained.', ['worker']),
98
+ workerCooldown: registry.gauge('fffleet_worker_cooldown', '1 while the worker gets no new jobs after a failed dispatch.', ['worker']),
99
+ workers: registry.gauge('fffleet_workers', 'Registered workers.'),
100
+ queued: registry.gauge('fffleet_queue_length', 'Jobs waiting for a worker, by class.', ['class']),
101
+ dispatchFailures: registry.counter('fffleet_dispatch_failures_total', 'Dispatches a worker did not accept.', ['worker', 'reason']),
102
+ workersLost: registry.counter('fffleet_workers_lost_total', 'Workers dropped after missing their heartbeats.'),
103
+ tokensIssued: registry.counter('fffleet_auth_tokens_issued_total', 'Tokens issued, by client.', ['client']),
104
+ loginFailures: registry.counter('fffleet_auth_login_failures_total', 'Token requests refused, by OAuth2 error.', ['error']),
105
+ };
106
+ m.info.set({ role: 'orchestrator', version: VERSION }, 1);
107
+ const scaleMetrics = {
108
+ instances: registry.gauge('fffleet_autoscaler_instances', 'Workers the autoscaler manages, by pool and state.', ['pool', 'state']),
109
+ creates: registry.counter('fffleet_autoscaler_creates_total', 'Workers the autoscaler tried to start.', ['pool', 'result']),
110
+ destroys: registry.counter('fffleet_autoscaler_destroys_total', 'Workers the autoscaler removed, by reason.', ['pool', 'reason']),
111
+ };
112
+ registry.collect(() => {
113
+ for (const g of [m.workerSlots, m.workerUsed, m.workerAge, m.workerDraining, m.workerCooldown, m.queued]) g.reset();
114
+ const now = Date.now();
115
+ for (const w of workers.values()) {
116
+ for (const [pool, total] of Object.entries(w.slots)) {
117
+ m.workerSlots.set({ worker: w.id, pool }, total);
118
+ m.workerUsed.set({ worker: w.id, pool }, w.used[pool] ?? 0);
119
+ }
120
+ m.workerAge.set({ worker: w.id }, (now - w.lastSeen) / 1000);
121
+ m.workerDraining.set({ worker: w.id }, w.draining ? 1 : 0);
122
+ m.workerCooldown.set({ worker: w.id }, w.cooldownUntil > now ? 1 : 0);
123
+ }
124
+ m.workers.set({}, workers.size);
125
+ for (const job of queue) m.queued.inc({ class: job.spec.class });
126
+ });
127
+
53
128
  /**
54
- * @typedef {{ id: string, url: string, slots: Record<string, number>, used: Record<string, number>,
129
+ * @typedef {{ id: string, url: string, slots: Record<string, number>, used: Record<string, number>, kinds: string[], token: string | null,
55
130
  * capabilities: Set<string>, version: string | null, lastSeen: number, draining: boolean, cooldownUntil: number, jobs: Set<string> }} Worker
56
131
  * @typedef {JobRecord & { worker?: Worker | null, pool?: string, follow?: AbortController, assignedAt?: number, released?: boolean }} Job
57
132
  */
58
133
 
59
- const workerHeaders = (extra = {}) => ({ ...extra, ...(workerToken ? { authorization: `Bearer ${workerToken}` } : {}) });
134
+ // A worker is called with the token it registered with: the shared worker token, or its own join secret.
135
+ const workerHeaders = (worker, extra = {}) => {
136
+ const t = worker?.token ?? workerToken;
137
+ return { ...extra, ...(t ? { authorization: `Bearer ${t}` } : {}) };
138
+ };
60
139
 
61
140
  function poolFor(worker, cls) {
62
141
  return worker.slots[cls] !== undefined ? cls : 'default';
@@ -64,10 +143,11 @@ export function createOrchestrator({
64
143
 
65
144
  function fits(worker, job) {
66
145
  if (worker.draining || worker.cooldownUntil > Date.now()) return false;
146
+ if (!worker.kinds.includes(job.spec.kind)) return false;
67
147
  const pool = poolFor(worker, job.spec.class);
68
148
  const total = worker.slots[pool] ?? 0;
69
149
  return total > 0 && (worker.used[pool] ?? 0) < total
70
- && worker.capabilities.has(`type:${job.spec.type}`) && satisfies(worker.capabilities, job.spec.requires);
150
+ && satisfies(worker.capabilities, implicitRequirements(job.spec)) && satisfies(worker.capabilities, job.spec.requires);
71
151
  }
72
152
 
73
153
  function load(worker) {
@@ -112,22 +192,25 @@ export function createOrchestrator({
112
192
  try {
113
193
  res = await fetch(`${worker.url}/v1/jobs`, {
114
194
  method: 'POST',
115
- headers: workerHeaders({ 'content-type': 'application/json' }),
195
+ headers: workerHeaders(worker, { 'content-type': 'application/json' }),
116
196
  body: JSON.stringify(job.spec),
117
197
  signal: AbortSignal.timeout(10000),
118
198
  });
119
199
  } catch (err) {
120
200
  log(`dispatch of ${job.id} to ${worker.id} failed: ${err.message}; dropping the worker until it re-registers`);
201
+ m.dispatchFailures.inc({ worker: worker.id, reason: 'unreachable' });
121
202
  return redispatch(job, worker);
122
203
  }
123
204
  if (job.final) return release(job); // cancelled while dispatching; the cancel already reached the worker or will be ignored
124
205
  if (res.status >= 500) {
125
206
  log(`worker ${worker.id} answered ${res.status} for ${job.id}; trying elsewhere`);
126
207
  worker.cooldownUntil = Date.now() + dispatchCooldownMs;
208
+ m.dispatchFailures.inc({ worker: worker.id, reason: 'server_error' });
127
209
  return redispatch(job, worker, false);
128
210
  }
129
211
  if (!res.ok) {
130
212
  const body = await res.json().catch(() => null);
213
+ m.dispatchFailures.inc({ worker: worker.id, reason: 'rejected' });
131
214
  job.push({ state: 'failed', error: { code: 'DISPATCH_REJECTED', message: `worker ${worker.id} rejected the job: ${body?.error?.message ?? `HTTP ${res.status}`}` } });
132
215
  return release(job);
133
216
  }
@@ -149,7 +232,7 @@ export function createOrchestrator({
149
232
  job.follow = ac;
150
233
  followJobEvents({
151
234
  url: `${worker.url}/v1/jobs/${encodeURIComponent(job.id)}/events`,
152
- headers: workerHeaders(),
235
+ headers: () => workerHeaders(worker),
153
236
  signal: ac.signal,
154
237
  maxRetries: 3,
155
238
  onEvent: e => {
@@ -194,7 +277,7 @@ export function createOrchestrator({
194
277
  log(`worker ${worker.id} removed${reason ? `: ${reason.message}` : ''}`);
195
278
  }
196
279
 
197
- function register(body) {
280
+ function register(body, bearer = null) {
198
281
  if (!body || typeof body.id !== 'string' || !body.id || typeof body.url !== 'string') {
199
282
  throw new FleetError('INVALID_WORKER', 'register needs id and url', { status: 400 });
200
283
  }
@@ -204,15 +287,23 @@ export function createOrchestrator({
204
287
  } catch (err) {
205
288
  throw new FleetError('INVALID_WORKER', err.message, { status: 400 });
206
289
  }
290
+ let kinds;
291
+ try {
292
+ kinds = normalizeKinds(body.kinds);
293
+ } catch (err) {
294
+ throw new FleetError('INVALID_WORKER', err.message, { status: 400 });
295
+ }
207
296
  const now = Date.now();
208
297
  let worker = workers.get(body.id);
209
298
  if (!worker) {
210
- worker = { id: body.id, url: '', slots, used: {}, capabilities: new Set(), version: null, lastSeen: now, draining: false, cooldownUntil: 0, jobs: new Set() };
299
+ worker = { id: body.id, url: '', slots, used: {}, kinds, token: null, capabilities: new Set(), version: null, lastSeen: now, draining: false, cooldownUntil: 0, jobs: new Set() };
211
300
  workers.set(body.id, worker);
212
301
  log(`worker ${body.id} joined at ${body.url} with slots ${JSON.stringify(slots)}`);
213
302
  }
214
303
  worker.url = body.url.replace(/\/+$/, '');
215
304
  worker.slots = slots;
305
+ worker.kinds = kinds;
306
+ worker.token = bearer;
216
307
  worker.capabilities = new Set(Array.isArray(body.capabilities) ? body.capabilities : []);
217
308
  worker.version = body.version ?? null;
218
309
  worker.lastSeen = now;
@@ -235,6 +326,7 @@ export function createOrchestrator({
235
326
  const now = Date.now();
236
327
  for (const worker of [...workers.values()]) {
237
328
  if (now - worker.lastSeen > heartbeatTimeoutMs) {
329
+ m.workersLost.inc();
238
330
  removeWorker(worker, { code: 'WORKER_LOST', message: `worker ${worker.id} missed its heartbeats` });
239
331
  }
240
332
  }
@@ -256,6 +348,7 @@ export function createOrchestrator({
256
348
  pruneFinished(jobs, keepFinished);
257
349
  const job = /** @type {Job} */ (new JobRecord(spec));
258
350
  jobs.set(spec.id, job);
351
+ jobStats.track(job);
259
352
  enqueue(job);
260
353
  pump();
261
354
  return { created: true, queued: queue.includes(job), job: job.snapshot() };
@@ -279,7 +372,7 @@ export function createOrchestrator({
279
372
  }
280
373
  const worker = job.worker;
281
374
  try {
282
- const res = await fetch(`${worker.url}/v1/jobs/${encodeURIComponent(id)}`, { method: 'DELETE', headers: workerHeaders(), signal: AbortSignal.timeout(5000) });
375
+ const res = await fetch(`${worker.url}/v1/jobs/${encodeURIComponent(id)}`, { method: 'DELETE', headers: workerHeaders(worker), signal: AbortSignal.timeout(5000) });
283
376
  if (!res.ok && res.status !== 404) throw new Error(`HTTP ${res.status}`);
284
377
  if (res.status === 404) throw new Error('worker does not know the job');
285
378
  } catch (err) {
@@ -295,7 +388,7 @@ export function createOrchestrator({
295
388
  if (job.final || !job.worker || job.state === 'queued') throw new FleetError('NOT_RUNNING', 'job is not running', { status: 409 });
296
389
  const res = await fetch(`${job.worker.url}/v1/jobs/${encodeURIComponent(id)}/stdin`, {
297
390
  method: 'POST',
298
- headers: workerHeaders({ 'content-type': 'application/octet-stream' }),
391
+ headers: workerHeaders(job.worker, { 'content-type': 'application/octet-stream' }),
299
392
  body: data,
300
393
  signal: AbortSignal.timeout(5000),
301
394
  });
@@ -303,6 +396,28 @@ export function createOrchestrator({
303
396
  if (!res.ok) throw new FleetError(body?.error?.code ?? 'STDIN_FAILED', body?.error?.message ?? `HTTP ${res.status}`, { status: res.status });
304
397
  return { bytes: body?.bytes ?? data.length };
305
398
  },
399
+ async closeStdin(id) {
400
+ const job = jobs.get(id);
401
+ if (!job) throw new FleetError('NOT_FOUND', `job ${id} not found`, { status: 404 });
402
+ if (job.final || !job.worker || job.state === 'queued') throw new FleetError('NOT_RUNNING', 'job is not running', { status: 409 });
403
+ const res = await fetch(`${job.worker.url}/v1/jobs/${encodeURIComponent(id)}/stdin/close`, { method: 'POST', headers: workerHeaders(job.worker), signal: AbortSignal.timeout(5000) });
404
+ const body = await res.json().catch(() => null);
405
+ if (!res.ok) throw new FleetError(body?.error?.code ?? 'STDIN_FAILED', body?.error?.message ?? `HTTP ${res.status}`, { status: res.status });
406
+ return { closed: true };
407
+ },
408
+ /** Streams a running job's stdout from its worker; waits while the job is still queued. */
409
+ async openStdout(id) {
410
+ const job = jobs.get(id);
411
+ if (!job) throw new FleetError('NOT_FOUND', `job ${id} not found`, { status: 404 });
412
+ if (!job.spec.stdout) throw new FleetError('NO_STDOUT', 'job was not started with stdout: true', { status: 409 });
413
+ const deadline = Date.now() + 60_000;
414
+ while (!job.worker || job.state === 'queued') {
415
+ if (job.final) throw new FleetError('NOT_RUNNING', 'job ended before it started', { status: 409 });
416
+ if (Date.now() > deadline) throw new FleetError('NOT_RUNNING', 'job did not start in time', { status: 409 });
417
+ await new Promise(r => setTimeout(r, 100));
418
+ }
419
+ return getStream(`${job.worker.url}/v1/jobs/${encodeURIComponent(id)}/stdout`, { headers: workerHeaders(job.worker) });
420
+ },
306
421
  capabilities() {
307
422
  const pools = {};
308
423
  const caps = new Set();
@@ -318,25 +433,61 @@ export function createOrchestrator({
318
433
  },
319
434
  };
320
435
 
321
- async function extraRoutes(req, res, reqUrl) {
322
- if (reqUrl.pathname === '/v1/workers/register' && req.method === 'POST') {
323
- if (!checkBearer(req, workerToken)) {
324
- send(res, 401, { error: { code: 'UNAUTHORIZED', message: 'missing or wrong worker token' } });
325
- return true;
436
+ async function extraRoutes(req, res, reqUrl, who) {
437
+ const path = reqUrl.pathname;
438
+ if (path === '/v1/auth/token' && req.method === 'POST') {
439
+ const raw = (await readBody(req, 64 * 1024)).toString('utf8');
440
+ const json = (req.headers['content-type'] ?? '').includes('application/json');
441
+ let body;
442
+ try {
443
+ body = json ? JSON.parse(raw || '{}') : new URLSearchParams(raw);
444
+ } catch {
445
+ body = {};
326
446
  }
447
+ const out = await issueToken({ req, body, clients: clientStore, signer });
448
+ if (out.status === 200) m.tokensIssued.inc({ client: out.body.access_token && JSON.parse(Buffer.from(out.body.access_token.split('.')[1], 'base64url')).sub });
449
+ else m.loginFailures.inc({ error: out.body.error });
450
+ send(res, out.status, out.body, out.headers);
451
+ return true;
452
+ }
453
+ if (path === '/v1/auth/keys' && req.method === 'GET') {
454
+ // Public keys are public: workers fetch them to check tokens without holding a secret.
455
+ send(res, 200, signer.jwks(), { 'cache-control': 'max-age=300' });
456
+ return true;
457
+ }
458
+ if (path === '/v1/workers/register' && req.method === 'POST') {
327
459
  try {
328
- send(res, 200, register(await readJson(req)));
460
+ const body = await readJson(req);
461
+ const given = bearerOf(req);
462
+ // The shared worker token, or the join secret of a worker this orchestrator started itself.
463
+ const ok = checkBearer(req, workerToken) || (given && body && autoscaler?.acceptsJoin(body.id, given));
464
+ if (!ok) {
465
+ send(res, 401, { error: { code: 'UNAUTHORIZED', message: 'missing or wrong worker token' } });
466
+ return true;
467
+ }
468
+ send(res, 200, register(body, given));
329
469
  } catch (err) {
330
470
  sendError(res, err);
331
471
  }
332
472
  return true;
333
473
  }
334
- const drain = reqUrl.pathname.match(/^\/v1\/workers\/([^/]+)\/drain$/);
335
- if ((reqUrl.pathname === '/v1/workers' && req.method === 'GET') || (drain && req.method === 'POST')) {
336
- if (!checkBearer(req, token)) {
337
- send(res, 401, { error: { code: 'UNAUTHORIZED', message: 'missing or wrong bearer token' } });
338
- return true;
474
+ if (path === '/v1/sd/prometheus' && req.method === 'GET') {
475
+ // Prometheus HTTP service discovery: one target per worker, scraped at its /metrics.
476
+ if (allowed(res, who, 'metrics')) {
477
+ send(res, 200, [...workers.values()].map(w => {
478
+ const u = new URL(w.url);
479
+ return { targets: [u.host], labels: { __scheme__: u.protocol.slice(0, -1), __metrics_path__: `${u.pathname.replace(/\/+$/, '')}/metrics`, fffleet_worker: w.id } };
480
+ }));
339
481
  }
482
+ return true;
483
+ }
484
+ if (path === '/v1/pools' && req.method === 'GET') {
485
+ if (allowed(res, who, 'admin')) send(res, 200, autoscaler ? autoscaler.describe() : { pools: [] });
486
+ return true;
487
+ }
488
+ const drain = path.match(/^\/v1\/workers\/([^/]+)\/drain$/);
489
+ if ((path === '/v1/workers' && req.method === 'GET') || (drain && req.method === 'POST')) {
490
+ if (!allowed(res, who, 'admin')) return true;
340
491
  if (drain) {
341
492
  const worker = workers.get(decodeURIComponent(drain[1]));
342
493
  if (!worker) send(res, 404, { error: { code: 'NOT_FOUND', message: 'worker not found' } });
@@ -353,23 +504,55 @@ export function createOrchestrator({
353
504
  }
354
505
 
355
506
  function describe(w) {
356
- return { id: w.id, url: w.url, slots: w.slots, used: w.used, draining: w.draining, version: w.version, lastSeen: new Date(w.lastSeen).toISOString(), jobs: [...w.jobs], capabilityCount: w.capabilities.size };
507
+ return { id: w.id, url: w.url, slots: w.slots, kinds: w.kinds, used: w.used, draining: w.draining, version: w.version, lastSeen: new Date(w.lastSeen).toISOString(), jobs: [...w.jobs], capabilityCount: w.capabilities.size };
357
508
  }
358
509
 
359
510
  return {
360
511
  backend,
361
512
  workers,
513
+ registry,
514
+ signer,
515
+ get autoscaler() {
516
+ return autoscaler;
517
+ },
362
518
  get url() {
363
519
  return url;
364
520
  },
365
521
  async start() {
366
- ({ server, url } = await listen(createApiHandler({ backend, token, extraRoutes }), { port, host }));
522
+ ({ server, url } = await listen(createApiHandler({ backend, authenticate, metrics: () => registry.render(), extraRoutes }), { port, host }));
523
+ if (!token && !clientStore) log('no FFFLEET_TOKEN and no clients file: the job API is open to anyone who can reach it');
367
524
  sweeper = setInterval(sweep, sweepMs);
368
525
  sweeper.unref?.();
369
526
  log(`fffleet-orchestrator listening on ${url}`);
527
+ if (scaling) {
528
+ const view = {
529
+ queue: () => queue.map(j => ({ id: j.id, spec: j.spec, waitedMs: Date.now() - Date.parse(j.createdAt) })),
530
+ workers: () => workers.values(),
531
+ drain: id => {
532
+ const w = workers.get(id);
533
+ if (w) w.draining = true;
534
+ },
535
+ forget: id => {
536
+ const w = workers.get(id);
537
+ if (w) removeWorker(w, { code: 'WORKER_REMOVED', message: `worker ${id} was removed by the autoscaler` });
538
+ },
539
+ publicUrl: () => scaling.publicUrl ?? url,
540
+ };
541
+ const providers = createProviders(scaling, { onExit: id => autoscaler?.exited(id), log, overrides: providerOverrides });
542
+ autoscaler = createAutoscaler({
543
+ config: scaling,
544
+ providers,
545
+ view,
546
+ joinKey: joinKey ?? scaling.autoscale.joinSecret ?? signingKeyBytes() ?? undefined,
547
+ log: msg => log(msg),
548
+ metrics: scaleMetrics,
549
+ });
550
+ await autoscaler.start();
551
+ }
370
552
  return this;
371
553
  },
372
554
  async stop() {
555
+ await autoscaler?.stop();
373
556
  clearInterval(sweeper);
374
557
  clearTimeout(pumpTimer);
375
558
  for (const job of jobs.values()) job.follow?.abort();
@@ -0,0 +1,118 @@
1
+ // Docker containers as workers, through the Docker Engine API (a unix socket or tcp://host:port).
2
+
3
+ import { request } from 'node:http';
4
+
5
+ /**
6
+ * Starts each worker as a container on a Docker network that the orchestrator shares, and reaches it
7
+ * there by container name.
8
+ *
9
+ * @param {object} opts
10
+ * @param {object} opts.pool The normalized pool.
11
+ * @param {(msg: string) => void} [opts.log]
12
+ * @param {(opts: { socketPath?: string, host?: string, port?: number, method: string, path: string, body?: object }) => Promise<{ status: number, body: any }>} [opts.call] For tests.
13
+ */
14
+ export function createDockerProvider({ pool, log = () => {}, call = engineCall }) {
15
+ const o = pool.options;
16
+ const target = dockerTarget(o.socket ?? process.env.DOCKER_HOST);
17
+ const image = o.image ?? o.workerImage;
18
+ const port = Number(o.port ?? 5100);
19
+ const api = (method, path, body) => call({ ...target, method, path, body });
20
+ const encodeId = id => encodeURIComponent(id);
21
+
22
+ async function pull() {
23
+ const [name, tag = 'latest'] = splitImage(image);
24
+ log(`docker: pulling ${image}`);
25
+ const res = await api('POST', `/images/create?fromImage=${encodeURIComponent(name)}&tag=${encodeURIComponent(tag)}`);
26
+ if (res.status >= 300) throw new Error(`could not pull ${image}: HTTP ${res.status} ${errorText(res.body)}`);
27
+ }
28
+
29
+ return {
30
+ name: 'docker',
31
+ billing: null,
32
+
33
+ async list(orchestratorId) {
34
+ const filters = JSON.stringify({ label: [`fffleet.orchestrator=${orchestratorId}`, `fffleet.pool=${pool.name}`] });
35
+ const res = await api('GET', `/containers/json?all=true&filters=${encodeURIComponent(filters)}`);
36
+ if (res.status !== 200) throw new Error(`docker list failed: HTTP ${res.status} ${errorText(res.body)}`);
37
+ return res.body
38
+ .filter(c => c.Labels?.['fffleet.worker'])
39
+ .map(c => ({ providerId: c.Id, workerId: c.Labels['fffleet.worker'], pool: pool.name, createdAt: (c.Created ?? 0) * 1000 }));
40
+ },
41
+
42
+ async create({ workerId, env, labels }) {
43
+ const body = {
44
+ Image: image,
45
+ Env: Object.entries({ ...env, PORT: String(port), HOST: '0.0.0.0', FFFLEET_ADVERTISE_URL: `http://${workerId}:${port}` }).map(([k, v]) => `${k}=${v}`),
46
+ Labels: labels,
47
+ ExposedPorts: { [`${port}/tcp`]: {} },
48
+ HostConfig: {
49
+ NetworkMode: o.network,
50
+ RestartPolicy: { Name: 'no' },
51
+ ...(o.cpus ? { NanoCpus: Math.round(Number(o.cpus) * 1e9) } : {}),
52
+ ...(o.memory ? { Memory: Number(o.memory) } : {}),
53
+ },
54
+ };
55
+ let res = await api('POST', `/containers/create?name=${encodeURIComponent(workerId)}`, body);
56
+ if (res.status === 404 && o.pull !== false) {
57
+ await pull();
58
+ res = await api('POST', `/containers/create?name=${encodeURIComponent(workerId)}`, body);
59
+ }
60
+ if (res.status !== 201) throw new Error(`docker create failed: HTTP ${res.status} ${errorText(res.body)}`);
61
+ const id = res.body.Id;
62
+ const started = await api('POST', `/containers/${encodeId(id)}/start`);
63
+ if (started.status >= 300 && started.status !== 304) {
64
+ await api('DELETE', `/containers/${encodeId(id)}?force=true`).catch(() => {});
65
+ throw new Error(`docker start failed: HTTP ${started.status} ${errorText(started.body)}`);
66
+ }
67
+ return { providerId: id };
68
+ },
69
+
70
+ async destroy(providerId) {
71
+ const res = await api('DELETE', `/containers/${encodeId(providerId)}?force=true&v=true`);
72
+ if (res.status >= 300 && res.status !== 404) throw new Error(`docker remove failed: HTTP ${res.status} ${errorText(res.body)}`);
73
+ },
74
+ };
75
+ }
76
+
77
+ const errorText = body => (typeof body === 'string' ? body : body?.message ?? '').slice(0, 200);
78
+
79
+ function splitImage(image) {
80
+ const at = image.lastIndexOf(':');
81
+ return at > image.lastIndexOf('/') ? [image.slice(0, at), image.slice(at + 1)] : [image, 'latest'];
82
+ }
83
+
84
+ /** A unix socket path, "unix:///path", or "tcp://host:port". */
85
+ export function dockerTarget(spec) {
86
+ if (!spec) return { socketPath: '/var/run/docker.sock' };
87
+ if (spec.startsWith('tcp://') || spec.startsWith('http://')) {
88
+ const u = new URL(spec.replace(/^tcp:/, 'http:'));
89
+ return { host: u.hostname, port: Number(u.port || 2375) };
90
+ }
91
+ return { socketPath: spec.replace(/^unix:\/\//, '') };
92
+ }
93
+
94
+ function engineCall({ socketPath, host, port, method, path, body }) {
95
+ return new Promise((resolve, reject) => {
96
+ const payload = body ? JSON.stringify(body) : null;
97
+ const req = request(
98
+ { socketPath, host, port, method, path, headers: { host: 'docker', ...(payload ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) } : {}) } },
99
+ res => {
100
+ const chunks = [];
101
+ res.on('data', c => chunks.push(c));
102
+ res.on('end', () => {
103
+ const text = Buffer.concat(chunks).toString('utf8');
104
+ let parsed = text;
105
+ try {
106
+ parsed = text ? JSON.parse(text) : null;
107
+ } catch {
108
+ // image pulls stream several JSON documents; the text is enough
109
+ }
110
+ resolve({ status: res.statusCode ?? 0, body: parsed });
111
+ });
112
+ },
113
+ );
114
+ req.setTimeout(10 * 60 * 1000, () => req.destroy(new Error('docker request timed out')));
115
+ req.once('error', reject);
116
+ req.end(payload);
117
+ });
118
+ }
@@ -0,0 +1,125 @@
1
+ // Hetzner Cloud servers as workers. Talks to the Cloud API (https://docs.hetzner.cloud) with fetch.
2
+
3
+ const API = 'https://api.hetzner.cloud/v1';
4
+ const HOUR = 3600000;
5
+
6
+ /**
7
+ * One provider per hetzner pool, so each pool keeps its own token, server type and labels.
8
+ *
9
+ * @param {object} opts
10
+ * @param {object} opts.pool The normalized pool (see normalizeConfig).
11
+ * @param {typeof fetch} [opts.fetch]
12
+ * @param {(msg: string) => void} [opts.log]
13
+ * @param {number} [opts.retryDelayMs] First delay when the API answers 429 or 5xx (doubles each try).
14
+ */
15
+ export function createHetznerProvider({ pool, fetch: f = globalThis.fetch, log = () => {}, retryDelayMs = 1000 }) {
16
+ const o = pool.options;
17
+ const base = (o.baseUrl ?? API).replace(/\/+$/, '');
18
+
19
+ async function api(method, path, body) {
20
+ for (let attempt = 0; ; attempt++) {
21
+ const res = await f(`${base}${path}`, {
22
+ method,
23
+ headers: { authorization: `Bearer ${o.token}`, ...(body ? { 'content-type': 'application/json' } : {}) },
24
+ body: body ? JSON.stringify(body) : undefined,
25
+ signal: AbortSignal.timeout(30000),
26
+ });
27
+ if ((res.status === 429 || res.status >= 500) && attempt < 3) {
28
+ const wait = Number(res.headers.get('retry-after')) * 1000 || retryDelayMs * 2 ** attempt;
29
+ log(`hetzner: ${method} ${path} answered ${res.status}; retrying in ${Math.round(wait / 100) / 10}s`);
30
+ await new Promise(r => setTimeout(r, wait));
31
+ continue;
32
+ }
33
+ const text = await res.text();
34
+ const json = text ? JSON.parse(text) : null;
35
+ if (!res.ok) {
36
+ const e = new Error(`Hetzner ${method} ${path} failed: HTTP ${res.status} ${json?.error?.code ?? ''} ${json?.error?.message ?? ''}`.trim());
37
+ e.status = res.status;
38
+ throw e;
39
+ }
40
+ return json;
41
+ }
42
+ }
43
+
44
+ return {
45
+ name: 'hetzner',
46
+ // Hetzner bills by the hour, so an idle server is kept until shortly before its hour is up.
47
+ billing: o.alignToBillingHour === false ? null : { alignMs: HOUR, windowMs: 5 * 60000 },
48
+
49
+ /** Servers of this pool that belong to the given orchestrator. */
50
+ async list(orchestratorId) {
51
+ const out = [];
52
+ for (let page = 1; page; ) {
53
+ const q = new URLSearchParams({ label_selector: `fffleet.orchestrator=${orchestratorId},fffleet.pool=${pool.name}`, per_page: '50', page: String(page) });
54
+ const res = await api('GET', `/servers?${q}`);
55
+ for (const s of res.servers ?? []) {
56
+ out.push({ providerId: String(s.id), workerId: s.labels?.['fffleet.worker'], pool: pool.name, createdAt: Date.parse(s.created) || Date.now() });
57
+ }
58
+ page = res.meta?.pagination?.next_page ?? 0;
59
+ }
60
+ return out.filter(s => s.workerId);
61
+ },
62
+
63
+ async create({ workerId, env, labels }) {
64
+ const body = {
65
+ name: `fffleet-${workerId}`,
66
+ server_type: o.serverType,
67
+ image: o.image ?? 'docker-ce',
68
+ ...(o.location ? { location: o.location } : {}),
69
+ ...(o.sshKeys?.length ? { ssh_keys: o.sshKeys } : {}),
70
+ ...(o.network ? { networks: [Number(o.network)] } : {}),
71
+ ...(o.firewalls?.length ? { firewalls: o.firewalls.map(id => ({ firewall: Number(id) })) } : {}),
72
+ labels,
73
+ user_data: cloudInit({ env, options: o }),
74
+ start_after_create: true,
75
+ automount: false,
76
+ };
77
+ const res = await api('POST', '/servers', body);
78
+ return { providerId: String(res.server.id) };
79
+ },
80
+
81
+ async destroy(providerId) {
82
+ try {
83
+ await api('DELETE', `/servers/${providerId}`);
84
+ } catch (err) {
85
+ if (err.status !== 404) throw err; // already gone
86
+ }
87
+ },
88
+ };
89
+ }
90
+
91
+ /**
92
+ * The cloud-init document a new server runs: it writes the worker's settings to a file readable only
93
+ * by root, works out its own address, and starts the worker image with Docker.
94
+ */
95
+ export function cloudInit({ env, options }) {
96
+ const port = Number(options.port ?? 5100);
97
+ const advertise = options.advertise ?? 'public';
98
+ const image = options.workerImage;
99
+ const metadata = 'http://169.254.169.254/hetzner/v1/metadata';
100
+ const addressCmd = advertise === 'private'
101
+ ? `curl -s --retry 10 --retry-connrefused ${metadata}/private-networks | grep -m1 -oE 'ip: [0-9.]+' | cut -d' ' -f2`
102
+ : `curl -s --retry 10 --retry-connrefused ${metadata}/public-ipv4`;
103
+ const envFile = Object.entries({ ...env, PORT: String(port), HOST: '0.0.0.0' }).map(([k, v]) => {
104
+ if (/[\r\n]/.test(v)) throw new Error(`environment variable ${k} cannot contain a line break`);
105
+ return `${k}=${v}`;
106
+ });
107
+ const login = options.registry
108
+ ? [`echo '${shellQuote(options.registry.password)}' | docker login ${options.registry.server ?? 'ghcr.io'} -u '${shellQuote(options.registry.username)}' --password-stdin`]
109
+ : [];
110
+ const lines = [
111
+ '#cloud-config',
112
+ 'write_files:',
113
+ ' - path: /etc/fffleet/worker.env',
114
+ " permissions: '0600'",
115
+ ' content: |',
116
+ ...envFile.map(l => ` ${l}`),
117
+ 'runcmd:',
118
+ ` - [ sh, -c, ${JSON.stringify(`IP=$(${addressCmd}); echo "FFFLEET_ADVERTISE_URL=http://$IP:${port}" >> /etc/fffleet/worker.env`)} ]`,
119
+ ...login.map(c => ` - [ sh, -c, ${JSON.stringify(c)} ]`),
120
+ ` - [ sh, -c, ${JSON.stringify(`docker run -d --name fffleet-worker --restart unless-stopped --env-file /etc/fffleet/worker.env -p ${port}:${port} ${(options.extraRunArgs ?? []).join(' ')} ${image}`.replace(/\s+/g, ' '))} ]`,
121
+ ];
122
+ return `${lines.join('\n')}\n`;
123
+ }
124
+
125
+ const shellQuote = s => String(s).replace(/'/g, "'\\''");
@@ -0,0 +1,21 @@
1
+ import { createDockerProvider } from './docker.js';
2
+ import { createHetznerProvider } from './hetzner.js';
3
+ import { createProcessProvider } from './process.js';
4
+
5
+ /**
6
+ * One provider per pool, keyed by pool name.
7
+ * @param {{ pools: any[] }} config
8
+ * @param {{ onExit?: (workerId: string, code: number | null) => void, log?: (msg: string) => void, fetch?: typeof fetch, overrides?: Record<string, any> }} [opts]
9
+ */
10
+ export function createProviders(config, { onExit, log, fetch, overrides = {} } = {}) {
11
+ const out = {};
12
+ for (const pool of config.pools) {
13
+ if (overrides[pool.name]) out[pool.name] = overrides[pool.name];
14
+ else if (pool.provider === 'process') out[pool.name] = createProcessProvider({ onExit, log });
15
+ else if (pool.provider === 'docker') out[pool.name] = createDockerProvider({ pool, log });
16
+ else out[pool.name] = createHetznerProvider({ pool, log, fetch });
17
+ }
18
+ return out;
19
+ }
20
+
21
+ export { createDockerProvider, createHetznerProvider, createProcessProvider };