mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 20:00:47 +00:00
refactor(api): implement caching for tunnel and version status endpoints
This commit is contained in:
@@ -1,11 +1,23 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getTunnelStatus, getTailscaleStatus, getDownloadStatus } from "@/lib/tunnel";
|
||||
|
||||
const STATUS_CACHE_TTL_MS = 3000; // coalesce rapid polls; underlying probes already cache 10s
|
||||
|
||||
// Survive hot reload; one cache per process. Only tunnel/tailscale probes are cached —
|
||||
// download progress stays live so the enable/download UI updates smoothly.
|
||||
const statusCache = (global.__tunnelStatusCache ??= { value: null, fetchedAt: 0 });
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const [tunnel, tailscale] = await Promise.all([getTunnelStatus(), getTailscaleStatus()]);
|
||||
let probes = statusCache.value;
|
||||
if (!probes || Date.now() - statusCache.fetchedAt >= STATUS_CACHE_TTL_MS) {
|
||||
const [tunnel, tailscale] = await Promise.all([getTunnelStatus(), getTailscaleStatus()]);
|
||||
probes = { tunnel, tailscale };
|
||||
statusCache.value = probes;
|
||||
statusCache.fetchedAt = Date.now();
|
||||
}
|
||||
const download = getDownloadStatus();
|
||||
return NextResponse.json({ tunnel, tailscale, download });
|
||||
return NextResponse.json({ ...probes, download });
|
||||
} catch (error) {
|
||||
console.error("Tunnel status error:", error);
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
@@ -2,6 +2,10 @@ import https from "https";
|
||||
import pkg from "../../../../package.json" with { type: "json" };
|
||||
|
||||
const NPM_PACKAGE_NAME = "9router";
|
||||
const VERSION_CACHE_TTL_MS = 3600000; // cache npm latest lookup for 1h
|
||||
|
||||
// Survive hot reload; one cache per process
|
||||
const versionCache = (global.__npmVersionCache ??= { value: null, fetchedAt: 0 });
|
||||
|
||||
// Fetch latest version from npm registry
|
||||
function fetchLatestVersion() {
|
||||
@@ -36,8 +40,20 @@ function compareVersions(a, b) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function getLatestVersionCached() {
|
||||
if (versionCache.value && Date.now() - versionCache.fetchedAt < VERSION_CACHE_TTL_MS) {
|
||||
return versionCache.value;
|
||||
}
|
||||
const latest = await fetchLatestVersion();
|
||||
if (latest) {
|
||||
versionCache.value = latest;
|
||||
versionCache.fetchedAt = Date.now();
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const latestVersion = await fetchLatestVersion();
|
||||
const latestVersion = await getLatestVersionCached();
|
||||
const currentVersion = pkg.version;
|
||||
const hasUpdate = latestVersion ? compareVersions(latestVersion, currentVersion) > 0 : false;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user