Files
HellCon/src/lib/connection-diagnostics.ts
T

133 lines
7.1 KiB
TypeScript

// Only allowlisted categories and numbers leave this module. Never retain raw
// SDP, candidate addresses/IDs, URLs, credentials, filenames or browser errors.
const candidateTypes = ['host', 'srflx', 'prflx', 'relay'] as const;
const protocols = ['udp', 'tcp'] as const;
const pairStates = ['frozen', 'waiting', 'in-progress', 'failed', 'succeeded'] as const;
const counters = ['requestsSent', 'requestsReceived', 'responsesSent', 'responsesReceived'] as const;
type StatsEntry = Record<string, unknown>;
type Stats = Pick<RTCStatsReport, 'forEach' | 'get'>;
const category = (value: unknown, allowed: readonly string[]) => typeof value === 'string' && allowed.includes(value) ? value : 'unknown';
const count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? String(value) : '?';
export function summarizeCandidates(sdp: string | undefined): string {
const counts = { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 };
for (const line of sdp?.split(/\r?\n/) ?? []) {
if (!line.startsWith('a=candidate:')) continue;
const type = category(line.match(/\styp\s+(\S+)/)?.[1], candidateTypes) as keyof typeof counts;
counts[type]++;
}
return Object.entries(counts).map(([type, n]) => `${type}=${n}`).join(' ') +
` end=${sdp?.split(/\r?\n/).includes('a=end-of-candidates') ? 'yes' : 'no'}`;
}
export function summarizeStats(stats: Stats): string[] {
const pairs: StatsEntry[] = [];
const selected = new Set<string>();
const candidates = { local: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 }, remote: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 } };
stats.forEach((entry: StatsEntry) => {
if (entry.type === 'transport' && typeof entry.selectedCandidatePairId === 'string') selected.add(entry.selectedCandidatePairId);
if (entry.type === 'candidate-pair') pairs.push(entry);
const side = entry.type === 'local-candidate' ? 'local' : entry.type === 'remote-candidate' ? 'remote' : null;
if (side) candidates[side][category(entry.candidateType, candidateTypes) as keyof typeof candidates.local]++;
});
const endpoint = (id: unknown) => {
const entry = typeof id === 'string' ? stats.get(id) as StatsEntry | undefined : undefined;
return `${category(entry?.candidateType, candidateTypes)}/${category(entry?.protocol, protocols)}`;
};
const lines = (['local', 'remote'] as const).map(side => `${side} stats: ` + Object.entries(candidates[side]).map(([type, n]) => `${type}=${n}`).join(' '));
lines.push(`pairs=${pairs.length}`);
// Put a selected route first, cap output on machines with many interfaces.
const isSelected = (pair: StatsEntry) => typeof pair.id === 'string' && selected.has(pair.id) || pair.selected === true;
pairs.sort((a, b) => Number(isSelected(b)) - Number(isSelected(a)));
for (const pair of pairs.slice(0, 12)) {
lines.push(`pair ${endpoint(pair.localCandidateId)} → ${endpoint(pair.remoteCandidateId)} ${category(pair.state, pairStates)}` +
` selected=${isSelected(pair)} nominated=${pair.nominated === true} ` + counters.map(key => `${key}=${count(pair[key])}`).join(' '));
}
stats.forEach((entry: StatsEntry) => {
if (entry.type === 'transport') lines.push(`transport dtls=${category(entry.dtlsState, ['new', 'connecting', 'connected', 'closed', 'failed'])}`);
});
if (pairs.length > 12) lines.push(`pairs omitted=${pairs.length - 12}`);
return lines;
}
export class ConnectionDiagnostics {
readonly lines: string[] = [];
private readonly started = performance.now();
private stopped = false;
private sampleTimers: ReturnType<typeof setTimeout>[] = [];
private samplingStarted = false;
private finishing: Promise<void> | undefined;
private readonly listeners: Array<[EventTarget, string, EventListener]> = [];
private readonly pc: RTCPeerConnection;
private readonly update: (lines: string[]) => void;
constructor(pc: RTCPeerConnection, update: (lines: string[]) => void) {
this.pc = pc; this.update = update;
const listen = (target: EventTarget, event: string, listener: EventListener) => {
target.addEventListener(event, listener);
this.listeners.push([target, event, listener]);
};
const state = () => {
this.sampleWhileChecking();
this.record(`pc=${category(pc.connectionState, ['new', 'connecting', 'connected', 'disconnected', 'failed', 'closed'])} ice=${category(pc.iceConnectionState, ['new', 'checking', 'connected', 'completed', 'disconnected', 'failed', 'closed'])} gathering=${category(pc.iceGatheringState, ['new', 'gathering', 'complete'])}`);
};
for (const event of ['connectionstatechange', 'iceconnectionstatechange', 'icegatheringstatechange']) listen(pc, event, state);
listen(pc, 'icecandidateerror', event => this.record(`ICE server error=${count((event as RTCPeerConnectionIceErrorEvent).errorCode)}`));
if (typeof document !== 'undefined') {
const visibility = () => this.record(`page=${category(document.visibilityState, ['visible', 'hidden'])}`);
listen(document, 'visibilitychange', visibility);
visibility();
}
state();
}
private sampleWhileChecking() {
if (this.stopped || this.finishing) return;
if (this.pc.iceConnectionState !== 'checking') {
for (const timer of this.sampleTimers) clearTimeout(timer);
this.sampleTimers = [];
return;
}
if (this.samplingStarted) return;
this.samplingStarted = true;
// Preserve evidence before browsers discard failed candidate pairs. Four
// bounded snapshots cover short setup failures without polling indefinitely.
this.sampleTimers = [3000, 6000, 9000, 12000].map(delay => setTimeout(() => {
if (this.stopped || this.finishing || this.pc.iceConnectionState !== 'checking') return;
this.record('connectivity sample');
void this.capture();
}, delay));
}
record(message: string) {
if (this.stopped) return;
this.lines.push(`${((performance.now() - this.started) / 1000).toFixed(1)}s ${message}`);
this.lines.splice(0, Math.max(0, this.lines.length - 80));
this.update([...this.lines]);
}
descriptions() {
this.record(`local code: ${summarizeCandidates(this.pc.localDescription?.sdp)}`);
this.record(`remote code: ${summarizeCandidates(this.pc.remoteDescription?.sdp)}`);
}
async capture() {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const stats = await Promise.race([
this.pc.getStats(),
new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), 300); }),
]);
if (stats) for (const line of summarizeStats(stats)) this.record(line);
else this.record('stats unavailable: deadline');
} catch { this.record('stats unavailable'); }
finally { clearTimeout(timer); }
}
// Request final stats while the connection is alive. Always close, even when
// getStats rejects or hangs. Reset can start a new session during this wait.
finish(close: () => void) {
for (const timer of this.sampleTimers) clearTimeout(timer);
this.sampleTimers = [];
return this.finishing ??= this.capture().finally(() => {
this.stopped = true;
for (const [target, event, listener] of this.listeners) target.removeEventListener(event, listener);
close();
});
}
}