import { d as defineEventHandler, c as createError, s as setResponseHeader, cj as getCacheService, eG as registry, E as dbQuery, eH as jobsByStatus, eA as loggerFor } from '../../nitro/nitro.mjs';
import { timingSafeEqual } from 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';

const log = loggerFor("routes.metrics");
function isAuthorized(event, expectedToken, allowPublic) {
  if (allowPublic) {
    return true;
  }
  if (!expectedToken) {
    return false;
  }
  const auth = event.node.req.headers.authorization;
  if (typeof auth !== "string" || !auth.startsWith("Bearer ")) {
    return false;
  }
  const provided = auth.slice("Bearer ".length).trim();
  if (provided.length === 0) {
    return false;
  }
  const a = Buffer.from(provided);
  const b = Buffer.from(expectedToken);
  if (a.length !== b.length) {
    return false;
  }
  return timingSafeEqual(a, b);
}
async function refreshQueueDepthGauge() {
  try {
    const rows = await dbQuery(
      "SELECT status, COUNT(*) as cnt FROM jobs GROUP BY status"
    );
    jobsByStatus.reset();
    for (const row of rows) {
      jobsByStatus.set({ status: row.status }, Number(row.cnt));
    }
  } catch (error) {
    log.warn(
      {
        err: error instanceof Error ? { message: error.message } : { message: String(error) }
      },
      "Failed to refresh job queue depth gauge"
    );
  }
}
const metrics_get = defineEventHandler(async (event) => {
  const expectedToken = process.env.METRICS_TOKEN;
  const allowPublic = process.env.METRICS_PUBLIC === "true";
  if (!expectedToken && !allowPublic) {
    throw createError({ statusCode: 404, statusMessage: "Not Found" });
  }
  if (!isAuthorized(event, expectedToken, allowPublic)) {
    setResponseHeader(event, "WWW-Authenticate", 'Bearer realm="metrics"');
    throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
  }
  await refreshQueueDepthGauge();
  await getCacheService().refreshMetrics();
  setResponseHeader(event, "Content-Type", registry.contentType);
  setResponseHeader(event, "Cache-Control", "no-store");
  return registry.metrics();
});

export { metrics_get as default };
//# sourceMappingURL=metrics.get.mjs.map
