Luigit
repositories / Unfugwart

Unfugwart

Discord caretaker for Abteilung Unfug

owned by admin

lifecycle.js

Raw
const MAX_HOLD_MS = 60 * 60_000;

const success = () => ({ status: 'success' });
const cancelled = () => ({ status: 'cancelled' });

export class Lifecycle {
  constructor({ serverId, api, delayMs = 600_000, startupTimeoutMs = 15 * 60_000, setTimer = setTimeout, clearTimer = clearTimeout, now = Date.now, log = console, onState = () => {}, onBeforeStart = () => {}, onStart = () => {}, onStop = () => {} }) {
    Object.assign(this, { serverId, api, delayMs, startupTimeoutMs, setTimer, clearTimer, now, log, onState, onBeforeStart, onStart, onStop });
    this.known = false; this.humans = 0; this.timer = null; this.deadlineAt = null;
    this.holdTimer = null; this.holdUntil = null; this.startupUntil = null;
    this.generation = 0; this.holdGeneration = 0; this.chain = Promise.resolve(success());
    this.closed = false; this.desiredStart = false; this.stopping = false; this.stoppingGeneration = null; this.stopOverride = false; this.emptySinceStop = false; this.error = null;
  }

  state() { return { known: this.known, humans: this.humans, desiredStart: this.desiredStart, stopping: this.stopping, deadlineAt: this.deadlineAt, holdUntil: this.holdUntil, startupUntil: this.startupUntil, error: this.error }; }
  emit() { this.onState(this.state()); }

  reconcile({ known, humans }) {
    const wasEmpty = this.known && this.humans === 0;
    this.known = known; this.humans = humans;
    if (this.stopOverride && known && humans === 0) this.emptySinceStop = true;
    if (this.closed || !known) { this.invalidate(); return this.chain; }
    if (this.holding()) {
      this.desiredStart = true;
      this.emit();
      return this.chain;
    }
    if (humans > 0) {
      this.invalidate();
      if (this.stopOverride && !this.emptySinceStop) { this.desiredStart = false; this.emit(); return this.chain; }
      this.stopOverride = false;
      this.error = null;
      const generation = this.generation;
      this.desiredStart = true;
      this.emit();
      return this.enqueue(() => this.startIfStopped(generation, () => this.occupied(generation)));
    }
    if (!wasEmpty) this.invalidate();
    if (this.timer === null) {
      const generation = this.generation;
      this.deadlineAt = this.now() + this.delayMs;
      this.timer = this.setTimer(() => this.expire(generation), this.delayMs);
    }
    this.desiredStart = false;
    this.emit();
    return this.chain;
  }

  manualStart() {
    this.invalidate();
    this.stopOverride = false; this.emptySinceStop = false; this.stopping = false; this.startupUntil = null; this.error = null;
    if (this.known && this.humans === 0) this.armEmptyGrace();
    const generation = this.generation;
    this.desiredStart = true;
    this.emit();
    return this.enqueue(() => this.startIfStopped(generation, () => this.active(generation)));
  }

  keepAwake(durationMs = MAX_HOLD_MS) {
    const duration = Math.min(MAX_HOLD_MS, Math.max(0, Number(durationMs) || 0));
    this.invalidate();
    const generation = this.generation;
    const holdGeneration = ++this.holdGeneration;
    if (this.holdTimer !== null) this.clearTimer(this.holdTimer);
    this.holdUntil = this.now() + duration;
    this.holdTimer = this.setTimer(() => {
      if (holdGeneration !== this.holdGeneration || this.closed) return;
      this.holdTimer = null; this.holdUntil = null;
      void this.reconcile({ known: this.known, humans: this.humans });
    }, duration);
    this.desiredStart = true; this.error = null; this.emit();
    return this.enqueue(() => this.startIfStopped(generation, () => this.active(generation)));
  }

  confirmedStop() {
    this.invalidate();
    if (this.holdTimer !== null) this.clearTimer(this.holdTimer);
    this.holdTimer = null; this.holdUntil = null; ++this.holdGeneration;
    const generation = this.generation;
    this.desiredStart = false; this.stopping = true; this.stoppingGeneration = generation; this.stopOverride = true; this.emptySinceStop = this.known && this.humans === 0; this.startupUntil = null; this.error = null;
    this.emit();
    return this.enqueue(() => this.stopIfRunning(generation, () => this.active(generation)));
  }

  observeTelemetry(telemetry) {
    if (telemetry?.phase === 'ready' || telemetry?.readiness) this.startupUntil = null;
    if (this.stopping && telemetry?.status === 'offline' && telemetry?.phase === 'offline') this.stopping = false;
    this.emit();
  }

  expire(generation) {
    if (generation !== this.generation || this.timer === null || this.holding()) return;
    this.timer = null; this.deadlineAt = null; this.stopping = true; this.stoppingGeneration = generation; this.emit();
    void this.enqueue(() => this.stopIfRunning(generation, () => this.current(generation)));
  }

  cancelStop(generation) {
    if (this.stoppingGeneration === generation) {
      this.stopping = false; this.stoppingGeneration = null; this.emit();
    }
    return cancelled();
  }

  async stopIfRunning(generation, valid) {
    if (!valid()) return this.cancelStop(generation);
    if (!await this.api.status(this.serverId)) { this.cancelStop(generation); return success(); }
    if (!valid()) return this.cancelStop(generation);
    const result = await this.api.stop(this.serverId, valid);
    if (result === null) return this.cancelStop(generation);
    await this.onStop();
    return success();
  }

  async startIfStopped(generation, valid) {
    if (!valid()) return cancelled();
    if (await this.api.status(this.serverId)) return valid() ? success() : cancelled();
    if (!valid() || this.starting()) return cancelled();
    const preparation = this.onBeforeStart();
    if (preparation?.then) await preparation;
    if (!valid()) return cancelled();
    const result = await this.api.start(this.serverId, valid);
    if (result === null || !valid()) return cancelled();
    this.startupUntil = this.now() + this.startupTimeoutMs;
    this.emit();
    const completed = this.onStart();
    if (completed?.then) await completed;
    return success();
  }

  armEmptyGrace() {
    if (this.timer !== null) this.clearTimer(this.timer);
    const generation = this.generation;
    this.deadlineAt = this.now() + this.delayMs;
    this.timer = this.setTimer(() => this.expire(generation), this.delayMs);
  }
  holding() { return this.holdUntil !== null && this.holdUntil > this.now(); }
  starting() { return this.startupUntil !== null && this.startupUntil > this.now(); }
  active(generation) { return !this.closed && generation === this.generation; }
  current(generation) { return this.active(generation) && this.known && this.humans === 0 && !this.holding(); }
  occupied(generation) { return this.active(generation) && this.known && this.humans > 0; }
  invalidate() { this.generation += 1; if (this.timer !== null) this.clearTimer(this.timer); this.timer = null; this.deadlineAt = null; this.emit(); }
  close() { this.closed = true; this.invalidate(); if (this.holdTimer !== null) this.clearTimer(this.holdTimer); this.holdTimer = null; this.holdUntil = null; }

  enqueue(action) {
    const run = this.chain.then(async () => {
      try { return await action(); }
      catch (error) {
        this.error = 'request-failed';
        if (this.stoppingGeneration === this.generation) { this.stopping = false; this.stoppingGeneration = null; }
        this.emit();
        this.log.error(`PufferPanel lifecycle ${this.serverId}: request failed`);
        return { status: 'failure' };
      }
    });
    this.chain = run;
    return run;
  }
}