VR-MEDIA / src /lib /keepalive.ts
Zero124's picture
VR Media Server 2.0 β€” latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
20.1 kB
// ---------------------------------------------------------------------------
// KEEP-ALIVE SCHEDULER β€” runs INSIDE the server / Space (no external cron).
//
// Hugging Face pauses a Space after a window with no inbound HTTP traffic.
// This module runs an in-process cron inside the Next.js Node runtime that
// pings the Space's OWN PUBLIC URL, so the request travels back through HF's
// edge and counts as real inbound activity.
//
// Modes (all timezone-aware, using the user's preferred IANA timezone):
// interval β€” ping every N minutes, around the clock
// window β€” ping every N minutes, but only between two local wall-clock
// times (e.g. 07:00–01:00 in America/Los_Angeles)
// daily β€” ping at specific local times (e.g. 03:00 and 15:30)
//
// Config lives in the SQLite Setting table, so it survives restarts and is
// editable from Settings β†’ Keep-alive in the UI. Environment variables only
// provide the initial defaults.
//
// LIMITATION worth knowing: an in-process scheduler runs only while the
// container is running. It prevents sleep; it cannot WAKE an already-sleeping
// Space. Use `interval` mode with a period below HF's idle timeout to stay up,
// and keep the optional external cron as a cold-start safety net.
// ---------------------------------------------------------------------------
export type KeepAliveMode = "interval" | "window" | "daily";
export interface KeepAliveConfig {
/** Master switch. */
enabled: boolean;
mode: KeepAliveMode;
/** Used by `interval` and `window` modes. Clamped to 1–1440. */
intervalMinutes: number;
/** Local times for `daily` mode, as "HH:mm" strings. */
times: string[];
/** Local window bounds for `window` mode, as "HH:mm". May wrap midnight. */
windowStart: string;
windowEnd: string;
/** IANA timezone all times are interpreted in, e.g. "America/Los_Angeles". */
timeZone: string;
/** Path pinged on the public URL. */
targetPath: string;
}
export interface KeepAlivePing {
at: string;
url: string;
status: number | null;
ok: boolean;
durationMs: number;
error?: string;
trigger: "schedule" | "manual" | "startup";
}
export interface KeepAliveState {
running: boolean;
nextRunAt: string | null;
lastPing: KeepAlivePing | null;
history: KeepAlivePing[];
resolvedBaseUrl: string;
totalPings: number;
failedPings: number;
}
const SETTING_KEY = "keep_alive_config";
const STATE_KEY = "keep_alive_state";
const MAX_HISTORY = 25;
// ---------------------------------------------------------------------------
// Defaults
// ---------------------------------------------------------------------------
function envInt(name: string, fallback: number): number {
const raw = process.env[name];
if (!raw) return fallback;
const n = Number.parseInt(raw, 10);
return Number.isFinite(n) ? n : fallback;
}
/** "HH:mm" validation β€” also accepts "H:mm". */
export function isValidTime(value: string): boolean {
return /^([01]?\d|2[0-3]):[0-5]\d$/.test(value.trim());
}
export function normalizeTime(value: string): string {
const [h, m] = value.trim().split(":");
return `${String(Number.parseInt(h, 10)).padStart(2, "0")}:${m}`;
}
/** Is this a timezone the runtime actually understands? */
export function isValidTimeZone(tz: string): boolean {
if (!tz) return false;
try {
new Intl.DateTimeFormat("en-US", { timeZone: tz });
return true;
} catch {
return false;
}
}
export function getDefaultConfig(): KeepAliveConfig {
const envTz =
process.env.KEEP_ALIVE_TIMEZONE ||
process.env.TZ ||
"UTC";
const envTimes = (process.env.KEEP_ALIVE_TIMES || "03:00")
.split(",")
.map((t) => t.trim())
.filter((t) => isValidTime(t))
.map(normalizeTime);
const mode = (process.env.KEEP_ALIVE_MODE || "interval") as KeepAliveMode;
return {
enabled: (process.env.KEEP_ALIVE_ENABLED || "true") !== "false",
mode: ["interval", "window", "daily"].includes(mode) ? mode : "interval",
intervalMinutes: Math.min(1440, Math.max(1, envInt("KEEP_ALIVE_INTERVAL_MINUTES", 10))),
times: envTimes.length > 0 ? envTimes : ["03:00"],
windowStart: isValidTime(process.env.KEEP_ALIVE_WINDOW_START || "")
? normalizeTime(process.env.KEEP_ALIVE_WINDOW_START as string)
: "07:00",
windowEnd: isValidTime(process.env.KEEP_ALIVE_WINDOW_END || "")
? normalizeTime(process.env.KEEP_ALIVE_WINDOW_END as string)
: "01:00",
timeZone: isValidTimeZone(envTz) ? envTz : "UTC",
targetPath: process.env.KEEP_ALIVE_PATH || "/api/ping",
};
}
/** Coerce arbitrary JSON into a valid config, falling back field by field. */
export function sanitizeConfig(input: unknown, base = getDefaultConfig()): KeepAliveConfig {
const raw = (input ?? {}) as Partial<KeepAliveConfig>;
const mode: KeepAliveMode =
raw.mode && ["interval", "window", "daily"].includes(raw.mode) ? raw.mode : base.mode;
const times = Array.isArray(raw.times)
? raw.times.filter((t): t is string => typeof t === "string" && isValidTime(t)).map(normalizeTime)
: base.times;
const interval =
typeof raw.intervalMinutes === "number" && Number.isFinite(raw.intervalMinutes)
? Math.min(1440, Math.max(1, Math.round(raw.intervalMinutes)))
: base.intervalMinutes;
const tz = typeof raw.timeZone === "string" && isValidTimeZone(raw.timeZone) ? raw.timeZone : base.timeZone;
let targetPath = typeof raw.targetPath === "string" && raw.targetPath.trim() ? raw.targetPath.trim() : base.targetPath;
if (!targetPath.startsWith("/")) targetPath = `/${targetPath}`;
return {
enabled: typeof raw.enabled === "boolean" ? raw.enabled : base.enabled,
mode,
intervalMinutes: interval,
times: times.length > 0 ? Array.from(new Set(times)).sort() : base.times,
windowStart:
typeof raw.windowStart === "string" && isValidTime(raw.windowStart)
? normalizeTime(raw.windowStart)
: base.windowStart,
windowEnd:
typeof raw.windowEnd === "string" && isValidTime(raw.windowEnd)
? normalizeTime(raw.windowEnd)
: base.windowEnd,
timeZone: tz,
targetPath,
};
}
// ---------------------------------------------------------------------------
// Timezone helpers β€” pure Intl, no external dependencies
// ---------------------------------------------------------------------------
interface ZonedParts {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
}
function getZonedParts(date: Date, timeZone: string): ZonedParts {
const fmt = new Intl.DateTimeFormat("en-US", {
timeZone,
hour12: false,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
const out: Record<string, number> = {};
for (const part of fmt.formatToParts(date)) {
if (part.type !== "literal") out[part.type] = Number.parseInt(part.value, 10);
}
return {
year: out.year,
month: out.month,
day: out.day,
// Intl can emit hour 24 for midnight in some locales/zones.
hour: out.hour === 24 ? 0 : out.hour,
minute: out.minute,
second: out.second,
};
}
/** Offset (ms) of `timeZone` at the given instant. */
function zoneOffsetMs(date: Date, timeZone: string): number {
const p = getZonedParts(date, timeZone);
const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);
return asUtc - Math.floor(date.getTime() / 1000) * 1000;
}
/**
* Convert a local wall-clock time in `timeZone` to a UTC timestamp.
* Iterates twice so DST transitions resolve correctly.
*/
function zonedTimeToUtc(
year: number,
month: number,
day: number,
hour: number,
minute: number,
timeZone: string
): number {
const naive = Date.UTC(year, month - 1, day, hour, minute, 0);
let ts = naive - zoneOffsetMs(new Date(naive), timeZone);
ts = naive - zoneOffsetMs(new Date(ts), timeZone);
return ts;
}
function parseHHmm(value: string): { hour: number; minute: number } {
const [h, m] = value.split(":");
return { hour: Number.parseInt(h, 10), minute: Number.parseInt(m, 10) };
}
/** Minutes since local midnight. */
function minutesOfDay(value: string): number {
const { hour, minute } = parseHHmm(value);
return hour * 60 + minute;
}
/** Is `now` inside the local window? Handles windows that wrap midnight. */
export function isInsideWindow(config: KeepAliveConfig, now = new Date()): boolean {
const p = getZonedParts(now, config.timeZone);
const current = p.hour * 60 + p.minute;
const start = minutesOfDay(config.windowStart);
const end = minutesOfDay(config.windowEnd);
if (start === end) return true; // full day
if (start < end) return current >= start && current < end;
return current >= start || current < end; // wraps midnight
}
/**
* Next scheduled ping, as a UTC timestamp in ms.
* Returns null when the schedule is disabled or empty.
*/
export function computeNextRun(config: KeepAliveConfig, from = new Date()): number | null {
if (!config.enabled) return null;
const fromMs = from.getTime();
if (config.mode === "interval") {
return fromMs + config.intervalMinutes * 60_000;
}
if (config.mode === "window") {
const candidate = fromMs + config.intervalMinutes * 60_000;
if (isInsideWindow(config, new Date(candidate))) return candidate;
// Outside the window β€” wake up exactly at the next window start.
const p = getZonedParts(from, config.timeZone);
const { hour, minute } = parseHHmm(config.windowStart);
let next = zonedTimeToUtc(p.year, p.month, p.day, hour, minute, config.timeZone);
if (next <= fromMs) {
const tomorrow = new Date(fromMs + 24 * 3600_000);
const tp = getZonedParts(tomorrow, config.timeZone);
next = zonedTimeToUtc(tp.year, tp.month, tp.day, hour, minute, config.timeZone);
}
return next;
}
// daily β€” earliest upcoming local time across today and tomorrow
if (config.times.length === 0) return null;
const candidates: number[] = [];
for (const dayOffset of [0, 1]) {
const ref = new Date(fromMs + dayOffset * 24 * 3600_000);
const p = getZonedParts(ref, config.timeZone);
for (const time of config.times) {
const { hour, minute } = parseHHmm(time);
const ts = zonedTimeToUtc(p.year, p.month, p.day, hour, minute, config.timeZone);
if (ts > fromMs) candidates.push(ts);
}
}
if (candidates.length === 0) return null;
return Math.min(...candidates);
}
/** Format an instant in the configured timezone, for UI and logs. */
export function formatInZone(iso: string | number | Date, timeZone: string): string {
const date = typeof iso === "object" ? iso : new Date(iso);
try {
return new Intl.DateTimeFormat("en-CA", {
timeZone,
hour12: false,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
timeZoneName: "short",
}).format(date);
} catch {
return date.toISOString();
}
}
// ---------------------------------------------------------------------------
// Public base URL resolution
// ---------------------------------------------------------------------------
/**
* The URL to ping. Priority:
* PUBLIC_URL β†’ SPACE_HOST (HF injects it) β†’ SPACE_ID β†’ localhost fallback.
* Pinging the public host is what makes HF count the traffic as inbound;
* localhost still keeps the event loop warm but does not reset the idle timer.
*/
export function resolveBaseUrl(): string {
const explicit = process.env.PUBLIC_URL?.trim();
if (explicit) return explicit.replace(/\/+$/, "");
const spaceHost = process.env.SPACE_HOST?.trim();
if (spaceHost) {
const host = spaceHost.replace(/^https?:\/\//, "").replace(/\/+$/, "");
return "https://" + host;
}
const spaceId = process.env.SPACE_ID?.trim();
if (spaceId && spaceId.includes("/")) {
const [owner, name] = spaceId.split("/");
const slug = `${owner}-${name}`.toLowerCase().replace(/[^a-z0-9-]/g, "-");
return "https://" + slug + ".hf.space";
}
return "http://127.0.0.1:" + (process.env.PORT || "7860");
}
export function isPublicUrlResolved(): boolean {
return !resolveBaseUrl().includes("127.0.0.1");
}
// ---------------------------------------------------------------------------
// Persistence (SQLite Setting table β€” key/value, no schema change needed)
// ---------------------------------------------------------------------------
async function getDb() {
const { db } = await import("./db");
return db;
}
export async function loadConfig(): Promise<KeepAliveConfig> {
try {
const db = await getDb();
const row = await db.setting.findUnique({ where: { key: SETTING_KEY } });
if (!row?.value) return getDefaultConfig();
return sanitizeConfig(JSON.parse(row.value));
} catch {
// DB not ready (first boot) β€” use env defaults.
return getDefaultConfig();
}
}
export async function saveConfig(config: KeepAliveConfig): Promise<void> {
const db = await getDb();
const value = JSON.stringify(config);
await db.setting.upsert({
where: { key: SETTING_KEY },
update: { value },
create: { key: SETTING_KEY, value },
});
}
async function persistLastPing(ping: KeepAlivePing): Promise<void> {
try {
const db = await getDb();
const value = JSON.stringify(ping);
await db.setting.upsert({
where: { key: STATE_KEY },
update: { value },
create: { key: STATE_KEY, value },
});
} catch {
// Non-fatal β€” keep-alive must never crash the server.
}
}
async function loadLastPing(): Promise<KeepAlivePing | null> {
try {
const db = await getDb();
const row = await db.setting.findUnique({ where: { key: STATE_KEY } });
return row?.value ? (JSON.parse(row.value) as KeepAlivePing) : null;
} catch {
return null;
}
}
// ---------------------------------------------------------------------------
// The scheduler singleton
// ---------------------------------------------------------------------------
interface SchedulerRuntime {
timer: ReturnType<typeof setTimeout> | null;
config: KeepAliveConfig;
nextRunAt: number | null;
lastPing: KeepAlivePing | null;
history: KeepAlivePing[];
totalPings: number;
failedPings: number;
started: boolean;
}
// Survives Next.js hot reloads and module re-evaluation.
const globalForKeepAlive = globalThis as unknown as {
__vrmsKeepAlive?: SchedulerRuntime;
};
function runtime(): SchedulerRuntime {
if (!globalForKeepAlive.__vrmsKeepAlive) {
globalForKeepAlive.__vrmsKeepAlive = {
timer: null,
config: getDefaultConfig(),
nextRunAt: null,
lastPing: null,
history: [],
totalPings: 0,
failedPings: 0,
started: false,
};
}
return globalForKeepAlive.__vrmsKeepAlive;
}
function log(message: string): void {
console.log(`[keep-alive] ${message}`);
}
/** Fire one ping immediately. Never throws. */
export async function pingOnce(
trigger: KeepAlivePing["trigger"] = "manual"
): Promise<KeepAlivePing> {
const rt = runtime();
const url = `${resolveBaseUrl()}${rt.config.targetPath}`;
const startedAt = Date.now();
let ping: KeepAlivePing;
try {
const res = await fetch(url, {
method: "GET",
cache: "no-store",
headers: { "User-Agent": "VRMediaServer-KeepAlive/2.0" },
signal: AbortSignal.timeout(30_000),
});
ping = {
at: new Date(startedAt).toISOString(),
url,
status: res.status,
ok: res.ok,
durationMs: Date.now() - startedAt,
trigger,
};
} catch (err) {
ping = {
at: new Date(startedAt).toISOString(),
url,
status: null,
ok: false,
durationMs: Date.now() - startedAt,
error: err instanceof Error ? err.message : "unknown error",
trigger,
};
}
rt.lastPing = ping;
rt.history = [ping, ...rt.history].slice(0, MAX_HISTORY);
rt.totalPings += 1;
if (!ping.ok) rt.failedPings += 1;
log(
`${ping.ok ? "ok" : "FAIL"} ${ping.status ?? "-"} ${url} (${ping.durationMs}ms, ${trigger})` +
(ping.error ? ` β€” ${ping.error}` : "")
);
void persistLastPing(ping);
return ping;
}
function clearTimer(rt: SchedulerRuntime): void {
if (rt.timer) {
clearTimeout(rt.timer);
rt.timer = null;
}
rt.nextRunAt = null;
}
function scheduleNext(rt: SchedulerRuntime): void {
clearTimer(rt);
if (!rt.config.enabled) {
log("disabled β€” no pings scheduled");
return;
}
const next = computeNextRun(rt.config, new Date());
if (next === null) {
log("no upcoming run resolved β€” scheduler idle");
return;
}
rt.nextRunAt = next;
// setTimeout caps at ~24.8 days; our max gap is 24h so a direct delay is safe.
const delay = Math.max(1_000, next - Date.now());
rt.timer = setTimeout(() => {
void (async () => {
// `window` mode may fire on a boundary β€” re-check before pinging.
if (rt.config.mode !== "window" || isInsideWindow(rt.config)) {
await pingOnce("schedule");
}
scheduleNext(rt);
})();
}, delay);
// Do not hold the process open on shutdown.
(rt.timer as unknown as { unref?: () => void }).unref?.();
log(
`next ping ${formatInZone(next, rt.config.timeZone)} (${rt.config.timeZone}) β€” mode=${rt.config.mode}`
);
}
/**
* Start the scheduler. Idempotent β€” safe to call from instrumentation and
* from route handlers. Loads persisted config, then arms the timer.
*/
export async function startKeepAlive(): Promise<void> {
const rt = runtime();
if (rt.started) return;
rt.started = true;
rt.config = await loadConfig();
rt.lastPing = await loadLastPing();
const base = resolveBaseUrl();
log(`scheduler starting β€” base=${base} tz=${rt.config.timeZone} mode=${rt.config.mode}`);
if (!isPublicUrlResolved()) {
log(
"WARNING: public URL not resolved (no PUBLIC_URL / SPACE_HOST). " +
"Pinging localhost keeps the process warm but will NOT reset the Hugging Face idle timer. " +
"Set PUBLIC_URL to your Space URL."
);
}
scheduleNext(rt);
}
/** Replace the config, persist it, and re-arm the timer. */
export async function updateKeepAliveConfig(patch: unknown): Promise<KeepAliveConfig> {
const rt = runtime();
const current = rt.started ? rt.config : await loadConfig();
const next = sanitizeConfig(
{ ...current, ...((patch ?? {}) as Partial<KeepAliveConfig>) },
current
);
rt.config = next;
rt.started = true;
await saveConfig(next);
scheduleNext(rt);
return next;
}
/** Current config (from memory when armed, otherwise from the DB). */
export async function getKeepAliveConfig(): Promise<KeepAliveConfig> {
const rt = runtime();
if (rt.started) return rt.config;
return loadConfig();
}
/** Full status for the Settings UI. */
export async function getKeepAliveState(): Promise<KeepAliveState> {
const rt = runtime();
if (!rt.lastPing) rt.lastPing = await loadLastPing();
return {
running: Boolean(rt.timer),
nextRunAt: rt.nextRunAt ? new Date(rt.nextRunAt).toISOString() : null,
lastPing: rt.lastPing,
history: rt.history,
resolvedBaseUrl: resolveBaseUrl(),
totalPings: rt.totalPings,
failedPings: rt.failedPings,
};
}
/** Record inbound traffic seen by /api/ping (used for the "last seen" readout). */
export function noteInboundPing(): void {
const rt = runtime();
rt.totalPings += 0; // inbound hits are not counted as outbound pings
void rt;
}