Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

2.5 KB
Raw Blame
import { NextResponse } from "next/server";
import path from "path";
import fs from "fs";
import { resolveDataDir } from "@/lib/dataPaths";
import {
  getAppLogRetentionDays,
  getCallLogRetentionDays,
  getCallLogsTableMaxRows,
  getProxyLogsTableMaxRows,
} from "@/lib/logEnv";
import { getDbBackupMaxFiles, getDbBackupRetentionDays } from "@/lib/db/backup";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";

/**
 * GET /api/storage/health — Return database storage information.
 * Provides: driver, dbPath, sizeBytes, lastBackupAt, retentionDays
 */
export async function GET() {
  try {
    const dataDir = resolveDataDir({});
    const dbFilePath = path.join(dataDir, "storage.sqlite");
    const backupsDir = path.join(dataDir, "db_backups");

    // Get DB file size
    let sizeBytes = 0;
    try {
      if (fs.existsSync(dbFilePath)) {
        const stat = fs.statSync(dbFilePath);
        sizeBytes = stat.size;
      }
    } catch {
      /* ignore */
    }

    // Get last backup info
    let lastBackupAt = null;
    let backupCount = 0;
    try {
      if (fs.existsSync(backupsDir)) {
        const files = fs
          .readdirSync(backupsDir)
          .filter((f) => f.startsWith("db_") && f.endsWith(".sqlite"))
          .sort()
          .reverse();
        backupCount = files.length;
        if (files.length > 0) {
          const latestStat = fs.statSync(path.join(backupsDir, files[0]));
          lastBackupAt = latestStat.mtime.toISOString();
        }
      }
    } catch {
      /* ignore */
    }

    // Get the display path (abbreviated with ~)
    const homeDir = process.env.HOME || process.env.USERPROFILE || "";
    const displayPath = dbFilePath.startsWith(homeDir)
      ? "~" + dbFilePath.slice(homeDir.length)
      : dbFilePath;

    return NextResponse.json({
      driver: "sqlite",
      dbPath: displayPath,
      sizeBytes,
      lastBackupAt,
      backupCount,
      retentionDays: {
        app: getAppLogRetentionDays(),
        call: getCallLogRetentionDays(),
      },
      tableMaxRows: {
        callLogs: getCallLogsTableMaxRows(),
        proxyLogs: getProxyLogsTableMaxRows(),
      },
      backupRetention: {
        maxFiles: getDbBackupMaxFiles(),
        days: getDbBackupRetentionDays(),
      },
      dataDir: dataDir.startsWith(homeDir) ? "~" + dataDir.slice(homeDir.length) : dataDir,
    });
  } catch (error) {
    console.error("[API] Error getting storage health:", error);
    return NextResponse.json({ error: sanitizeErrorMessage(error) }, { status: 500 });
  }
}