Luigit
repositories / Unfugwart

Unfugwart

Discord caretaker for Abteilung Unfug

owned by admin

telemetry.js

Raw
const clamp = value => Math.max(0, Math.min(100, value));

function parseValheim(telemetry, line, observedAt) {
  const update = /Update state \([^)]*\):\s*(verifying install|downloading).*?progress:\s*([\d.]+)(?:\s*\(\s*(\d+)\s*\/\s*(\d+)\s*\))?/i.exec(line);
  if (update) {
    const reported = Number(update[2]); const current = Number(update[3]); const total = Number(update[4]);
    return telemetry.set('updating', total > 0 ? clamp(current / total * 100) : Number.isFinite(reported) ? clamp(reported) : null, observedAt);
  }
  if (/Success!\s+App|Initialize engine version:/i.test(line)) {
    telemetry.state.readiness = false; telemetry.state.stopping = false;
    telemetry.state.players = null; telemetry.state.lastPlayerObservationAt = null;
    return telemetry.set('starting', null, observedAt);
  }
  if (/(?:ZNet\.LoadWorld:|ZDOMan\.LoadChunks|world\s+load|loading\s+world)/i.test(line)) { telemetry.state.players = null; telemetry.state.lastPlayerObservationAt = null; return telemetry.set('loading-world', null, observedAt); }
  if (/Game server connected/i.test(line) && !telemetry.state.stopping) return telemetry.set('ready', null, observedAt);
  if (/OnApplicationQuit|Shutting down|ZNet Shutdown|Stopping listening socket/i.test(line)) return telemetry.set('stopping', null, observedAt);
  const save = /\b(?:world\s+)?save\s*\(\s*(\d+)\s*\/\s*(\d+)\s*\)/i.exec(line);
  if (save) {
    const progress = Number(save[2]) > 0 ? clamp(Number(save[1]) / Number(save[2]) * 100) : null;
    if (Number(save[1]) === Number(save[2]) && /\bdone\b/i.test(line)) {
      return telemetry.set(telemetry.state.stopping ? 'stopping' : telemetry.state.readiness ? 'ready' : 'process-running', null, observedAt);
    }
    return telemetry.set('saving', progress, observedAt);
  }
  if (/(?:world\s+)?save(?:d| complete| finished)/i.test(line)) {
    if (telemetry.state.stopping) return telemetry.set('stopping', null, observedAt);
    if (telemetry.state.readiness) return telemetry.set('ready', null, observedAt);
    return;
  }
  const players = /^(?:\[[^\]]+\]\s*)?(?:(?:\d{1,2}\/\d{1,2}\/\d{4}\s+)?\d{2}:\d{2}:\d{2}:?\s+)?Connections\s+(\d+)\s+ZDOS:/i.exec(line);
  if (players) { telemetry.state.players = Number(players[1]); telemetry.state.lastPlayerObservationAt = observedAt; telemetry.state.updatedAt = observedAt; }
}

const gameParsers = { generic: () => {}, valheim: parseValheim };
export const GAME_TYPES = Object.freeze(Object.keys(gameParsers));

export class Telemetry {
  constructor({ game = 'generic', now = Date.now } = {}) {
    if (!GAME_TYPES.includes(game)) throw new Error('Unsupported game profile');
    this.game = game; this.readsConsole = game !== 'generic'; this.now = now;
    this.decoder = new TextDecoder(); this.partial = ''; this.state = this.empty();
  }
  empty() { return { status: 'offline', phase: 'offline', progress: null, updatedAt: null, lastPlayerObservationAt: null, players: null, readiness: false, stopping: false }; }
  reset({ status = 'offline' } = {}) {
    this.decoder = new TextDecoder(); this.partial = '';
    const phase = status === 'offline' ? 'offline' : status === 'unknown' ? 'unknown' : status === 'starting' ? 'not-ready' : 'process-running';
    this.state = { ...this.empty(), status, phase };
    return this.snapshot();
  }
  snapshot() { return { ...this.state }; }
  observe(status, observedAt = this.now()) {
    if (this.state.stopping && status !== 'offline') return this.snapshot();
    this.state.status = status; this.state.updatedAt = observedAt;
    if (status === 'offline') { this.state.phase = 'offline'; this.state.stopping = false; this.state.readiness = false; }
    else if (!this.state.readiness && (this.state.phase === 'offline' || this.state.phase === 'unknown')) this.state.phase = status === 'starting' ? 'not-ready' : 'process-running';
    return this.snapshot();
  }
  feed(bytes, observedAt = this.now()) { this.consume(this.decoder.decode(bytes, { stream: true }), observedAt); return this.snapshot(); }
  consume(text, observedAt) { const lines = (this.partial + text).split(/\r\n|\n|\r/); this.partial = lines.pop(); for (const line of lines) this.line(line, observedAt); }
  line(line, observedAt) { gameParsers[this.game](this, line, observedAt); }
  set(phase, progress, observedAt) {
    this.state.stopping = this.state.stopping || phase === 'stopping';
    this.state.status = this.state.stopping ? 'stopping' : 'running'; this.state.phase = phase; this.state.progress = progress; this.state.updatedAt = observedAt;
    if (phase === 'ready') this.state.readiness = true;
  }
}

export class PollController {
  constructor({ serverId, api, game = 'generic', telemetry = new Telemetry({ game }), intervalMs = 5_000, startupTimeoutMs = 15 * 60_000, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, onState = () => {}, onObservation = () => {} }) {
    Object.assign(this, { serverId, api, telemetry, intervalMs, startupTimeoutMs, now, setTimer, clearTimer, onState, onObservation });
    this.cursor = null; this.timer = null; this.polling = false; this.closed = false; this.startupUntil = 0; this.generation = 0;
  }
  state() { return { ...this.telemetry.snapshot(), game: this.telemetry.game, readsConsole: this.telemetry.readsConsole }; }
  async prepareStartup() {
    const generation = ++this.generation;
    this.startupUntil = this.now() + this.startupTimeoutMs;
    this.cursor = null; this.telemetry.reset({ status: 'starting' }); this.emit();
    if (!this.telemetry.readsConsole) return true;
    const console = await this.api.console(this.serverId, 0);
    if (this.closed || generation !== this.generation) return false;
    this.cursor = console.epoch;
    return true;
  }
  beginStartup() {
    this.startupUntil = this.now() + this.startupTimeoutMs;
    this.emit();
  }
  beginStop() {
    this.startupUntil = 0;
    this.telemetry.set('stopping', null, this.now());
    this.emit();
  }
  async start() { if (this.closed) return; await this.poll(); this.schedule(); }
  close() { this.closed = true; ++this.generation; if (this.timer !== null) this.clearTimer(this.timer); this.timer = null; }
  schedule() { if (this.closed || this.timer !== null) return; this.timer = this.setTimer(async () => { this.timer = null; await this.poll(); this.schedule(); }, this.intervalMs); }
  async poll() {
    if (this.closed || this.polling) return this.state();
    this.polling = true; const generation = this.generation;
    try {
      const observedAt = this.now(); const running = await this.api.status(this.serverId);
      if (this.closed || generation !== this.generation) return this.state();
      const startup = this.startupUntil > observedAt;
      if (!running && !startup) { this.cursor = null; this.telemetry.reset({ status: 'offline' }); this.emit(); return this.state(); }
      if (!this.telemetry.readsConsole) {
        this.telemetry.observe(running ? 'running' : 'starting', observedAt);
        this.telemetry.state.phase = this.telemetry.state.stopping ? 'stopping' : running ? 'process-running' : 'not-ready';
        if (!startup) this.startupUntil = 0;
        this.emit(); return this.state();
      }
      this.telemetry.observe(startup ? 'starting' : 'running', observedAt);
      const console = await this.api.console(this.serverId, this.cursor ?? 0);
      if (this.closed || generation !== this.generation) return this.state();
      if (this.cursor === null || console.epoch < this.cursor) { this.telemetry.reset({ status: running ? 'running' : 'starting' }); this.cursor = console.epoch; }
      else { this.telemetry.feed(console.logs, observedAt); this.cursor = console.epoch; }
      if (this.telemetry.state.readiness || !startup) this.startupUntil = 0;
      this.emit(); return this.state();
    } catch {
      if (!this.closed && generation === this.generation) { this.cursor = null; this.telemetry.reset({ status: 'unknown' }); this.emit(); }
      return this.state();
    } finally { this.polling = false; }
  }
  emit() { const state = this.state(); this.onState(state); this.onObservation(state); }
}