feat: add Sprite host keepalive to prevent auto-pause
- Add SpriteHostKeepalive (server/sprite-keepalive.ts) maintaining a lightweight heartbeat session per enabled Sprite host so Fly Sprites does not auto-pause and drop the Paseo relay connection - Wire keepalive into agent hooks, RPC handlers, and host connect/launch paths via onHostReady/onHostRemoved hooks - Reconcile every 30s against ~/.paseo/hosts.json enabled hosts with backoff reconnect; persist desired set to plugin-data - Add keepSpriteHostsAwake setting (default true) with settings UI toggle and live subscription
This commit is contained in:
1 parent
2ded63183b
commit
0b923ff019
6 files changed
+491
-3
No files matched your search
@@ -20,9 +20,15 @@ function errorMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
export interface SpriteAgentToolHooks {
|
||||
onHostReady?: (spriteName: string) => void;
|
||||
onHostRemoved?: (spriteName: string) => void;
|
||||
}
|
||||
|
||||
export function createSpriteAgentTools(
|
||||
manager: SpritesManager,
|
||||
_provider: FlySpritesProviderRegistration,
|
||||
hooks?: SpriteAgentToolHooks,
|
||||
): AgentToolDefinition[] {
|
||||
const spriteListTool = defineAgentTool({
|
||||
name: "sprite_list",
|
||||
@@ -123,6 +129,7 @@ export function createSpriteAgentTools(
|
||||
remoteDir: input.remoteDir,
|
||||
provider: input.provider,
|
||||
background: input.background,
|
||||
onHostReady: hooks?.onHostReady,
|
||||
});
|
||||
|
||||
let waitResult: unknown;
|
||||
@@ -366,6 +373,7 @@ export function createSpriteAgentTools(
|
||||
}),
|
||||
async execute(input, context) {
|
||||
try {
|
||||
hooks?.onHostRemoved?.(input.spriteName);
|
||||
await manager.deleteSprite(input.spriteName);
|
||||
await removeSpriteHostRegistration(context.paseo, input.spriteName).catch(() => undefined);
|
||||
return textResult(`Deleted sprite ${input.spriteName}.`, { spriteName: input.spriteName, deleted: true });
|
||||
|
||||
@@ -357,6 +357,7 @@ export async function ensureSpriteHost(options: {
|
||||
syncLocalPath?: string;
|
||||
remoteDir?: string;
|
||||
onProgress?: (phase: string, spriteName?: string) => void;
|
||||
onHostReady?: (spriteName: string) => void;
|
||||
}): Promise<{
|
||||
spriteName: string;
|
||||
serverId: string;
|
||||
@@ -378,6 +379,7 @@ export async function ensureSpriteHost(options: {
|
||||
const dir = await options.paseo.hosts.list();
|
||||
const existing = dir.hosts.find((h) => h.source.key === sourceKey);
|
||||
if (existing && existing.enabled && existing.status === "online" && existing.serverId) {
|
||||
options.onHostReady?.(sprite.name);
|
||||
return {
|
||||
spriteName: sprite.name,
|
||||
serverId: existing.serverId,
|
||||
@@ -410,6 +412,7 @@ export async function ensureSpriteHost(options: {
|
||||
});
|
||||
}
|
||||
invalidateSpriteHostsCache(options.paseo);
|
||||
options.onHostReady?.(sprite.name);
|
||||
|
||||
let online: HostSummary;
|
||||
if (registration.status === "online" && registration.serverId) {
|
||||
@@ -501,6 +504,7 @@ export async function launchSpriteAgent(options: {
|
||||
provider?: string;
|
||||
background?: boolean;
|
||||
onProgress?: (phase: string, spriteName?: string) => void;
|
||||
onHostReady?: (spriteName: string) => void;
|
||||
}): Promise<{
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
@@ -516,6 +520,7 @@ export async function launchSpriteAgent(options: {
|
||||
syncLocalPath: options.syncLocalPath,
|
||||
remoteDir: options.remoteDir,
|
||||
onProgress: options.onProgress,
|
||||
onHostReady: options.onHostReady,
|
||||
});
|
||||
|
||||
const progress = (phase: string) => options.onProgress?.(phase, host.spriteName);
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
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<typeof setTimeout> | 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<Set<string> | 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<string>();
|
||||
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<FlySpritesSettings>;
|
||||
private readonly desired = new Set<string>();
|
||||
private readonly entries = new Map<string, KeepaliveEntry>();
|
||||
private paseo: PaseoApi | null = null;
|
||||
private reconcileTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private reconcileInFlight = false;
|
||||
private lastReconcileAt = 0;
|
||||
private disposed = false;
|
||||
|
||||
constructor(
|
||||
manager: SpritesManager,
|
||||
getSettings: () => Promise<FlySpritesSettings>,
|
||||
) {
|
||||
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<void> {
|
||||
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<string> | null = null;
|
||||
if (this.paseo) {
|
||||
const dir = await Promise.race([
|
||||
this.paseo.hosts.list(),
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), 4_000)),
|
||||
]).catch(() => null);
|
||||
|
||||
if (dir) {
|
||||
nextDesired = new Set<string>();
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
const settings = await this.getSettings().catch(() => null);
|
||||
if (!settings?.keepSpriteHostsAwake) return;
|
||||
await this.startSession(spriteName);
|
||||
}
|
||||
|
||||
private async startSession(spriteName: string): Promise<void> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user