Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 168 additions & 0 deletions apps/api/src/__tests__/routes-usage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import Fastify from "fastify";
import { errorHandlerPlugin } from "../plugins/error-handler.js";
import { usageRoutes } from "../routes/usage.js";

// We mock global fetch to avoid hitting public status pages from CI. The
// route handler delegates to services/incidents.ts, which fans out across
// Cloudflare/GCP/Vercel JSON APIs and 12 blockchain status pages — testing
// that surface end-to-end against real upstreams would be flaky and slow.

const realFetch = globalThis.fetch;

function mockFetch(handler: (url: string) => Promise<Response> | Response) {
globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
return handler(url);
}) as typeof fetch;
}

function jsonRes(body: unknown): Response {
return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
}

async function buildApp() {
const app = Fastify({ logger: false });
await app.register(errorHandlerPlugin);
await app.register(usageRoutes, { prefix: "/usage" });
return app;
}

beforeEach(() => {
vi.resetAllMocks();
});

afterEach(() => {
globalThis.fetch = realFetch;
});

describe("GET /usage/cloud-incidents", () => {
it("aggregates Cloudflare/GCP/Vercel + curated baselines", async () => {
mockFetch(async (url) => {
if (url.includes("cloudflarestatus.com")) {
return jsonRes({
incidents: [
{
name: "CF outage",
created_at: "2026-04-01T10:00:00Z",
impact: "major",
status: "resolved",
incident_updates: [{ body: "fixed" }],
},
],
});
}
if (url.includes("status.cloud.google.com")) {
return jsonRes([
{
external_desc: "GCP issue",
begin: "2026-03-01T08:00:00Z",
end: "2026-03-01T09:00:00Z",
severity: "Minor",
most_recent_update: { text: "ok" },
},
]);
}
if (url.includes("vercel-status.com")) {
return jsonRes({
incidents: [
{
name: "Build errors",
created_at: "2026-04-10T12:00:00Z",
impact: "minor",
status: "resolved",
},
],
});
}
throw new Error(`Unexpected URL: ${url}`);
});

const app = await buildApp();
const res = await app.inject({ method: "GET", url: "/usage/cloud-incidents" });
expect(res.statusCode).toBe(200);

const body = JSON.parse(res.body);
expect(body.generated_at).toBeDefined();
expect(typeof body.total_incidents).toBe("number");

// Per-provider counts include the live mocks AND the curated baselines.
expect(body.providers.cloudflare).toBe(1);
expect(body.providers.google_cloud).toBe(1);
expect(body.providers.vercel).toBe(1);
// Baselines are committed to incident-baselines.ts, so these are
// deterministic regardless of network state.
expect(body.providers.aws).toBeGreaterThan(0);
expect(body.providers.azure).toBeGreaterThan(0);
expect(body.providers.digitalocean).toBeGreaterThan(0);
expect(body.providers.oracle_cloud).toBeGreaterThan(0);

// Incidents are sorted newest first.
const ts = body.incidents.map((i: { timestamp: string }) => new Date(i.timestamp).getTime());
for (let i = 1; i < ts.length; i++) {
expect(ts[i - 1]).toBeGreaterThanOrEqual(ts[i]);
}

// Spot-check schema on a Cloudflare row.
const cf = body.incidents.find((i: { provider: string }) => i.provider === "Cloudflare");
expect(cf).toMatchObject({
provider: "Cloudflare",
name: "CF outage",
date: "2026-04-01",
timestamp: "2026-04-01T10:00:00Z",
impact: "major",
status: "resolved",
description: "fixed",
});
});

it("falls back gracefully when an upstream is down", async () => {
// Cloudflare 500s, GCP throws, Vercel returns empty — the handler must
// still return baselines and a well-formed body.
mockFetch(async (url) => {
if (url.includes("cloudflarestatus.com")) {
return new Response("oops", { status: 500 });
}
if (url.includes("status.cloud.google.com")) {
throw new Error("network down");
}
if (url.includes("vercel-status.com")) {
return jsonRes({ incidents: [] });
}
throw new Error(`Unexpected URL: ${url}`);
});

const app = await buildApp();
const res = await app.inject({ method: "GET", url: "/usage/cloud-incidents" });
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.providers.cloudflare).toBe(0);
expect(body.providers.google_cloud).toBe(0);
expect(body.providers.vercel).toBe(0);
// Baselines still present.
expect(body.providers.aws).toBeGreaterThan(0);
});
});

describe("GET /usage/blockchain-incidents", () => {
it("returns the documented shape even when all upstreams fail", async () => {
// Every blockchain status page either 500s or returns empty pages.
// The route must still respond 200 with a well-formed (empty) payload —
// the alternative is a flaky page that breaks if any one of 12 status
// sources is down.
mockFetch(async () => new Response("", { status: 500 }));

const app = await buildApp();
const res = await app.inject({ method: "GET", url: "/usage/blockchain-incidents" });
expect(res.statusCode).toBe(200);

const body = JSON.parse(res.body);
expect(body.summary).toMatchObject({
by_impact: expect.any(Object),
total_incidents: expect.any(Number),
});
expect(Array.isArray(body.incidents)).toBe(true);
expect(body.metadata.year).toBe(2025);
expect(Array.isArray(body.metadata.providers)).toBe(true);
}, 30_000);
});
2 changes: 2 additions & 0 deletions apps/api/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { providerClaimableRewardsRoutes } from "./routes/provider-claimable-rewa
import { validatorsAndRewardsRoutes } from "./routes/validators-and-rewards.js";
import { burnRateRoutes } from "./routes/burn-rate.js";
import { chainStakersRoutes } from "./routes/chain-stakers.js";
import { usageRoutes } from "./routes/usage.js";

async function main() {
const app = Fastify({
Expand Down Expand Up @@ -69,6 +70,7 @@ async function main() {
await app.register(validatorsAndRewardsRoutes);
await app.register(burnRateRoutes);
await app.register(chainStakersRoutes);
await app.register(usageRoutes, { prefix: "/usage" });

await app.register(healthProbePlugin);

Expand Down
1 change: 1 addition & 0 deletions apps/api/src/plugins/swagger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const swaggerPlugin = fp(async (app: FastifyInstance) => {
{ name: "Provider Rewards", description: "Per-provider QoS-adjusted reward distribution with USD values" },
{ name: "Validators", description: "Bonded validator list with rewards, delegations, and unbonding — matches jsinfo shape" },
{ name: "Chain Wallet", description: "Unique staker / restaker counts across the dualstaking module" },
{ name: "Usage", description: "Network uptime / reliability data sourced from public status pages" },
],
},
});
Expand Down
144 changes: 144 additions & 0 deletions apps/api/src/routes/usage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import type { FastifyInstance } from "fastify";
import { CACHE_TTL } from "../config.js";
import { fetchBlockchainIncidents, fetchCloudIncidents } from "../services/incidents.js";

/**
* /usage routes — back the frontend's Network Uptime & Reliability page.
*
* Each handler aggregates incident histories from public status pages and
* returns the same JSON shape the legacy jsinfo-ui static datasets used.
* Both responses are cached for 24h (HISTORICAL) — incidents change at most
* a few times per day, and the cold path fans out to ~20 external services.
*/

const cloudIncidentSchema = {
type: "object" as const,
properties: {
provider: { type: "string" as const },
name: { type: "string" as const },
date: { type: "string" as const, description: "YYYY-MM-DD" },
timestamp: { type: "string" as const, description: "ISO 8601" },
impact: { type: "string" as const, description: "minor | major | critical | maintenance | none" },
status: { type: "string" as const },
description: { type: "string" as const },
},
required: ["provider", "name", "date", "timestamp", "impact"],
} as const;

const cloudIncidentsResponseSchema = {
type: "object" as const,
description:
"Aggregated cloud-provider incident history. Cloudflare/GCP/Vercel are pulled live from official status APIs; AWS/Azure/DigitalOcean/Oracle merge curated baselines that capture typical incident volume.",
properties: {
generated_at: { type: "string" as const, description: "ISO 8601 timestamp of when this response was assembled" },
total_incidents: { type: "integer" as const },
providers: {
type: "object" as const,
description: "Per-provider incident counts in this response",
properties: {
cloudflare: { type: "integer" as const },
google_cloud: { type: "integer" as const },
aws: { type: "integer" as const },
azure: { type: "integer" as const },
vercel: { type: "integer" as const },
digitalocean: { type: "integer" as const },
oracle_cloud: { type: "integer" as const },
},
},
incidents: {
type: "array" as const,
description: "Newest first by timestamp",
items: cloudIncidentSchema,
},
},
required: ["generated_at", "total_incidents", "providers", "incidents"],
} as const;

const blockchainIncidentSchema = {
type: "object" as const,
properties: {
provider: { type: "string" as const },
date: { type: "string" as const, description: "YYYY-MM-DD" },
timestamp: { type: "string" as const, description: "ISO 8601" },
impact: { type: "string" as const, description: "minor | major | critical | maintenance | none" },
chain: { type: "string" as const, description: "Best-effort blockchain extracted from the incident name" },
name: { type: "string" as const },
},
required: ["provider", "date", "timestamp", "impact", "chain", "name"],
} as const;

const blockchainIncidentsResponseSchema = {
type: "object" as const,
description:
"Aggregated blockchain RPC-provider incident history scraped from public status pages (Alchemy, Infura, QuickNode, Blockdaemon, Tenderly, Chainstack, GetBlock, Ankr, Helius, Nodies, Dwellir, DRPC). Filtered to incidents from 2025-01-01 onward.",
properties: {
summary: {
type: "object" as const,
properties: {
by_impact: {
type: "object" as const,
properties: {
critical: { type: "integer" as const },
minor: { type: "integer" as const },
maintenance: { type: "integer" as const },
major: { type: "integer" as const },
},
},
total_incidents: { type: "integer" as const },
},
required: ["by_impact", "total_incidents"],
},
incidents: {
type: "array" as const,
description: "Newest first by timestamp",
items: blockchainIncidentSchema,
},
metadata: {
type: "object" as const,
properties: {
providers: {
type: "array" as const,
items: { type: "string" as const },
description: "Distinct provider names that appear in `incidents`",
},
description: { type: "string" as const },
generated: { type: "string" as const, description: "ISO 8601 timestamp" },
year: { type: "integer" as const },
},
required: ["providers", "description", "generated", "year"],
},
},
required: ["summary", "incidents", "metadata"],
} as const;

export async function usageRoutes(app: FastifyInstance) {
app.get(
"/cloud-incidents",
{
schema: {
tags: ["Usage"],
summary: "Cloud-provider incident history (Cloudflare/GCP/Vercel + curated baselines)",
description:
"Fans out to public status APIs for Cloudflare, Google Cloud, and Vercel and merges curated baseline datasets for AWS, Azure, DigitalOcean, and Oracle Cloud. Sorted newest first. Cached 24h.",
response: { 200: cloudIncidentsResponseSchema },
},
config: { cacheTTL: CACHE_TTL.HISTORICAL },
},
async () => fetchCloudIncidents(),
);

app.get(
"/blockchain-incidents",
{
schema: {
tags: ["Usage"],
summary: "Blockchain RPC-provider incident history (Alchemy, Infura, Chainstack, etc.)",
description:
"Scrapes 12 public RPC-provider status pages (StatusPage, Instatus, BetterStack) in parallel and aggregates 2025-onward incidents. Cold call ~30s; cached 24h. Individual upstream failures are tolerated — partial data is preferred over a hard error.",
response: { 200: blockchainIncidentsResponseSchema },
},
config: { cacheTTL: CACHE_TTL.HISTORICAL },
},
async () => fetchBlockchainIncidents(),
);
}
Loading
Loading