import { describe, it, expect, beforeEach, vi } from "vitest"; import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@hivegrid/metrics"; import { startMetricsScheduler } from "./metrics-scheduler.js"; let registry: MetricsRegistry; let metrics: DefaultMetrics; beforeEach(() => { registry = createMetricsRegistry({ serviceName: "worker-test", collectDefaultProcessMetrics: false }); metrics = createDefaultMetrics(registry); }); describe("startMetricsScheduler", () => { it("schedules both pollers at the configured cadence", () => { const setIntervalCalls: Array<{ ms: number }> = []; const scheduler = startMetricsScheduler({ metrics, fetchQueueDepth: async () => [], fetchBusinessGauges: async () => ({ activeTenants: 0, activeUsers24h: 0, subscriptionActiveByPlanId: {} }), setInterval: (_h, ms) => { setIntervalCalls.push({ ms }); return { ms }; }, clearInterval: () => undefined, queueIntervalMs: 30_000, businessIntervalMs: 60_000, }); expect(setIntervalCalls.map((c) => c.ms)).toEqual([30_000, 60_000]); scheduler.stop(); }); it("refreshQueueDepth writes both active and waiting gauges", async () => { const scheduler = startMetricsScheduler({ metrics, fetchQueueDepth: async () => [ { queue: "email", active: 2, waiting: 7 }, { queue: "exports", active: 0, waiting: 3 }, ], fetchBusinessGauges: async () => ({ activeTenants: 0, activeUsers24h: 0, subscriptionActiveByPlanId: {} }), setInterval: () => undefined, clearInterval: () => undefined, }); await scheduler.refreshQueueDepth(); const text = await registry.metrics(); expect(text).toMatch(/queue_jobs_active\{[^}]*queue="email"[^}]*\} 2/); expect(text).toMatch(/queue_jobs_waiting\{[^}]*queue="email"[^}]*\} 7/); expect(text).toMatch(/queue_jobs_active\{[^}]*queue="exports"[^}]*\} 0/); expect(text).toMatch(/queue_jobs_waiting\{[^}]*queue="exports"[^}]*\} 3/); scheduler.stop(); }); it("refreshBusinessGauges sets tenant / user / plan gauges", async () => { const scheduler = startMetricsScheduler({ metrics, fetchQueueDepth: async () => [], fetchBusinessGauges: async () => ({ activeTenants: 42, activeUsers24h: 137, subscriptionActiveByPlanId: { pro: 5, free: 100 }, }), setInterval: () => undefined, clearInterval: () => undefined, }); await scheduler.refreshBusinessGauges(); const text = await registry.metrics(); expect(text).toMatch(/active_tenants[^\n]* 42/); expect(text).toMatch(/active_users_24h[^\n]* 137/); expect(text).toMatch(/subscription_active\{[^}]*plan_id="pro"[^}]*\} 5/); expect(text).toMatch(/subscription_active\{[^}]*plan_id="free"[^}]*\} 100/); scheduler.stop(); }); it("swallows errors and logs them — gauges keep their last value", async () => { const error = vi.fn(); const scheduler = startMetricsScheduler({ metrics, fetchQueueDepth: async () => { throw new Error("redis down"); }, fetchBusinessGauges: async () => ({ activeTenants: 0, activeUsers24h: 0, subscriptionActiveByPlanId: {} }), logger: { error }, setInterval: () => undefined, clearInterval: () => undefined, }); await scheduler.refreshQueueDepth(); expect(error).toHaveBeenCalledTimes(1); expect(error.mock.calls[0]![1]).toBe("metrics-scheduler queue-depth refresh failed"); scheduler.stop(); }); it("coalesces overlapping metric refreshes instead of piling up polls", async () => { let resolveQueueDepth: ((samples: readonly []) => void) | undefined; let resolveBusiness: ((sample: { activeTenants: number; activeUsers24h: number; subscriptionActiveByPlanId: {} }) => void) | undefined; const fetchQueueDepth = vi.fn( () => new Promise((resolve) => { resolveQueueDepth = resolve; }) ); const fetchBusinessGauges = vi.fn( () => new Promise<{ activeTenants: number; activeUsers24h: number; subscriptionActiveByPlanId: {} }>((resolve) => { resolveBusiness = resolve; }) ); const scheduler = startMetricsScheduler({ metrics, fetchQueueDepth, fetchBusinessGauges, setInterval: () => undefined, clearInterval: () => undefined, }); const queueRefreshes = [scheduler.refreshQueueDepth(), scheduler.refreshQueueDepth()]; const businessRefreshes = [scheduler.refreshBusinessGauges(), scheduler.refreshBusinessGauges()]; expect(fetchQueueDepth).toHaveBeenCalledTimes(1); expect(fetchBusinessGauges).toHaveBeenCalledTimes(1); resolveQueueDepth?.([]); resolveBusiness?.({ activeTenants: 0, activeUsers24h: 0, subscriptionActiveByPlanId: {} }); await Promise.all([...queueRefreshes, ...businessRefreshes]); void scheduler.refreshQueueDepth(); void scheduler.refreshBusinessGauges(); expect(fetchQueueDepth).toHaveBeenCalledTimes(2); expect(fetchBusinessGauges).toHaveBeenCalledTimes(2); resolveQueueDepth?.([]); resolveBusiness?.({ activeTenants: 0, activeUsers24h: 0, subscriptionActiveByPlanId: {} }); scheduler.stop(); }); it("stop() is idempotent and clears both timers", () => { const clears: unknown[] = []; const scheduler = startMetricsScheduler({ metrics, fetchQueueDepth: async () => [], fetchBusinessGauges: async () => ({ activeTenants: 0, activeUsers24h: 0, subscriptionActiveByPlanId: {} }), setInterval: () => ({ token: Math.random() }), clearInterval: (h) => clears.push(h), }); scheduler.stop(); scheduler.stop(); expect(clears.length).toBe(2); }); });