Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/health.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Health of the market-data providers (contract: docs/next/CONTRACT.md §3).47 *48 * GET /api/v2/data/health49 *50 * For FMP, FinData and EODHD: is a key configured, does a cheap real request answer (cached 60 s, 4 s timeout),51 * and what does the current plan really serve. Coverage is probed, never assumed: each capability is one minimal52 * real request, refreshed every six hours, and a capability the plan refuses is listed in `notes` with the53 * provider's own answer. Counters are those of this data layer since the process started. No key, URL or account54 * detail ever appears in the response.55 */56import type { Express, Request, Response } from "express";57import { ProviderError, SingleFlight, TtlCache, cachedFlight, isoDay, providerConfigured, providerJson, providerStats, sanitizeProviderMessage, type ProviderId, type ProviderRequest } from "./dataLayer";5859const PROBE_TIMEOUT_MS = 4_000;60const LIVENESS_TTL_MS = 60_000;61const CAPABILITY_TTL_MS = 6 * 3_600_000;62/** A capability whose probe timed out or could not connect is asked again sooner: that says nothing about the plan. */63const CAPABILITY_RETRY_MS = 10 * 60_000;6465type Body = unknown;66interface Probe {67 id: string;68 label: string;69 path: string;70 req?: (nowMs: number) => ProviderRequest;71 /** Whether the answer really contains the data (an empty array is "nothing", not coverage). Returns a detail to show, or true. */72 check: (body: Body) => boolean | string;73}7475const rows = (b: Body): Record<string, unknown>[] => (Array.isArray(b) ? (b as Record<string, unknown>[]) : []);76const nonEmpty = (b: Body) => rows(b).length > 0;77const hasPrice = (b: Body) => typeof rows(b)[0]?.price === "number";78const daysAgo = (nowMs: number, n: number) => isoDay(nowMs - n * 86_400_000);79/** Most recent weekday strictly before today (UTC): a day the sector snapshot can exist for. */80function lastWeekday(nowMs: number): string {81 for (let back = 1; back < 5; back++) {82 const d = new Date(nowMs - back * 86_400_000);83 if (d.getUTCDay() !== 0 && d.getUTCDay() !== 6) return d.toISOString().slice(0, 10);84 }85 return daysAgo(nowMs, 1);86}87const fdData = (b: Body): Record<string, unknown>[] => rows((b as { data?: unknown } | null)?.data);88const fdRows = (b: Body): Record<string, unknown>[] => rows((b as { rows?: unknown } | null)?.rows);89const sqlProbe = (sql: string): ProviderRequest => ({ method: "POST", body: { sql, max_rows: 1 } });90const thisYear = (nowMs: number) => new Date(nowMs).getUTCFullYear();9192/** The first probe of each provider is its liveness check. */93export const PROBES: Record<ProviderId, Probe[]> = {94 fmp: [95 { id: "quotes", label: "stock and ETF quotes", path: "/quote", req: () => ({ params: { symbol: "AAPL" } }), check: hasPrice },96 { id: "daily_bars", label: "daily bars", path: "/historical-price-eod/full", req: (t) => ({ params: { symbol: "AAPL", from: daysAgo(t, 7) } }), check: nonEmpty },97 { id: "intraday_bars", label: "intraday bars (1 min to 4 h)", path: "/historical-chart/1hour", req: (t) => ({ params: { symbol: "AAPL", from: daysAgo(t, 5) } }), check: nonEmpty },98 { id: "statements", label: "financial statements", path: "/income-statement", req: () => ({ params: { symbol: "AAPL", period: "annual", limit: 1 } }), check: nonEmpty },99 { id: "international", label: "non-US listings", path: "/quote", req: () => ({ params: { symbol: "RY.TO" } }), check: hasPrice },100 { id: "indices", label: "index quotes", path: "/quote", req: () => ({ params: { symbol: "^GSPC" } }), check: hasPrice },101 { id: "fx", label: "currency quotes", path: "/quote", req: () => ({ params: { symbol: "EURUSD" } }), check: hasPrice },102 { id: "commodities", label: "commodity quotes", path: "/quote", req: () => ({ params: { symbol: "GCUSD" } }), check: hasPrice },103 { id: "crypto", label: "crypto quotes", path: "/quote", req: () => ({ params: { symbol: "BTCUSD" } }), check: hasPrice },104 { id: "treasury", label: "Treasury yields", path: "/treasury-rates", req: (t) => ({ params: { from: daysAgo(t, 10) } }), check: nonEmpty },105 { id: "economic_calendar", label: "economic calendar", path: "/economic-calendar", req: (t) => ({ params: { from: isoDay(t), to: isoDay(t + 2 * 86_400_000) } }), check: nonEmpty },106 { id: "sector_performance", label: "sector performance", path: "/sector-performance-snapshot", req: (t) => ({ params: { date: lastWeekday(t), exchange: "NYSE" } }), check: nonEmpty },107 { id: "movers", label: "market movers", path: "/biggest-gainers", check: nonEmpty },108 { id: "market_calendar", label: "exchange hours and holidays", path: "/holidays-by-exchange", req: () => ({ params: { exchange: "NYSE" } }), check: nonEmpty },109 ],110 findata: [111 {112 id: "us_daily_bars",113 label: "US stock and ETF daily bars",114 path: "/market/bars",115 req: (t) => ({ params: { symbol: "SPY", interval: "1d", start: daysAgo(t, 12), end: isoDay(t), adjustment: "split_div", limit: 20 } }),116 check: (b) => {117 const d = fdData(b);118 const last = d.map((r) => String(r.session_date ?? "")).sort().pop();119 return d.length > 0 ? `last session loaded: ${last}` : false;120 },121 },122 { id: "us_intraday_bars", label: "US stock and ETF 1-minute bars", path: "/market/bars", req: (t) => ({ params: { symbol: "SPY", interval: "1m", start: daysAgo(t, 12), end: isoDay(t), adjustment: "split_div", limit: 1 } }), check: (b) => fdData(b).length > 0 },123 { id: "indices", label: "index bars", path: "/query", req: (t) => sqlProbe(`SELECT session_date FROM market_bars_index_1d_raw WHERE symbol = 'SPX' AND year = ${thisYear(t)} LIMIT 1`), check: (b) => fdRows(b).length > 0 },124 { id: "crypto", label: "crypto bars (by base asset: BTC)", path: "/query", req: (t) => sqlProbe(`SELECT session_date FROM market_bars_crypto_1d_raw WHERE symbol = 'BTC' AND year = ${thisYear(t)} LIMIT 1`), check: (b) => fdRows(b).length > 0 },125 { id: "fx_intraday", label: "currency intraday bars (no daily series)", path: "/query", req: (t) => sqlProbe(`SELECT session_date FROM market_bars_fx_1h_raw WHERE symbol = 'EURUSD' AND year = ${thisYear(t)} LIMIT 1`), check: (b) => fdRows(b).length > 0 },126 { id: "fundamentals", label: "point-in-time SEC fundamentals", path: "/fundamentals/AAPL", req: () => ({ params: { period_type: "a", limit: 1 } }), check: (b) => fdData(b).length > 0 },127 {128 id: "options_eod",129 label: "end-of-day option chains",130 path: "/query",131 req: () => sqlProbe("SELECT max(trade_date) AS d FROM options_eod WHERE underlying = 'AAPL' AND period = 'latest'"),132 check: (b) => {133 const d = String(fdRows(b)[0]?.d ?? "").slice(0, 10);134 return /^\d{4}-\d{2}-\d{2}$/.test(d) ? `latest chain: ${d}` : false;135 },136 },137 ],138 eodhd: [139 { id: "delayed_quotes", label: "delayed quotes", path: "/real-time/AAPL.US", check: (b) => Number.isFinite(Number((b as { close?: unknown } | null)?.close)) },140 { id: "eod_bars", label: "end-of-day bars", path: "/eod/AAPL.US", req: (t) => ({ params: { from: daysAgo(t, 7) } }), check: nonEmpty },141 { id: "intraday_bars", label: "intraday bars", path: "/intraday/AAPL.US", req: (t) => ({ params: { interval: "1h", from: Math.floor(t / 1000) - 5 * 86_400 } }), check: nonEmpty },142 { id: "options", label: "option chains (US)", path: "/mp/unicornbay/options/contracts", req: () => ({ params: { "filter[underlying_symbol]": "AAPL", "page[limit]": 1 } }), check: (b) => rows((b as { data?: unknown } | null)?.data).length > 0 },143 { id: "news", label: "news", path: "/news", req: () => ({ params: { s: "AAPL.US", limit: 1 } }), check: nonEmpty },144 { id: "fundamentals", label: "fundamentals", path: "/fundamentals/AAPL.US", req: () => ({ params: { filter: "General::Code" } }), check: (b) => b !== null && b !== undefined && b !== "" },145 { id: "earnings_calendar", label: "earnings calendar", path: "/calendar/earnings", req: (t) => ({ params: { from: isoDay(t), to: isoDay(t + 86_400_000) } }), check: (b) => b !== null && typeof b === "object" },146 { id: "economic_events", label: "economic events", path: "/economic-events", req: (t) => ({ params: { from: isoDay(t), to: isoDay(t + 86_400_000), limit: 1 } }), check: (b) => Array.isArray(b) },147 { id: "macro", label: "macro indicators", path: "/macro-indicator/USA", req: () => ({ params: { indicator: "gdp_current_usd" } }), check: nonEmpty },148 ],149};150151const NAMES: Record<ProviderId, string> = { fmp: "Financial Modeling Prep", findata: "FinData OS", eodhd: "EODHD" };152const KEY_NAMES: Record<ProviderId, string> = { fmp: "FMP_API_KEY", findata: "FINDATA_API_KEY", eodhd: "EODHD_API_KEY" };153/** What the owner's routing does with each provider — a statement about this server, not about the plan. */154const ROLES: Record<ProviderId, string> = {155 fmp: "Primary source (asked first).",156 findata: "Fallback for bars when FMP fails or has nothing; US stocks and ETFs, indices, crypto by base asset.",157 eodhd: "Options and delayed quotes for listings FMP does not return.",158};159160export interface CapabilityResult {161 id: string;162 label: string;163 ok: boolean;164 /** "plan" = refused by the subscription; "empty" = answered without data; "timeout"/"network"… = not known. */165 status: "ok" | "plan" | "empty" | "not_found" | "rate_limit" | "timeout" | "network" | "error";166 detail: string | null;167 latencyMs: number;168 checkedAt: number;169}170171export async function runProbe(provider: ProviderId, probe: Probe, nowMs = Date.now()): Promise<CapabilityResult> {172 const started = Date.now();173 const done = (ok: boolean, status: CapabilityResult["status"], detail: string | null): CapabilityResult => ({ id: probe.id, label: probe.label, ok, status, detail, latencyMs: Date.now() - started, checkedAt: Date.now() });174 try {175 const body = await providerJson(provider, probe.path, { ...(probe.req?.(nowMs) ?? {}), timeoutMs: PROBE_TIMEOUT_MS, track: false });176 const verdict = probe.check(body);177 if (verdict === false) return done(false, "empty", "The provider answered without data.");178 return done(true, "ok", typeof verdict === "string" ? verdict : null);179 } catch (e) {180 if (!(e instanceof ProviderError)) return done(false, "error", sanitizeProviderMessage((e as Error)?.message));181 const status: CapabilityResult["status"] = e.kind === "plan" ? "plan" : e.kind === "not_found" ? "not_found" : e.kind === "rate_limit" ? "rate_limit" : e.kind === "timeout" ? "timeout" : e.kind === "network" ? "network" : "error";182 return done(false, status, e.message);183 }184}185186export interface ProviderHealth {187 id: ProviderId;188 name: string;189 configured: boolean;190 ok: boolean;191 latencyMs: number | null;192 checkedAt: number | null;193 error: string | null;194 coverage: string[];195 notes: string;196 capabilities: CapabilityResult[];197 calls: number;198 errors: number;199 lastError: string | null;200 lastErrorAt: number | null;201}202203const liveness = new TtlCache<CapabilityResult>(8);204const livenessFlight = new SingleFlight<CapabilityResult>();205const capabilities = new TtlCache<CapabilityResult[]>(8);206const capabilitiesFlight = new SingleFlight<CapabilityResult[]>();207208const undecided = (c: CapabilityResult) => c.status === "timeout" || c.status === "network" || c.status === "rate_limit" || c.status === "error";209210/** Human summary of what the probes found. Pure. */211export function summarizeCapabilities(provider: ProviderId, caps: CapabilityResult[]): { coverage: string[]; notes: string } {212 const coverage = caps.filter((c) => c.ok).map((c) => c.label);213 const parts: string[] = [ROLES[provider]];214 const details = caps.filter((c) => c.ok && c.detail).map((c) => `${c.label} — ${c.detail}`);215 if (details.length) parts.push(`${details.join("; ")}.`);216 const refused = caps.filter((c) => c.status === "plan").map((c) => c.label);217 if (refused.length) parts.push(`Refused by the current plan: ${refused.join(", ")}.`);218 const empty = caps.filter((c) => c.status === "empty" || c.status === "not_found").map((c) => c.label);219 if (empty.length) parts.push(`Answered without data: ${empty.join(", ")}.`);220 const unknown = caps.filter(undecided).map((c) => `${c.label} (${c.status})`);221 if (unknown.length) parts.push(`Could not be checked just now: ${unknown.join(", ")}.`);222 if (provider === "eodhd" && caps.some((c) => c.id === "delayed_quotes" && c.ok)) parts.push("Its quotes are delayed about 15–20 minutes.");223 return { coverage, notes: parts.join(" ") };224}225226async function providerHealth(id: ProviderId, nowMs: number): Promise<ProviderHealth> {227 const stats = providerStats()[id];228 const base = { id, name: NAMES[id], calls: stats.calls, errors: stats.errors, lastError: stats.lastError, lastErrorAt: stats.lastErrorAt };229 if (!providerConfigured(id)) {230 return { ...base, configured: false, ok: false, latencyMs: null, checkedAt: null, error: null, coverage: [], notes: `Not configured on this server (${KEY_NAMES[id]} is not set). ${ROLES[id]}`, capabilities: [] };231 }232 const [first, ...rest] = PROBES[id];233 const [live, caps] = await Promise.all([234 cachedFlight(liveness, livenessFlight, id, LIVENESS_TTL_MS, () => runProbe(id, first, nowMs)),235 cachedFlight(236 capabilities,237 capabilitiesFlight,238 id,239 (list) => (list.some(undecided) ? CAPABILITY_RETRY_MS : CAPABILITY_TTL_MS),240 () => Promise.all(rest.map((p) => runProbe(id, p, nowMs))),241 ),242 ]);243 const all = [live, ...caps];244 const { coverage, notes } = summarizeCapabilities(id, all);245 return { ...base, configured: true, ok: live.ok, latencyMs: live.latencyMs, checkedAt: live.checkedAt, error: live.ok ? null : (live.detail ?? live.status), coverage, notes, capabilities: all };246}247248/** Health of the three providers. The liveness probes are at most 60 s old, the coverage probes at most six hours. */249export async function getDataHealth(nowMs = Date.now()): Promise<{ providers: ProviderHealth[]; checkedAt: number }> {250 const providers = await Promise.all((["fmp", "findata", "eodhd"] as ProviderId[]).map((id) => providerHealth(id, nowMs)));251 return { providers, checkedAt: Date.now() };252}253254export function registerHealthRoutes(app: Express): void {255 app.get("/api/v2/data/health", async (_req: Request, res: Response) => {256 res.set("Cache-Control", "private, no-store");257 try {258 res.json(await getDataHealth());259 } catch (e) {260 res.status(500).json({ error: "Health check failed." });261 void e;262 }263 });264}265266/** Test hook. */267export function resetHealth(): void {268 liveness.clear();269 capabilities.clear();270}271