import { mkdir, readFile, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; import type { SpriteCommand } from "@fly/sprites"; import type { PaseoApi } from "@getpaseo/client"; import type { FlySpritesSettings } from "../shared/settings"; import { getHostSpriteName, isSpriteHost } from "./sprite-hosts"; import { sanitizeSpriteName, type SpritesManager } from "./sprites-manager"; interface KeepaliveEntry { spriteName: string; cmd: SpriteCommand | null; startedAt: number; starting: boolean; retryCount: number; reconnectTimer: ReturnType | null; } const RECONCILE_INTERVAL_MS = 30_000; const HEARTBEAT_SCRIPT = "while true; do printf '.\\n'; sleep 10; done"; const BACKOFF_STEPS_MS = [2_000, 4_000, 8_000, 15_000, 30_000]; function unrefTimer(timer: unknown): void { if ( timer && typeof timer === "object" && "unref" in timer && typeof (timer as { unref?: unknown }).unref === "function" ) { (timer as { unref(): void }).unref(); } } function paseoHomeDir(): string { return process.env.PASEO_HOME || path.join(homedir(), ".paseo"); } function stateFilePath(): string { return path.join(paseoHomeDir(), "plugin-data", "fly-sprites-workers", "keepalive-hosts.json"); } function paseoHostsFilePath(): string { return path.join(paseoHomeDir(), "hosts.json"); } function errMsg(error: unknown): string { return error instanceof Error ? error.message : String(error); } function isNotFoundError(message: string): boolean { return /\b404\b|not found/i.test(message); } function isAuthError(message: string): boolean { return /\b401\b|authentication failed|unauthorized/i.test(message); } async function readEnabledSpriteHostsFromDisk(): Promise | null> { try { const raw = await readFile(paseoHostsFilePath(), "utf8"); const parsed = JSON.parse(raw); const list = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" && Array.isArray((parsed as { hosts?: unknown }).hosts) ? (parsed as { hosts: unknown[] }).hosts : null; if (!list) return null; const names = new Set(); for (const item of list) { if (!item || typeof item !== "object") continue; const host = item as { enabled?: unknown; source?: { key?: unknown }; metadata?: { provider?: unknown; spriteName?: unknown }; label?: unknown; }; if (host.enabled === false) continue; const sourceKey = typeof host.source?.key === "string" ? host.source.key : ""; const provider = typeof host.metadata?.provider === "string" ? host.metadata.provider : ""; if (!sourceKey.startsWith("fly-sprite:") && provider !== "fly-sprites") continue; const rawName = (typeof host.metadata?.spriteName === "string" && host.metadata.spriteName.trim()) || (sourceKey.startsWith("fly-sprite:") ? sourceKey.slice("fly-sprite:".length) : "") || (typeof host.label === "string" ? host.label.trim() : ""); const normalized = sanitizeSpriteName(rawName); if (normalized) names.add(normalized); } return names; } catch { return null; } } export class SpriteHostKeepalive { private readonly manager: SpritesManager; private readonly getSettings: () => Promise; private readonly desired = new Set(); private readonly entries = new Map(); private paseo: PaseoApi | null = null; private reconcileTimer: ReturnType | null = null; private reconcileInFlight = false; private lastReconcileAt = 0; private disposed = false; constructor( manager: SpritesManager, getSettings: () => Promise, ) { this.manager = manager; this.getSettings = getSettings; } start(): void { if (this.disposed) return; void this.loadPersistedAndStart(); if (!this.reconcileTimer) { this.reconcileTimer = setInterval(() => { void this.reconcile(); }, RECONCILE_INTERVAL_MS); unrefTimer(this.reconcileTimer); } } attachPaseo(paseo: PaseoApi): void { if (this.disposed) return; const isFirstAttach = this.paseo === null; this.paseo = paseo; if (isFirstAttach || Date.now() - this.lastReconcileAt > 15_000) { void this.reconcile(); } } keepAwake(spriteName: string): void { if (this.disposed) return; const normalized = sanitizeSpriteName(spriteName); if (!normalized) return; const added = !this.desired.has(normalized); this.desired.add(normalized); if (added) { void this.savePersisted(); } void this.ensureStartedIfEnabled(normalized); } release(spriteName: string): void { const normalized = sanitizeSpriteName(spriteName); if (!normalized) return; const removed = this.desired.delete(normalized); if (removed) { void this.savePersisted(); } this.stopSession(normalized); } onSettingsChanged(keepAwake: boolean): void { if (this.disposed) return; if (!keepAwake) { for (const name of [...this.entries.keys()]) { this.stopSession(name); } return; } for (const name of this.desired) { void this.startSession(name); } void this.reconcile(); } async reconcile(): Promise { if (this.disposed || this.reconcileInFlight) return; this.reconcileInFlight = true; this.lastReconcileAt = Date.now(); try { const settings = await this.getSettings(); if (!settings.keepSpriteHostsAwake) { for (const name of [...this.entries.keys()]) { this.stopSession(name); } return; } let nextDesired: Set | null = null; if (this.paseo) { const dir = await Promise.race([ this.paseo.hosts.list(), new Promise((resolve) => setTimeout(() => resolve(null), 4_000)), ]).catch(() => null); if (dir) { nextDesired = new Set(); for (const host of dir.hosts) { if (isSpriteHost(host) && host.enabled) { const name = sanitizeSpriteName(getHostSpriteName(host)); if (name) nextDesired.add(name); } } } } else { nextDesired = await readEnabledSpriteHostsFromDisk(); } if (nextDesired) { let changed = nextDesired.size !== this.desired.size; if (!changed) { for (const name of nextDesired) { if (!this.desired.has(name)) { changed = true; break; } } } for (const existing of [...this.desired]) { if (!nextDesired.has(existing)) { this.desired.delete(existing); this.stopSession(existing); } } for (const name of nextDesired) { this.desired.add(name); } if (changed) { void this.savePersisted(); } } for (const name of this.desired) { const entry = this.entries.get(name); if (!entry || (!entry.cmd && !entry.starting && !entry.reconnectTimer)) { void this.startSession(name); } } } finally { this.reconcileInFlight = false; } } dispose(): void { this.disposed = true; if (this.reconcileTimer) { clearInterval(this.reconcileTimer); this.reconcileTimer = null; } for (const name of [...this.entries.keys()]) { this.stopSession(name); } this.entries.clear(); } private async loadPersistedAndStart(): Promise { const diskHosts = await readEnabledSpriteHostsFromDisk(); if (diskHosts) { for (const name of diskHosts) { this.desired.add(name); } if (diskHosts.size > 0) { void this.savePersisted(); } } else { try { const raw = await readFile(stateFilePath(), "utf8"); const parsed = JSON.parse(raw) as { hosts?: unknown }; if (Array.isArray(parsed.hosts)) { for (const item of parsed.hosts) { if (typeof item === "string" && item.trim()) { this.desired.add(sanitizeSpriteName(item.trim())); } } } } catch { // No persisted keepalive hosts yet. } } if (this.disposed || this.desired.size === 0) return; const settings = await this.getSettings().catch(() => null); if (!settings?.keepSpriteHostsAwake) return; for (const name of this.desired) { void this.startSession(name); } } private async savePersisted(): Promise { try { const file = stateFilePath(); await mkdir(path.dirname(file), { recursive: true }); const payload = JSON.stringify({ hosts: [...this.desired].sort() }, null, 2); await writeFile(file, payload, "utf8"); } catch { // Non-fatal persistence error. } } private async ensureStartedIfEnabled(spriteName: string): Promise { const settings = await this.getSettings().catch(() => null); if (!settings?.keepSpriteHostsAwake) return; await this.startSession(spriteName); } private async startSession(spriteName: string): Promise { if (this.disposed || !this.desired.has(spriteName)) return; let entry = this.entries.get(spriteName); if (!entry) { entry = { spriteName, cmd: null, startedAt: 0, starting: false, retryCount: 0, reconnectTimer: null, }; this.entries.set(spriteName, entry); } if (entry.starting || entry.cmd) return; if (entry.reconnectTimer) { clearTimeout(entry.reconnectTimer); entry.reconnectTimer = null; } entry.starting = true; try { const { client } = await this.manager.getClient(); if (this.disposed || !this.desired.has(spriteName)) { entry.starting = false; return; } const sprite = client.sprite(spriteName); const cmd = sprite.spawn("bash", ["-c", HEARTBEAT_SCRIPT]); entry.cmd = cmd; entry.startedAt = Date.now(); entry.starting = false; let settled = false; const handleDisconnect = (reason: string) => { if (settled) return; settled = true; if (entry!.cmd === cmd) { entry!.cmd = null; } try { cmd.close(); } catch { // Ignore close errors. } if (this.disposed || !this.desired.has(spriteName)) return; if (isNotFoundError(reason)) { console.warn(`[fly-sprites] keepalive(${spriteName}) stopped: ${reason}`); return; } if (isAuthError(reason)) { void this.manager.clearExchangedTokenCache().catch(() => undefined); } const aliveMs = Date.now() - entry!.startedAt; if (aliveMs > 20_000) { entry!.retryCount = 0; } const delayMs = BACKOFF_STEPS_MS[Math.min(entry!.retryCount, BACKOFF_STEPS_MS.length - 1)]; entry!.retryCount += 1; console.warn( `[fly-sprites] keepalive(${spriteName}) disconnected (${reason}); reconnecting in ${delayMs}ms`, ); entry!.reconnectTimer = setTimeout(() => { if (entry) entry.reconnectTimer = null; void this.ensureStartedIfEnabled(spriteName); }, delayMs); unrefTimer(entry!.reconnectTimer); }; cmd.on("spawn", () => { console.log(`[fly-sprites] keepalive(${spriteName}) active`); }); cmd.stdout.on("data", () => { if (entry && Date.now() - entry.startedAt > 15_000) { entry.retryCount = 0; } }); cmd.stderr.on("data", () => { // Drain stderr so buffers never stall. }); cmd.on("error", (err: unknown) => { handleDisconnect(errMsg(err)); }); cmd.on("exit", (code: number) => { handleDisconnect(`exit ${code}`); }); } catch (error) { entry.starting = false; if (this.disposed || !this.desired.has(spriteName)) return; const reason = errMsg(error); if (isNotFoundError(reason)) return; const delayMs = BACKOFF_STEPS_MS[Math.min(entry.retryCount, BACKOFF_STEPS_MS.length - 1)]; entry.retryCount += 1; console.warn( `[fly-sprites] keepalive(${spriteName}) failed to start (${reason}); retrying in ${delayMs}ms`, ); entry.reconnectTimer = setTimeout(() => { if (entry) entry.reconnectTimer = null; void this.ensureStartedIfEnabled(spriteName); }, delayMs); unrefTimer(entry.reconnectTimer); } } private stopSession(spriteName: string): void { const entry = this.entries.get(spriteName); if (!entry) return; if (entry.reconnectTimer) { clearTimeout(entry.reconnectTimer); entry.reconnectTimer = null; } if (entry.cmd) { const cmd = entry.cmd; entry.cmd = null; try { cmd.kill("SIGTERM"); cmd.close(); } catch { // Ignore already-closed handles. } console.log(`[fly-sprites] keepalive(${spriteName}) stopped`); } this.entries.delete(spriteName); } }