### user You are a code expert. Please use your professional knowledge to generate accurate and professional responses. Make sure the code you provide is executable whenever possible. Develop a CDN distribution monitoring tool that checks website access speed and availability across different global regions. Display loading times and error rates for various regions on a map, with support for setting detection frequency and alert conditions. Provide historical data comparison and trend analysis, as well as CDN node switching recommendations. ### assistant · thinking The user wants a CDN distribution monitoring tool. I should build something concrete and executable. Let me design a full-stack solution: 1. Backend: Node.js (Express) or Python (FastAPI) that performs probes from multiple regions. Real multi-region probing requires distributed agents or third-party APIs. I'll simulate/abstract: provide a "probe agent" architecture where you can run agents in different regions (or use a configurable list of probe endpoints / public APIs like Cloudflare's speed test or a headless check). Also provide a simulation mode for demo. 2. Store historical data — SQLite (better-sqlite3) or in-memory + JSON file. Keep dependencies minimal so it's executable. 3. Frontend: HTML + Leaflet map showing regions colored by latency/error rate, charts (Chart.js) for trend, alerting rules engine, CDN node switching recommendation. Let me make it practical: Node.js with Express, better-sqlite3 maybe too heavy? Let's use `node:sqlite`? Node 22+ has experimental `node:sqlite`. Safer: use a simple JSON file store or `sqlite3`? To make it "executable whenever possible", minimize native deps. I'll use plain Node with only `express` and maybe `ws`. Actually could use zero deps with node:http. But express is fine. Hmm, but I want it robust. Let me use: - Backend: Node.js + Express + ws (WebSocket for live updates) + better-sqlite3? Let's avoid native compile. Use a JSON-lines append-only store — simple and dependency free. Actually for trend analysis, JSON in memory with periodic snapshot to disk is fine. Let me plan the architecture: ``` cdn-monitor/ ├── package.json ├── server.js # Express + WS API ├── src/ │ ├── config.js # config load/validate │ ├── store.js # time-series storage (ring buffer + JSONL persist) │ ├── prober.js # performs probes (HTTP HEAD/GET timing, DNS, TLS) │ ├── scheduler.js # frequency-based scheduling │ ├── alerts.js # alert rules engine │ ├── recommend.js # CDN node switching recommendation │ └── regions.js # region definitions (lat/lng, code) ├── public/ │ ├── index.html │ ├── app.js │ └── style.css └── config.json ``` Probing from different regions: In reality you need agents. I'll implement: - `local` probe: real HTTP requests from this machine. - `remote` probes: HTTP calls to configured agent endpoints (each agent returns its own measurement). Provide an agent script `agent.js` you can deploy to a VPS in each region. - `simulate` mode: for demo when no agents available, generate synthetic data with realistic patterns. That's a good honest design. Let me write the code. Key metrics per probe: - region, target, timestamp - dnsMs, connectMs, tlsMs, ttfbMs, totalMs, status, ok, errorType - cacheHit (via CF-Cache-Status / X-Cache header), cdn node id (via headers like `cf-ray`, `x-served-by`, `x-cache`) Alert rules: - rule: { id, metric: 'p95_latency'|'error_rate'|'availability', region: 'all'|'eu-west', comparator: '>', threshold: 800, windowSec: 300, forSec: 60, severity } - Alert engine evaluates on each tick with sliding windows. Recommendation engine: - For each region, compare current p95 latency and error rate against baseline (e.g., 24h median). If degradation > threshold, recommend switching to a different PoP/origin/route. Compute score per candidate and suggest. - Since we can't actually change CDN, we give recommendations: e.g., "Region eu-west-1: p95 1240ms vs baseline 210ms (+490%). Suspected: origin overload / PoP degradation. Recommended action: failover traffic to PoP ams-2 / enable tiered cache / reduce TTL". Let me write concrete code. I'll write: **regions.js** — list of ~20 regions with code, name, lat, lng, agentUrl optional. **prober.js** — perform a probe: ```js async function probeHttp(url, timeoutMs) { const start = process.hrtime.bigint(); ... } ``` Node's fetch (undici) doesn't expose DNS/connect/TLS timings easily. Use `http`/`https` module with `socket` events: `lookup`, `connect`, `secureConnect`, and response `firstByte`. That gives good breakdown. Let's do that. ```js const http = require('http'); const https = require('https'); const { URL } = require('url'); function probeHttp(target, timeoutMs) { return new Promise((resolve) => { const url = new URL(target.url); const lib = url.protocol === 'https:' ? https : http; const t = { start: process.hrtime.bigint() }; const marks = {}; const ms = (a, b) => Number(b - a) / 1e6; const req = lib.request({ method: target.method || 'GET', hostname: url.hostname, port: url.port || (url.protocol === 'https:' ? 443 : 80), path: url.pathname + url.search, headers: { 'user-agent': 'cdn-monitor/1.0', 'accept-encoding': 'gzip, br', ...(target.headers||{}) }, timeout: timeoutMs, lookup: ... // default }); req.on('socket', (socket) => { socket.once('lookup', () => marks.dns = process.hrtime.bigint()); socket.once('connect', () => marks.connect = process.hrtime.bigint()); socket.once('secureConnect', () => marks.tls = process.hrtime.bigint()); }); req.on('response', (res) => { marks.ttfb = process.hrtime.bigint(); let bytes = 0; res.on('data', (c) => bytes += c.length); res.on('end', () => { marks.end = process.hrtime.bigint(); resolve(build(res, bytes)); }); // If we only want TTFB, we could destroy. But total time is useful. }); req.on('timeout', ...); req.on('error', ...); }); } ``` Careful: for HTTPS, `lookup` then `connect` then `secureConnect`. Fine. Timings: - dnsMs = marks.dns - start - connectMs = (marks.connect - marks.dns) or (marks.secureConnect - marks.connect) for TLS - tlsMs = secureConnect - connect - ttfbMs = ttfb - start (or ttfb - last handshake) - totalMs = end - start Also extract CDN headers: `cf-ray`, `cf-cache-status`, `x-cache`, `x-served-by`, `x-amz-cf-pop`, `server`, `age`, `x-cache-hits`, `via`. Map to PoP code where possible. **Remote agent**: POST to agentUrl `/probe` with target, agent performs local probe, returns result. Include a simple agent script. **Simulation**: if no agents configured for a region, generate synthetic measurement seeded by region + target + hour to be deterministic-ish plus noise. Include occasional incidents. **store.js** — ring buffer per (region,target) with max N samples (e.g., 20k) and JSONL append to disk. Provide query API: `series(filter, from, to, bucket)`. **alerts.js** — rules with state machine (pending/firing/resolved), cooldown, webhook notify. **recommend.js** — analyze and produce recommendations. **scheduler.js** — setInterval per target with configurable frequencySec. **server.js** — REST + WS + static. Frontend: Leaflet from CDN (unpkg), Chart.js from CDN. Map markers colored by status. Click region → detail panel with chart. Alert rules editor. Recommendations panel. Historical comparison (current vs previous period). Since it's a lot of code, I'll be organized but keep it reasonably concise while complete. Let me write it. Let me think about the data model: ```js // sample { ts: 1699999999999, region: 'eu-west-1', targetId: 'main-site', ok: true, status: 200, totalMs: 213.4, dnsMs: 12.1, connectMs: 30.2, tlsMs: 45.0, ttfbMs: 180.5, bytes: 51200, cacheHit: true, pop: 'AMS', error: null, simulated: true } ``` Aggregation for map: for a window (default 5 min), per region: count, okRate, errorRate, p50, p95, p99, avg. Trend: bucket by minute/hour. Recommendation logic: - Compute baseline = median p95 over previous 24h (excluding last hour) — or if insufficient data, use cross-region median. - For each region: degradationRatio = currentP95 / baselineP95. - If degradationRatio > threshold (1.5) or errorRate > threshold (0.05) → generate recommendation with severity and suggested actions: - If cacheHit rate low → "cache hit ratio dropped, check cache key / TTL" - If ttfb dominates → "origin latency dominates → enable origin shield / switch origin region" - If dnsMs high → "DNS resolution slow → consider DNS provider change or preconnect" - If TLS high → "TLS handshake slow → enable session resumption/OCSP stapling/TLS1.3" - Suggest alternate PoPs from healthy regions with similar geography. Also "CDN node switching recommendations" — I'll implement: pick candidate PoPs (from healthy regions) and score by latency, and recommend switching traffic (via DNS/Anycast steering or origin shield region change). OK. Also need alert conditions UI. Let me also add a `/api/export` for CSV. Now, let's write the code. I'll aim for correctness. package.json: ```json { "name": "cdn-monitor", "version": "1.0.0", "type": "commonjs", "scripts": { "start": "node server.js", "agent": "node agent.js" }, "dependencies": { "express": "^4.19.2", "ws": "^8.18.0" } } ``` Maybe I should avoid ws and use SSE (Server-Sent Events) — no dependency, works great for one-way push. Yes! Use SSE. Then only express is needed. Actually I could even avoid express... but express is fine and commonly available. Let's keep express only. Actually, let's use zero runtime deps except express. Good. Let me now write each file. ### config.js / config.json ```json { "port": 8787, "probeIntervalSec": 60, "historyRetentionHours": 72, "requestTimeoutMs": 10000, "targets": [ { "id": "main-site", "name": "Main Website", "url": "https://www.example.com/", "method": "GET", "weight": 1 } ], "regions": ["us-east", "us-west", "eu-west", ...], "agents": { "eu-west": "http://eu-west-agent.internal:8787/probe" }, "simulateMissingRegions": true, "alerts": [ { "id": "p95-high", "name": "P95 latency > 800ms", "metric": "p95", "windowSec": 300, "comparator": ">", "threshold": 800, "forSec": 120, "regions": ["*"], "targets": ["*"], "severity": "warning", "cooldownSec": 600 }, { "id": "error-rate", "name": "Error rate > 5%", "metric": "errorRate", "windowSec": 300, "comparator": ">", "threshold": 0.05, "forSec": 60, "regions": ["*"], "severity": "critical" }, { "id": "availability", "name": "Availability < 99%", "metric": "availability", "windowSec": 600, "comparator": "<", "threshold": 0.99, "forSec": 120, "severity": "critical" } ], "webhook": { "url": "", "enabled": false } } ``` ### regions.js List with lat/lng and cloud PoP mapping. I'll define ~16 regions: - us-east (N. Virginia) 38.13,-78.45 - us-west (Oregon) 45.87,-119.69 - us-central (Iowa) 41.26,-95.86 - ca-central (Montreal) 45.5,-73.57 - sa-east (São Paulo) -23.55,-46.63 - eu-west (Ireland) 53.41,-8.24 - eu-central (Frankfurt) 50.11,8.68 - eu-north (Stockholm) 59.33,18.06 - uk-south (London) 51.51,-0.13 - af-south (Cape Town) -33.92,18.42 - me-south (Bahrain) 26.07,50.55 - ap-south (Mumbai) 19.08,72.88 - ap-southeast (Singapore) 1.35,103.82 - ap-northeast (Tokyo) 35.68,139.69 - ap-east (Hong Kong) 22.32,114.17 - ap-northeast-2 (Seoul) 37.57,126.98 - au-southeast (Sydney) -33.87,151.21 Good, 17. ### store.js ```js class Store { constructor({ retentionHours, maxPointsPerSeries }) { ... } add(sample) {...} query({targetId, region, from, to}) {...} aggregate({from, to, bucketSec, ...}) {...} } ``` Store internally: Map key `${targetId}|${region}` → array of samples sorted by ts, with pruning. Persistence: append JSONL to `data/samples.jsonl`, and on start, load last N hours. Also periodic compaction. Let's keep it simple: append on every write (batched via a write stream), and on boot read the file filtering by retention. Actually appending every sample could be heavy at high frequency, but fine for this scale. ### prober.js Includes `localProbe`, `remoteProbe`, `simulateProbe`. ### scheduler.js Runs on interval, iterates targets × regions, probes in parallel with concurrency limit. ### alerts.js Evaluate rules on each evaluation tick (every 15s or after each probe batch). State per rule+region+target: `{ since, firing, lastNotified }`. ### recommend.js ### server.js API: - GET /api/config - PUT /api/config (update frequency, alerts) - GET /api/regions - GET /api/summary?windowSec=300 → per region aggregates - GET /api/timeseries?region=&target=&from=&to=&bucketSec= - GET /api/comparison?windowSec=3600 → current vs previous - GET /api/alerts → active alerts + history - GET /api/recommendations - GET /api/stream → SSE - POST /api/probe/run → trigger immediate probe Now the frontend. I'll write it with vanilla JS + Leaflet + Chart.js from CDN. Layout: - Header with status, controls (interval select, run now). - Left: map (Leaflet with dark tiles? Use OSM standard tiles or CartoDB dark). Use CartoDB dark_matter — free. - Right: region detail panel + trend chart. - Bottom: alerts list, recommendations, alert rule editor. Let me write the frontend carefully but not insanely long. Let me start writing files. **server.js** ```js const path = require('path'); const fs = require('fs'); const express = require('express'); const { loadConfig, saveConfig } = require('./src/config'); const { Store } = require('./src/store'); const { Prober } = require('./src/prober'); const { Scheduler } = require('./src/scheduler'); const { AlertEngine } = require('./src/alerts'); const { buildRecommendations } = require('./src/recommend'); const { REGIONS, getRegion } = require('./src/regions'); const { aggregate, percentile } = require('./src/stats'); ``` Let me write stats.js with percentile, mean, aggregateBuckets. OK let's write it all out. I need to be careful with code correctness. Let me write each module. --- **src/regions.js** ```js 'use strict'; const REGIONS = [ { code: 'us-east-1', name: 'N. Virginia, US', lat: 38.13, lng: -78.45, cloud: 'aws', area: 'north-america' }, ... ]; const REGION_MAP = new Map(REGIONS.map(r => [r.code, r])); function getRegion(code) { return REGION_MAP.get(code) || null; } function regionList() { return REGIONS.map(r => ({...r})); } module.exports = { REGIONS, getRegion, regionList }; ``` **src/stats.js** ```js function percentile(sortedOrNot, p) { if (!arr.length) return null; const a = [...arr].sort((x,y)=>x-y); const idx = (a.length - 1) * p; const lo = Math.floor(idx), hi = Math.ceil(idx); if (lo === hi) return a[lo]; return a[lo] + (a[hi] - a[lo]) * (idx - lo); } ``` Also `mean`, `median`, `stdev`, `summarize(samples, windowMs)` returning {count, okCount, errorRate, availability, p50, p95, p99, avg, min, max, avgBreakdown}. Also `bucketize(samples, from, to, bucketMs)`. Also `trend(current, previous)` → percent change, direction. **src/store.js** ```js class Store { constructor({ dataDir, retentionHours }) { this.series = new Map(); // key -> array this.dataDir = dataDir; this.retentionMs = retentionHours*3600*1000; this.file = path.join(dataDir, 'samples.jsonl'); fs.mkdirSync(dataDir, { recursive: true }); this._load(); this._stream = fs.createWriteStream(this.file, { flags: 'a' }); } _key(targetId, region) { return `${targetId}::${region}`; } add(sample) { const k = this._key(sample.targetId, sample.region); let arr = this.series.get(k); if (!arr) { arr = []; this.series.set(k, arr); } arr.push(sample); this._stream.write(JSON.stringify(sample) + '\n'); this._prune(arr); } ... } ``` Pruning: on add, if arr.length > 5000, shift. Also time-based prune on interval. Load: read file line by line (readFileSync + split, filter by ts). For big files, streaming would be better but keep simple; add a size guard. Query: filter samples by target/region/time. `aggregateWindow({ from, to, targetId, region })` returns summarize. `byRegion({from, to})` → map region → summary (across targets). I'll keep targets mostly one, but support multiple. **src/prober.js** ```js const http = require('http'); const https = require('https'); const { URL } = require('url'); const UA = 'CDNMonitor/1.0 (+https://example.com/monitor)'; function probeOnce({ url, method='GET', headers={}, timeoutMs=10000, maxBytes=65536 }) { return new Promise((resolve) => { let finished = false; const t0 = process.hrtime.bigint(); const marks = {}; const done = (result) => { if (!finished) { finished = true; resolve(result); } }; let parsed; try { parsed = new URL(url); } catch (e) { return done(fail('invalid_url', e.message)); } const isHttps = parsed.protocol === 'https:'; const lib = isHttps ? https : http; const startedAt = Date.now(); const req = lib.request({ protocol: parsed.protocol, hostname: parsed.hostname, port: parsed.port || (isHttps ? 443 : 80), path: `${parsed.pathname}${parsed.search}`, method, headers: { 'user-agent': UA, 'accept': '*/*', ...headers }, timeout: timeoutMs, // keepAlive false so we measure full handshake agent: false, }); req.on('socket', (socket) => { socket.once('lookup', () => { marks.dns = process.hrtime.bigint(); }); socket.once('connect', () => { marks.connect = process.hrtime.bigint(); }); socket.once('secureConnect', () => { marks.tls = process.hrtime.bigint(); }); }); req.on('response', (res) => { marks.ttfb = process.hrtime.bigint(); let bytes = 0; res.on('data', (chunk) => { bytes += chunk.length; if (bytes >= maxBytes) { req.destroy(); finish(res, bytes); } }); res.on('end', () => finish(res, bytes)); res.on('error', (e) => done(fail('stream_error', e.message))); }); req.on('timeout', () => { req.destroy(new Error('timeout')); }); req.on('error', (e) => done(fail(e.code === 'ETIMEDOUT' || /timeout/i.test(e.message) ? 'timeout' : (e.code || 'network_error'), e.message))); req.end(); function finish(res, bytes) { const tEnd = process.hrtime.bigint(); ... } }); } ``` Careful: calling `req.destroy()` after response — `res` may emit 'aborted'. Let's just handle with a `finished` flag. Actually, when we destroy the request after maxBytes, 'end' won't fire. So call finish explicitly. And guard against double. ms conversion helper: `const ms = (a,b) => a && b ? Number(b-a)/1e6 : null;` Build result: ```js const status = res.statusCode; const ok = status >= 200 && status < 400; const dnsMs = marks.dns ? ms(t0, marks.dns) : null; const connectMs = marks.connect && marks.dns ? ms(marks.dns, marks.connect) : null; const tlsMs = marks.tls && marks.connect ? ms(marks.connect, marks.tls) : null; const handshakeEnd = marks.tls || marks.connect; const ttfbMs = marks.ttfb ? ms(handshakeEnd || t0, marks.ttfb) : null; // hmm ``` Actually let's define ttfbMs as total time to first byte from start (common definition), and also `waitMs` = ttfb - handshakeEnd. I'll report: - dnsMs - connectMs - tlsMs - waitMs (server processing) - totalMs (full request including body download) totalMs = ms(t0, tEnd). CDN headers extraction: ```js function extractCdn(res) { const h = res.headers; const pop = h['cf-ray'] ? String(h['cf-ray']).split('-')[1] : (h['x-amz-cf-pop'] || h['x-served-by'] || h['x-cache'] || null); const cacheStatus = h['cf-cache-status'] || h['x-cache'] || h['x-cache-status'] || null; const hit = cacheStatus ? /hit|HIT/.test(String(cacheStatus)) : null; ... } ``` For `x-served-by` (Fastly) it's like "cache-lhr6372-LHR". Extract the last token. OK, `pop` may be undefined. Fine. **Simulation** for regions without agents: generate plausible data. ```js function simulateProbe({ region, target, tick }) { const r = getRegion(region); const base = BASE_LATENCY[region] ?? 120; ... } ``` Base latency per region relative to origin. Add diurnal variation via sin of hour, plus noise, plus occasional incident (random 2% chance lasting a few ticks). Use deterministic PRNG seeded on region+target+tick so restarts are consistent-ish? Not necessary; but for demo stability, use Math.random. I'll make an incident model: with probability 0.01 per tick, a region enters "degraded" state for 3-10 ticks. Keep a module-level state map. **src/scheduler.js** ```js class Scheduler { constructor({ config, store, onSample, onBatchComplete }) {...} start() { this._loop(); } setInterval(sec) {...} async runOnce() { ... } } ``` Run cycle: build tasks = targets × regions. Concurrency 6. For each task: get agent URL from config.agents[region]; if present → remote probe; else if config.simulateMissingRegions → simulate; else skip (record error 'no_agent'). Emit sample. **src/alerts.js** ```js class AlertEngine { constructor({ config, store, notify }) { this.states = new Map(); // key -> {status, since, lastFiredAt} this.active = []; this.history = []; } evaluate(now = Date.now()) {...} } ``` For each rule: for each region in rule.regions (expand '*'), for each target: compute metric over window. Compare. Track state with `forSec` requirement. Metrics: - `p95`, `p99`, `p50`, `avg` (latency ms) - `errorRate` (0-1) - `availability` (0-1) - `cacheHitRate` (0-1) Notification: console + webhook POST if enabled. **src/recommend.js** ```js function buildRecommendations({ store, config, regions, windowSec = 900, baselineHours = 24 }) { const now = Date.now(); const current = store.byRegion({ from: now - windowSec*1000, to: now }); const baseline = store.byRegion({ from: now - baselineHours*3600e3, to: now - 3600e3 }); ... } ``` For each region: - cur = current.get(region), base = baseline.get(region) - if !cur or cur.count < 2 → skip - ratio = cur.p95 / max(base.p95, 20) - errorRate = cur.errorRate - Score = weighted. - If ratio > 1.5 or errorRate > 0.05 or availability < 0.99 → issue. - Determine likely cause from breakdown: dominant phase among dns/connect/tls/wait relative to baseline. - Find alternate candidate regions: healthy regions with lowest p95 (in same area first). - Produce recommendation object: ```js { id, region, targetId, severity, score, metrics: {p95, errorRate, availability, baselineP95, ratio}, likelyCause, actions: [ '...' ], suggestedPops: [ {region, p95, errorRate} ], confidence: 0.0-1.0 } ``` Also produce global recommendations: e.g., if a region consistently has high cache miss rate. Good. **Frontend** `public/index.html` with Leaflet CSS/JS + Chart.js from CDN. app.js: - fetch /api/regions, /api/config - init map - SSE /api/stream for updates (send summary every 5s) - render markers with color by status - click region → detail - charts - alerts panel - recommendations panel - rule editor form (simple JSON textarea + save) Let me write a reasonably complete frontend. Color scale: green (p95 < 300 & err <1%), yellow, orange, red. Let me write the code now, for real. I'll be careful with the SSE implementation in server.js. ```js app.get('/api/stream', (req, res) => { res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no', }); res.flushHeaders(); const client = { res }; clients.add(client); res.write(`event: hello\ndata: ${JSON.stringify({ ts: Date.now() })}\n\n`); const ping = setInterval(() => res.write(': ping\n\n'), 15000); req.on('close', () => { clearInterval(ping); clients.delete(client); }); }); ``` Broadcast function sends `event: snapshot` with summary+alerts+recommendations. Rebuild snapshot every N seconds (e.g., 5s) or after each probe batch. Now let's write everything. Also `agent.js` — standalone probe agent to deploy in other regions. ```js const express = require('express'); const { probeOnce } = require('./src/prober'); const app = express(); app.use(express.json()); app.post('/probe', async (req, res) => { const { url, method, headers, timeoutMs } = req.body || {}; if (!url) return res.status(400).json({ error: 'url required' }); const result = await probeOnce({ url, method, headers, timeoutMs }); res.json({ region: process.env.AGENT_REGION || 'unknown', ...result }); }); app.get('/health', (req,res)=>res.json({ok:true, region: process.env.AGENT_REGION})); app.listen(process.env.PORT || 8790); ``` The remote probe in prober.js: ```js async function remoteProbe({ agentUrl, target, timeoutMs }) { const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), timeoutMs + 2000); try { const r = await fetch(agentUrl, { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({...}), signal: ctrl.signal }); const j = await r.json(); return { ...j, source: 'agent' }; } catch(e) { return { ok:false, error:'agent_unreachable', errorMessage: e.message, totalMs: null, source: 'agent' }; } finally { clearTimeout(t); } } ``` Node 18+ has global fetch. Good. Now writing files. Let me write out the full prober carefully. ```js 'use strict'; const http = require('http'); const https = require('https'); const DEFAULT_UA = 'CDNMonitor/1.0'; function hrToMs(a, b) { if (a == null || b == null) return null; return Number(b - a) / 1e6; } function extractCdnInfo(headers = {}) { const h = {}; for (const [k, v] of Object.entries(headers)) h[k.toLowerCase()] = v; let pop = null; let provider = null; if (h['cf-ray']) { provider = 'cloudflare'; pop = String(h['cf-ray']).split('-').pop() || null; } else if (h['x-amz-cf-pop']) { provider = 'cloudfront'; pop = h['x-amz-cf-pop']; } else if (h['x-served-by']) { provider = 'fastly'; const parts = String(h['x-served-by']).split('-'); pop = parts[parts.length-1]; } else if (h['x-akamai-transformed'] || h['akamai-grn']) { provider = 'akamai'; pop = h['akamai-grn'] || null; } else if (h['x-azure-ref']) { provider = 'azure'; } const cacheRaw = h['cf-cache-status'] || h['x-cache'] || h['x-cache-status'] || h['x-fastly-cache'] || null; let cacheHit = null; if (cacheRaw) { const s = String(cacheRaw).toUpperCase(); if (s.includes('HIT')) cacheHit = true; else if (s.includes('MISS') || s.includes('EXPIRED') || s.includes('REVALIDATED') || s.includes('BYPASS') || s.includes('DYNAMIC')) cacheHit = false; } return { provider, pop: pop ? String(pop).toUpperCase() : null, cacheStatus: cacheRaw, cacheHit }; } ``` Note: for `x-served-by: cache-lhr6372-LHR`, split('-').pop() = 'LHR'. Good. Main probe: ```js function probeOnce({ url, method = 'GET', headers = {}, timeoutMs = 10000, maxBytes = 131072, region = null, targetId = null }) { return new Promise((resolve) => { const startedAt = Date.now(); const t0 = process.hrtime.bigint(); const marks = {}; let settled = false; const settle = (payload) => { if (settled) return; settled = true; resolve({ ts: startedAt, region, targetId, url, ok: false, status: null, totalMs: null, dnsMs: null, connectMs: null, tlsMs: null, ttfbMs: null, waitMs: null, bytes: 0, provider: null, pop: null, cacheStatus: null, cacheHit: null, error: null, errorMessage: null, source: 'local', ...payload, }); }; let parsed; try { parsed = new URL(url); } catch (e) { return settle({ error: 'invalid_url', errorMessage: String(e.message) }); } if (!/^https?:$/.test(parsed.protocol)) return settle({ error: 'unsupported_protocol' }); const isHttps = parsed.protocol === 'https:'; const lib = isHttps ? https : http; const req = lib.request({ protocol: parsed.protocol, hostname: parsed.hostname, port: parsed.port || (isHttps ? 443 : 80), path: `${parsed.pathname}${parsed.search}`, method, headers: { 'user-agent': DEFAULT_UA, accept: '*/*', 'accept-encoding': 'identity', ...headers }, timeout: timeoutMs, agent: false, }); req.on('socket', (socket) => { socket.once('lookup', () => { marks.dns = process.hrtime.bigint(); }); socket.once('connect', () => { marks.connect = process.hrtime.bigint(); }); socket.once('secureConnect', () => { marks.tls = process.hrtime.bigint(); }); }); req.on('response', (res) => { marks.ttfb = process.hrtime.bigint(); let bytes = 0; const finish = () => { const tEnd = process.hrtime.bigint(); const cdn = extractCdnInfo(res.headers); const handshakeEnd = marks.tls || marks.connect || t0; const status = res.statusCode; settle({ ok: status >= 200 && status < 400, status, totalMs: round(hrToMs(t0, tEnd)), dnsMs: round(hrToMs(t0, marks.dns)), connectMs: round(hrToMs(marks.dns, marks.connect)), tlsMs: round(hrToMs(marks.connect, marks.tls)), ttfbMs: round(hrToMs(t0, marks.ttfb)), waitMs: round(hrToMs(handshakeEnd, marks.ttfb)), bytes, ...cdn, error: status >= 400 ? `http_${status}` : null, }); }; res.on('data', (chunk) => { bytes += chunk.length; if (bytes >= maxBytes) { finish(); req.destroy(); } }); res.on('end', finish); res.on('error', () => finish()); }); req.on('timeout', () => { req.destroy(new Error('timeout')); }); req.on('error', (err) => { const tEnd = process.hrtime.bigint(); const code = err.code || (/(timeout)/i.test(err.message) ? 'ETIMEDOUT' : 'network_error'); settle({ ok: false, totalMs: round(hrToMs(t0, tEnd)), dnsMs: round(hrToMs(t0, marks.dns)), connectMs: round(hrToMs(marks.dns, marks.connect)), tlsMs: round(hrToMs(marks.connect, marks.tls)), error: code, errorMessage: err.message, }); }); req.end(); }); } ``` Note: `hrToMs` with null returns null; round(null) should return null. ```js function round(v) { return v == null ? null : Math.round(v * 10) / 10; } ``` Wait, there's a bug: `marks.dns` may be undefined when connect fires... handled by hrToMs returning null. But `connectMs = hrToMs(marks.dns, marks.connect)` — if dns undefined, returns null. Fine. Hmm, but for HTTP (non-TLS), `secureConnect` never fires, so tlsMs null. Good. Also note `socket.once('lookup')` may not fire if the hostname is an IP address or if DNS is cached... With `agent: false`, a new socket is created, but Node's DNS lookup is still performed (may be cached by libuv? No, Node doesn't cache DNS by default unless using `dns.setDefaultResultOrder`... actually libuv's getaddrinfo has no cache; but the OS may cache). If the host is an IP literal, 'lookup' still fires? Node emits 'lookup' event only when a DNS lookup happens. For IP literals, Node skips lookup and the event may not fire. That's fine, dnsMs null. Now simulation: ```js const SIM_STATE = new Map(); const REGION_BASE_MS = { 'us-east-1': 45, 'us-east-2': 55, 'us-west-1': 90, 'us-west-2': 80, ... }; ``` Actually base latency should be relative to an origin. Let's define a fictional origin in us-east-1 and derive RTT-ish values. Simplify: each region has a `baseMs` value representing p50. Add jitter. ```js function simulateProbe({ region, targetId, url }) { const r = getRegion(region); const key = `${region}::${targetId}`; const now = Date.now(); let st = SIM_STATE.get(key); if (!st) { st = { incidentUntil: 0, incidentSeverity: 0 }; SIM_STATE.set(key, st); } if (now > st.incidentUntil && Math.random() < 0.012) { st.incidentUntil = now + (60 + Math.random()*600) * 1000; st.incidentSeverity = 0.5 + Math.random() * 3; } const degraded = now < st.incidentUntil; const base = r.baseMs; const hour = new Date(now).getUTCHours(); const diurnal = 1 + 0.18 * Math.sin(((hour - 3) / 24) * Math.PI * 2); const jitter = 0.85 + Math.random() * 0.4; let total = base * diurnal * jitter * (degraded ? st.incidentSeverity + 1 : 1); const dns = 5 + Math.random() * 25; const connect = 10 + Math.random() * 40; const tls = url.startsWith('https') ? 25 + Math.random() * 60 : null; const ttfb = total * 0.6 + dns + connect + (tls || 0); total = ttfb + Math.random() * 120; const errorRate = degraded ? 0.08 * st.incidentSeverity : 0.004; const isError = Math.random() < errorRate; ... } ``` Return a sample with `simulated: true`. Good enough for demo. Now the store. ```js 'use strict'; const fs = require('fs'); const path = require('path'); class Store { constructor({ dataDir = './data', retentionHours = 72, maxPerSeries = 20000 } = {}) { this.dataDir = dataDir; this.retentionMs = retentionHours * 3600 * 1000; this.maxPerSeries = maxPerSeries; this.series = new Map(); fs.mkdirSync(dataDir, { recursive: true }); this.file = path.join(dataDir, 'samples.jsonl'); this._load(); this._out = fs.createWriteStream(this.file, { flags: 'a' }); } _key(targetId, region) { return `${targetId}::${region}`; } _load() { if (!fs.existsSync(this.file)) return; const cutoff = Date.now() - this.retentionMs; let content; try { content = fs.readFileSync(this.file, 'utf8'); } catch { return; } const lines = content.split('\n'); for (const line of lines) { if (!line) continue; let s; try { s = JSON.parse(line); } catch { continue; } if (!s || !s.ts || s.ts < cutoff) continue; const k = this._key(s.targetId, s.region); let arr = this.series.get(k); if (!arr) { arr = []; this.series.set(k, arr); } arr.push(s); } } add(sample) { if (!sample || !sample.region || !sample.targetId) return; const k = this._key(sample.targetId, sample.region); let arr = this.series.get(k); if (!arr) { arr = []; this.series.set(k, arr); } arr.push(sample); if (arr.length > this.maxPerSeries) arr.splice(0, arr.length - this.maxPerSeries); try { this._out.write(JSON.stringify(sample) + '\n'); } catch {} } addMany(samples) { for (const s of samples) this.add(s); } prune(now = Date.now()) { const cutoff = now - this.retentionMs; for (const [k, arr] of this.series) { let i = 0; while (i < arr.length && arr[i].ts < cutoff) i++; if (i > 0) arr.splice(0, i); if (arr.length === 0) this.series.delete(k); } } query({ targetId = null, region = null, from = 0, to = Date.now() } = {}) { const out = []; for (const [k, arr] of this.series) { const [t, r] = k.split('::'); if (targetId && t !== targetId) continue; if (region && r !== region) continue; for (const s of arr) if (s.ts >= from && s.ts <= to) out.push(s); } out.sort((a,b) => a.ts - b.ts); return out; } ... } ``` Hmm, iterating all series for each query is fine at this scale. `byRegion({from, to, targetId})` → Map region → samples array. Then summarize. `close()` to end stream. Now stats. ```js function percentile(values, p) { if (!values || values.length === 0) return null; const a = values.slice().sort((x, y) => x - y); if (a.length === 1) return a[0]; const idx = (a.length - 1) * p; const lo = Math.floor(idx), hi = Math.ceil(idx); if (lo === hi) return a[lo]; return a[lo] + (a[hi] - a[lo]) * (idx - lo); } function mean(v) { ... } function summarize(samples) { if (!samples || !samples.length) return null; const n = samples.length; const ok = samples.filter(s => s.ok); const lat = samples.map(s => s.totalMs).filter(v => typeof v === 'number'); const okLat = ok.map(s => s.totalMs).filter(v => typeof v === 'number'); const cacheKnown = samples.filter(s => s.cacheHit !== null && s.cacheHit !== undefined); return { count: n, okCount: ok.length, errorCount: n - ok.length, availability: ok.length / n, errorRate: 1 - ok.length / n, p50: percentile(okLat, 0.5), p95: percentile(okLat, 0.95), p99: percentile(okLat, 0.99), avg: okLat.length ? okLat.reduce((a,b)=>a+b,0)/okLat.length : null, min: okLat.length ? Math.min(...okLat) : null, max: okLat.length ? Math.max(...okLat) : null, cacheHitRate: cacheKnown.length ? cacheKnown.filter(s=>s.cacheHit).length / cacheKnown.length : null, breakdown: { dnsMs: avgOf(samples, 'dnsMs'), connectMs: avgOf(samples, 'connectMs'), tlsMs: avgOf(samples, 'tlsMs'), ttfbMs: avgOf(samples, 'ttfbMs'), waitMs: avgOf(samples, 'waitMs'), }, statusCodes: countBy(samples, s => s.status || s.error || 'unknown'), pops: countBy(samples, s => s.pop || 'unknown'), }; } ``` Note: `Math.min(...okLat)` with huge arrays can blow the stack; use reduce. Use reduce. `bucketize(samples, from, to, bucketMs)` → array of {ts, ...summary}. Now alerts. ```js class AlertEngine { constructor({ store, config, onEvent }) {...} getMetric(rule, ctx) ... evaluate() {...} } ``` Implementation: ```js evaluate(now = Date.now()) { const events = []; const rules = this.config.alerts || []; for (const rule of rules) { const windowMs = (rule.windowSec || 300) * 1000; const from = now - windowMs; const regions = expand(rule.regions, this.config.regions); const targets = expand(rule.targets, this.config.targets.map(t => t.id)); for (const region of regions) { for (const targetId of targets) { const samples = this.store.query({ region, targetId, from, to: now }); if (samples.length < (rule.minSamples || 2)) continue; const summary = summarize(samples); const value = pickMetric(summary, rule.metric); if (value == null) continue; const breached = compare(value, rule.comparator, rule.threshold); const key = `${rule.id}::${region}::${targetId}`; let st = this.states.get(key) || { breachedSince: null, firing: false, lastNotified: 0 }; if (breached) { if (!st.breachedSince) st.breachedSince = now; const held = now - st.breachedSince >= (rule.forSec || 0) * 1000; if (held && !st.firing) { st.firing = true; const event = { type: 'fired', ... }; events.push(event); this.history.push(event); } } else { st.breachedSince = null; if (st.firing) { st.firing = false; const event = {type:'resolved', ...}; events.push(event); this.history.push(event); } } this.states.set(key, st); } } } ... } ``` Also cooldown for notifications. Active alerts list = states where firing. Also need to notify: call `this.onEvent(event)`. Now recommend. ```js function buildRecommendations({ store, config, windowSec = 900, baselineHours = 24 }) { const now = Date.now(); const cur = store.byRegion({ from: now - windowSec*1000, to: now }); const base = store.byRegion({ from: now - baselineHours*3600e3, to: now - 3600e3 }); const regions = []; for (const [region, samples] of cur) { const s = summarize(samples); const b = base.get(region) ? summarize(base.get(region)) : null; regions.push({ region, current: s, baseline: b }); } // global median p95 as fallback baseline ... } ``` Then produce recs. Let me write the full logic. ```js const DEGRADE_P95_RATIO = 1.5; const DEGRADE_ERROR_RATE = 0.05; const DEGRADE_AVAILABILITY = 0.99; function dominantPhase(breakdown, baselineBreakdown) { const phases = ['dnsMs','connectMs','tlsMs','waitMs']; let best = null, bestDelta = 0; for (const p of phases) { const c = breakdown?.[p]; const b = baselineBreakdown?.[p]; if (c == null) continue; const delta = b ? (c - b) : c; if (delta > bestDelta) { bestDelta = delta; best = p; } } return best; } ``` Actions per phase: - dnsMs → 'DNS resolution degraded — verify resolver health / enable DNS prefetch / lower TTL' - connectMs → 'TCP handshake slow — check PoP/edge health, MTU, or route congestion' - tlsMs → 'TLS handshake slow — enable TLS 1.3, session resumption, OCSP stapling' - waitMs → 'Origin response slow (TTFB) — enable Origin Shield, check origin load, increase cache TTL' Plus cache hit rate. Candidate PoPs: healthy regions sorted by p95, prefer same `area`. Now the server. Let me now write out everything properly. For the frontend, I'll write index.html with a layout, style.css, and app.js. Let me think about the snapshot payload for SSE: ```js { ts, regions: [ { code, name, lat, lng, status, p95, p50, errorRate, availability, cacheHitRate, count, simulated } ], activeAlerts: [...], recommendations: [...], meta: { lastRunAt, nextRunAt, intervalSec, probing } } ``` Detail on demand: `/api/timeseries?region=X&target=Y&from=&to=&bucketSec=` And `/api/comparison?region=X&windowSec=3600` → current vs previous window, plus delta. Alright, let's write the frontend. HTML structure: ```html

CDN Distribution Monitor

...
...
...
``` Use grid layout. Let me write app.js. ```js const state = { regions: [], config: null, summary: new Map(), selected: null, chart: null, }; ``` Init: ```js async function init() { const [regions, config] = await Promise.all([fetchJson('/api/regions'), fetchJson('/api/config')]); state.regions = regions; state.config = config; initMap(); connectStream(); renderRules(); } ``` Map: Leaflet with CartoDB dark tiles. ```js map = L.map('map', { worldCopyJump: true, zoomControl: true }).setView([20, 10], 2); L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { attribution: '© OpenStreetMap © CARTO', subdomains: 'abcd', maxZoom: 19 }).addTo(map); ``` Markers: `L.circleMarker([lat,lng], {radius, color, fillColor, fillOpacity})`. Also draw a "pulse" for critical. Region detail: on click, fetch timeseries and comparison, render chart with Chart.js. Chart: line chart of p95 and errorRate over time (dual axis) — or two charts. Keep one chart with two datasets and two y-axes. OK. Let's write. Also alert rules editor: a table of rules with fields, plus "Add rule" and "Save". I'll make it a simple form-based editor with a JSON textarea fallback. Actually a proper table editor is nicer but longer. Let me do a compact editable table. Given length constraints, I'll do a table with inputs. Let me write it. Also I should include a README with run instructions. Let me now produce the final code. I'll write files in order. One more consideration: `store.byRegion` — implement: ```js byRegion({ from, to, targetId = null }) { const map = new Map(); for (const s of this.query({ targetId, from, to })) { if (!map.has(s.region)) map.set(s.region, []); map.get(s.region).push(s); } return map; } ``` And `byTargetRegion`. OK, writing now. For the scheduler, I want the probe cycle to be robust: ```js class Scheduler { constructor({ config, store, onSample, onCycle }) { this.config = config; this.store = store; this.onSample = onSample; this.onCycle = onCycle; this.timer = null; this.running = false; this.lastRunAt = null; this.nextRunAt = null; this.cycleCount = 0; } get intervalMs() { return Math.max(5, this.config.probeIntervalSec || 60) * 1000; } start() { this.stop(); this._schedule(); this.runOnce().catch(()=>{}); } stop() { if (this.timer) clearTimeout(this.timer); this.timer = null; } _schedule() { const delay = this.intervalMs; this.nextRunAt = Date.now() + delay; this.timer = setTimeout(async () => { await this.runOnce().catch(()=>{}); this._schedule(); }, delay); if (this.timer.unref) this.timer.unref(); } async runOnce() { if (this.running) return { skipped: true }; this.running = true; ... } } ``` Hmm, `unref` would let process exit; but server keeps it alive anyway. I'll not unref. Actually careful: `_schedule` sets timer, then runOnce on start immediately. Fine. runOnce: ```js async runOnce() { if (this.running) return { skipped: true }; this.running = true; const t0 = Date.now(); this.cycleCount++; const tasks = []; for (const target of this.config.targets) { for (const region of this.config.regions) { tasks.push({ target, region }); } } const results = []; const concurrency = Math.min(8, tasks.length); let idx = 0; const workers = Array.from({ length: concurrency }, async () => { while (idx < tasks.length) { const my = tasks[idx++]; const sample = await this._probe(my.target, my.region); results.push(sample); this.store.add(sample); if (this.onSample) this.onSample(sample); } }); await Promise.all(workers); this.running = false; this.lastRunAt = Date.now(); const cycle = { ts: this.lastRunAt, durationMs: Date.now() - t0, count: results.length, cycle: this.cycleCount }; if (this.onCycle) this.onCycle(cycle); return cycle; } async _probe(target, region) { const agentUrl = (this.config.agents || {})[region]; const timeoutMs = this.config.requestTimeoutMs || 10000; let sample; if (agentUrl) { sample = await remoteProbe({ agentUrl, target, timeoutMs, region }); } else if (this.config.simulateMissingRegions) { sample = simulateProbe({ region, target }); } else { sample = { ok: false, error: 'no_agent', errorMessage: `No agent configured for ${region}`, totalMs: null }; } return { ts: Date.now(), region, targetId: target.id, targetName: target.name, url: target.url, ...sample, }; } ``` Careful: sample may override ts/region. Put the spread first then override. Actually `...sample` includes ts/region/targetId from prober. Let me spread sample first, then set the authoritative fields. But prober's `ts` is the start time — good, keep it. Hmm, but I want region/targetId from the scheduler. Let me do: ```js return { ...sample, ts: sample.ts || Date.now(), region, targetId: target.id, targetName: target.name, url: target.url, }; ``` Good. Now server.js. ```js const express = require('express'); const path = require('path'); const { loadConfig, saveConfig } = require('./src/config'); const { Store } = require('./src/store'); const { Scheduler } = require('./src/scheduler'); const { AlertEngine } = require('./src/alerts'); const { buildRecommendations } = require('./src/recommend'); const { summarize, bucketize } = require('./src/stats'); const { regionList, REGIONS } = require('./src/regions'); const config = loadConfig(); const store = new Store({ dataDir: path.join(__dirname, 'data'), retentionHours: config.historyRetentionHours || 72 }); const app = express(); app.use(express.json({ limit: '1mb' })); app.use(express.static(path.join(__dirname, 'public'))); const sseClients = new Set(); function broadcast(event, data) { const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; for (const res of sseClients) { try { res.write(payload); } catch {} } } const alertEngine = new AlertEngine({ store, config, onEvent: (e) => broadcast('alert', e) }); const scheduler = new Scheduler({ config, store, onSample: () => {}, onCycle: () => scheduleSnapshot() }); ``` Snapshot builder: ```js let snapshotTimer = null; let lastSnapshot = null; function buildSnapshot() { const now = Date.now(); const windowSec = config.summaryWindowSec || 300; const byRegion = store.byRegion({ from: now - windowSec*1000, to: now }); const regions = REGIONS.map(r => { const samples = byRegion.get(r.code) || []; const s = samples.length ? summarize(samples) : null; return { ...r, count: samples.length, p50: s?.p50 ?? null, p95: s?.p95 ?? null, p99: s?.p99 ?? null, avg: s?.avg ?? null, errorRate: s?.errorRate ?? null, availability: s?.availability ?? null, cacheHitRate: s?.cacheHitRate ?? null, breakdown: s?.breakdown ?? null, status: statusOf(s, samples.length), simulated: samples.length ? !!samples[samples.length-1].simulated : false, lastTs: samples.length ? samples[samples.length-1].ts : null, }; }); const recommendations = buildRecommendations({ store, config, windowSec: 900 }); return { ts: now, windowSec, regions, alerts: alertEngine.activeAlerts(), alertHistory: alertEngine.history.slice(-50).reverse(), recommendations, meta: { lastRunAt: scheduler.lastRunAt, nextRunAt: scheduler.nextRunAt, intervalSec: config.probeIntervalSec, probing: scheduler.running, cycles: scheduler.cycleCount, targets: config.targets.map(t => ({id:t.id,name:t.name,url:t.url})), totalSamples: store.totalSamples(), }, }; } ``` statusOf: 'unknown' if no data, 'healthy' if availability >= 0.99 and p95 < threshold, 'degraded', 'critical'. Let me define thresholds in config: `statusThresholds: { p95Warn: 500, p95Crit: 1000, errorWarn: 0.02, errorCrit: 0.1, availabilityWarn: 0.99, availabilityCrit: 0.95 }`. scheduleSnapshot: debounce, rebuild and broadcast at most every 3 s. ```js function scheduleSnapshot() { if (snapshotTimer) return; snapshotTimer = setTimeout(() => { snapshotTimer = null; lastSnapshot = buildSnapshot(); broadcast('snapshot', lastSnapshot); }, 500); } ``` And a heartbeat every 5 s to broadcast. Actually, let's broadcast the snapshot on every cycle completion + every 10s heartbeat (rebuild). Endpoints: ```js app.get('/api/config', (req,res) => res.json(publicConfig())); app.put('/api/config', (req,res) => { ... update probeIntervalSec, alerts, targets ... saveConfig; res.json(publicConfig()); }); app.get('/api/regions', (req,res) => res.json(regionList())); app.get('/api/snapshot', (req,res) => res.json(lastSnapshot || buildSnapshot())); app.get('/api/timeseries', ...); app.get('/api/comparison', ...); app.get('/api/recommendations', ...); app.get('/api/export.csv', ...); app.post('/api/probe/run', async (req,res) => { const r = await scheduler.runOnce(); scheduleSnapshot(); res.json(r); }); app.get('/api/stream', ...); ``` timeseries: ```js app.get('/api/timeseries', (req, res) => { const region = req.query.region; const targetId = req.query.target || null; const to = req.query.to ? Number(req.query.to) : Date.now(); const from = req.query.from ? Number(req.query.from) : to - 3600e3; const bucketSec = Math.max(10, Number(req.query.bucketSec || 60)); const samples = store.query({ region, targetId, from, to }); const buckets = bucketize(samples, from, to, bucketSec*1000); res.json({ region, targetId, from, to, bucketSec, buckets, summary: summarize(samples) }); }); ``` comparison: ```js app.get('/api/comparison', (req, res) => { const region = req.query.region; const targetId = req.query.target || null; const windowSec = Number(req.query.windowSec || 3600); const now = Date.now(); const current = summarize(store.query({ region, targetId, from: now - windowSec*1000, to: now })); const previous = summarize(store.query({ region, targetId, from: now - 2*windowSec*1000, to: now - windowSec*1000 })); res.json({ region, targetId, windowSec, current, previous, delta: computeDelta(current, previous) }); }); ``` computeDelta in stats.js. CSV export. OK, now write the frontend. Let me finalize and write everything out. I'll be careful. For the frontend, I need to keep it manageable but functional. Let me write it. ```html CDN Distribution Monitor ... ``` Now app.js. I'll write it as an IIFE or module. Let me write it now in full. ```js const $ = (sel) => document.querySelector(sel); const state = { regions: [], config: null, snapshot: null, markers: new Map(), map: null, selectedRegion: null, chart: null, autoRefresh: true, }; ``` initMap: ```js function initMap() { const map = L.map('map', { minZoom: 1, maxZoom: 8, worldCopyJump: true, attributionControl: true }); map.setView([25, 5], 2); L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { subdomains: 'abcd', maxZoom: 19, attribution: '© OpenStreetMap contributors © CARTO' }).addTo(map); state.map = map; } ``` Careful: setting maxZoom 8 while tiles go to 19 is fine. renderMap(regions): ```js function renderMap(regions) { for (const r of regions) { const color = statusColor(r.status); let marker = state.markers.get(r.code); if (!marker) { marker = L.circleMarker([r.lat, r.lng], { radius: 8, color, weight: 2, fillColor: color, fillOpacity: 0.65, }).addTo(state.map); marker.on('click', () => selectRegion(r.code)); state.markers.set(r.code, marker); } marker.setStyle({ color, fillColor: color, radius: r.status === 'critical' ? 13 : r.status === 'degraded' ? 10 : 8 }); marker.bindTooltip(`${r.name}
p95: ${fmtMs(r.p95)} · err: ${fmtPct(r.errorRate)}`, { direction: 'top' }); } } ``` Hmm, bindTooltip each render replaces. Fine. selectRegion: sets state.selectedRegion, updates detail, fetches timeseries + comparison. Chart rendering with Chart.js: ```js async function renderDetail(regionCode) { const region = state.regions.find(r => r.code === regionCode); const target = state.config.targets[0]; const to = Date.now(), from = to - 6*3600*1000; const [ts, cmp] = await Promise.all([ fetchJson(`/api/timeseries?region=${regionCode}&target=${target.id}&from=${from}&to=${to}&bucketSec=300`), fetchJson(`/api/comparison?region=${regionCode}&target=${target.id}&windowSec=3600`), ]); ... } ``` Chart: labels = bucket times, datasets: p95 (line, y axis 0), errorRate*100 (line, y1). OK. Rules editor: render a table from state.config.alerts, with inputs bound by data-index and data-field. Save button collects and PUTs. Let me write the code. Now, let me also handle the "detection frequency" setting: a select for probeIntervalSec with options 15/30/60/120/300/600. Alright. Writing final code now. One thing — the `express.static` and `express.json` order: put json before static, fine. Also need to handle config reload when PUT changes interval → restart scheduler. ```js app.put('/api/config', (req, res) => { const body = req.body || {}; if (body.probeIntervalSec != null) config.probeIntervalSec = clamp(Number(body.probeIntervalSec), 5, 3600); if (Array.isArray(body.alerts)) config.alerts = body.alerts; if (Array.isArray(body.targets) && body.targets.length) config.targets = body.targets; if (body.summaryWindowSec != null) config.summaryWindowSec = clamp(Number(body.summaryWindowSec), 30, 3600); if (body.statusThresholds) config.statusThresholds = { ...config.statusThresholds, ...body.statusThresholds }; saveConfig(config); scheduler.stop(); scheduler.start(); scheduleSnapshot(); res.json(publicConfig()); }); ``` Careful: scheduler.start() runs a probe immediately. Maybe just reschedule without immediate run. I'll add `scheduler.restart()` that reschedules without running immediately... Actually running immediately is fine and gives quick feedback. But it could be surprising. Let me add a `restart({ runNow = false })`. Simplify: `scheduler.stop(); scheduler.setInterval(); scheduler.start();` — start() runs once immediately. I'll just accept it, but let me make start() not run immediately if it was already run recently... Overkill. I'll make start() schedule only, and call runOnce() explicitly at boot. ```js start() { this.stop(); this._schedule(); } ``` And at boot: `scheduler.start(); scheduler.runOnce();`. Good, cleaner. Now writing everything out for real. Let me write the config.js: ```js 'use strict'; const fs = require('fs'); const path = require('path'); const CONFIG_PATH = path.join(__dirname, '..', 'config.json'); const DEFAULTS = { port: 8787, probeIntervalSec: 60, summaryWindowSec: 300, historyRetentionHours: 72, requestTimeoutMs: 10000, maxBytes: 131072, simulateMissingRegions: true, agents: {}, regions: [...], targets: [...], statusThresholds: {...}, alerts: [...], webhook: { enabled: false, url: '' } }; ``` I'll put regions list in regions.js and reference default all region codes. loadConfig: read file if exists, deep merge with defaults, write back if missing. OK, final write-up. Let me count the files: 1. package.json 2. config.json (optional — generated) 3. server.js 4. agent.js 5. src/regions.js 6. src/stats.js 7. src/store.js 8. src/prober.js 9. src/scheduler.js 10. src/alerts.js 11. src/recommend.js 12. src/config.js 13. public/index.html 14. public/style.css 15. public/app.js 16. README.md That's a lot but let's do it. I'll keep each file focused. Let me write. For regions baseMs (simulated p50 latency to a US-East origin): - us-east-1: 35 - us-east-2: 55 - us-west-1: 95 - us-west-2: 85 - ca-central-1: 70 - sa-east-1: 160 - eu-west-1: 110 - eu-west-2: 115 - eu-central-1: 125 - eu-north-1: 140 - af-south-1: 230 - me-south-1: 200 - ap-south-1: 210 - ap-southeast-1: 240 - ap-northeast-1: 180 - ap-east-1: 200 - ap-northeast-2: 190 - ap-southeast-2: 250 Good. Now writing. For the `simulateProbe`, I need `getRegion`. Let me write prober.js fully. Also I should make sure `probeOnce` is exported for agent.js. Now, in `simulateProbe`, produce a full sample shape. ```js function simulateProbe({ region, target }) { const r = getRegion(region) || { baseMs: 150 }; const key = `${region}::${target.id}`; const now = Date.now(); let st = SIM_STATE.get(key); if (!st) { st = { incidentUntil: 0, severity: 1, pop: pickPop(region) }; SIM_STATE.set(key, st); } if (now >= st.incidentUntil && Math.random() < 0.015) { st.incidentUntil = now + (90 + Math.random() * 600) * 1000; st.severity = 1.6 + Math.random() * 2.6; } const degraded = now < st.incidentUntil; const base = r.baseMs; const hour = new Date(now).getUTCHours(); const diurnal = 1 + 0.15 * Math.sin(((hour - 4) / 24) * Math.PI * 2); const noise = 0.85 + Math.random() * 0.35; const mult = degraded ? st.severity : 1; const dnsMs = round(4 + Math.random() * 22); const connectMs = round((8 + Math.random() * 30) * mult); const tlsMs = target.url.startsWith('https') ? round((20 + Math.random() * 45) * mult) : null; const waitMs = round(base * diurnal * noise * mult * 0.75); const ttfbMs = round(dnsMs + connectMs + (tlsMs || 0) + waitMs); const bytes = Math.round(20000 + Math.random() * 180000); const totalMs = round(ttfbMs + bytes / (120 + Math.random() * 400) * 8); // hmm ... } ``` Simplify: totalMs = ttfbMs + downloadMs, downloadMs = 20 + Math.random()*180. errorRate = degraded ? min(0.35, 0.03 * st.severity) : 0.003. isError = Math.random() < errorRate. If error: status 502/503/504/0 with error 'http_502' etc. totalMs may be ttfb or null. cacheHit = Math.random() < (degraded ? 0.55 : 0.88). pop: use a mapping region→pop code. I'll add `pop` field to REGIONS entries. OK good — add `pop` to each region definition. Now writing for real. Let me produce the final answer. I'll present the files with brief explanations and a run guide. Let me be careful about one thing in `bucketize`: ```js function bucketize(samples, from, to, bucketMs) { const n = Math.max(1, Math.ceil((to - from) / bucketMs)); const buckets = Array.from({ length: n }, (_, i) => ({ ts: from + i * bucketMs, samples: [] })); for (const s of samples) { const i = Math.min(n - 1, Math.max(0, Math.floor((s.ts - from) / bucketMs))); buckets[i].samples.push(s); } return buckets.map(b => { const sum = b.samples.length ? summarize(b.samples) : null; return { ts: b.ts, count: b.samples.length, ...(sum || {}) }; }); } ``` Careful with `...sum` overriding `ts`? summarize doesn't return ts. OK. But it returns `count` too — fine, same value. If n is huge (e.g., 6h with 10s buckets = 2160), fine. Guard n <= 5000. Alright, writing. Also for the trend comparison in the frontend I'll show delta arrows. Let me write everything now. One more: `publicConfig()` should not leak webhook secret. I'll include webhook.url though since it's local. Fine, just include everything except nothing. Final: write the README with instructions. Let me write out the code. Actually for `store.totalSamples()`: ```js totalSamples() { let n = 0; for (const arr of this.series.values()) n += arr.length; return n; } ``` OK. Writing now — final answer. For style.css I'll write a compact dark theme. Let me make sure the Chart.js usage is correct: `new Chart(ctx, { type: 'line', data: {...}, options: {...} })`. For dual axis: `scales: { y: {...}, y1: { position: 'right', grid: { drawOnChartArea: false } } }`. OK writing. I also need to handle the case where `/api/comparison` returns null current/previous (no data) — guard in the frontend. Let me write the final code. Also, in `alerts.js`, `expand` function: ```js function expand(list, all) { if (!Array.isArray(list) || list.length === 0 || list.includes('*')) return all.slice(); return list.filter(x => all.includes(x)); } ``` Now writing out. Let me also make sure `AlertEngine.activeAlerts()` returns objects with rule info. ```js activeAlerts() { const out = []; for (const [key, st] of this.states) { if (!st.firing) continue; out.push({ ...st.meta, key, since: st.breachedSince, severity: st.rule.severity, ruleName: st.rule.name, metric: st.rule.metric, threshold: st.rule.threshold, comparator: st.rule.comparator, value: st.lastValue, region: st.region, targetId: st.targetId }); } return out; } ``` I'll store meta on the state. OK. Write. Time to output. I'll organize the answer with a file tree, then the code, then run instructions. Let me write the final code carefully now. Note on `req.destroy()` after finish in prober — after `finish()` is called and settled, subsequent 'error' events from destroy will call settle again but it's guarded. Good. Actually there's an issue: in the `res.on('data')` handler, when bytes >= maxBytes, I call `finish()` then `req.destroy()`. `finish()` reads `res.headers` and `res.statusCode` — fine. But then `req.destroy()` triggers 'error' on req with `ECONNRESET` maybe — guarded by `settled`. Good. But careful: `finish` could be called twice (once from data threshold, once from 'end'). Guarded by `settled` in `settle`. But `finish` itself does work twice — minor. Add a local guard. Let me add `let responded = false;` in the response handler. OK, final. Also: `req.on('timeout')` — Node's `timeout` option sets socket timeout; the request emits 'timeout' but doesn't abort automatically, so destroy is right. Writing now. For the frontend fetch of `/api/config`, the config contains `targets`, `alerts`, `probeIntervalSec`, etc. Let me finalize. I'll write `public/app.js` with sections: helpers, map, detail, charts, alerts, recommendations, rules. Alright, generating the answer. Length is going to be big but that's expected. Let me go. One more detail for `statusOf`: ```js function statusOf(summary, count) { if (!summary || count === 0) return 'unknown'; const t = config.statusThresholds; if (summary.availability < t.availabilityCrit || summary.errorRate > t.errorCrit || summary.p95 > t.p95Crit) return 'critical'; if (summary.availability < t.availabilityWarn || summary.errorRate > t.errorWarn || summary.p95 > t.p95Warn) return 'degraded'; return 'healthy'; } ``` Careful with null p95 (all errors). Guard. OK writing. In recommend.js, `buildRecommendations` signature `{ store, config, windowSec }`. Let's also pass `baselineHours`. Let me write it. ```js function buildRecommendations({ store, config, windowSec = 900, baselineHours = 24 }) { const now = Date.now(); const curMap = store.byRegion({ from: now - windowSec * 1000, to: now }); const baseMap = store.byRegion({ from: now - baselineHours * 3600e3, to: now - 3600e3 }); const rows = []; for (const [region, samples] of curMap) { if (!samples.length) continue; const current = summarize(samples); const bSamples = baseMap.get(region) || []; const baseline = bSamples.length >= 5 ? summarize(bSamples) : null; rows.push({ region, current, baseline }); } if (!rows.length) return []; // fallback baseline: median p95 across regions in current window const p95s = rows.map(r => r.current.p95).filter(v => v != null).sort((a,b)=>a-b); const fallbackP95 = p95s.length ? p95s[Math.floor(p95s.length/2)] : null; const recs = []; for (const row of rows) { const { region, current, baseline } = row; const baseP95 = baseline?.p95 ?? fallbackP95; const ratio = baseP95 && current.p95 ? current.p95 / baseP95 : null; const errRate = current.errorRate ?? 0; const avail = current.availability ?? 1; const cacheRate = current.cacheHitRate; const issues = []; if (ratio != null && ratio >= 1.5) issues.push(`p95 latency ${fmtMs(current.p95)} vs baseline ${fmtMs(baseP95)} (${ratio.toFixed(2)}x)`); if (errRate >= 0.05) issues.push(`error rate ${(errRate*100).toFixed(1)}%`); if (avail < 0.99) issues.push(`availability ${(avail*100).toFixed(2)}%`); if (cacheRate != null && cacheRate < 0.6) issues.push(`cache hit rate ${(cacheRate*100).toFixed(0)}%`); if (!issues.length) continue; ... } } ``` Severity: score = 0; weight. Candidate regions: healthy rows (no issues) sorted by p95 asc, prefer same area. Actions from dominant phase. Then push rec. Sort recs by score desc. Let me write helper `fmtMs`. OK, writing the answer now. Final. I also need `getRegion` in recommend for area matching. Alright. Let me write the code output now, carefully. Also note: in `buildRecommendations` I use `store.byRegion({ from, to })` which returns Map. Good. Let me write it all. For the "CDN node switching recommendation", I'll frame candidate PoPs as `switchCandidates`. Final output time. I'll write concise but complete code. ### assistant · answer Here's a complete CDN distribution monitoring tool with a Node.js backend and a Leaflet-based map dashboard. It probes your website from multiple global regions, visualizes latency and error rates, supports alert rules, and generates node switching recommendations. ```bash cdn-monitor/ ├── package.json ├── config.json # auto-generated on first run ├── server.js # API + SSE + static host ├── agent.js # deployable remote probe agent ├── src/ │ ├── regions.js # global region/PoP catalog │ ├── stats.js # percentile / summarize / bucketize │ ├── store.js # time-series ring buffer + JSONL persistence │ ├── prober.js # HTTP timing probe + agent + simulator │ ├── scheduler.js # frequency-controlled probe scheduler │ ├── alerts.js # alert rules engine │ ├── recommend.js # degradation analysis & PoP switch advice │ └── config.js # config load/save/defaults └── public/ ├── index.html ├── style.css └── app.js ``` ## 1. `package.json` ```json { "name": "cdn-monitor", "version": "1.0.0", "private": true, "description": "Global CDN distribution monitoring, alerting and PoP switching advisor", "main": "server.js", "scripts": { "start": "node server.js", "agent": "node agent.js", "dev": "node --watch server.js" }, "engines": { "node": ">=18.0.0" }, "dependencies": { "express": "^4.19.2" } } ``` ## 2. `src/regions.js` ```js 'use strict'; /** Global probe regions. `baseMs` is the simulated p50 RTT to a US-East origin. */ const REGIONS = [ { code: 'us-east-1', name: 'N. Virginia, US', lat: 38.13, lng: -78.45, area: 'north-america', pop: 'IAD', baseMs: 35 }, { code: 'us-east-2', name: 'Ohio, US', lat: 40.00, lng: -83.02, area: 'north-america', pop: 'CMH', baseMs: 55 }, { code: 'us-west-1', name: 'N. California, US', lat: 37.77, lng: -122.42, area: 'north-america', pop: 'SFO', baseMs: 95 }, { code: 'us-west-2', name: 'Oregon, US', lat: 45.87, lng: -119.69, area: 'north-america', pop: 'PDX', baseMs: 85 }, { code: 'ca-central-1', name: 'Montreal, CA', lat: 45.50, lng: -73.57, area: 'north-america', pop: 'YUL', baseMs: 70 }, { code: 'sa-east-1', name: 'São Paulo, BR', lat: -23.55, lng: -46.63, area: 'south-america', pop: 'GRU', baseMs: 160 }, { code: 'eu-west-1', name: 'Dublin, IE', lat: 53.41, lng: -8.24, area: 'europe', pop: 'DUB', baseMs: 110 }, { code: 'eu-west-2', name: 'London, UK', lat: 51.51, lng: -0.13, area: 'europe', pop: 'LHR', baseMs: 115 }, { code: 'eu-central-1', name: 'Frankfurt, DE', lat: 50.11, lng: 8.68, area: 'europe', pop: 'FRA', baseMs: 125 }, { code: 'eu-north-1', name: 'Stockholm, SE', lat: 59.33, lng: 18.06, area: 'europe', pop: 'ARN', baseMs: 140 }, { code: 'af-south-1', name: 'Cape Town, ZA', lat: -33.92, lng: 18.42, area: 'africa', pop: 'CPT', baseMs: 230 }, { code: 'me-south-1', name: 'Bahrain', lat: 26.07, lng: 50.55, area: 'middle-east', pop: 'BAH', baseMs: 200 }, { code: 'ap-south-1', name: 'Mumbai, IN', lat: 19.08, lng: 72.88, area: 'asia', pop: 'BOM', baseMs: 210 }, { code: 'ap-southeast-1', name: 'Singapore, SG', lat: 1.35, lng: 103.82, area: 'asia', pop: 'SIN', baseMs: 240 }, { code: 'ap-northeast-1', name: 'Tokyo, JP', lat: 35.68, lng: 139.69, area: 'asia', pop: 'NRT', baseMs: 180 }, { code: 'ap-northeast-2', name: 'Seoul, KR', lat: 37.57, lng: 126.98, area: 'asia', pop: 'ICN', baseMs: 190 }, { code: 'ap-east-1', name: 'Hong Kong, HK', lat: 22.32, lng: 114.17, area: 'asia', pop: 'HKG', baseMs: 200 }, { code: 'ap-southeast-2', name: 'Sydney, AU', lat: -33.87, lng: 151.21, area: 'oceania', pop: 'SYD', baseMs: 250 } ]; const REGION_MAP = new Map(REGIONS.map((r) => [r.code, r])); function getRegion(code) { return REGION_MAP.get(code) || null; } function regionList() { return REGIONS.map((r) => ({ ...r })); } function allRegionCodes() { return REGIONS.map((r) => r.code); } module.exports = { REGIONS, REGION_MAP, getRegion, regionList, allRegionCodes }; ``` ## 3. `src/stats.js` ```js 'use strict'; function percentile(values, p) { if (!values || values.length === 0) return null; const a = values.slice().sort((x, y) => x - y); if (a.length === 1) return a[0]; const idx = (a.length - 1) * p; const lo = Math.floor(idx); const hi = Math.ceil(idx); if (lo === hi) return a[lo]; return a[lo] + (a[hi] - a[lo]) * (idx - lo); } function round1(v) { return v == null || Number.isNaN(v) ? null : Math.round(v * 10) / 10; } function avgOf(samples, field) { const vals = samples.map((s) => s[field]).filter((v) => typeof v === 'number' && !Number.isNaN(v)); if (!vals.length) return null; return round1(vals.reduce((a, b) => a + b, 0) / vals.length); } function countBy(samples, fn) { const out = {}; for (const s of samples) { const k = String(fn(s) ?? 'unknown'); out[k] = (out[k] || 0) + 1; } return out; } /** Aggregate a raw sample list into a metric summary. */ function summarize(samples) { if (!samples || samples.length === 0) return null; const n = samples.length; const okSamples = samples.filter((s) => s.ok); const okLat = okSamples.map((s) => s.totalMs).filter((v) => typeof v === 'number' && !Number.isNaN(v)); const cacheKnown = samples.filter((s) => s.cacheHit === true || s.cacheHit === false); return { count: n, okCount: okSamples.length, errorCount: n - okSamples.length, availability: okSamples.length / n, errorRate: 1 - okSamples.length / n, p50: round1(percentile(okLat, 0.5)), p95: round1(percentile(okLat, 0.95)), p99: round1(percentile(okLat, 0.99)), avg: okLat.length ? round1(okLat.reduce((a, b) => a + b, 0) / okLat.length) : null, min: okLat.length ? round1(okLat.reduce((a, b) => (a < b ? a : b))) : null, max: okLat.length ? round1(okLat.reduce((a, b) => (a > b ? a : b))) : null, cacheHitRate: cacheKnown.length ? cacheKnown.filter((s) => s.cacheHit).length / cacheKnown.length : null, breakdown: { dnsMs: avgOf(samples, 'dnsMs'), connectMs: avgOf(samples, 'connectMs'), tlsMs: avgOf(samples, 'tlsMs'), ttfbMs: avgOf(samples, 'ttfbMs'), waitMs: avgOf(samples, 'waitMs') }, statusCodes: countBy(samples, (s) => s.status || s.error || 'unknown'), pops: countBy(samples, (s) => s.pop || 'unknown') }; } /** Split samples into fixed-size time buckets, summarizing each. */ function bucketize(samples, from, to, bucketMs) { const span = Math.max(bucketMs, to - from); const n = Math.min(5000, Math.max(1, Math.ceil(span / bucketMs))); const buckets = Array.from({ length: n }, (_, i) => ({ ts: from + i * bucketMs, list: [] })); for (const s of samples) { const i = Math.min(n - 1, Math.max(0, Math.floor((s.ts - from) / bucketMs))); buckets[i].list.push(s); } return buckets.map((b) => { const sum = b.list.length ? summarize(b.list) : null; return { ts: b.ts, count: b.list.length, p50: sum?.p50 ?? null, p95: sum?.p95 ?? null, p99: sum?.p99 ?? null, avg: sum?.avg ?? null, errorRate: sum?.errorRate ?? null, availability: sum?.availability ?? null, cacheHitRate: sum?.cacheHitRate ?? null }; }); } function pctChange(current, previous) { if (current == null || previous == null || previous === 0) return null; return (current - previous) / previous; } /** Compare two summaries and return per-metric deltas. */ function computeDelta(current, previous) { if (!current) return null; const keys = ['p50', 'p95', 'p99', 'avg', 'errorRate', 'availability', 'cacheHitRate']; const out = { baseline: previous || null }; for (const k of keys) { const c = current[k] ?? null; const p = previous ? previous[k] ?? null : null; out[k] = { current: c, previous: p, absolute: c != null && p != null ? round1(c - p) : null, percent: pctChange(c, p) }; } return out; } module.exports = { percentile, summarize, bucketize, computeDelta, pctChange, round1, countBy, avgOf }; ``` ## 4. `src/store.js` ```js 'use strict'; const fs = require('fs'); const path = require('path'); /** * Append-only time-series store. * In-memory ring buffer per (targetId, region) series + JSONL persistence. */ class Store { constructor({ dataDir = './data', retentionHours = 72, maxPerSeries = 20000 } = {}) { this.dataDir = dataDir; this.retentionMs = retentionHours * 3600 * 1000; this.maxPerSeries = maxPerSeries; this.series = new Map(); this.totalWritten = 0; fs.mkdirSync(dataDir, { recursive: true }); this.file = path.join(dataDir, 'samples.jsonl'); this._load(); this._out = fs.createWriteStream(this.file, { flags: 'a' }); } _key(targetId, region) { return `${targetId}::${region}`; } _load() { if (!fs.existsSync(this.file)) return; let content; try { const stat = fs.statSync(this.file); if (stat.size > 256 * 1024 * 1024) { console.warn('[store] samples.jsonl > 256MB, skipping full reload'); return; } content = fs.readFileSync(this.file, 'utf8'); } catch (err) { console.warn('[store] load failed:', err.message); return; } const cutoff = Date.now() - this.retentionMs; let loaded = 0; for (const line of content.split('\n')) { if (!line) continue; let s; try { s = JSON.parse(line); } catch { continue; } if (!s || !s.ts || s.ts < cutoff || !s.region || !s.targetId) continue; const k = this._key(s.targetId, s.region); let arr = this.series.get(k); if (!arr) { arr = []; this.series.set(k, arr); } arr.push(s); loaded++; } if (loaded) console.log(`[store] restored ${loaded} samples (${this.series.size} series)`); } add(sample) { if (!sample || !sample.region || !sample.targetId || !sample.ts) return; const k = this._key(sample.targetId, sample.region); let arr = this.series.get(k); if (!arr) { arr = []; this.series.set(k, arr); } arr.push(sample); if (arr.length > this.maxPerSeries) arr.splice(0, arr.length - this.maxPerSeries); this.totalWritten++; try { this._out.write(JSON.stringify(sample) + '\n'); } catch { /* ignore */ } } addMany(samples) { for (const s of samples) this.add(s); } prune(now = Date.now()) { const cutoff = now - this.retentionMs; for (const [k, arr] of this.series) { let i = 0; while (i < arr.length && arr[i].ts < cutoff) i++; if (i > 0) arr.splice(0, i); if (arr.length === 0) this.series.delete(k); } } query({ targetId = null, region = null, from = 0, to = Date.now() } = {}) { const out = []; for (const [k, arr] of this.series) { const sep = k.indexOf('::'); const t = k.slice(0, sep); const r = k.slice(sep + 2); if (targetId && t !== targetId) continue; if (region && r !== region) continue; for (const s of arr) if (s.ts >= from && s.ts <= to) out.push(s); } out.sort((a, b) => a.ts - b.ts); return out; } /** Returns Map */ byRegion({ from = 0, to = Date.now(), targetId = null } = {}) { const map = new Map(); for (const s of this.query({ targetId, from, to })) { let arr = map.get(s.region); if (!arr) { arr = []; map.set(s.region, arr); } arr.push(s); } return map; } /** Returns Map> */ byTargetRegion({ from = 0, to = Date.now() } = {}) { const map = new Map(); for (const s of this.query({ from, to })) { let byRegion = map.get(s.targetId); if (!byRegion) { byRegion = new Map(); map.set(s.targetId, byRegion); } let arr = byRegion.get(s.region); if (!arr) { arr = []; byRegion.set(s.region, arr); } arr.push(s); } return map; } latest(region, targetId) { const arr = this.series.get(this._key(targetId, region)); return arr && arr.length ? arr[arr.length - 1] : null; } totalSamples() { let n = 0; for (const arr of this.series.values()) n += arr.length; return n; } close() { try { this._out.end(); } catch { /* ignore */ } } } module.exports = { Store }; ``` ## 5. `src/prober.js` ```js 'use strict'; const http = require('http'); const https = require('https'); const { getRegion } = require('./regions'); const DEFAULT_UA = 'CDNMonitor/1.0 (+https://github.com/example/cdn-monitor)'; function hrToMs(a, b) { if (a == null || b == null) return null; return Number(b - a) / 1e6; } function round1(v) { return v == null || Number.isNaN(v) ? null : Math.round(v * 10) / 10; } /** Extract CDN provider / PoP / cache status from response headers. */ function extractCdnInfo(headers = {}) { const h = {}; for (const [k, v] of Object.entries(headers)) h[k.toLowerCase()] = v; let provider = null; let pop = null; if (h['cf-ray']) { provider = 'cloudflare'; pop = String(h['cf-ray']).split('-').pop(); } else if (h['x-amz-cf-pop']) { provider = 'cloudfront'; pop = String(h['x-amz-cf-pop']); } else if (h['x-served-by']) { provider = 'fastly'; const parts = String(h['x-served-by']).split('-'); pop = parts[parts.length - 1]; } else if (h['x-akamai-transformed'] || h['akamai-grn']) { provider = 'akamai'; pop = h['akamai-grn'] ? String(h['akamai-grn']) : null; } else if (h['x-azure-ref']) { provider = 'azure-frontdoor'; } else if (h['x-cache'] && h['via']) { provider = 'generic'; } const cacheRaw = h['cf-cache-status'] || h['x-cache'] || h['x-cache-status'] || h['x-fastly-cache'] || null; let cacheHit = null; if (cacheRaw) { const s = String(cacheRaw).toUpperCase(); if (s.includes('HIT')) cacheHit = true; else if (/(MISS|EXPIRED|REVALIDATED|BYPASS|DYNAMIC|STALE)/.test(s)) cacheHit = false; } return { provider, pop: pop ? String(pop).toUpperCase() : null, cacheStatus: cacheRaw, cacheHit }; } /** * Perform a single HTTP(S) probe and return a fully populated sample. * Timing phases: DNS -> TCP connect -> TLS -> TTFB -> body download. */ function probeOnce({ url, method = 'GET', headers = {}, timeoutMs = 10000, maxBytes = 131072, region = null, targetId = null, source = 'local' }) { return new Promise((resolve) => { const startedAt = Date.now(); const t0 = process.hrtime.bigint(); const marks = {}; let settled = false; const settle = (payload) => { if (settled) return; settled = true; resolve({ ts: startedAt, region, targetId, url, ok: false, status: null, totalMs: null, dnsMs: null, connectMs: null, tlsMs: null, ttfbMs: null, waitMs: null, bytes: 0, provider: null, pop: null, cacheStatus: null, cacheHit: null, error: null, errorMessage: null, source, ...payload }); }; let parsed; try { parsed = new URL(url); } catch (err) { return settle({ error: 'invalid_url', errorMessage: String(err.message) }); } if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { return settle({ error: 'unsupported_protocol', errorMessage: parsed.protocol }); } const isHttps = parsed.protocol === 'https:'; const lib = isHttps ? https : http; const req = lib.request({ protocol: parsed.protocol, hostname: parsed.hostname, port: parsed.port || (isHttps ? 443 : 80), path: `${parsed.pathname}${parsed.search}`, method, headers: { 'user-agent': DEFAULT_UA, accept: '*/*', 'accept-encoding': 'identity', 'cache-control': 'no-cache', ...headers }, timeout: timeoutMs, agent: false // force a fresh connection so handshake timings are meaningful }); req.on('socket', (socket) => { socket.once('lookup', () => { marks.dns = process.hrtime.bigint(); }); socket.once('connect', () => { marks.connect = process.hrtime.bigint(); }); socket.once('secureConnect', () => { marks.tls = process.hrtime.bigint(); }); }); req.on('response', (res) => { marks.ttfb = process.hrtime.bigint(); let bytes = 0; let responded = false; const finish = () => { if (responded) return; responded = true; const tEnd = process.hrtime.bigint(); const cdn = extractCdnInfo(res.headers); const handshakeEnd = marks.tls || marks.connect || t0; const status = res.statusCode; settle({ ok: status >= 200 && status < 400, status, totalMs: round1(hrToMs(t0, tEnd)), dnsMs: round1(hrToMs(t0, marks.dns)), connectMs: round1(hrToMs(marks.dns, marks.connect)), tlsMs: round1(hrToMs(marks.connect, marks.tls)), ttfbMs: round1(hrToMs(t0, marks.ttfb)), waitMs: round1(hrToMs(handshakeEnd, marks.ttfb)), bytes, provider: cdn.provider, pop: cdn.pop, cacheStatus: cdn.cacheStatus, cacheHit: cdn.cacheHit, error: status >= 400 ? `http_${status}` : null }); }; res.on('data', (chunk) => { bytes += chunk.length; if (bytes >= maxBytes) { finish(); req.destroy(); } }); res.on('end', finish); res.on('error', finish); }); req.on('timeout', () => { req.destroy(new Error('timeout')); }); req.on('error', (err) => { const tEnd = process.hrtime.bigint(); const code = err.code || (/timeout/i.test(err.message) ? 'ETIMEDOUT' : 'network_error'); settle({ ok: false, totalMs: round1(hrToMs(t0, tEnd)), dnsMs: round1(hrToMs(t0, marks.dns)), connectMs: round1(hrToMs(marks.dns, marks.connect)), tlsMs: round1(hrToMs(marks.connect, marks.tls)), error: code, errorMessage: err.message }); }); req.end(); }); } /** Call a remote probe agent deployed in another region. */ async function remoteProbe({ agentUrl, target, region, timeoutMs = 10000 }) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs + 3000); try { const res = await fetch(agentUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ url: target.url, method: target.method || 'GET', headers: target.headers || {}, timeoutMs, targetId: target.id }), signal: controller.signal }); if (!res.ok) throw new Error(`agent responded ${res.status}`); const json = await res.json(); return { ...json, region, targetId: target.id, source: 'agent' }; } catch (err) { return { ts: Date.now(), region, targetId: target.id, url: target.url, ok: false, totalMs: null, error: 'agent_unreachable', errorMessage: err.message, source: 'agent' }; } finally { clearTimeout(timer); } } /* ------------------------------------------------------------------ */ /* Simulator: used for regions without a deployed agent (demo mode). */ /* ------------------------------------------------------------------ */ const SIM_STATE = new Map(); function simulateProbe({ region, target }) { const meta = getRegion(region) || { baseMs: 150, pop: 'XXX' }; const key = `${region}::${target.id}`; const now = Date.now(); let st = SIM_STATE.get(key); if (!st) { st = { incidentUntil: 0, severity: 1 }; SIM_STATE.set(key, st); } // Random incident window (degraded PoP / origin trouble) if (now >= st.incidentUntil && Math.random() < 0.015) { st.incidentUntil = now + (90 + Math.random() * 600) * 1000; st.severity = 1.6 + Math.random() * 2.6; } const degraded = now < st.incidentUntil; const mult = degraded ? st.severity : 1; const hour = new Date(now).getUTCHours(); const diurnal = 1 + 0.15 * Math.sin(((hour - 4) / 24) * Math.PI * 2); const noise = 0.85 + Math.random() * 0.35; const dnsMs = round1(4 + Math.random() * 22); const connectMs = round1((8 + Math.random() * 30) * mult); const tlsMs = String(target.url).startsWith('https') ? round1((20 + Math.random() * 45) * mult) : null; const waitMs = round1(meta.baseMs * diurnal * noise * mult * 0.75); const ttfbMs = round1(dnsMs + connectMs + (tlsMs || 0) + waitMs); const bytes = Math.round(20000 + Math.random() * 180000); const totalMs = round1(ttfbMs + 15 + Math.random() * 160); const errorRate = degraded ? Math.min(0.35, 0.03 * st.severity) : 0.003; const isError = Math.random() < errorRate; const cacheHit = Math.random() < (degraded ? 0.55 : 0.88); const statuses = [502, 503, 504]; const status = isError ? statuses[Math.floor(Math.random() * statuses.length)] : 200; return { ts: now, region, targetId: target.id, url: target.url, ok: !isError, status, totalMs: isError && Math.random() < 0.4 ? null : totalMs, dnsMs, connectMs, tlsMs, ttfbMs, waitMs, bytes, provider: 'simulated', pop: meta.pop, cacheStatus: cacheHit ? 'HIT' : 'MISS', cacheHit, error: isError ? `http_${status}` : null, errorMessage: null, simulated: true, source: 'simulator' }; } module.exports = { probeOnce, remoteProbe, simulateProbe, extractCdnInfo }; ``` ## 6. `src/scheduler.js` ```js 'use strict'; const { probeOnce, remoteProbe, simulateProbe } = require('./prober'); /** * Runs probe cycles across every (target x region) pair at a configurable * frequency. Falls back to a remote agent or the simulator per region. */ class Scheduler { constructor({ config, store, onSample, onCycle }) { this.config = config; this.store = store; this.onSample = onSample || (() => {}); this.onCycle = onCycle || (() => {}); this.timer = null; this.running = false; this.lastRunAt = null; this.nextRunAt = null; this.cycleCount = 0; this.lastCycle = null; } get intervalMs() { return Math.max(5, Number(this.config.probeIntervalSec) || 60) * 1000; } start() { this.stop(); this._schedule(); } stop() { if (this.timer) clearTimeout(this.timer); this.timer = null; } _schedule() { const delay = this.intervalMs; this.nextRunAt = Date.now() + delay; this.timer = setTimeout(async () => { try { await this.runOnce(); } catch (err) { console.error('[scheduler] cycle failed:', err.message); } this._schedule(); }, delay); } async runOnce() { if (this.running) return { skipped: true, reason: 'already_running' }; this.running = true; const started = Date.now(); this.cycleCount++; const tasks = []; for (const target of this.config.targets || []) { for (const region of this.config.regions || []) { tasks.push({ target, region }); } } const concurrency = Math.min(8, Math.max(1, tasks.length)); let cursor = 0; const results = []; const worker = async () => { while (cursor < tasks.length) { const { target, region } = tasks[cursor++]; const sample = await this._probe(target, region); results.push(sample); this.store.add(sample); this.onSample(sample); } }; try { await Promise.all(Array.from({ length: concurrency }, worker)); } finally { this.running = false; } this.lastRunAt = Date.now(); this.lastCycle = { ts: this.lastRunAt, durationMs: this.lastRunAt - started, samples: results.length, cycle: this.cycleCount, errors: results.filter((r) => !r.ok).length }; this.onCycle(this.lastCycle); return this.lastCycle; } async _probe(target, region) { const timeoutMs = Number(this.config.requestTimeoutMs) || 10000; const agentUrl = (this.config.agents || {})[region]; let sample; if (agentUrl) { sample = await remoteProbe({ agentUrl, target, region, timeoutMs }); } else if (this.config.simulateMissingRegions !== false) { sample = simulateProbe({ region, target }); } else { sample = await probeOnce({ url: target.url, method: target.method, headers: target.headers, timeoutMs, region, targetId: target.id, source: 'local' }); } return { ...sample, ts: sample.ts || Date.now(), region, targetId: target.id, targetName: target.name || target.id, url: target.url }; } } module.exports = { Scheduler }; ``` ## 7. `src/alerts.js` ```js 'use strict'; const { summarize } = require('./stats'); function expand(list, all) { if (!Array.isArray(list) || list.length === 0 || list.includes('*')) return all.slice(); return list.filter((x) => all.includes(x)); } function pickMetric(summary, metric) { switch (metric) { case 'p50': return summary.p50; case 'p95': return summary.p95; case 'p99': return summary.p99; case 'avg': return summary.avg; case 'errorRate': return summary.errorRate; case 'availability': return summary.availability; case 'cacheHitRate': return summary.cacheHitRate; default: return null; } } function compare(value, comparator, threshold) { switch (comparator) { case '>': return value > threshold; case '>=': return value >= threshold; case '<': return value < threshold; case '<=': return value <= threshold; case '==': return value === threshold; default: return false; } } /** * Stateful alert engine. A rule fires only after the condition has held * continuously for `forSec` seconds, and re-notification respects `cooldownSec`. */ class AlertEngine { constructor({ store, config, onEvent }) { this.store = store; this.config = config; this.onEvent = onEvent || (() => {}); this.states = new Map(); this.history = []; this.maxHistory = 500; } updateConfig(config) { this.config = config; } evaluate(now = Date.now()) { const events = []; const rules = this.config.alerts || []; const allRegions = (this.config.regions || []).slice(); const allTargets = (this.config.targets || []).map((t) => t.id); for (const rule of rules) { if (rule.enabled === false) continue; const windowMs = (Number(rule.windowSec) || 300) * 1000; const from = now - windowMs; const regions = expand(rule.regions, allRegions); const targets = expand(rule.targets, allTargets); for (const region of regions) { for (const targetId of targets) { const samples = this.store.query({ region, targetId, from, to: now }); if (samples.length < (Number(rule.minSamples) || 2)) continue; const summary = summarize(samples); const value = pickMetric(summary, rule.metric); if (value == null) continue; const breached = compare(value, rule.comparator, Number(rule.threshold)); const key = `${rule.id}::${region}::${targetId}`; let st = this.states.get(key); if (!st) { st = { rule, region, targetId, breachedSince: null, firing: false, lastNotifiedAt: 0, lastValue: null, peakValue: null }; this.states.set(key, st); } st.rule = rule; st.lastValue = value; st.peakValue = st.peakValue == null ? value : (rule.comparator.startsWith('>') ? Math.max(st.peakValue, value) : Math.min(st.peakValue, value)); if (breached) { if (!st.breachedSince) st.breachedSince = now; const heldFor = now - st.breachedSince; const required = (Number(rule.forSec) || 0) * 1000; const cooldownOk = now - st.lastNotifiedAt >= (Number(rule.cooldownSec) || 300) * 1000; if (heldFor >= required && !st.firing) { st.firing = true; st.lastNotifiedAt = now; const ev = this._event('fired', st, value, now); events.push(ev); } else if (st.firing && cooldownOk && rule.repeatNotify) { st.lastNotifiedAt = now; const ev = this._event('reminder', st, value, now); events.push(ev); } } else { st.breachedSince = null; st.peakValue = null; if (st.firing) { st.firing = false; const ev = this._event('resolved', st, value, now); events.push(ev); } } } } } for (const ev of events) { this.history.push(ev); if (this.history.length > this.maxHistory) this.history.shift(); this._notify(ev); } return events; } _event(type, st, value, ts) { const rule = st.rule; return { type, ts, ruleId: rule.id, ruleName: rule.name || rule.id, severity: rule.severity || 'warning', metric: rule.metric, comparator: rule.comparator, threshold: Number(rule.threshold), value, region: st.region, targetId: st.targetId, durationSec: st.breachedSince ? Math.round((ts - st.breachedSince) / 1000) : 0, message: type === 'resolved' ? `${rule.name || rule.id} recovered in ${st.region} (${rule.metric}=${fmt(value, rule.metric)})` : `${rule.name || rule.id} in ${st.region}: ${rule.metric}=${fmt(value, rule.metric)} ${rule.comparator} ${fmt(rule.threshold, rule.metric)}` }; } _notify(ev) { const tag = ev.severity === 'critical' ? '[CRITICAL]' : '[ALERT]'; console.log(`${tag} ${ev.type.toUpperCase()} ${ev.message}`); try { this.onEvent(ev); } catch { /* ignore */ } const wh = this.config.webhook; if (wh && wh.enabled && wh.url) { fetch(wh.url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(ev) }).catch((err) => console.warn('[alerts] webhook failed:', err.message)); } } activeAlerts() { const out = []; for (const [key, st] of this.states) { if (!st.firing) continue; out.push({ key, ruleId: st.rule.id, ruleName: st.rule.name || st.rule.id, severity: st.rule.severity || 'warning', metric: st.rule.metric, comparator: st.rule.comparator, threshold: Number(st.rule.threshold), value: st.lastValue, peakValue: st.peakValue, region: st.region, targetId: st.targetId, since: st.breachedSince, durationSec: st.breachedSince ? Math.round((Date.now() - st.breachedSince) / 1000) : 0 }); } return out.sort((a, b) => (a.severity === b.severity ? b.durationSec - a.durationSec : a.severity === 'critical' ? -1 : 1)); } } function fmt(v, metric) { if (v == null) return 'n/a'; if (metric === 'errorRate' || metric === 'availability' || metric === 'cacheHitRate') { return `${(v * 100).toFixed(2)}%`; } return `${Number(v).toFixed(1)}ms`; } module.exports = { AlertEngine, compare, pickMetric }; ``` ## 8. `src/recommend.js` ```js 'use strict'; const { summarize } = require('./stats'); const { getRegion } = require('./regions'); const P95_RATIO_THRESHOLD = 1.5; const ERROR_RATE_THRESHOLD = 0.05; const AVAILABILITY_THRESHOLD = 0.99; const CACHE_HIT_THRESHOLD = 0.6; function fmtMs(v) { return v == null ? 'n/a' : `${Number(v).toFixed(0)}ms`; } function fmtPct(v) { return v == null ? 'n/a' : `${(v * 100).toFixed(1)}%`; } /** Identify which timing phase grew the most versus baseline. */ function dominantPhase(current, baseline) { const phases = ['dnsMs', 'connectMs', 'tlsMs', 'waitMs']; let best = null; let bestDelta = 0; for (const p of phases) { const c = current?.breakdown?.[p]; if (c == null) continue; const b = baseline?.breakdown?.[p]; const delta = b != null ? c - b : c; if (delta > bestDelta) { bestDelta = delta; best = p; } } return best; } const PHASE_ADVICE = { dnsMs: 'DNS resolution is the bottleneck — verify resolver health, lower TTL, enable DNS prefetch/preconnect.', connectMs: 'TCP handshake is slow — likely edge PoP congestion or sub-optimal BGP routing. Consider Anycast re-steering.', tlsMs: 'TLS handshake is slow — enable TLS 1.3, session resumption and OCSP stapling at the edge.', waitMs: 'Origin response (TTFB) is slow — enable Origin Shield / tiered cache, raise cache TTL, or scale the origin.' }; /** * Build a ranked list of degradation findings + CDN node switching advice. */ function buildRecommendations({ store, config, windowSec = 900, baselineHours = 24 }) { const now = Date.now(); const currentMap = store.byRegion({ from: now - windowSec * 1000, to: now }); const baselineMap = store.byRegion({ from: now - baselineHours * 3600e3, to: now - 3600e3 }); const rows = []; for (const [region, samples] of currentMap) { if (!samples.length) continue; const current = summarize(samples); const baseSamples = baselineMap.get(region) || []; const baseline = baseSamples.length >= 5 ? summarize(baseSamples) : null; rows.push({ region, current, baseline }); } if (!rows.length) return []; const p95s = rows.map((r) => r.current.p95).filter((v) => v != null).sort((a, b) => a - b); const fallbackP95 = p95s.length ? p95s[Math.floor(p95s.length / 2)] : null; const healthy = []; const findings = []; for (const row of rows) { const { region, current, baseline } = row; const baseP95 = baseline?.p95 ?? fallbackP95; const ratio = baseP95 && current.p95 ? current.p95 / baseP95 : null; const errorRate = current.errorRate ?? 0; const availability = current.availability ?? 1; const cacheHitRate = current.cacheHitRate; const issues = []; let score = 0; if (ratio != null && ratio >= P95_RATIO_THRESHOLD) { issues.push(`p95 ${fmtMs(current.p95)} vs baseline ${fmtMs(baseP95)} (${ratio.toFixed(2)}x)`); score += Math.min(60, (ratio - 1) * 45); } if (errorRate >= ERROR_RATE_THRESHOLD) { issues.push(`error rate ${fmtPct(errorRate)}`); score += Math.min(70, errorRate * 400); } if (availability < AVAILABILITY_THRESHOLD) { issues.push(`availability ${fmtPct(availability)}`); score += Math.min(60, (AVAILABILITY_THRESHOLD - availability) * 1200); } if (cacheHitRate != null && cacheHitRate < CACHE_HIT_THRESHOLD) { issues.push(`cache hit rate ${fmtPct(cacheHitRate)}`); score += 15; } const entry = { region, current, baseline, baseP95, ratio, issues, score }; if (issues.length === 0) healthy.push(entry); else findings.push(entry); } const recommendations = []; for (const f of findings) { const meta = getRegion(f.region) || {}; const severity = f.score >= 70 ? 'critical' : f.score >= 35 ? 'warning' : 'info'; const phase = dominantPhase(f.current, f.baseline); const actions = []; if (phase && PHASE_ADVICE[phase]) actions.push(PHASE_ADVICE[phase]); if ((f.current.errorRate ?? 0) >= ERROR_RATE_THRESHOLD) { actions.push('Verify origin health and CDN edge error logs; temporarily raise failover priority to a secondary origin.'); } if ((f.current.cacheHitRate ?? 1) < CACHE_HIT_THRESHOLD) { actions.push('Cache hit ratio is low — review cache keys, query-string handling and TTL policy.'); } // Candidate PoPs: healthy regions, prefer same continent, sorted by p95 const candidates = healthy .filter((h) => h.region !== f.region) .map((h) => ({ region: h.region, name: (getRegion(h.region) || {}).name || h.region, pop: (getRegion(h.region) || {}).pop || null, p95: h.current.p95, errorRate: h.current.errorRate, sameArea: (getRegion(h.region) || {}).area === meta.area })) .sort((a, b) => { if (a.sameArea !== b.sameArea) return a.sameArea ? -1 : 1; return (a.p95 ?? Infinity) - (b.p95 ?? Infinity); }) .slice(0, 3); if (candidates.length) { actions.push( `Re-steer traffic away from ${meta.pop || f.region} toward ${candidates .map((c) => `${c.pop || c.region} (${fmtMs(c.p95)})`) .join(', ')} via DNS/Anycast weight adjustment or origin-shield relocation.` ); } else { actions.push('No healthy alternative PoP found in the current window — escalate to the CDN provider.'); } const confidence = Math.min(0.98, 0.45 + f.current.count / 200 + (f.baseline ? 0.2 : 0)); recommendations.push({ id: `rec-${f.region}-${now}`, region: f.region, regionName: meta.name || f.region, pop: meta.pop || null, severity, score: Math.round(f.score), confidence: Math.round(confidence * 100) / 100, summary: `${meta.name || f.region}: ${f.issues.join(' · ')}`, issues: f.issues, likelyCause: phase ? phase.replace('Ms', '').toUpperCase() : 'UNKNOWN', metrics: { p95: f.current.p95, baselineP95: f.baseP95, ratio: f.ratio, errorRate: f.current.errorRate, availability: f.current.availability, cacheHitRate: f.current.cacheHitRate, samples: f.current.count }, actions, switchCandidates: candidates }); } return recommendations.sort((a, b) => b.score - a.score); } module.exports = { buildRecommendations, dominantPhase }; ``` ## 9. `src/config.js` ```js 'use strict'; const fs = require('fs'); const path = require('path'); const { allRegionCodes } = require('./regions'); const CONFIG_PATH = path.join(__dirname, '..', 'config.json'); const DEFAULTS = { port: 8787, probeIntervalSec: 60, summaryWindowSec: 300, historyRetentionHours: 72, requestTimeoutMs: 10000, maxBytes: 131072, simulateMissingRegions: true, regions: allRegionCodes(), agents: {}, targets: [ { id: 'main-site', name: 'Main Website', url: 'https://www.example.com/', method: 'GET', headers: {} } ], statusThresholds: { p95Warn: 500, p95Crit: 1000, errorWarn: 0.02, errorCrit: 0.1, availabilityWarn: 0.99, availabilityCrit: 0.95 }, alerts: [ { id: 'p95-latency', name: 'P95 latency above 800ms', enabled: true, metric: 'p95', comparator: '>', threshold: 800, windowSec: 300, forSec: 120, cooldownSec: 600, minSamples: 3, severity: 'warning', regions: ['*'], targets: ['*'] }, { id: 'error-rate', name: 'Error rate above 5%', enabled: true, metric: 'errorRate', comparator: '>', threshold: 0.05, windowSec: 300, forSec: 60, cooldownSec: 300, minSamples: 3, severity: 'critical', regions: ['*'], targets: ['*'] }, { id: 'availability', name: 'Availability below 99%', enabled: true, metric: 'availability', comparator: '<', threshold: 0.99, windowSec: 600, forSec: 120, cooldownSec: 600, minSamples: 5, severity: 'critical', regions: ['*'], targets: ['*'] } ], webhook: { enabled: false, url: '' } }; function deepMerge(base, override) { if (override === undefined || override === null) return base; if (Array.isArray(base) || Array.isArray(override)) return override; if (typeof base === 'object' && typeof override === 'object') { const out = { ...base }; for (const k of Object.keys(override)) out[k] = deepMerge(base[k], override[k]); return out; } return override; } function loadConfig() { let fileConfig = {}; if (fs.existsSync(CONFIG_PATH)) { try { fileConfig = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')); } catch (err) { console.warn('[config] invalid config.json, using defaults:', err.message); } } const merged = deepMerge(DEFAULTS, fileConfig); if (!fs.existsSync(CONFIG_PATH)) saveConfig(merged); return merged; } function saveConfig(config) { try { fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2)); } catch (err) { console.warn('[config] save failed:', err.message); } } module.exports = { loadConfig, saveConfig, CONFIG_PATH, DEFAULTS }; ``` ## 10. `server.js` ```js 'use strict'; const path = require('path'); const express = require('express'); const { loadConfig, saveConfig } = require('./src/config'); const { Store } = require('./src/store'); const { Scheduler } = require('./src/scheduler'); const { AlertEngine } = require('./src/alerts'); const { buildRecommendations } = require('./src/recommend'); const { summarize, bucketize, computeDelta } = require('./src/stats'); const { regionList, REGIONS } = require('./src/regions'); const config = loadConfig(); const store = new Store({ dataDir: path.join(__dirname, 'data'), retentionHours: Number(config.historyRetentionHours) || 72 }); const app = express(); app.use(express.json({ limit: '1mb' })); app.use(express.static(path.join(__dirname, 'public'))); /* ------------------------------------------------------------------ */ /* SSE fan-out */ /* ------------------------------------------------------------------ */ const sseClients = new Set(); function broadcast(event, data) { const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; for (const res of sseClients) { try { res.write(payload); } catch { sseClients.delete(res); } } } /* ------------------------------------------------------------------ */ /* Snapshot builder */ /* ------------------------------------------------------------------ */ function statusOf(summary, count) { if (!summary || count === 0) return 'unknown'; const t = config.statusThresholds || {}; const p95 = summary.p95; const err = summary.errorRate ?? 0; const avail = summary.availability ?? 1; if (avail < (t.availabilityCrit ?? 0.95) || err > (t.errorCrit ?? 0.1) || (p95 != null && p95 > (t.p95Crit ?? 1000))) { return 'critical'; } if (avail < (t.availabilityWarn ?? 0.99) || err > (t.errorWarn ?? 0.02) || (p95 != null && p95 > (t.p95Warn ?? 500))) { return 'degraded'; } return 'healthy'; } function buildSnapshot() { const now = Date.now(); const windowSec = Number(config.summaryWindowSec) || 300; const byRegion = store.byRegion({ from: now - windowSec * 1000, to: now }); const regions = REGIONS.map((r) => { const samples = byRegion.get(r.code) || []; const s = samples.length ? summarize(samples) : null; const last = samples.length ? samples[samples.length - 1] : null; return { code: r.code, name: r.name, lat: r.lat, lng: r.lng, area: r.area, pop: r.pop, count: samples.length, p50: s?.p50 ?? null, p95: s?.p95 ?? null, p99: s?.p99 ?? null, avg: s?.avg ?? null, min: s?.min ?? null, max: s?.max ?? null, errorRate: s?.errorRate ?? null, availability: s?.availability ?? null, cacheHitRate: s?.cacheHitRate ?? null, breakdown: s?.breakdown ?? null, statusCodes: s?.statusCodes ?? null, observedPop: last?.pop ?? r.pop, provider: last?.provider ?? null, simulated: !!last?.simulated, status: statusOf(s, samples.length), lastTs: last?.ts ?? null }; }); return { ts: now, windowSec, regions, alerts: alertEngine.activeAlerts(), alertHistory: alertEngine.history.slice(-60).reverse(), recommendations: buildRecommendations({ store, config, windowSec: Math.max(900, windowSec) }), meta: { lastRunAt: scheduler.lastRunAt, nextRunAt: scheduler.nextRunAt, intervalSec: config.probeIntervalSec, probing: scheduler.running, cycles: scheduler.cycleCount, lastCycle: scheduler.lastCycle, totalSamples: store.totalSamples(), targets: (config.targets || []).map((t) => ({ id: t.id, name: t.name, url: t.url })) } }; } let snapshotTimer = null; let lastSnapshot = null; function scheduleSnapshot() { if (snapshotTimer) return; snapshotTimer = setTimeout(() => { snapshotTimer = null; try { lastSnapshot = buildSnapshot(); broadcast('snapshot', lastSnapshot); } catch (err) { console.error('[snapshot] failed:', err.message); } }, 400); } /* ------------------------------------------------------------------ */ /* Engines */ /* ------------------------------------------------------------------ */ const alertEngine = new AlertEngine({ store, config, onEvent: (ev) => broadcast('alert', ev) }); const scheduler = new Scheduler({ config, store, onSample: () => {}, onCycle: () => scheduleSnapshot() }); /* ------------------------------------------------------------------ */ /* REST API */ /* ------------------------------------------------------------------ */ app.get('/api/config', (req, res) => res.json(config)); app.put('/api/config', (req, res) => { const body = req.body || {}; if (body.probeIntervalSec != null) { config.probeIntervalSec = Math.min(3600, Math.max(5, Number(body.probeIntervalSec) || 60)); } if (body.summaryWindowSec != null) { config.summaryWindowSec = Math.min(3600, Math.max(30, Number(body.summaryWindowSec) || 300)); } if (Array.isArray(body.alerts)) config.alerts = body.alerts; if (Array.isArray(body.targets) && body.targets.length) config.targets = body.targets; if (Array.isArray(body.regions) && body.regions.length) config.regions = body.regions; if (body.statusThresholds && typeof body.statusThresholds === 'object') { config.statusThresholds = { ...config.statusThresholds, ...body.statusThresholds }; } if (body.webhook && typeof body.webhook === 'object') { config.webhook = { ...config.webhook, ...body.webhook }; } saveConfig(config); alertEngine.updateConfig(config); scheduler.stop(); scheduler.start(); scheduleSnapshot(); res.json(config); }); app.get('/api/regions', (req, res) => res.json(regionList())); app.get('/api/snapshot', (req, res) => { if (!lastSnapshot) lastSnapshot = buildSnapshot(); res.json(lastSnapshot); }); app.get('/api/timeseries', (req, res) => { const region = req.query.region; const targetId = req.query.target || null; const to = req.query.to ? Number(req.query.to) : Date.now(); const from = req.query.from ? Number(req.query.from) : to - 3600 * 1000; const bucketSec = Math.min(3600, Math.max(5, Number(req.query.bucketSec) || 60)); const samples = store.query({ region, targetId, from, to }); res.json({ region, targetId, from, to, bucketSec, buckets: bucketize(samples, from, to, bucketSec * 1000), summary: summarize(samples) }); }); app.get('/api/comparison', (req, res) => { const region = req.query.region; const targetId = req.query.target || null; const windowSec = Math.min(86400, Math.max(60, Number(req.query.windowSec) || 3600)); const now = Date.now(); const current = summarize(store.query({ region, targetId, from: now - windowSec * 1000, to: now })); const previous = summarize( store.query({ region, targetId, from: now - 2 * windowSec * 1000, to: now - windowSec * 1000 }) ); res.json({ region, targetId, windowSec, current, previous, delta: computeDelta(current, previous) }); }); app.get('/api/recommendations', (req, res) => { const windowSec = Math.max(300, Number(req.query.windowSec) || 900); res.json(buildRecommendations({ store, config, windowSec })); }); app.post('/api/probe/run', async (req, res) => { try { const cycle = await scheduler.runOnce(); scheduleSnapshot(); res.json({ ok: true, cycle }); } catch (err) { res.status(500).json({ ok: false, error: err.message }); } }); app.get('/api/export.csv', (req, res) => { const region = req.query.region || null; const targetId = req.query.target || null; const to = req.query.to ? Number(req.query.to) : Date.now(); const from = req.query.from ? Number(req.query.from) : to - 24 * 3600 * 1000; const samples = store.query({ region, targetId, from, to }); const cols = [ 'ts', 'iso', 'region', 'targetId', 'ok', 'status', 'totalMs', 'dnsMs', 'connectMs', 'tlsMs', 'ttfbMs', 'waitMs', 'bytes', 'provider', 'pop', 'cacheStatus', 'cacheHit', 'error' ]; const lines = [cols.join(',')]; for (const s of samples) { lines.push( cols .map((c) => { const v = c === 'iso' ? new Date(s.ts).toISOString() : s[c]; if (v == null) return ''; const str = String(v); return str.includes(',') ? `"${str.replace(/"/g, '""')}"` : str; }) .join(',') ); } res.setHeader('content-type', 'text/csv; charset=utf-8'); res.setHeader('content-disposition', 'attachment; filename="cdn-monitor.csv"'); res.send(lines.join('\n')); }); app.get('/api/stream', (req, res) => { res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' }); res.flushHeaders?.(); sseClients.add(res); res.write(`event: hello\ndata: ${JSON.stringify({ ts: Date.now() })}\n\n`); if (lastSnapshot) res.write(`event: snapshot\ndata: ${JSON.stringify(lastSnapshot)}\n\n`); const ping = setInterval(() => { try { res.write(': ping\n\n'); } catch { /* ignore */ } }, 15000); req.on('close', () => { clearInterval(ping); sseClients.delete(res); }); }); app.get('/health', (req, res) => res.json({ ok: true, ts: Date.now(), samples: store.totalSamples(), cycles: scheduler.cycleCount }) ); /* ------------------------------------------------------------------ */ /* Bootstrap */ /* ------------------------------------------------------------------ */ const PORT = Number(process.env.PORT) || Number(config.port) || 8787; scheduler.start(); scheduler.runOnce().catch((err) => console.error('[boot] initial cycle failed:', err.message)); // Periodic maintenance: retention pruning + snapshot heartbeat setInterval(() => store.prune(), 5 * 60 * 1000); setInterval(() => scheduleSnapshot(), 10 * 1000); setInterval(() => alertEngine.evaluate(), 15 * 1000); const server = app.listen(PORT, () => { console.log(`\n CDN Distribution Monitor`); console.log(` → http://localhost:${PORT}`); console.log(` → ${config.targets.length} target(s) × ${config.regions.length} region(s)`); console.log(` → probe interval: ${config.probeIntervalSec}s`); console.log(` → agent regions: ${Object.keys(config.agents || {}).join(', ') || 'none (simulation mode)'}\n`); }); function shutdown() { console.log('\n[shutdown] flushing store...'); scheduler.stop(); store.close(); server.close(() => process.exit(0)); setTimeout(() => process.exit(0), 2000); } process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); ``` ## 11. `agent.js` (deploy to a VPS in each region) ```js 'use strict'; /** * Remote probe agent. Deploy one per region: * AGENT_REGION=eu-west-1 PORT=8790 node agent.js * Then register it in config.json: * "agents": { "eu-west-1": "http://eu-west-1-host:8790/probe" } */ const express = require('express'); const { probeOnce } = require('./src/prober'); const REGION = process.env.AGENT_REGION || 'unknown'; const PORT = Number(process.env.PORT) || 8790; const app = express(); app.use(express.json({ limit: '256kb' })); app.post('/probe', async (req, res) => { const { url, method, headers, timeoutMs, targetId } = req.body || {}; if (!url) return res.status(400).json({ error: 'url is required' }); const result = await probeOnce({ url, method: method || 'GET', headers: headers || {}, timeoutMs: Math.min(30000, Number(timeoutMs) || 10000), region: REGION, targetId: targetId || null, source: 'agent' }); res.json(result); }); app.get('/health', (req, res) => { res.json({ ok: true, region: REGION, ts: Date.now(), uptime: process.uptime() }); }); app.listen(PORT, () => { console.log(`[agent] region=${REGION} listening on :${PORT}`); }); ``` ## 12. `public/index.html` ```html CDN Distribution Monitor

CDN Distribution Monitor

connecting…
healthy degraded critical no data

Active alerts 0

CDN node switching recommendations

Alert rules

``` ## 13. `public/style.css` ```css :root { --bg: #0b0f17; --panel: #121826; --panel-2: #171f30; --border: #223049; --text: #e6ecf5; --muted: #8b9bb4; --green: #22c55e; --yellow: #f5c542; --orange: #f97316; --red: #ef4444; --blue: #3b82f6; --gray: #64748b; } * { box-sizing: border-box; } html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 13px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } body { display: flex; flex-direction: column; } /* ---------- top bar ---------- */ .topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 10px 16px; background: var(--panel); border-bottom: 1px solid var(--border); flex-wrap: wrap; } .brand { display: flex; align-items: center; gap: 10px; } .brand h1 { font-size: 15px; margin: 0; font-weight: 600; letter-spacing: .2px; } .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--gray); box-shadow: 0 0 8px currentColor; } .dot.live { background: var(--green); color: var(--green); } .dot.down { background: var(--red); color: var(--red); } .controls { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } .controls label { color: var(--muted); display: flex; align-items: center; gap: 6px; } select, input, textarea { background: var(--panel-2); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 5px 8px; font: inherit; outline: none; } select:focus, input:focus, textarea:focus { border-color: var(--blue); } .btn { background: var(--panel-2); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 6px 12px; cursor: pointer; font: inherit; transition: .15s; } .btn:hover { border-color: var(--blue); } .btn.primary { background: var(--blue); border-color: var(--blue); color: #fff; } .btn.ghost { background: transparent; } .btn.small { padding: 4px 10px; font-size: 12px; } .status-line { color: var(--muted); font-variant-numeric: tabular-nums; } /* ---------- layout ---------- */ .layout { flex: 1; display: grid; grid-template-columns: 1fr 380px; min-height: 0; } .map-panel { position: relative; min-height: 0; } #map { width: 100%; height: 100%; background: #0a0e15; } .legend { position: absolute; bottom: 12px; left: 12px; z-index: 500; background: rgba(18, 24, 38, .9); border: 1px solid var(--border); border-radius: 8px; padding: 8px 12px; display: flex; gap: 14px; font-size: 12px; } .legend span { display: flex; align-items: center; gap: 6px; color: var(--muted); } .sw { width: 9px; height: 9px; border-radius: 50%; display: inline-block; } .sw.healthy { background: var(--green); } .sw.degraded { background: var(--yellow); } .sw.critical { background: var(--red); } .sw.unknown { background: var(--gray); } .side-panel { border-left: 1px solid var(--border); background: var(--panel); display: flex; flex-direction: column; min-height: 0; overflow: hidden; } .region-detail { padding: 14px; border-bottom: 1px solid var(--border); } .region-detail h3 { margin: 0 0 8px; font-size: 14px; } .muted { color: var(--muted); } .kv { display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; margin-top: 8px; } .kv dt { color: var(--muted); } .kv dd { margin: 0; text-align: right; font-variant-numeric: tabular-nums; } .delta-up { color: var(--red); } .delta-down { color: var(--green); } .delta-flat { color: var(--muted); } .chart-wrap { flex: 1; padding: 12px; min-height: 220px; } /* ---------- bottom ---------- */ .bottom { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px; background: var(--border); border-top: 1px solid var(--border); height: 300px; } .panel { background: var(--panel); padding: 12px 14px; display: flex; flex-direction: column; min-height: 0; } .panel h2 { font-size: 12px; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); margin: 0 0 10px; display: flex; align-items: center; gap: 8px; } .badge { background: var(--panel-2); border: 1px solid var(--border); border-radius: 10px; padding: 0 7px; font-size: 11px; color: var(--text); } .badge.crit { background: var(--red); border-color: var(--red); color: #fff; } .scroll { overflow-y: auto; flex: 1; padding-right: 4px; } .scroll::-webkit-scrollbar { width: 8px; } .scroll::-webkit-scrollbar-thumb { background: #263349; border-radius: 4px; } .item { border: 1px solid var(--border); border-left-width: 3px; border-radius: 6px; padding: 8px 10px; margin-bottom: 8px; background: var(--panel-2); } .item.critical { border-left-color: var(--red); } .item.warning { border-left-color: var(--yellow); } .item.info { border-left-color: var(--blue); } .item .title { font-weight: 600; margin-bottom: 4px; } .item .meta { color: var(--muted); font-size: 11.5px; } .item ul { margin: 6px 0 0; padding-left: 16px; color: var(--muted); } .item ul li { margin-bottom: 3px; } /* ---------- rules editor ---------- */ .rules-actions { display: flex; gap: 8px; margin-top: 8px; } .rule-row { display: grid; grid-template-columns: 1.4fr 1fr .8fr .8fr .8fr .8fr auto; gap: 6px; align-items: center; margin-bottom: 6px; } .rule-row input, .rule-row select { width: 100%; padding: 4px 6px; font-size: 12px; } .rule-row .del { background: transparent; border: none; color: var(--red); cursor: pointer; font-size: 15px; } @media (max-width: 1100px) { .layout { grid-template-columns: 1fr; grid-template-rows: 55vh 1fr; } .side-panel { border-left: none; border-top: 1px solid var(--border); } .bottom { grid-template-columns: 1fr; height: auto; } .panel { height: 260px; } } ``` ## 14. `public/app.js` ```js 'use strict'; const $ = (s) => document.querySelector(s); const $$ = (s) => Array.from(document.querySelectorAll(s)); const state = { regions: [], config: null, snapshot: null, markers: new Map(), map: null, chart: null, selected: null, windowSec: 300 }; /* ------------------------------------------------------------------ */ /* Helpers */ /* ------------------------------------------------------------------ */ async function fetchJson(url, options) { const res = await fetch(url, options); if (!res.ok) throw new Error(`${url} → ${res.status}`); return res.json(); } const fmtMs = (v) => (v == null ? '—' : `${Number(v).toFixed(0)} ms`); const fmtPct = (v) => (v == null ? '—' : `${(Number(v) * 100).toFixed(1)}%`); const fmtTime = (ts) => (ts ? new Date(ts).toLocaleTimeString() : '—'); function statusColor(status) { switch (status) { case 'healthy': return '#22c55e'; case 'degraded': return '#f5c542'; case 'critical': return '#ef4444'; default: return '#64748b'; } } function deltaClass(v, invert = false) { if (v == null || Math.abs(v) < 0.001) return 'delta-flat'; const bad = invert ? v < 0 : v > 0; return bad ? 'delta-up' : 'delta-down'; } function deltaText(v) { if (v == null) return '—'; const pct = (v * 100).toFixed(1); return `${v > 0 ? '+' : ''}${pct}%`; } /* ------------------------------------------------------------------ */ /* Map */ /* ------------------------------------------------------------------ */ function initMap() { const map = L.map('map', { minZoom: 1, maxZoom: 6, worldCopyJump: true, zoomControl: true }); map.setView([22, 8], 2); L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { subdomains: 'abcd', maxZoom: 19, attribution: '© OpenStreetMap contributors © CARTO' }).addTo(map); state.map = map; } function renderMap(regions) { for (const r of regions) { const color = statusColor(r.status); const radius = r.status === 'critical' ? 13 : r.status === 'degraded' ? 10 : 8; let marker = state.markers.get(r.code); if (!marker) { marker = L.circleMarker([r.lat, r.lng], { radius, color, weight: 2, fillColor: color, fillOpacity: 0.6 }).addTo(state.map); marker.on('click', () => selectRegion(r.code)); state.markers.set(r.code, marker); } else { marker.setStyle({ color, fillColor: color }); marker.setRadius(radius); } marker.bindTooltip( `${r.name}
` + `p95: ${fmtMs(r.p95)} · p50: ${fmtMs(r.p50)}
` + `errors: ${fmtPct(r.errorRate)} · avail: ${fmtPct(r.availability)}
` + `PoP: ${r.observedPop || '—'} · samples: ${r.count}` + (r.simulated ? '
simulated' : ''), { direction: 'top', opacity: 0.95 } ); } } /* ------------------------------------------------------------------ */ /* Region detail + trend chart */ /* ------------------------------------------------------------------ */ async function selectRegion(code) { state.selected = code; const region = state.regions.find((r) => r.code === code); if (!region) return; renderDetailHeader(region); const target = state.config?.targets?.[0]; if (!target) return; const to = Date.now(); const from = to - 6 * 3600 * 1000; try { const [ts, cmp] = await Promise.all([ fetchJson(`/api/timeseries?region=${code}&target=${encodeURIComponent(target.id)}&from=${from}&to=${to}&bucketSec=300`), fetchJson(`/api/comparison?region=${code}&target=${encodeURIComponent(target.id)}&windowSec=3600`) ]); renderComparison(cmp); renderChart(ts.buckets); } catch (err) { console.warn('detail fetch failed', err); } } function renderDetailHeader(r) { const el = $('#regionDetail'); el.innerHTML = `

${r.name} · ${r.code}

PoP ${r.observedPop || '—'} · ${r.count} samples · status ${r.status}
p50
${fmtMs(r.p50)}
p95
${fmtMs(r.p95)}
p99
${fmtMs(r.p99)}
Error rate
${fmtPct(r.errorRate)}
Availability
${fmtPct(r.availability)}
Cache hit
${fmtPct(r.cacheHitRate)}
DNS
${fmtMs(r.breakdown?.dnsMs)}
Connect
${fmtMs(r.breakdown?.connectMs)}
TLS
${fmtMs(r.breakdown?.tlsMs)}
Origin wait
${fmtMs(r.breakdown?.waitMs)}
`; } function renderComparison(cmp) { const box = $('#comparisonBox'); if (!box) return; const d = cmp?.delta; if (!d) { box.innerHTML = '

Not enough history for comparison yet.

'; return; } box.innerHTML = `
Last ${cmp.windowSec / 60} min vs previous period
p95
${fmtMs(d.p95.current)} ${deltaText(d.p95.percent)}
Error rate
${fmtPct(d.errorRate.current)} ${deltaText(d.errorRate.percent)}
Availability
${fmtPct(d.availability.current)} ${deltaText(d.availability.percent)}
`; } function renderChart(buckets) { const ctx = $('#trendChart'); if (!ctx) return; const labels = buckets.map((b) => new Date(b.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })); const p95 = buckets.map((b) => b.p95); const err = buckets.map((b) => (b.errorRate == null ? null : b.errorRate * 100)); if (state.chart) state.chart.destroy(); state.chart = new Chart(ctx, { type: 'line', data: { labels, datasets: [ { label: 'p95 (ms)', data: p95, borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,.15)', fill: true, tension: 0.3, pointRadius: 0, borderWidth: 2, yAxisID: 'y' }, { label: 'error rate (%)', data: err, borderColor: '#ef4444', backgroundColor: 'transparent', tension: 0.3, pointRadius: 0, borderWidth: 2, borderDash: [4, 3], yAxisID: 'y1' } ] }, options: { responsive: true, maintainAspectRatio: false, animation: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { labels: { color: '#8b9bb4', boxWidth: 10, font: { size: 11 } } } }, scales: { x: { ticks: { color: '#64748b', maxTicksLimit: 8, font: { size: 10 } }, grid: { color: '#1b2434' } }, y: { position: 'left', ticks: { color: '#64748b', font: { size: 10 } }, grid: { color: '#1b2434' }, title: { display: true, text: 'ms', color: '#64748b', font: { size: 10 } } }, y1: { position: 'right', min: 0, ticks: { color: '#64748b', font: { size: 10 } }, grid: { drawOnChartArea: false }, title: { display: true, text: '%', color: '#64748b', font: { size: 10 } } } } } }); } /* ------------------------------------------------------------------ */ /* Alerts */ /* ------------------------------------------------------------------ */ function renderAlerts(snapshot) { const list = $('#alertsList'); const badge = $('#alertCount'); const alerts = snapshot.alerts || []; badge.textContent = alerts.length; badge.className = alerts.some((a) => a.severity === 'critical') ? 'badge crit' : 'badge'; if (!alerts.length) { list.innerHTML = '

No active alerts. All regions within thresholds.

'; return; } list.innerHTML = alerts .map( (a) => `
${escapeHtml(a.ruleName)}
${escapeHtml(a.region)} · ${a.metric} = ${formatMetric(a.value, a.metric)} (${a.comparator} ${formatMetric(a.threshold, a.metric)}) · firing for ${Math.round(a.durationSec / 60)} min
` ) .join(''); } function formatMetric(v, metric) { if (v == null) return '—'; if (['errorRate', 'availability', 'cacheHitRate'].includes(metric)) return fmtPct(v); return fmtMs(v); } /* ------------------------------------------------------------------ */ /* Recommendations */ /* ------------------------------------------------------------------ */ function renderRecommendations(snapshot) { const list = $('#recsList'); const recs = snapshot.recommendations || []; if (!recs.length) { list.innerHTML = '

No degradation detected. All regions performing within baseline.

'; return; } list.innerHTML = recs .map( (r) => `
${escapeHtml(r.regionName)} ${r.pop ? `(${r.pop})` : ''} · score ${r.score} · confidence ${(r.confidence * 100).toFixed(0)}%
${escapeHtml(r.summary)}
    ${r.actions.map((a) => `
  • ${escapeHtml(a)}
  • `).join('')}
${ r.switchCandidates?.length ? `
Candidates: ${r.switchCandidates .map((c) => `${escapeHtml(c.pop || c.region)} (${fmtMs(c.p95)})`) .join(' · ')}
` : '' }
` ) .join(''); } /* ------------------------------------------------------------------ */ /* Rules editor */ /* ------------------------------------------------------------------ */ const METRICS = ['p95', 'p99', 'p50', 'avg', 'errorRate', 'availability', 'cacheHitRate']; const COMPARATORS = ['>', '>=', '<', '<=']; function renderRules() { const list = $('#rulesList'); const rules = state.config?.alerts || []; if (!rules.length) { list.innerHTML = '

No rules configured.

'; return; } list.innerHTML = rules .map( (r, i) => `
` ) .join(''); } function collectRules() { const rows = $$('#rulesList .rule-row'); return rows.map((row, i) => { const get = (f) => row.querySelector(`[data-field="${f}"]`).value; const existing = state.config.alerts[i] || {}; const metric = get('metric'); const rawThreshold = Number(get('threshold')); return { ...existing, id: existing.id || `rule-${Date.now()}-${i}`, name: get('name') || `Rule ${i + 1}`, enabled: existing.enabled !== false, metric, comparator: get('comparator'), threshold: rawThreshold, windowSec: Number(get('windowSec')) || 300, forSec: Number(get('forSec')) || 0, cooldownSec: existing.cooldownSec || 300, minSamples: existing.minSamples || 3, severity: existing.severity || 'warning', regions: existing.regions || ['*'], targets: existing.targets || ['*'] }; }); } async function saveRules() { const alerts = collectRules(); const updated = await fetchJson('/api/config', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ alerts }) }); state.config = updated; renderRules(); flash('Alert rules saved'); } /* ------------------------------------------------------------------ */ /* Snapshot handling */ /* ------------------------------------------------------------------ */ function applySnapshot(snapshot) { state.snapshot = snapshot; state.regions = snapshot.regions; renderMap(snapshot.regions); renderAlerts(snapshot); renderRecommendations(snapshot); const m = snapshot.meta; $('#statusLine').textContent = `${m.targets.length} target(s) · ${snapshot.regions.length} regions · ` + `last cycle ${fmtTime(m.lastRunAt)} · ${m.totalSamples.toLocaleString()} samples`; if (state.selected) { const r = snapshot.regions.find((x) => x.code === state.selected); if (r) renderDetailHeader(r); } } /* ------------------------------------------------------------------ */ /* SSE */ /* ------------------------------------------------------------------ */ function connectStream() { const es = new EventSource('/api/stream'); es.addEventListener('open', () => { $('#connDot').className = 'dot live'; }); es.addEventListener('snapshot', (e) => { try { applySnapshot(JSON.parse(e.data)); } catch (err) { console.warn(err); } }); es.addEventListener('alert', (e) => { try { const ev = JSON.parse(e.data); flash(`${ev.severity.toUpperCase()}: ${ev.message}`, ev.severity === 'critical'); } catch { /* ignore */ } }); es.addEventListener('error', () => { $('#connDot').className = 'dot down'; }); } /* ------------------------------------------------------------------ */ /* UI wiring */ /* ------------------------------------------------------------------ */ function flash(msg, isError = false) { const el = $('#statusLine'); const prev = el.textContent; el.textContent = msg; el.style.color = isError ? '#ef4444' : '#22c55e'; setTimeout(() => { el.textContent = prev; el.style.color = ''; }, 4000); } function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]) ); } function escapeAttr(s) { return escapeHtml(s).replace(/`/g, '`'); } async function boot() { state.config = await fetchJson('/api/config'); state.windowSec = state.config.summaryWindowSec || 300; $('#intervalSelect').value = String(state.config.probeIntervalSec); $('#windowSelect').value = String(state.windowSec); initMap(); renderRules(); connectStream(); $('#intervalSelect').addEventListener('change', async (e) => { const probeIntervalSec = Number(e.target.value); state.config = await fetchJson('/api/config', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ probeIntervalSec }) }); flash(`Probe frequency set to ${probeIntervalSec}s`); }); $('#windowSelect').addEventListener('change', async (e) => { const summaryWindowSec = Number(e.target.value); state.windowSec = summaryWindowSec; await fetchJson('/api/config', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ summaryWindowSec }) }); flash(`Aggregation window set to ${summaryWindowSec}s`); }); $('#runNowBtn').addEventListener('click', async () => { flash('Running probe cycle…'); try { const r = await fetchJson('/api/probe/run', { method: 'POST' }); flash(`Cycle done: ${r.cycle.samples} samples in ${r.cycle.durationMs}ms`); } catch (err) { flash(`Probe failed: ${err.message}`, true); } }); $('#exportBtn').addEventListener('click', () => { window.location.href = '/api/export.csv'; }); $('#addRuleBtn').addEventListener('click', () => { state.config.alerts = [ ...(state.config.alerts || []), { id: `rule-${Date.now()}`, name: 'New rule', enabled: true, metric: 'p95', comparator: '>', threshold: 800, windowSec: 300, forSec: 60, cooldownSec: 300, minSamples: 3, severity: 'warning', regions: ['*'], targets: ['*'] } ]; renderRules(); }); $('#saveRulesBtn').addEventListener('click', saveRules); $('#rulesList').addEventListener('click', (e) => { const idx = e.target.getAttribute('data-del'); if (idx == null) return; state.config.alerts.splice(Number(idx), 1); renderRules(); }); // Initial snapshot try { applySnapshot(await fetchJson('/api/snapshot')); } catch (err) { console.warn('initial snapshot failed', err); } } boot().catch((err) => { console.error(err); document.body.insertAdjacentHTML( 'afterbegin', `
Boot failed: ${escapeHtml(err.message)}
` ); }); ``` ## 15. `README.md` ```markdown # CDN Distribution Monitor Multi-region website availability, latency and CDN PoP health monitor with map visualization, alerting and node-switching recommendations. ## Quick start ```bash npm install npm start # open http://localhost:8787 ``` On first run `config.json` is generated with 18 probe regions and a placeholder target (`https://www.example.com/`). Edit the `targets` array to point at your own site, then restart. ## Real multi-region probing By default, regions without a configured agent use a **built-in simulator** so you can explore the UI immediately. For real measurements, deploy one agent per region: ```bash # on a VPS in Dublin AGENT_REGION=eu-west-1 PORT=8790 node agent.js ``` Then register it: ```json "agents": { "eu-west-1": "http://eu-west-1-host:8790/probe", "ap-northeast-1": "http://tokyo-host:8790/probe" } ``` Set `"simulateMissingRegions": false` to make un-agented regions report a `no_agent` error instead of simulated data. ## Metrics collected per probe | Field | Meaning | |---|---| | `dnsMs` | DNS resolution | | `connectMs` | TCP handshake | | `tlsMs` | TLS handshake | | `ttfbMs` | Total time to first byte | | `waitMs` | Origin/server processing after handshake | | `totalMs` | Full request including body download | | `pop` | CDN PoP extracted from `cf-ray` / `x-amz-cf-pop` / `x-served-by` | | `cacheHit` | Derived from `cf-cache-status` / `x-cache` | | `status`, `error` | HTTP status or transport error code | ## API | Method | Path | Description | |---|---|---| | GET | `/api/snapshot` | Current per-region aggregates, alerts, recommendations | | GET | `/api/timeseries` | Bucketed history (`region`, `target`, `from`, `to`, `bucketSec`) | | GET | `/api/comparison` | Current vs previous window deltas | | GET | `/api/recommendations` | Degradation analysis + PoP switch advice | | GET | `/api/export.csv` | Raw sample export | | POST | `/api/probe/run` | Trigger an immediate probe cycle | | GET | `/api/stream` | SSE feed: `snapshot`, `alert` events | | PUT | `/api/config` | Update frequency, window, alert rules, targets | ## Alert rule shape ```json { "id": "p95-latency", "name": "P95 latency above 800ms", "enabled": true, "metric": "p95", "comparator": ">", "threshold": 800, "windowSec": 300, "forSec": 120, "cooldownSec": 600, "minSamples": 3, "severity": "warning", "regions": ["*"], "targets": ["*"] } ``` Supported metrics: `p50`, `p95`, `p99`, `avg`, `errorRate`, `availability`, `cacheHitRate`. Comparators: `>`, `>=`, `<`, `<=`, `==`. A rule fires only after the condition holds continuously for `forSec` seconds, and resolves automatically when the condition clears. ## Recommendation engine For every region the engine compares the current window against a 24-hour baseline and flags: - p95 latency ≥ 1.5× baseline - error rate ≥ 5% - availability < 99% - cache hit rate < 60% It then identifies the dominant degraded timing phase (DNS / TCP / TLS / origin wait), emits targeted remediation actions, and ranks healthy regions as PoP switching candidates (same continent preferred, sorted by p95). ## Production notes - Deploy agents behind a private network or add an auth header. - Point `webhook.url` at Slack/PagerDuty and set `webhook.enabled: true`. - `data/samples.jsonl` is append-only; rotate it periodically for long runs. - Set `historyRetentionHours` to control in-memory retention. ``` ### Global CDN Monitoring & Decision Dashboard This dashboard turns probe data into actionable insights across every region. - **Live global map** – Each region is a colored circle on a Leaflet map, with green, yellow, red, or gray indicating health. Hovering shows p95 latency, error rate, and sample count. - **Per-region trend & comparison** – Click any region to view a 6-hour latency and error-rate chart, plus a side-by-side comparison of the last window versus the previous one. - **Alert rules editor** – Create or modify rules based on p95, p99, error rate, availability, or cache hit rate. Each rule can require the condition to hold for a set duration before firing. - **Switching recommendations** – When a region degrades, the engine ranks healthy alternative PoPs and suggests specific actions like DNS re-steering or cache TTL adjustments. --- **Optimization Tip:** Replace the placeholder target `https://www.example.com/` in `config.json` with your own site URL, and deploy `agent.js` on servers in the regions you care about for real measurements instead of simulated data.