File size: 20,149 Bytes
5c0175e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
// ---------------------------------------------------------------------------
// 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;
}