|
| 1 | +// rtt-report.js — raw RTT sample history + batched shipping to the proxy. |
| 2 | +// |
| 3 | +// The EMA in ./latency.js keeps the ADAPTIVE state (one live number); this |
| 4 | +// module keeps the HISTORY: raw {at, rtt} pairs from the ping probe, batched |
| 5 | +// and POSTed to the proxy's /rtstats endpoint so per-session link quality |
| 6 | +// reaches analytics instead of dying with the page. Payload is structural |
| 7 | +// telemetry only — millisecond integers and elapsed offsets. No field text, |
| 8 | +// no page content, no URLs. |
| 9 | +// |
| 10 | +// Shipping mirrors diag.js's /klog discipline: sendBeacon when available |
| 11 | +// (survives unload), fetch as fallback, bounded queue so a black hole endpoint |
| 12 | +// cannot grow memory. The session id is parsed from the gateway path |
| 13 | +// (/liveview/<session>/<token>/...) when present — the proxy only sees its |
| 14 | +// internal path, so this is what lets one pod serve many sessions without |
| 15 | +// server-side URL rewriting. |
| 16 | +// |
| 17 | +// CONSTRAINED-LINK DISCIPLINE (same rule as diag.js): telemetry must never |
| 18 | +// compete with the input stream for airtime while a session is actively |
| 19 | +// struggling. The periodic timer flush stands down on a constrained link — |
| 20 | +// samples stay queued in the ring (which holds ~20min) and ride out with the |
| 21 | +// pagehide beacon or a later healthy-window tick. Measuring a bad link must |
| 22 | +// not make the bad link worse. The fetch path additionally refuses to stack |
| 23 | +// requests behind one that has not settled: on a half-open connection each |
| 24 | +// hung POST would otherwise pin one of the browser's few per-host sockets. |
| 25 | + |
| 26 | +import { nowMs, siblingPath } from './env.js'; |
| 27 | +import { linkLatency } from './latency.js'; |
| 28 | + |
| 29 | +const SAMPLE_MAX = 256; // ring bound: ~20min of pings at the 5s mean |
| 30 | +const FLUSH_BATCH_MAX = 128; |
| 31 | +const FLUSH_MS = 30000; |
| 32 | +// One-shot early flush after the first sample: sessions are routinely killed |
| 33 | +// within seconds, and at the 30s cadence they'd die with every sample still |
| 34 | +// client-side — the teardown readers can only see what reached the proxy. |
| 35 | +const EARLY_FLUSH_MS = 3000; |
| 36 | +const CONSTRAINED_MS = 700; // matches diag.js's shedding threshold |
| 37 | + |
| 38 | +function rttPath() { |
| 39 | + try { return siblingPath('/rtstats'); } catch (_) { return '/rtstats'; } |
| 40 | +} |
| 41 | + |
| 42 | +function constrainedLink() { |
| 43 | + if (linkLatency() >= CONSTRAINED_MS) return true; |
| 44 | + try { |
| 45 | + const c = navigator.connection; |
| 46 | + if (c && (c.saveData || c.effectiveType === 'slow-2g' || c.effectiveType === '2g')) return true; |
| 47 | + } catch (_) {} |
| 48 | + return false; |
| 49 | +} |
| 50 | + |
| 51 | +// Session correlation. Absent on non-gateway hosts (local harnesses, embeds) — |
| 52 | +// callers treat null as "aggregate by connection instead". |
| 53 | +export function sessionIdFromPath() { |
| 54 | + try { |
| 55 | + const m = /\/liveview\/([^/]+)\//.exec(location.pathname); |
| 56 | + return m ? m[1].slice(0, 64) : null; |
| 57 | + } catch (_) { return null; } |
| 58 | +} |
| 59 | + |
| 60 | +let samples = []; // [{at, rtt}] — at is ABSOLUTE (performance.now ms) |
| 61 | +let flushTimer = null; |
| 62 | +let earlyFlushArmed = false; |
| 63 | +let fetchInFlight = false; |
| 64 | + |
| 65 | +function ensureFlushTimer() { |
| 66 | + if (flushTimer !== null || typeof setInterval !== 'function') return; |
| 67 | + flushTimer = setInterval(function () { |
| 68 | + if (constrainedLink()) return; // shed now; pagehide still beacons the ring |
| 69 | + flushSamples(); |
| 70 | + }, FLUSH_MS); |
| 71 | +} |
| 72 | + |
| 73 | +// Returns true if the payload was handed to the platform (beacon queued / fetch |
| 74 | +// started). A false return means "not shipped" so the caller can keep the data. |
| 75 | +function post(payload) { |
| 76 | + const body = JSON.stringify(payload); |
| 77 | + try { |
| 78 | + if (navigator.sendBeacon && body.length < 60000) { |
| 79 | + if (navigator.sendBeacon(rttPath(), new Blob([body], { type: 'application/json' }))) return true; |
| 80 | + } |
| 81 | + } catch (_) {} |
| 82 | + if (!window.fetch || fetchInFlight) return false; |
| 83 | + fetchInFlight = true; |
| 84 | + window.fetch(rttPath(), { |
| 85 | + method: 'POST', body, keepalive: true, |
| 86 | + headers: { 'Content-Type': 'application/json' }, |
| 87 | + }).catch(function () {}).then(function () { fetchInFlight = false; }); |
| 88 | + return true; |
| 89 | +} |
| 90 | + |
| 91 | +// Ship the oldest samples, oldest-first, capped per batch. Samples are only |
| 92 | +// dropped from the queue once actually handed off; anything not shipped stays |
| 93 | +// queued (the ring bound already caps how far behind a dead endpoint can fall). |
| 94 | +export function flushSamples() { |
| 95 | + if (!samples.length) return; |
| 96 | + const batch = samples.slice(0, FLUSH_BATCH_MAX); |
| 97 | + const t0 = batch[0].at; |
| 98 | + const shipped = post({ |
| 99 | + sid: sessionIdFromPath(), |
| 100 | + t0: Math.round(t0), |
| 101 | + // Offsets, not absolute stamps: small payloads, no wall clock leaked. |
| 102 | + samples: batch.map((s) => ({ at: Math.round(s.at - t0), rtt: s.rtt })), |
| 103 | + }); |
| 104 | + if (shipped) samples.splice(0, batch.length); |
| 105 | +} |
| 106 | + |
| 107 | +export function recordRttSample(rtt) { |
| 108 | + if (!(rtt >= 0 && rtt < 20000)) return; |
| 109 | + ensureFlushTimer(); |
| 110 | + if (!earlyFlushArmed && typeof setTimeout === 'function') { |
| 111 | + earlyFlushArmed = true; |
| 112 | + setTimeout(function () { |
| 113 | + if (constrainedLink()) return; // same shedding rule as the periodic timer |
| 114 | + flushSamples(); |
| 115 | + }, EARLY_FLUSH_MS); |
| 116 | + } |
| 117 | + samples.push({ at: nowMs(), rtt: Math.round(rtt) }); |
| 118 | + while (samples.length > SAMPLE_MAX) samples.shift(); |
| 119 | + // Batch-full flush is unconditional (it fires ~once per 10 minutes of pings, |
| 120 | + // so it costs nothing even mid-struggle); only the TIMER flush sheds. |
| 121 | + if (samples.length >= FLUSH_BATCH_MAX) flushSamples(); |
| 122 | +} |
| 123 | + |
| 124 | +// Test/observability read of the unsent queue. |
| 125 | +export function pendingSampleCount() { return samples.length; } |
| 126 | + |
| 127 | +try { |
| 128 | + window.addEventListener('pagehide', flushSamples); |
| 129 | + window.addEventListener('beforeunload', flushSamples); |
| 130 | + document.addEventListener('visibilitychange', function () { if (document.hidden) flushSamples(); }); |
| 131 | +} catch (_) {} |
0 commit comments