Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

feat(route): add on-demand route observability

AAA37c34d903159
diff --git a/scripts/peer-assisted-benchmark.ts b/scripts/peer-assisted-benchmark.ts
index 29d5e5a7..69a63ff8 100644
--- a/scripts/peer-assisted-benchmark.ts
+++ b/scripts/peer-assisted-benchmark.ts
@@ -989,8 +989,7 @@ export function buildBenchmarkInitScript(options: {
let transitionRevision = -1;
let transitionPhase = null;
let plannedRouteAssignment = null;
- const canary = { droppedProofs: 0, prepareUpdates: 0, activeUpdates: 0, routeFailed: 0 };
- let dropParentProof = false;
+ const canary = { prepareUpdates: 0, activeUpdates: 0, routeFailed: 0 };
const nativeSends = new WeakMap();
function isOpaqueId(value) {
@@ -1175,11 +1174,6 @@ export function buildBenchmarkInitScript(options: {
socket.send = function(data) {
let parsed = null;
if (typeof data === "string") { try { parsed = JSON.parse(data); } catch {} }
- if (dropParentProof && parsed?.type === "parent-edge-quality-evidence") {
- canary.droppedProofs += 1;
- handleSignalMessage(data, "out", socket);
- return undefined;
- }
const result = nativeSend.call(socket, data);
handleSignalMessage(data, "out", socket);
return result;
@@ -1439,24 +1433,15 @@ export function buildBenchmarkInitScript(options: {
};
}
- function configureCanary(value) {
- if (!value || typeof value.dropParentProof !== "boolean") return false;
- dropParentProof = value.dropParentProof;
- return true;
- }
function canarySnapshot() {
return { ...canary, connectionCount: connections.length, maxActiveOutboundMediaEdges: state.maxActiveOutboundMediaEdges };
}
function sendViewerQualityEvidence(message) {
return message?.type === "viewer-quality-evidence" && sendCanaryMessage(message);
}
- function sendParentEdgeQualityEvidence(message) {
- return message?.type === "parent-edge-quality-evidence" && sendCanaryMessage(message);
- }
-
Object.defineProperty(globalThis, "__SCREENER_BENCHMARK__", {
configurable: false,
- value: { sample, progress, snapshot, canarySnapshot, configureCanary, sendViewerQualityEvidence, sendParentEdgeQualityEvidence, stop: () => clearInterval(videoObserver) },
+ value: { sample, progress, snapshot, canarySnapshot, sendViewerQualityEvidence, stop: () => clearInterval(videoObserver) },
});
})();`;
}
@@ -2288,11 +2273,9 @@ async function runViewerMbbCanary(
if (!targetHandle || !parentHandle || !candidateHandle || !old || target.routeRevision === null || !target.peerId || !parent.peerId || !old.connectionId) return failed("probe-unavailable");
const oldFrames = old.receiveTotals?.framesTotal ?? 0;
const revision = target.routeRevision;
- await evaluate(cdp, parentHandle, "globalThis.__SCREENER_BENCHMARK__.configureCanary({dropParentProof:true})");
const send = (page: PageHandle, method: string, message: unknown) =>
evaluate<boolean>(cdp, page, `globalThis.__SCREENER_BENCHMARK__.${method}(${JSON.stringify(message)})`);
let windows = 0;
- let proofs = 0;
for (let sequence = 0; sequence < 3; sequence += 1) {
const windowSent = await send(targetHandle, "sendViewerQualityEvidence", {
type: "viewer-quality-evidence", guard: { connectionId: old.connectionId, routeRevision: revision },
@@ -2303,13 +2286,6 @@ async function runViewerMbbCanary(
codec: null, codecProfile: null, codecParameters: null },
});
if (windowSent) windows += 1;
- await delay(100, signal);
- const proofSent = await send(parentHandle, "sendParentEdgeQualityEvidence", {
- type: "parent-edge-quality-evidence", viewerPeerId: target.peerId,
- guard: { connectionId: old.connectionId, routeRevision: revision }, viewerSequence: sequence,
- proof: { kind: "sender-limited", packetsSentDelta: 100, reason: "bandwidth" },
- });
- if (proofSent) proofs += 1;
if (sequence < 2) await delay(2_100, signal);
}
let retained = false, provisional = false, promoted = false, sameIdentity = false, framesAdvanced = false;
@@ -2339,10 +2315,8 @@ async function runViewerMbbCanary(
if (promoted && sameIdentity && retained && framesAdvanced) break;
await delay(100, signal);
}
- await evaluate(cdp, parentHandle, "globalThis.__SCREENER_BENCHMARK__.configureCanary({dropParentProof:false})");
const assertions = {
- syntheticCorrelatedEvidence: windows === 3 && proofs === 3,
- parentProofSuppressed: parentTelemetry.droppedProofs > 0,
+ syntheticViewerEvidence: windows === 3,
oldEdgeRetained: retained,
provisionalPcObserved: provisional,
promotedToViewerCandidate: promoted,
@@ -2352,20 +2326,19 @@ async function runViewerMbbCanary(
noRouteFailed: targetTelemetry.routeFailed === 0 && parentTelemetry.routeFailed === 0 && candidateTelemetry.routeFailed === 0,
};
return { kind: "viewer-mbb", status: Object.values(assertions).every(Boolean) ? "passed" : "failed", assertions,
- counters: { pages: pages.length, evidenceWindows: windows, parentProofs: proofs,
- droppedParentProofs: parentTelemetry.droppedProofs, routePrepareUpdates: targetTelemetry.prepareUpdates + parentTelemetry.prepareUpdates + candidateTelemetry.prepareUpdates,
+ counters: { pages: pages.length, evidenceWindows: windows,
+ routePrepareUpdates: targetTelemetry.prepareUpdates + parentTelemetry.prepareUpdates + candidateTelemetry.prepareUpdates,
routeActiveUpdates: targetTelemetry.activeUpdates + parentTelemetry.activeUpdates + candidateTelemetry.activeUpdates,
maxActiveOutboundEdges: Math.max(targetTelemetry.maxActiveOutboundMediaEdges, parentTelemetry.maxActiveOutboundMediaEdges, candidateTelemetry.maxActiveOutboundMediaEdges),
routeFailedMessages: targetTelemetry.routeFailed + parentTelemetry.routeFailed + candidateTelemetry.routeFailed },
...(Object.values(assertions).every(Boolean) ? {} : { failureCode: "probe-unavailable" as const }) };
} catch {
- if (parentHandle) await evaluate(cdp, parentHandle, "globalThis.__SCREENER_BENCHMARK__.configureCanary({dropParentProof:false})").catch(() => undefined);
return failed("probe-unavailable");
}
}
async function canary(cdp: CdpConnection, page: PageHandle): Promise<{
- droppedProofs: number; prepareUpdates: number; activeUpdates: number; routeFailed: number;
+ prepareUpdates: number; activeUpdates: number; routeFailed: number;
maxActiveOutboundMediaEdges: number;
}> {
return evaluate(cdp, page, "globalThis.__SCREENER_BENCHMARK__.canarySnapshot()");
diff --git a/src/client/lib/diagnostic-export.ts b/src/client/lib/diagnostic-export.ts
index efcc9924..032fbf52 100644
--- a/src/client/lib/diagnostic-export.ts
+++ b/src/client/lib/diagnostic-export.ts
@@ -1,6 +1,47 @@
+import type { RouteDiagnosticSnapshot } from "../../shared/protocol";
import type { ConnectionMetrics } from "../types";
-export const DIAGNOSTIC_SCHEMA_VERSION = 1;
+export const DIAGNOSTIC_SCHEMA_VERSION = 2;
+
+const ROUTE_TIMING_KEYS = [
+ "queueWaitMs",
+ "candidateStartMs",
+ "firstDecodedFrameMs",
+ "finalMs",
+] as const satisfies readonly (keyof RouteDiagnosticSnapshot["children"][number])[];
+
+export interface RouteTimingDistribution {
+ sampleCount: number;
+ pendingCount: number;
+ rawMs: number[];
+ p50Ms: number | null;
+ p95Ms: number | null;
+ maxMs: number | null;
+}
+
+export function summarizeRouteTiming(
+ values: readonly (number | null)[],
+): RouteTimingDistribution {
+ const rawMs = values
+ .filter((value): value is number => value !== null)
+ .toSorted((left, right) => left - right);
+ return {
+ sampleCount: rawMs.length,
+ pendingCount: values.length - rawMs.length,
+ rawMs,
+ p50Ms: nearestRank(rawMs, 0.5),
+ p95Ms: nearestRank(rawMs, 0.95),
+ maxMs: rawMs.at(-1) ?? null,
+ };
+}
+
+function nearestRank(
+ sortedValues: readonly number[],
+ percentile: number,
+): number | null {
+ if (sortedValues.length === 0) return null;
+ return sortedValues[Math.ceil(percentile * sortedValues.length) - 1] ?? null;
+}
const DIAGNOSTIC_METRIC_KEYS = [
"sampleWindowMs", "captureWidth", "captureHeight",
@@ -38,11 +79,22 @@ export function createDiagnosticReport(
role: "host" | "viewer",
connections: readonly DiagnosticConnectionInput[],
exportedAt = new Date(),
+ routeSnapshot: RouteDiagnosticSnapshot | null = null,
) {
+ const route = role === "host" ? routeSnapshot : null;
return {
schemaVersion: DIAGNOSTIC_SCHEMA_VERSION,
exportedAt: exportedAt.toISOString(),
role,
+ route,
+ routeTimingSummary: route
+ ? Object.fromEntries(
+ ROUTE_TIMING_KEYS.map((key) => [
+ key,
+ summarizeRouteTiming(route.children.map((child) => child[key])),
+ ]),
+ )
+ : null,
connections: connections.map((connection) => ({
scope: connection.scope,
route: connection.route,
@@ -62,9 +114,15 @@ export function createDiagnosticReport(
export function downloadDiagnosticReport(
role: "host" | "viewer",
connections: readonly DiagnosticConnectionInput[],
+ routeSnapshot: RouteDiagnosticSnapshot | null = null,
): void {
const exportedAt = new Date();
- const report = createDiagnosticReport(role, connections, exportedAt);
+ const report = createDiagnosticReport(
+ role,
+ connections,
+ exportedAt,
+ routeSnapshot,
+ );
const blob = new Blob([`${JSON.stringify(report, null, 2)}\n`], {
type: "application/json;charset=utf-8",
});
diff --git a/src/client/media/parent-edge-quality-evidence.ts b/src/client/media/parent-edge-quality-evidence.ts
deleted file mode 100644
index 48e4eacd..00000000
--- a/src/client/media/parent-edge-quality-evidence.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import {
- MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES,
- parentEdgeQualityEvidenceMessageSchema,
- type ClientMessage,
- type ServerMessage,
-} from "../../shared/protocol";
-import type { PeerSnapshot } from "../types";
-
-type ViewerQualityEvidence = Extract<
- ServerMessage,
- { type: "viewer-quality-evidence" }
->;
-
-const PARENT_EDGE_QUALITY_MIN_LOSS_PACKETS = 100;
-const PARENT_EDGE_QUALITY_HIGH_LOSS_RATIO = 0.3;
-
-export function parentEdgeQualityEvidenceFromSnapshot(
- evidence: ViewerQualityEvidence,
- snapshot: PeerSnapshot | null,
-): Extract<ClientMessage, { type: "parent-edge-quality-evidence" }> | null {
- if (
- snapshot === null ||
- snapshot.peerId !== evidence.viewerPeerId ||
- snapshot.connectionId !== evidence.guard.connectionId ||
- snapshot.connectionState !== "connected"
- ) {
- return null;
- }
- const { metrics } = snapshot;
- const packetsSentDelta = metrics.intervalPacketsSent;
- const sampleWindowMs = metrics.sampleWindowMs;
- const windowMs =
- sampleWindowMs !== null && Number.isFinite(sampleWindowMs)
- ? Math.round(sampleWindowMs)
- : null;
- if (
- !Number.isSafeInteger(packetsSentDelta) ||
- packetsSentDelta === null ||
- packetsSentDelta <= 0 ||
- windowMs === null ||
- !Number.isSafeInteger(windowMs) ||
- windowMs < 1_000 ||
- windowMs > 5_000
- ) {
- return null;
- }
-
- const remotePacketsLostDelta = metrics.intervalPacketsLost;
- const senderLimitation =
- metrics.qualityLimitationReason === "cpu" ||
- metrics.qualityLimitationReason === "bandwidth"
- ? metrics.qualityLimitationReason
- : null;
- const hasHighRemoteLoss =
- Number.isSafeInteger(remotePacketsLostDelta) &&
- remotePacketsLostDelta !== null &&
- remotePacketsLostDelta > 0 &&
- packetsSentDelta >= PARENT_EDGE_QUALITY_MIN_LOSS_PACKETS &&
- remotePacketsLostDelta / packetsSentDelta >=
- PARENT_EDGE_QUALITY_HIGH_LOSS_RATIO;
- const proof = senderLimitation
- ? {
- kind: "sender-limited" as const,
- packetsSentDelta,
- reason: senderLimitation,
- }
- : hasHighRemoteLoss
- ? {
- kind: "remote-loss" as const,
- packetsSentDelta,
- remotePacketsLostDelta,
- }
- : { kind: "sending" as const, packetsSentDelta };
- const parsed = parentEdgeQualityEvidenceMessageSchema.safeParse({
- type: "parent-edge-quality-evidence",
- viewerPeerId: evidence.viewerPeerId,
- guard: evidence.guard,
- viewerSequence: evidence.sequence,
- proof,
- });
- if (!parsed.success) {
- return null;
- }
- return JSON.stringify(parsed.data).length <=
- MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES
- ? parsed.data
- : null;
-}
-
-export class ParentEdgeQualityEvidenceReporter {
- private readonly samplesByViewer = new Map<
- string,
- { connectionId: string; sampleTimestampMs: number }
- >();
-
- offer(
- evidence: ViewerQualityEvidence,
- snapshot: PeerSnapshot | null,
- ): Extract<ClientMessage, { type: "parent-edge-quality-evidence" }> | null {
- const sampleTimestampMs = snapshot?.metrics.sampleTimestampMs;
- if (
- snapshot === null ||
- typeof sampleTimestampMs !== "number" ||
- !Number.isFinite(sampleTimestampMs)
- ) {
- return null;
- }
- const previous = this.samplesByViewer.get(evidence.viewerPeerId);
- if (
- previous?.connectionId === evidence.guard.connectionId &&
- sampleTimestampMs <= previous.sampleTimestampMs
- ) {
- return null;
- }
- const message = parentEdgeQualityEvidenceFromSnapshot(evidence, snapshot);
- if (!message) {
- return null;
- }
- this.samplesByViewer.set(evidence.viewerPeerId, {
- connectionId: evidence.guard.connectionId,
- sampleTimestampMs,
- });
- return message;
- }
-
- forget(viewerPeerId: string): void {
- this.samplesByViewer.delete(viewerPeerId);
- }
-
- reset(): void {
- this.samplesByViewer.clear();
- }
-}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index cc0fbeb1..d4a22924 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -97,9 +97,6 @@ import {
import {
HostProvisionalChild,
} from "../media/host-provisional-child";
-import {
- ParentEdgeQualityEvidenceReporter,
-} from "../media/parent-edge-quality-evidence";
import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
import {
classifyHostViewerQualityEvidence,
@@ -270,6 +267,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const videoRef = useRef<HTMLVideoElement | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const signalRef = useRef<SignalingClient | null>(null);
+ const pendingDiagnosticExportRef = useRef<
+ DiagnosticConnectionInput[] | null
+ >(null);
const displayNameRef = useRef(displayName);
const hostClientIdRef = useRef<string | null>(null);
const viewerPasswordActionRef = useRef<string | null | undefined>(undefined);
@@ -286,9 +286,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const viewerQualityEvidenceTimersRef = useRef(
new Map<string, number>(),
);
- const parentEdgeQualityEvidenceReporterRef = useRef(
- new ParentEdgeQualityEvidenceReporter(),
- );
const peerAssistedRef = useRef(false);
const activeRouteRevisionRef = useRef(0);
const generationRef = useRef(0);
@@ -420,12 +417,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
activeHostChildPeerIdsRef.current = [];
endpointMediaCopyCapacityRef.current = MAX_ENDPOINT_MEDIA_CHILDREN;
hostPeerIdRef.current = null;
+ pendingDiagnosticExportRef.current = null;
viewerQualityEvidenceTimersRef.current.forEach((timer) =>
window.clearTimeout(timer),
);
viewerQualityEvidenceTimersRef.current.clear();
viewerQualityEvidenceRef.current.clear();
- parentEdgeQualityEvidenceReporterRef.current.reset();
activeRouteRevisionRef.current = 0;
void hostSfuRouteRef.current?.disconnect();
hostSfuRouteRef.current = null;
@@ -527,6 +524,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
signal.stop();
}
signalRef.current = null;
+ pendingDiagnosticExportRef.current = null;
shareGenerationRef.current = null;
peersRef.current.forEach((peer) => peer.dispose());
peersRef.current.clear();
@@ -556,7 +554,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
);
viewerQualityEvidenceTimersRef.current.clear();
viewerQualityEvidenceRef.current = new Map();
- parentEdgeQualityEvidenceReporterRef.current.reset();
setViewerQualityEvidence(new Map());
activeRouteRevisionRef.current = 0;
setSignalStatus("offline");
@@ -678,15 +675,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
) {
return;
}
- if (evidenceSource === "direct") {
- const parentEvidence = parentEdgeQualityEvidenceReporterRef.current.offer(
- evidence,
- directSnapshot,
- );
- if (peerAssistedRef.current && parentEvidence) {
- signalRef.current?.send(parentEvidence);
- }
- }
commitViewerQualityEvidence(
evidence.viewerPeerId,
presentViewerQualityEvidence(
@@ -915,7 +903,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
function removePeer(peerId: string): void {
clearViewerQualityEvidence(peerId);
- parentEdgeQualityEvidenceReporterRef.current.forget(peerId);
const peer = peersRef.current.get(peerId);
if (peer) {
retiredConnectionsRef.current.set(peerId, peer.connectionId);
@@ -1274,6 +1261,13 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
setParticipantPresence(message.viewers);
return;
}
+ if (message.type === "route-diagnostic-snapshot") {
+ const connections = pendingDiagnosticExportRef.current;
+ if (!connections) return;
+ pendingDiagnosticExportRef.current = null;
+ downloadDiagnosticReport("host", connections, message.snapshot);
+ return;
+ }
if (message.type === "route-update") {
if (peerAssistedRef.current) {
const route = ensureHostSfuRoute(generation);
@@ -1503,6 +1497,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
isCurrentGeneration(generation) &&
signalRef.current === signal
) {
+ if (status !== "connected") {
+ pendingDiagnosticExportRef.current = null;
+ }
setSignalStatus(status);
}
},
@@ -2149,8 +2146,29 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
<ConnectionDetailsToggle
checked={showConnectionDetails}
onChange={setShowConnectionDetails}
- onExport={diagnosticConnections.length > 0
- ? () => downloadDiagnosticReport("host", diagnosticConnections)
+ onExport={phase === "live"
+ ? () => {
+ if (pendingDiagnosticExportRef.current) return;
+ const connections = diagnosticConnections.map(
+ (connection) => ({
+ ...connection,
+ metrics: { ...connection.metrics },
+ }),
+ );
+ pendingDiagnosticExportRef.current = connections;
+ if (
+ !signalRef.current?.send({
+ type: "request-route-diagnostic",
+ })
+ ) {
+ pendingDiagnosticExportRef.current = null;
+ downloadDiagnosticReport(
+ "host",
+ connections,
+ null,
+ );
+ }
+ }
: undefined}
/>
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index a7472a24..1f3c1a0a 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -43,9 +43,6 @@ import { labelParticipantSnapshot } from "../lib/viewer-presence";
import { downloadDiagnosticReport, type DiagnosticConnectionInput } from "../lib/diagnostic-export";
import { DecodedFrameStallDetector } from "../media/decoded-frame-stall";
import type { QualitySettings } from "../media/quality";
-import {
- ParentEdgeQualityEvidenceReporter,
-} from "../media/parent-edge-quality-evidence";
import { relayCapacityMessageForBrowser } from "../media/relay-capability";
import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
import {
@@ -341,8 +338,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const qualityEvidenceReporter = new ViewerQualityEvidenceReporter(
(message) => active && signal.send(message),
);
- const parentEdgeQualityEvidenceReporter =
- new ParentEdgeQualityEvidenceReporter();
function commitRelayChildEvidence(
presentation: ViewerQualityEvidencePresentation | null,
@@ -394,13 +389,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
) {
return;
}
- const parentEvidence = parentEdgeQualityEvidenceReporter.offer(
- evidence,
- relaySnapshot,
- );
- if (parentEvidence) {
- signal.send(parentEvidence);
- }
commitRelayChildEvidence(
presentViewerQualityEvidence(
relayChildEvidenceCurrent,
@@ -462,11 +450,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
previousChildPeerIds.some(
(peerId, index) => peerId !== nextChildPeerIds[index],
);
- for (const peerId of previousChildPeerIds) {
- if (!nextChildPeerIds.includes(peerId)) {
- parentEdgeQualityEvidenceReporter.forget(peerId);
- }
- }
if (changed) {
clearRelayChildEvidence();
}
@@ -638,7 +621,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
return;
}
currentAssignment = { parentPeerId: null, childPeerIds: [] };
- parentEdgeQualityEvidenceReporter.reset();
setSfuUpstream(null);
clearPeerState();
viewerRelay?.setChildren([]);
@@ -1260,7 +1242,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
active = false;
currentPeerId = null;
qualityEvidenceReporter.reset();
- parentEdgeQualityEvidenceReporter.reset();
clearRelayChildEvidence();
sfuStandbyPrewarmer?.dispose();
signal.stop();
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index f3cb9a70..f8b24558 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -91,7 +91,10 @@ interface PreparedCandidate {
}
type PrepareResult =
- | { kind: "denied"; serverAdmission: "sfu" | false }
+ | {
+ kind: "denied";
+ rejectionBucket: "stale" | "sfu-admission" | "candidate-failed";
+ }
| { kind: "ready"; prepared: PreparedCandidate };
export interface SfuFallbackOptions {
@@ -190,7 +193,7 @@ export class HybridMediaRouter {
input.role === "host"
? this.options.endpointMediaCopyCapacity
: (room.advertisedCapacityByViewer.get(input.peerId) ?? 0),
- }),
+ }, this.now()),
);
}
const snapshot = room.controller?.snapshot();
@@ -227,11 +230,22 @@ export class HybridMediaRouter {
const room = this.rooms.get(roomId);
if (!room?.controller) return;
const before = room.controller.snapshot().revision;
- this.releaseResources(room.controller.setPaused(paused));
+ this.releaseResources(room.controller.setPaused(paused, this.now()));
if (room.controller.snapshot().revision !== before) this.broadcastActive(roomId, room);
if (!paused) this.requestPump(roomId);
}
+ routeDiagnosticSnapshot(
+ roomId: string,
+ ): Extract<ServerMessage, { type: "route-diagnostic-snapshot" }>["snapshot"] {
+ return (
+ this.rooms.get(roomId)?.controller?.routeDiagnosticSnapshot(this.now()) ?? {
+ children: [],
+ operation: null,
+ }
+ );
+ }
+
isActivePeerParentOf(
roomId: string,
parentPeerId: string,
@@ -366,6 +380,7 @@ export class HybridMediaRouter {
participant.peerId,
participant.sessionId,
downstreamEdges,
+ this.now(),
)
) {
this.requestPump(participant.roomId);
@@ -413,6 +428,14 @@ export class HybridMediaRouter {
);
}
if (controller.snapshot().revision !== before) this.broadcastActive(participant.roomId, room);
+ if (settled.exhausted) {
+ this.sendViewerRouteStatus(participant.roomId, participant.peerId, {
+ type: "route-status",
+ revision: controller.snapshot().revision,
+ state: "failed",
+ reason: "route-exhausted",
+ });
+ }
this.requestPump(participant.roomId);
}
@@ -441,7 +464,7 @@ export class HybridMediaRouter {
childSessionId: participant.sessionId,
routeRevision: snapshot.revision,
connectionId: edge.connectionId,
- });
+ }, this.now());
this.requestPump(participant.roomId);
}
@@ -484,6 +507,18 @@ export class HybridMediaRouter {
);
this.releaseResources(settled.released);
if (controller.snapshot().revision !== before) this.broadcastActive(participant.roomId, room);
+ if (settled.exhausted) {
+ this.sendViewerRouteStatus(
+ participant.roomId,
+ operation.childPeerId,
+ {
+ type: "route-status",
+ revision: controller.snapshot().revision,
+ state: "failed",
+ reason: "route-exhausted",
+ },
+ );
+ }
this.requestPump(participant.roomId);
return;
}
@@ -503,7 +538,7 @@ export class HybridMediaRouter {
routeRevision: snapshot.revision,
generation: publication.generation,
connectionId: publication.connectionId,
- });
+ }, this.now());
const invalid = controller.snapshot();
this.releaseResources(
controller.retireHostPublication({
@@ -532,7 +567,7 @@ export class HybridMediaRouter {
routeRevision: snapshot.revision,
connectionId: edge.connectionId,
...(edge.kind === "peer" ? { parentSessionId: edge.parentSessionId } : {}),
- });
+ }, this.now());
this.requestPump(participant.roomId);
}
@@ -557,7 +592,9 @@ export class HybridMediaRouter {
const room = this.rooms.get(roomId);
room?.advertisedCapacityByViewer.delete(peerId);
this.options.deleteConnectionId(roomId, peerId);
- if (room?.controller?.confirmDeparture(peerId)) this.requestPump(roomId);
+ if (room?.controller?.confirmDeparture(peerId, this.now())) {
+ this.requestPump(roomId);
+ }
}
stopRoom(roomId: string): void {
@@ -598,7 +635,7 @@ export class HybridMediaRouter {
role: "host",
sessionId: host.sessionId,
effectiveDownstreamCapacity: this.options.endpointMediaCopyCapacity,
- });
+ }, this.now());
for (const viewer of this.options.roomStore.getConnectedViewers(roomId)) {
room.controller.upsertParticipant({
peerId: viewer.peerId,
@@ -606,7 +643,7 @@ export class HybridMediaRouter {
sessionId: viewer.sessionId,
effectiveDownstreamCapacity:
room.advertisedCapacityByViewer.get(viewer.peerId) ?? 0,
- });
+ }, this.now());
}
}
@@ -639,6 +676,14 @@ export class HybridMediaRouter {
const reconciled = controller.reconcile(this.now());
this.releaseResources(reconciled.released);
if (controller.snapshot().revision !== beforeRevision) this.broadcastActive(roomId, room);
+ for (const peerId of reconciled.failedPeerIds) {
+ this.sendViewerRouteStatus(roomId, peerId, {
+ type: "route-status",
+ revision: controller.snapshot().revision,
+ state: "failed",
+ reason: "route-exhausted",
+ });
+ }
const operation = reconciled.operation ?? controller.snapshot().operation;
if (!operation) {
this.clearDeadline(room);
@@ -660,20 +705,38 @@ export class HybridMediaRouter {
(plan.endpointTransition.kind === "bounded-gap" ? 2 : 1),
);
if (preparation.kind === "denied") {
- if (preparation.serverAdmission === "sfu") {
+ if (preparation.rejectionBucket === "sfu-admission") {
+ if (
+ !controller.noteCurrentCandidateRejection(
+ guard,
+ "sfu-admission",
+ )
+ ) {
+ continue;
+ }
this.resourceWaiterRoomIds.add(roomId);
+ this.sendViewerRouteStatus(roomId, operation.childPeerId, {
+ type: "route-status",
+ revision: operation.baseRevision,
+ state: "waiting",
+ reason: "sfu-admission",
+ });
this.scheduleDeadline(roomId, room, operation);
return;
}
- const skipped = controller.skipCurrentCandidate(guard, this.now());
+ const skipped = controller.skipCurrentCandidate(
+ guard,
+ this.now(),
+ preparation.rejectionBucket,
+ );
this.releaseResources(skipped.released);
if (skipped.exhausted) {
- this.sendViewerError(
- roomId,
- operation.childPeerId,
- "PEER_NOT_FOUND",
- "No usable media route is available",
- );
+ this.sendViewerRouteStatus(roomId, operation.childPeerId, {
+ type: "route-status",
+ revision: controller.snapshot().revision,
+ state: "failed",
+ reason: "route-exhausted",
+ });
}
continue;
}
@@ -682,6 +745,14 @@ export class HybridMediaRouter {
const beforeGap = controller.snapshot().revision;
const gap = controller.retireCurrentCandidateProducer(guard, this.now());
this.releaseResources(gap.released);
+ if (gap.exhausted) {
+ this.sendViewerRouteStatus(roomId, operation.childPeerId, {
+ type: "route-status",
+ revision: controller.snapshot().revision,
+ state: "failed",
+ reason: "route-exhausted",
+ });
+ }
if (!gap.accepted) {
this.releaseReservation(preparation.prepared.reservation);
continue;
@@ -705,12 +776,12 @@ export class HybridMediaRouter {
this.releaseResources(begun.released);
if (!begun.accepted || !begun.operation?.current) {
if (begun.exhausted) {
- this.sendViewerError(
- roomId,
- operation.childPeerId,
- "PEER_NOT_FOUND",
- "No usable media route is available",
- );
+ this.sendViewerRouteStatus(roomId, operation.childPeerId, {
+ type: "route-status",
+ revision: controller.snapshot().revision,
+ state: "failed",
+ reason: "route-exhausted",
+ });
}
continue;
}
@@ -736,7 +807,7 @@ export class HybridMediaRouter {
const child = this.options.roomStore.getConnectedViewer(roomId, operation.childPeerId);
const shareGeneration = this.options.getShareGeneration(roomId);
if (!child || child.sessionId !== operation.childSessionId || !shareGeneration) {
- return { kind: "denied", serverAdmission: false };
+ return { kind: "denied", rejectionBucket: "stale" };
}
const connectionId = opaqueId();
const overlap =
@@ -756,7 +827,7 @@ export class HybridMediaRouter {
const fallback = this.options.sfuFallback;
const host = this.options.roomStore.getConnectedHost(roomId);
if (!fallback || !host || host.peerId !== room.hostPeerId) {
- return { kind: "denied", serverAdmission: false };
+ return { kind: "denied", rejectionBucket: "stale" };
}
if (plan.tuple.publication === "reuse") {
const publication = snapshot.hostPublication;
@@ -764,14 +835,14 @@ export class HybridMediaRouter {
!publication ||
publication.resource.kind !== "sfu-publication"
) {
- return { kind: "denied", serverAdmission: false };
+ return { kind: "denied", rejectionBucket: "stale" };
}
const fence: SfuSubscriptionFence = {
...publication.resource.fence,
viewerPeerId: operation.childPeerId,
};
if (!fallback.admission.reserveSubscription(fence)) {
- return { kind: "denied", serverAdmission: "sfu" };
+ return { kind: "denied", rejectionBucket: "sfu-admission" };
}
const currentEdge = snapshot.upstreamByViewer.get(operation.childPeerId);
const edge =
@@ -810,7 +881,7 @@ export class HybridMediaRouter {
};
} catch {
fallback.admission.releaseSubscription(fence);
- return { kind: "denied", serverAdmission: false };
+ return { kind: "denied", rejectionBucket: "candidate-failed" };
}
}
@@ -846,12 +917,12 @@ export class HybridMediaRouter {
viewerPeerId: operation.childPeerId,
};
if (!fallback.admission.reservePublication(publicationFence)) {
- return { kind: "denied", serverAdmission: "sfu" };
+ return { kind: "denied", rejectionBucket: "sfu-admission" };
}
if (!fallback.admission.reserveSubscription(subscriptionFence)) {
fallback.admission.beginDrain(publicationFence);
this.scheduleSfuDrain(publicationFence);
- return { kind: "denied", serverAdmission: "sfu" };
+ return { kind: "denied", rejectionBucket: "sfu-admission" };
}
const subscription = subscriptionResource(subscriptionFence);
const publicationConnectionId = publicationGeneration;
@@ -905,7 +976,7 @@ export class HybridMediaRouter {
} catch {
this.releaseResource(subscription);
this.releaseResource(publication);
- return { kind: "denied", serverAdmission: false };
+ return { kind: "denied", rejectionBucket: "candidate-failed" };
}
}
@@ -1210,12 +1281,12 @@ export class HybridMediaRouter {
this.releaseResources(expired.released);
if (room.controller.snapshot().revision !== before) this.broadcastActive(roomId, room);
if (expired.exhausted) {
- this.sendViewerError(
- roomId,
- operation.childPeerId,
- "PEER_NOT_FOUND",
- "No usable media route is available",
- );
+ this.sendViewerRouteStatus(roomId, operation.childPeerId, {
+ type: "route-status",
+ revision: room.controller.snapshot().revision,
+ state: "failed",
+ reason: "route-exhausted",
+ });
}
this.requestPump(roomId);
}, Math.max(0, operation.wakeAtMs - this.now()));
@@ -1322,7 +1393,7 @@ export class HybridMediaRouter {
routeRevision: snapshot.revision,
generation: publication.generation,
connectionId: publication.connectionId,
- });
+ }, this.now());
const invalid = controller.snapshot();
this.releaseResources(
controller.retireHostPublication({
@@ -1407,14 +1478,13 @@ export class HybridMediaRouter {
if (host) this.options.sendToSession(host.sessionId, { type: "error", code, message });
}
- private sendViewerError(
+ private sendViewerRouteStatus(
roomId: string,
viewerPeerId: string,
- code: ErrorCode,
- message: string,
+ message: Extract<ServerMessage, { type: "route-status" }>,
): void {
const viewer = this.options.roomStore.getConnectedViewer(roomId, viewerPeerId);
- if (viewer) this.options.sendToSession(viewer.sessionId, { type: "error", code, message });
+ if (viewer) this.options.sendToSession(viewer.sessionId, message);
}
}
diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.ts
index 36a77bb6..65fc58bb 100644
--- a/src/server/room-route-controller.ts
+++ b/src/server/room-route-controller.ts
@@ -1,4 +1,10 @@
-import { MAX_MEDIA_ROUTE_REVISION } from "../shared/protocol.js";
+import {
+ MAX_MEDIA_ROUTE_REVISION,
+ type RouteDemandReason,
+ type RouteDiagnosticFinalRoute,
+ type RouteDiagnosticRejectionBucket,
+ type RouteDiagnosticSnapshot,
+} from "../shared/protocol.js";
import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";
export type CandidateTuple =
@@ -108,6 +114,7 @@ interface Attempt<Resource> {
interface ChildOperation<Resource> {
childPeerId: string;
childSessionId: string;
+ reason: RouteDemandReason;
baseRevision: number;
candidates: CandidatePlan[];
cursor: number;
@@ -119,6 +126,7 @@ interface ChildOperation<Resource> {
export interface OperationSnapshot {
childPeerId: string;
childSessionId: string;
+ reason: RouteDemandReason;
baseRevision: number;
factVersion: number;
candidates: readonly CandidatePlan[];
@@ -140,6 +148,7 @@ export interface RouteSnapshot<Resource> {
export interface ReconcileResult<Resource> {
operation?: OperationSnapshot;
removedPeerIds: readonly string[];
+ failedPeerIds: readonly string[];
released: readonly Resource[];
}
@@ -166,6 +175,17 @@ interface HostPublication<Resource> {
resource: Resource;
}
+interface RouteTimingRecord {
+ demandAtMs: number;
+ reason: RouteDemandReason;
+ operationStartedAtMs?: number;
+ candidateStartedAtMs?: number;
+ firstDecodedFrameAtMs?: number;
+ finalAtMs?: number;
+ finalRoute: RouteDiagnosticFinalRoute;
+ rejectionBucket: RouteDiagnosticRejectionBucket;
+}
+
export class RoomRouteController<Resource = unknown> {
private readonly participants = new Map<string, Participant>();
private readonly upstreamByViewer = new Map<string, CommittedEdge<Resource>>();
@@ -176,6 +196,7 @@ export class RoomRouteController<Resource = unknown> {
private factVersion = 0;
private nextJoinOrder = 0;
private paused = false;
+ private readonly routeTimings = new Map<string, RouteTimingRecord>();
constructor(private readonly options: ControllerOptions) {
assertEndpointMediaCopyCapacity(options.endpointMediaCopyCapacity);
@@ -195,7 +216,84 @@ export class RoomRouteController<Resource = unknown> {
};
}
- upsertParticipant(input: ParticipantInput): readonly Resource[] {
+ routeDiagnosticSnapshot(nowMs: number): RouteDiagnosticSnapshot {
+ const viewers = [...this.participants.values()]
+ .filter(
+ (participant) =>
+ participant.role === "viewer" &&
+ participant.sessionId !== null &&
+ !participant.departureConfirmed,
+ )
+ .sort(compareParticipant);
+ const ordinals = new Map(
+ viewers.map((viewer, index) => [viewer.peerId, index + 1] as const),
+ );
+ const children: RouteDiagnosticSnapshot["children"] = viewers.map(
+ (viewer) => {
+ const ordinal = ordinals.get(viewer.peerId)!;
+ const edge = this.upstreamByViewer.get(viewer.peerId);
+ const record = this.routeTimings.get(viewer.peerId);
+ const finalRoute = this.currentFinalRoute(viewer.peerId);
+ return {
+ ordinal,
+ parent: this.diagnosticParent(edge, ordinals),
+ effectiveCapacity: viewer.effectiveDownstreamCapacity,
+ childCount: this.childrenOf(viewer.peerId).filter((childPeerId) => {
+ const childEdge = this.upstreamByViewer.get(childPeerId);
+ return childEdge?.kind === "peer" && childEdge.physicalActive;
+ }).length,
+ demandAgeMs: record
+ ? elapsedMs(record.demandAtMs, nowMs)
+ : null,
+ queueWaitMs:
+ record?.operationStartedAtMs === undefined
+ ? null
+ : elapsedMs(record.demandAtMs, record.operationStartedAtMs),
+ candidateStartMs:
+ record?.candidateStartedAtMs === undefined
+ ? null
+ : elapsedMs(record.demandAtMs, record.candidateStartedAtMs),
+ firstDecodedFrameMs:
+ record?.firstDecodedFrameAtMs === undefined
+ ? null
+ : elapsedMs(record.demandAtMs, record.firstDecodedFrameAtMs),
+ finalMs:
+ record?.finalAtMs === undefined
+ ? null
+ : elapsedMs(record.demandAtMs, record.finalAtMs),
+ finalRoute:
+ finalRoute === "waiting"
+ ? record?.finalRoute === "failed"
+ ? "failed"
+ : "waiting"
+ : finalRoute,
+ rejectionBucket: record?.rejectionBucket ?? "none",
+ };
+ },
+ );
+ const operation = this.operation;
+ const childOrdinal = operation
+ ? ordinals.get(operation.childPeerId)
+ : undefined;
+ return {
+ children,
+ operation:
+ operation && childOrdinal !== undefined
+ ? {
+ childOrdinal,
+ reason: operation.reason,
+ stage: operation.current ? "first-frame" : "admission",
+ cursor: operation.cursor,
+ candidateCount: operation.candidates.length,
+ }
+ : null,
+ };
+ }
+
+ upsertParticipant(
+ input: ParticipantInput,
+ nowMs?: number,
+ ): readonly Resource[] {
if ((input.peerId === this.options.hostPeerId) !== (input.role === "host")) {
throw new Error("Route Host identity is inconsistent");
}
@@ -208,7 +306,7 @@ export class RoomRouteController<Resource = unknown> {
const previousSessionId = current.sessionId;
if (previousSessionId !== input.sessionId) {
const revisionBefore = this.revision;
- released.push(...this.abortOperation());
+ released.push(...this.abortOperation(nowMs, "stale"));
current.sessionId = input.sessionId;
const rebound = this.rebindCommittedSession(input.peerId, input.sessionId);
released.push(...rebound.released);
@@ -229,6 +327,13 @@ export class RoomRouteController<Resource = unknown> {
current.blockedAtFactVersion = undefined;
}
if (changed) this.touchFacts();
+ if (
+ input.role === "viewer" &&
+ nowMs !== undefined &&
+ !this.usableRoute(input.peerId)
+ ) {
+ this.recordDemand(input.peerId, nowMs, "join");
+ }
return released;
} else {
this.participants.set(input.peerId, {
@@ -238,6 +343,9 @@ export class RoomRouteController<Resource = unknown> {
joinOrder: this.nextJoinOrder++,
});
}
+ if (input.role === "viewer" && nowMs !== undefined) {
+ this.recordDemand(input.peerId, nowMs, "join");
+ }
this.touchFacts();
return [];
}
@@ -250,19 +358,30 @@ export class RoomRouteController<Resource = unknown> {
return true;
}
- confirmDeparture(peerId: string): boolean {
+ confirmDeparture(peerId: string, nowMs?: number): boolean {
const participant = this.participants.get(peerId);
if (!participant || participant.role === "host") return false;
+ this.routeTimings.delete(peerId);
if (participant.departureConfirmed && participant.sessionId === null &&
participant.effectiveDownstreamCapacity === 0) return true;
participant.sessionId = null;
participant.departureConfirmed = true;
participant.effectiveDownstreamCapacity = 0;
+ if (nowMs !== undefined) {
+ for (const childPeerId of this.childrenOf(peerId)) {
+ this.recordDemand(childPeerId, nowMs, "parent-departed");
+ }
+ }
this.touchFacts();
return true;
}
- setEffectiveCapacity(peerId: string, sessionId: string, value: number): boolean {
+ setEffectiveCapacity(
+ peerId: string,
+ sessionId: string,
+ value: number,
+ nowMs?: number,
+ ): boolean {
const participant = this.participants.get(peerId);
if (!participant || participant.sessionId !== sessionId) return false;
const capacity = this.effectiveCapacity(value);
@@ -270,6 +389,11 @@ export class RoomRouteController<Resource = unknown> {
if (!changed) return true;
participant.effectiveDownstreamCapacity = capacity;
participant.blockedAtFactVersion = undefined;
+ if (nowMs !== undefined) {
+ for (const childPeerId of this.overflowPeerChildren(peerId)) {
+ this.recordDemand(childPeerId, nowMs, "capacity-reduction");
+ }
+ }
this.touchFacts();
return true;
}
@@ -314,7 +438,7 @@ export class RoomRouteController<Resource = unknown> {
this.assertGraph();
}
- invalidateEdge(guard: EdgeGuard): boolean {
+ invalidateEdge(guard: EdgeGuard, nowMs?: number): boolean {
const child = this.participants.get(guard.childPeerId);
const edge = this.upstreamByViewer.get(guard.childPeerId);
if (!child || child.sessionId !== guard.childSessionId || this.revision !== guard.routeRevision ||
@@ -331,6 +455,9 @@ export class RoomRouteController<Resource = unknown> {
key: edgeTupleKey(edge),
factVersion: this.factVersion,
};
+ if (nowMs !== undefined) {
+ this.recordDemand(guard.childPeerId, nowMs, "edge-unavailable");
+ }
}
return true;
}
@@ -340,7 +467,7 @@ export class RoomRouteController<Resource = unknown> {
routeRevision: number;
generation: string;
connectionId: string;
- }): boolean {
+ }, nowMs?: number): boolean {
const publication = this.hostPublication;
if (!publication || this.revision !== guard.routeRevision ||
publication.hostSessionId !== guard.hostSessionId ||
@@ -348,6 +475,13 @@ export class RoomRouteController<Resource = unknown> {
publication.connectionId !== guard.connectionId) return false;
if (publication.usable) {
publication.usable = false;
+ if (nowMs !== undefined) {
+ for (const [childPeerId, edge] of this.upstreamByViewer) {
+ if (edge.kind === "sfu") {
+ this.recordDemand(childPeerId, nowMs, "edge-unavailable");
+ }
+ }
+ }
this.touchFacts();
}
return true;
@@ -419,27 +553,40 @@ export class RoomRouteController<Resource = unknown> {
return [publication.resource];
}
- setPaused(paused: boolean): readonly Resource[] {
+ setPaused(paused: boolean, nowMs?: number): readonly Resource[] {
if (this.paused === paused) return [];
this.paused = paused;
this.touchFacts();
- return paused ? this.abortOperation() : [];
+ return paused ? this.abortOperation(nowMs, "aborted") : [];
}
reconcile(nowMs: number): ReconcileResult<Resource> {
const released: Resource[] = [];
const validation = this.validateOrAdvance(nowMs);
released.push(...validation.released);
+ const failedPeerIds = validation.exhaustedChildPeerId
+ ? [validation.exhaustedChildPeerId]
+ : [];
if (this.paused || this.operation) {
- return { operation: this.operationSnapshot(), removedPeerIds: [], released };
+ return {
+ operation: this.operationSnapshot(),
+ removedPeerIds: [],
+ failedPeerIds,
+ released,
+ };
}
const removedPeerIds = this.pruneDepartedLeaves(released);
for (let remaining = this.participants.size; remaining > 0; remaining -= 1) {
const bootstrap = this.bootstrapForBlockedDemand();
const childPeerId = bootstrap ?? this.selectNextChild();
- if (!childPeerId) return { removedPeerIds, released };
+ if (!childPeerId) return { removedPeerIds, failedPeerIds, released };
const child = this.participants.get(childPeerId)!;
+ const reason = bootstrap
+ ? "sfu-bootstrap"
+ : (this.routeTimings.get(childPeerId)?.reason ??
+ this.routeDemandReason(childPeerId));
+ this.ensureDemand(childPeerId, nowMs, reason);
const candidates = this.buildCandidates(childPeerId, bootstrap !== undefined);
if (candidates.length === 0) {
if (this.retireInvalidOperationEdge(childPeerId, released)) {
@@ -447,20 +594,36 @@ export class RoomRouteController<Resource = unknown> {
this.touchFacts();
}
child.blockedAtFactVersion = this.factVersion;
+ this.finishTiming(
+ childPeerId,
+ nowMs,
+ "failed",
+ reason === "capacity-reduction"
+ ? "endpoint-capacity"
+ : "candidate-failed",
+ );
+ if (bootstrap === undefined) failedPeerIds.push(childPeerId);
continue;
}
+ this.startOperationTiming(childPeerId, nowMs);
this.operation = {
childPeerId,
childSessionId: child.sessionId!,
+ reason,
baseRevision: this.revision,
candidates,
cursor: 0,
deadlineAtMs: nowMs + this.options.operationTimeoutMs,
builtAtFactVersion: this.factVersion,
};
- return { operation: this.operationSnapshot(), removedPeerIds, released };
+ return {
+ operation: this.operationSnapshot(),
+ removedPeerIds,
+ failedPeerIds,
+ released,
+ };
}
- return { removedPeerIds, released };
+ return { removedPeerIds, failedPeerIds, released };
}
beginCurrentCandidate(input: {
@@ -515,16 +678,39 @@ export class RoomRouteController<Resource = unknown> {
publicationConnectionId: input.publicationConnectionId,
reservation: input.reservation,
};
+ this.startCandidateTiming(operation.childPeerId, input.nowMs);
return { accepted: true, operation: this.operationSnapshot(), released: validation.released };
}
- skipCurrentCandidate(guard: CandidateCursorGuard, nowMs: number): BeginResult<Resource> {
+ noteCurrentCandidateRejection(
+ guard: CandidateCursorGuard,
+ bucket: RouteDiagnosticRejectionBucket,
+ ): boolean {
+ const operation = this.operation;
+ if (
+ !operation ||
+ operation.current ||
+ !this.cursorGuardMatches(guard, operation)
+ ) {
+ return false;
+ }
+ this.noteRejection(operation.childPeerId, bucket);
+ return true;
+ }
+
+ skipCurrentCandidate(
+ guard: CandidateCursorGuard,
+ nowMs: number,
+ bucket: RouteDiagnosticRejectionBucket = "stale",
+ ): BeginResult<Resource> {
const validation = this.validateOrAdvance(nowMs);
const operation = this.operation;
if (!operation || operation.current || !this.cursorGuardMatches(guard, operation)) {
return { accepted: false, released: validation.released, exhausted: validation.exhausted };
}
+ this.noteRejection(operation.childPeerId, bucket);
operation.cursor += 1;
+ this.clearCandidateTiming(operation.childPeerId);
const advanced = this.validateOrAdvance(nowMs);
return {
operation: this.operationSnapshot(),
@@ -609,6 +795,7 @@ export class RoomRouteController<Resource = unknown> {
return { accepted: false, exhausted: validation.exhausted, activeRevision: this.revision, released: validation.released };
}
if (!commitReservation(attempt.reservation)) {
+ this.noteRejection(operation.childPeerId, "candidate-failed");
const failed = this.validateOrAdvance(nowMs, guard);
return {
accepted: false,
@@ -617,11 +804,37 @@ export class RoomRouteController<Resource = unknown> {
released: [...validation.released, ...failed.released],
};
}
+ this.finishTiming(
+ operation.childPeerId,
+ nowMs,
+ attempt.tuple.kind === "peer" ? "direct" : "sfu",
+ "none",
+ true,
+ );
+ const displacedSfuChildren =
+ attempt.tuple.kind === "sfu" && attempt.tuple.publication === "replace"
+ ? [...this.upstreamByViewer]
+ .filter(
+ ([childPeerId, edge]) =>
+ childPeerId !== operation.childPeerId && edge.kind === "sfu",
+ )
+ .map(([childPeerId]) => childPeerId)
+ : [];
const released = [...validation.released, ...this.commitAttempt(operation, attempt)];
+ for (const childPeerId of displacedSfuChildren) {
+ this.ensureDemand(childPeerId, nowMs, "edge-unavailable");
+ }
return { accepted: true, activeRevision: this.revision, released };
}
candidateFailed(guard: CandidateGuard, nowMs: number): SettleResult<Resource> {
+ const operation = this.operation;
+ if (
+ operation?.current &&
+ this.guardMatches(guard, operation, operation.current)
+ ) {
+ this.noteRejection(operation.childPeerId, "candidate-failed");
+ }
const validation = this.validateOrAdvance(nowMs, guard);
if (validation.consumedGuard) {
return { accepted: true, exhausted: validation.exhausted, activeRevision: this.revision, released: validation.released };
@@ -646,23 +859,47 @@ export class RoomRouteController<Resource = unknown> {
this.upstreamByViewer.clear();
this.hostPublication = null;
this.participants.clear();
+ this.routeTimings.clear();
this.paused = true;
return [...resources];
}
private validateOrAdvance(nowMs: number, failedGuard?: CandidateGuard): {
- released: Resource[]; exhausted?: boolean; expired: boolean; consumedGuard: boolean;
+ released: Resource[];
+ exhausted?: boolean;
+ exhaustedChildPeerId?: string;
+ expired: boolean;
+ consumedGuard: boolean;
} {
const released: Resource[] = [];
- const result = { released, exhausted: undefined as boolean | undefined, expired: false, consumedGuard: false };
+ const result: {
+ released: Resource[];
+ exhausted?: boolean;
+ exhaustedChildPeerId?: string;
+ expired: boolean;
+ consumedGuard: boolean;
+ } = { released, expired: false, consumedGuard: false };
let operation = this.operation;
if (!operation) return result;
if (nowMs >= operation.deadlineAtMs) {
if (operation.current) released.push(...reservationResources(operation.current.reservation));
if (operation.current) this.advanceActiveRevision(operation);
const factsChanged = operation.builtAtFactVersion !== this.factVersion;
+ this.finishTiming(
+ operation.childPeerId,
+ nowMs,
+ factsChanged ? "waiting" : "failed",
+ factsChanged ? "stale" : "operation-deadline",
+ );
this.blockAndClear(operation, !factsChanged, released);
- return { ...result, exhausted: !factsChanged, expired: true };
+ return {
+ ...result,
+ exhausted: !factsChanged,
+ exhaustedChildPeerId: factsChanged
+ ? undefined
+ : operation.childPeerId,
+ expired: true,
+ };
}
if (this.advanceExpiredCandidateStage(operation, nowMs, released)) {
result.expired = true;
@@ -670,6 +907,12 @@ export class RoomRouteController<Resource = unknown> {
if (this.participants.get(operation.childPeerId)?.sessionId !== operation.childSessionId) {
if (operation.current) released.push(...reservationResources(operation.current.reservation));
if (operation.current) this.advanceActiveRevision(operation);
+ this.finishTiming(
+ operation.childPeerId,
+ nowMs,
+ this.currentFinalRoute(operation.childPeerId),
+ "aborted",
+ );
this.operation = undefined;
return result;
}
@@ -683,22 +926,41 @@ export class RoomRouteController<Resource = unknown> {
const guardFailed = failedGuard && this.guardMatches(failedGuard, operation, attempt);
const plan = operation.candidates[operation.cursor];
if (!guardFailed && plan && this.candidateValid(operation.childPeerId, plan, attempt)) return result;
+ if (!guardFailed) {
+ this.noteRejection(operation.childPeerId, "stale");
+ }
released.push(...reservationResources(attempt.reservation));
this.advanceActiveRevision(operation);
operation.current = undefined;
operation.cursor += 1;
+ this.clearCandidateTiming(operation.childPeerId);
result.consumedGuard = Boolean(guardFailed);
this.replanRemaining(operation);
}
while (operation.cursor < operation.candidates.length &&
!this.candidateValid(operation.childPeerId, operation.candidates[operation.cursor]!)) {
+ this.noteRejection(operation.childPeerId, "stale");
operation.cursor += 1;
+ this.clearCandidateTiming(operation.childPeerId);
}
if (operation.cursor < operation.candidates.length) return result;
const factsChanged = operation.builtAtFactVersion !== this.factVersion;
+ this.finishTiming(
+ operation.childPeerId,
+ nowMs,
+ factsChanged ? "waiting" : "failed",
+ factsChanged
+ ? "stale"
+ : this.routeTimings.get(operation.childPeerId)?.rejectionBucket ===
+ "none"
+ ? "candidate-failed"
+ : this.routeTimings.get(operation.childPeerId)!.rejectionBucket,
+ );
this.blockAndClear(operation, !factsChanged, released);
- result.exhausted =
- !factsChanged && !this.bootstrapForBlockedDemand();
+ result.exhausted = !factsChanged && !this.bootstrapForBlockedDemand();
+ if (result.exhausted) {
+ result.exhaustedChildPeerId = operation.childPeerId;
+ }
}
return result;
}
@@ -959,6 +1221,7 @@ export class RoomRouteController<Resource = unknown> {
if (edge && edge.transport !== "direct" && edge.physicalActive) released.push(edge.resource);
this.upstreamByViewer.delete(participant.peerId);
this.participants.delete(participant.peerId);
+ this.routeTimings.delete(participant.peerId);
removed.push(participant.peerId);
changed = true;
}
@@ -974,8 +1237,19 @@ export class RoomRouteController<Resource = unknown> {
return removed;
}
- private abortOperation(): Resource[] {
+ private abortOperation(
+ nowMs?: number,
+ bucket: RouteDiagnosticRejectionBucket = "aborted",
+ ): Resource[] {
if (!this.operation) return [];
+ if (nowMs !== undefined) {
+ this.finishTiming(
+ this.operation.childPeerId,
+ nowMs,
+ this.currentFinalRoute(this.operation.childPeerId),
+ bucket,
+ );
+ }
const released = this.operation.current ? reservationResources(this.operation.current.reservation) : [];
if (this.operation.current) this.advanceActiveRevision(this.operation);
this.operation = undefined;
@@ -1054,6 +1328,7 @@ export class RoomRouteController<Resource = unknown> {
const operation = this.operation;
if (!operation) return undefined;
return { childPeerId: operation.childPeerId, childSessionId: operation.childSessionId,
+ reason: operation.reason,
baseRevision: operation.baseRevision, factVersion: operation.builtAtFactVersion,
candidates: operation.candidates.map(cloneCandidatePlan),
cursor: operation.cursor, deadlineAtMs: operation.deadlineAtMs,
@@ -1082,10 +1357,12 @@ export class RoomRouteController<Resource = unknown> {
return false;
}
if (operation.current) {
+ this.noteRejection(operation.childPeerId, "first-frame-timeout");
released.push(...reservationResources(operation.current.reservation));
this.advanceActiveRevision(operation);
operation.current = undefined;
operation.cursor += 1;
+ this.clearCandidateTiming(operation.childPeerId);
}
while (
operation.cursor < operation.candidates.length &&
@@ -1266,6 +1543,147 @@ export class RoomRouteController<Resource = unknown> {
return resources;
}
+ private diagnosticParent(
+ edge: CommittedEdge<Resource> | undefined,
+ ordinals: ReadonlyMap<string, number>,
+ ): RouteDiagnosticSnapshot["children"][number]["parent"] {
+ if (!edge || !edge.usable || !edge.physicalActive) {
+ return { kind: "none" };
+ }
+ if (edge.kind === "sfu") {
+ return this.hostPublication?.usable &&
+ this.hostPublication.physicalActive &&
+ this.hostPublication.generation === edge.publicationGeneration
+ ? { kind: "sfu" }
+ : { kind: "none" };
+ }
+ if (edge.parentPeerId === this.options.hostPeerId) {
+ return { kind: "host" };
+ }
+ const ordinal = ordinals.get(edge.parentPeerId);
+ return ordinal === undefined
+ ? { kind: "none" }
+ : { kind: "viewer", ordinal };
+ }
+
+ private recordDemand(
+ childPeerId: string,
+ nowMs: number,
+ reason: RouteDemandReason,
+ ): void {
+ const record: RouteTimingRecord = {
+ demandAtMs: nowMs,
+ reason,
+ finalRoute: "waiting",
+ rejectionBucket: "none",
+ };
+ if (this.operation?.childPeerId === childPeerId) {
+ this.operation.reason = reason;
+ record.operationStartedAtMs = nowMs;
+ }
+ this.routeTimings.set(childPeerId, record);
+ }
+
+ private ensureDemand(
+ childPeerId: string,
+ nowMs: number,
+ reason: RouteDemandReason,
+ ): void {
+ if (!this.routeTimings.has(childPeerId)) {
+ this.recordDemand(childPeerId, nowMs, reason);
+ }
+ }
+
+ private startOperationTiming(childPeerId: string, nowMs: number): void {
+ const record = this.routeTimings.get(childPeerId);
+ if (!record) return;
+ record.operationStartedAtMs = nowMs;
+ record.candidateStartedAtMs = undefined;
+ record.firstDecodedFrameAtMs = undefined;
+ record.finalAtMs = undefined;
+ record.finalRoute = "waiting";
+ record.rejectionBucket = "none";
+ }
+
+ private startCandidateTiming(childPeerId: string, nowMs: number): void {
+ const record = this.routeTimings.get(childPeerId);
+ if (!record) return;
+ record.candidateStartedAtMs = nowMs;
+ record.firstDecodedFrameAtMs = undefined;
+ record.finalAtMs = undefined;
+ record.finalRoute = "waiting";
+ record.rejectionBucket = "none";
+ }
+
+ private noteRejection(
+ childPeerId: string,
+ bucket: RouteDiagnosticRejectionBucket,
+ ): void {
+ const record = this.routeTimings.get(childPeerId);
+ if (record) record.rejectionBucket = bucket;
+ }
+
+ private clearCandidateTiming(childPeerId: string): void {
+ const record = this.routeTimings.get(childPeerId);
+ if (!record) return;
+ record.candidateStartedAtMs = undefined;
+ record.firstDecodedFrameAtMs = undefined;
+ record.finalAtMs = undefined;
+ record.finalRoute = "waiting";
+ }
+
+ private finishTiming(
+ childPeerId: string,
+ nowMs: number,
+ finalRoute: RouteDiagnosticFinalRoute,
+ rejectionBucket: RouteDiagnosticRejectionBucket,
+ firstDecodedFrame = false,
+ ): void {
+ const record = this.routeTimings.get(childPeerId);
+ if (!record) return;
+ if (firstDecodedFrame) record.firstDecodedFrameAtMs = nowMs;
+ record.finalAtMs = nowMs;
+ record.finalRoute = finalRoute;
+ record.rejectionBucket = rejectionBucket;
+ }
+
+ private usableRoute(childPeerId: string): boolean {
+ return this.currentFinalRoute(childPeerId) !== "waiting";
+ }
+
+ private currentFinalRoute(
+ childPeerId: string,
+ ): RouteDiagnosticFinalRoute {
+ const edge = this.upstreamByViewer.get(childPeerId);
+ if (!edge?.usable || !edge.physicalActive) return "waiting";
+ if (edge.kind === "peer") {
+ return this.sourceUsable(edge.parentPeerId) ? "direct" : "waiting";
+ }
+ return this.hostPublication?.usable &&
+ this.hostPublication.physicalActive &&
+ this.hostPublication.generation === edge.publicationGeneration
+ ? "sfu"
+ : "waiting";
+ }
+
+ private routeDemandReason(childPeerId: string): RouteDemandReason {
+ const edge = this.upstreamByViewer.get(childPeerId);
+ if (!edge) return "join";
+ if (
+ edge.kind === "peer" &&
+ this.participants.get(edge.parentPeerId)?.departureConfirmed
+ ) {
+ return "parent-departed";
+ }
+ if (
+ edge.kind === "peer" &&
+ this.overflowPeerChildren(edge.parentPeerId).includes(childPeerId)
+ ) {
+ return "capacity-reduction";
+ }
+ return "edge-unavailable";
+ }
+
private rebindCommittedSession(
peerId: string,
sessionId: string,
@@ -1344,6 +1762,11 @@ function compareParticipant(left: Participant, right: Participant): number {
return left.joinOrder - right.joinOrder || left.peerId.localeCompare(right.peerId);
}
+function elapsedMs(startedAtMs: number, endedAtMs: number): number | null {
+ const elapsed = Math.floor(endedAtMs - startedAtMs);
+ return Number.isSafeInteger(elapsed) && elapsed >= 0 ? elapsed : null;
+}
+
function tupleKey(tuple: CandidateTuple): string {
return tuple.kind === "peer" ? `peer:${tuple.parentPeerId}` : `sfu:${tuple.publication}`;
}
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index c3de900e..c5b595ae 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -8,12 +8,10 @@ import {
DEFAULT_HOST_DISPLAY_NAME_PREFIX,
DEFAULT_VIEWER_DISPLAY_NAME,
DEFAULT_QUALITY_SETTINGS,
- MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES,
MAX_SIGNAL_BYTES,
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
SIGNALING_PROTOCOL,
VIEWER_QUALITY_EVIDENCE_INTERVAL_MS,
- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS,
decodeClientMessage,
type ClientMessage,
type CodeEntryPolicy,
@@ -72,7 +70,6 @@ interface ViewerQualityEvidenceGate {
routeRevision: number;
sequence: number;
acceptedAtMs: number;
- parentEvidenceAccepted: boolean;
}
interface ViewerMediaReadyState {
@@ -337,12 +334,9 @@ export class SignalingServer {
return;
}
if (
- ((message.type === "viewer-quality-evidence" &&
- Buffer.byteLength(encoded, "utf8") >
- MAX_VIEWER_QUALITY_EVIDENCE_BYTES) ||
- (message.type === "parent-edge-quality-evidence" &&
- Buffer.byteLength(encoded, "utf8") >
- MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES))
+ message.type === "viewer-quality-evidence" &&
+ Buffer.byteLength(encoded, "utf8") >
+ MAX_VIEWER_QUALITY_EVIDENCE_BYTES
) {
this.rejectInvalidMessage(socket);
return;
@@ -845,12 +839,25 @@ export class SignalingServer {
message.revision,
);
return;
+ case "request-route-diagnostic":
+ if (authenticated.role !== "host") {
+ this.sendError(
+ socket,
+ "FORBIDDEN",
+ "Only the host may request route diagnostics",
+ );
+ return;
+ }
+ this.send(socket, {
+ type: "route-diagnostic-snapshot",
+ snapshot: this.hybridMediaRouter?.routeDiagnosticSnapshot(
+ authenticated.roomId,
+ ) ?? { children: [], operation: null },
+ });
+ return;
case "viewer-quality-evidence":
this.handleViewerQualityEvidence(socket, authenticated, message);
return;
- case "parent-edge-quality-evidence":
- this.handleParentEdgeQualityEvidence(socket, authenticated, message);
- return;
case "set-display-name":
if (
authenticated.role === "host" &&
@@ -1245,7 +1252,6 @@ export class SignalingServer {
routeRevision,
sequence: message.sequence,
acceptedAtMs: now,
- parentEvidenceAccepted: false,
});
const host = this.options.roomStore.getConnectedHost(source.roomId);
if (!host || host.sessionId === parent.sessionId) {
@@ -1265,58 +1271,6 @@ export class SignalingServer {
}
}
- private handleParentEdgeQualityEvidence(
- socket: WebSocket,
- source: AuthenticatedSession,
- message: Extract<
- ClientMessage,
- { type: "parent-edge-quality-evidence" }
- >,
- ): void {
- if (!this.isHybridMediaEnabled()) {
- return;
- }
- const sourceState = this.socketStates.get(socket);
- if (!sourceState || sourceState.authenticated !== source) {
- return;
- }
- const viewer = this.options.roomStore.getConnectedViewer(
- source.roomId,
- message.viewerPeerId,
- );
- const gate = this.viewerQualityEvidenceGates.get(
- viewerConnectionKey(source.roomId, message.viewerPeerId),
- );
- const edge = this.hybridMediaRouter?.resolveActivePeerEdge(
- source.roomId,
- message.viewerPeerId,
- );
- const connectionId = this.connectionIdsByViewer.get(
- viewerConnectionKey(source.roomId, message.viewerPeerId),
- );
- const now = this.now();
- if (
- !viewer ||
- !gate ||
- gate.parentEvidenceAccepted ||
- source.peerId !== gate.parentPeerId ||
- sourceState.sessionId !== gate.parentSessionId ||
- viewer.sessionId !== gate.viewerSessionId ||
- connectionId !== gate.connectionId ||
- edge?.parentPeerId !== source.peerId ||
- edge.revision !== gate.routeRevision ||
- message.guard.connectionId !== gate.connectionId ||
- message.guard.routeRevision !== gate.routeRevision ||
- message.viewerSequence !== gate.sequence ||
- now < gate.acceptedAtMs ||
- now - gate.acceptedAtMs > VIEWER_QUALITY_EVIDENCE_EXPIRY_MS
- ) {
- return;
- }
-
- gate.parentEvidenceAccepted = true;
- }
-
private routeSignal(
sourceSocket: WebSocket,
source: AuthenticatedSession,
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index b26b69ea..b1a076c3 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -12,7 +12,6 @@ export const MAX_MEDIA_ROUTE_REVISION = Number.MAX_SAFE_INTEGER;
export const MAX_SFU_TOKEN_LENGTH = 8 * 1024;
export const MAX_ICE_SERVER_URLS = 8;
export const MAX_VIEWER_QUALITY_EVIDENCE_BYTES = 2 * 1024;
-export const MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES = 2 * 1024;
export const VIEWER_QUALITY_EVIDENCE_INTERVAL_MS = 2_000;
export const VIEWER_QUALITY_EVIDENCE_EXPIRY_MS = 5_000;
export const MAX_DISPLAY_NAME_CODE_POINTS = 24;
@@ -338,6 +337,141 @@ export const mediaRouteRevisionSchema = z
export const mediaRoutePhaseSchema = z.enum(["prepare", "active"]);
export type MediaRoutePhase = z.infer<typeof mediaRoutePhaseSchema>;
+export const routeDemandReasonSchema = z.enum([
+ "join",
+ "edge-unavailable",
+ "parent-departed",
+ "capacity-reduction",
+ "sfu-bootstrap",
+]);
+export type RouteDemandReason = z.infer<typeof routeDemandReasonSchema>;
+
+export const routeDiagnosticFinalRouteSchema = z.enum([
+ "direct",
+ "sfu",
+ "waiting",
+ "failed",
+]);
+export type RouteDiagnosticFinalRoute = z.infer<
+ typeof routeDiagnosticFinalRouteSchema
+>;
+
+export const routeDiagnosticRejectionBucketSchema = z.enum([
+ "none",
+ "stale",
+ "endpoint-capacity",
+ "sfu-admission",
+ "candidate-failed",
+ "first-frame-timeout",
+ "operation-deadline",
+ "aborted",
+]);
+export type RouteDiagnosticRejectionBucket = z.infer<
+ typeof routeDiagnosticRejectionBucketSchema
+>;
+
+const routeDiagnosticDurationSchema = z
+ .number()
+ .int()
+ .min(0)
+ .max(Number.MAX_SAFE_INTEGER)
+ .nullable();
+const routeDiagnosticOrdinalSchema = z
+ .number()
+ .int()
+ .min(1)
+ .max(MAX_VIEWERS_PER_ROOM_LIMIT);
+const routeDiagnosticParentSchema = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("none") }).strict(),
+ z.object({ kind: z.literal("host") }).strict(),
+ z.object({ kind: z.literal("sfu") }).strict(),
+ z
+ .object({
+ kind: z.literal("viewer"),
+ ordinal: routeDiagnosticOrdinalSchema,
+ })
+ .strict(),
+]);
+const routeDiagnosticChildSchema = z
+ .object({
+ ordinal: routeDiagnosticOrdinalSchema,
+ parent: routeDiagnosticParentSchema,
+ effectiveCapacity: z
+ .number()
+ .int()
+ .min(0)
+ .max(MAX_ENDPOINT_MEDIA_COPY_CAPACITY),
+ childCount: z
+ .number()
+ .int()
+ .min(0)
+ .max(MAX_ENDPOINT_MEDIA_COPY_CAPACITY),
+ demandAgeMs: routeDiagnosticDurationSchema,
+ queueWaitMs: routeDiagnosticDurationSchema,
+ candidateStartMs: routeDiagnosticDurationSchema,
+ firstDecodedFrameMs: routeDiagnosticDurationSchema,
+ finalMs: routeDiagnosticDurationSchema,
+ finalRoute: routeDiagnosticFinalRouteSchema,
+ rejectionBucket: routeDiagnosticRejectionBucketSchema,
+ })
+ .strict();
+const routeDiagnosticOperationSchema = z
+ .object({
+ childOrdinal: routeDiagnosticOrdinalSchema,
+ reason: routeDemandReasonSchema,
+ stage: z.enum(["admission", "first-frame"]),
+ cursor: z.number().int().min(0).max(MAX_VIEWERS_PER_ROOM_LIMIT),
+ candidateCount: z.number().int().min(1).max(MAX_VIEWERS_PER_ROOM_LIMIT + 1),
+ })
+ .strict();
+
+export const routeDiagnosticSnapshotSchema = z
+ .object({
+ children: z
+ .array(routeDiagnosticChildSchema)
+ .max(MAX_VIEWERS_PER_ROOM_LIMIT),
+ operation: routeDiagnosticOperationSchema.nullable(),
+ })
+ .strict()
+ .superRefine((snapshot, context) => {
+ const ordinals = new Set(snapshot.children.map((child) => child.ordinal));
+ if (ordinals.size !== snapshot.children.length) {
+ context.addIssue({
+ code: "custom",
+ message: "Route diagnostic ordinals must be unique",
+ path: ["children"],
+ });
+ return;
+ }
+ for (const [index, child] of snapshot.children.entries()) {
+ if (
+ child.parent.kind === "viewer" &&
+ (!ordinals.has(child.parent.ordinal) ||
+ child.parent.ordinal === child.ordinal)
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Route diagnostic parent ordinal is invalid",
+ path: ["children", index, "parent"],
+ });
+ }
+ }
+ if (
+ snapshot.operation &&
+ (!ordinals.has(snapshot.operation.childOrdinal) ||
+ snapshot.operation.cursor >= snapshot.operation.candidateCount)
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Route diagnostic operation is invalid",
+ path: ["operation"],
+ });
+ }
+ });
+export type RouteDiagnosticSnapshot = z.infer<
+ typeof routeDiagnosticSnapshotSchema
+>;
+
export const sfuPublicationGenerationSchema = opaqueIdSchema;
export const participantRouteAssignmentSchema = z
@@ -439,42 +573,6 @@ export const viewerQualityEvidenceMessageSchema = z
message: "Viewer freeze duration exceeds its evidence window",
});
-const parentEdgeQualityProofSchema = z.discriminatedUnion("kind", [
- z
- .object({
- kind: z.literal("sending"),
- packetsSentDelta: z.number().int().min(1).max(1_000_000),
- })
- .strict(),
- z
- .object({
- kind: z.literal("sender-limited"),
- packetsSentDelta: z.number().int().min(1).max(1_000_000),
- reason: z.enum(["cpu", "bandwidth"]),
- })
- .strict(),
- z
- .object({
- kind: z.literal("remote-loss"),
- packetsSentDelta: z.number().int().min(1).max(1_000_000),
- remotePacketsLostDelta: z.number().int().min(1).max(1_000_000),
- })
- .strict(),
-]);
-export type ParentEdgeQualityProof = z.infer<
- typeof parentEdgeQualityProofSchema
->;
-
-export const parentEdgeQualityEvidenceMessageSchema = z
- .object({
- type: z.literal("parent-edge-quality-evidence"),
- viewerPeerId: opaqueIdSchema,
- guard: viewerQualityEvidenceGuardSchema,
- viewerSequence: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
- proof: parentEdgeQualityProofSchema,
- })
- .strict();
-
const authenticateMessageSchema = z.discriminatedUnion("role", [
z
.object({
@@ -574,8 +672,8 @@ export const clientMessageSchema = z.union([
revision: mediaRouteRevisionSchema,
})
.strict(),
+ z.object({ type: z.literal("request-route-diagnostic") }).strict(),
viewerQualityEvidenceMessageSchema,
- parentEdgeQualityEvidenceMessageSchema,
z
.object({
type: z.literal("set-display-name"),
@@ -735,6 +833,30 @@ export const serverMessageSchema = z.union([
})
.strict(),
]),
+ z.discriminatedUnion("state", [
+ z
+ .object({
+ type: z.literal("route-status"),
+ revision: mediaRouteRevisionSchema,
+ state: z.literal("waiting"),
+ reason: z.literal("sfu-admission"),
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal("route-status"),
+ revision: mediaRouteRevisionSchema,
+ state: z.literal("failed"),
+ reason: z.literal("route-exhausted"),
+ })
+ .strict(),
+ ]),
+ z
+ .object({
+ type: z.literal("route-diagnostic-snapshot"),
+ snapshot: routeDiagnosticSnapshotSchema,
+ })
+ .strict(),
z
.object({
type: z.literal("sfu-config"),
diff --git a/tests/diagnostic-export.test.ts b/tests/diagnostic-export.test.ts
index 589f730c..abcca9dd 100644
--- a/tests/diagnostic-export.test.ts
+++ b/tests/diagnostic-export.test.ts
@@ -4,6 +4,7 @@ import {
createDiagnosticReport,
DIAGNOSTIC_SCHEMA_VERSION,
downloadDiagnosticReport,
+ summarizeRouteTiming,
type DiagnosticConnectionInput,
} from "../src/client/lib/diagnostic-export.ts";
import { EMPTY_METRICS } from "../src/client/types.ts";
@@ -180,9 +181,100 @@ describe("diagnostic export privacy boundary", () => {
expect(append).toHaveBeenCalledWith(link);
expect(link.download).toMatch(/^screener-diagnostics-host-.*\.json$/);
expect(revokeObjectURL).toHaveBeenCalledWith("blob:diagnostic");
- expect(await createdBlob!.text()).toContain(`"schemaVersion": 1`);
+ expect(await createdBlob!.text()).toContain(`"schemaVersion": 2`);
} finally {
vi.unstubAllGlobals();
}
});
+
+ it("reports raw 20-Viewer timings with nearest-rank percentiles", () => {
+ const values = Array.from({ length: 20 }, (_, index) =>
+ index % 5 === 0 ? null : (20 - index) * 10,
+ );
+
+ const expected = {
+ sampleCount: 16,
+ pendingCount: 4,
+ rawMs: [
+ 10, 20, 30, 40, 60, 70, 80, 90, 110, 120, 130, 140, 160, 170,
+ 180, 190,
+ ],
+ p50Ms: 90,
+ p95Ms: 190,
+ maxMs: 190,
+ };
+ expect(summarizeRouteTiming(values)).toEqual(expected);
+ const report = createDiagnosticReport(
+ "host",
+ [],
+ new Date("2026-08-24T12:00:00.000Z"),
+ {
+ children: values.map((finalMs, index) => ({
+ ordinal: index + 1,
+ parent: { kind: "none" as const },
+ effectiveCapacity: 0,
+ childCount: 0,
+ demandAgeMs: 200,
+ queueWaitMs: finalMs,
+ candidateStartMs: finalMs,
+ firstDecodedFrameMs: finalMs,
+ finalMs,
+ finalRoute: finalMs === null ? "waiting" as const : "direct" as const,
+ rejectionBucket: "none" as const,
+ })),
+ operation: null,
+ },
+ );
+ expect(report.route?.children).toHaveLength(20);
+ expect(report.routeTimingSummary?.finalMs).toEqual(expected);
+ expect(summarizeRouteTiming([null, null])).toEqual({
+ sampleCount: 0,
+ pendingCount: 2,
+ rawMs: [],
+ p50Ms: null,
+ p95Ms: null,
+ maxMs: null,
+ });
+ });
+
+ it("includes only sanitized route fields in a Host export", () => {
+ const route = {
+ children: [
+ {
+ ordinal: 1,
+ parent: { kind: "host" as const },
+ effectiveCapacity: 2,
+ childCount: 0,
+ demandAgeMs: 120,
+ queueWaitMs: 10,
+ candidateStartMs: 20,
+ firstDecodedFrameMs: 70,
+ finalMs: 70,
+ finalRoute: "direct" as const,
+ rejectionBucket: "none" as const,
+ },
+ ],
+ operation: null,
+ };
+ const report = createDiagnosticReport(
+ "host",
+ [],
+ new Date("2026-08-24T12:00:00.000Z"),
+ route,
+ );
+
+ expect(report.route).toEqual(route);
+ expect(report.routeTimingSummary).toMatchObject({
+ queueWaitMs: { sampleCount: 1, pendingCount: 0, rawMs: [10] },
+ finalMs: { p50Ms: 70, p95Ms: 70, maxMs: 70 },
+ });
+ expect(
+ createDiagnosticReport(
+ "viewer",
+ [],
+ new Date("2026-08-24T12:00:00.000Z"),
+ route,
+ ),
+ ).toMatchObject({ route: null, routeTimingSummary: null });
+ });
});
diff --git a/tests/hybrid-media-router.test.ts b/tests/hybrid-media-router.test.ts
index b99f252a..7ca08f8c 100644
--- a/tests/hybrid-media-router.test.ts
+++ b/tests/hybrid-media-router.test.ts
@@ -358,4 +358,94 @@ describe("HybridMediaRouter v7 runtime", () => {
await router.close();
});
+ it("emits typed exhaustion and clears diagnostics on departure and room deletion", async () => {
+ const { store, sent, router } = harness(1);
+ const room = await store.createRoom();
+ const host = connectHost(store, room);
+ complete(router, host);
+ const viewer = connectViewer(store, room, "diagnostic");
+ complete(router, viewer);
+ await vi.waitFor(() =>
+ expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),
+ );
+ const prepared = preparedFor(sent, viewer.sessionId)!;
+ expect(router.routeDiagnosticSnapshot(room.roomId).children).toHaveLength(1);
+
+ router.handleRouteFailed(viewer, {
+ type: "route-failed",
+ revision: prepared.revision,
+ phase: "prepare",
+ connectionId: prepared.candidate.connectionId,
+ });
+ await vi.waitFor(() =>
+ expect(
+ sent
+ .get(viewer.sessionId)
+ ?.findLast((message) => message.type === "route-status"),
+ ).toMatchObject({
+ state: "failed",
+ reason: "route-exhausted",
+ }),
+ );
+
+ router.removeViewer(room.roomId, viewer.peerId);
+ expect(router.routeDiagnosticSnapshot(room.roomId)).toEqual({
+ children: [],
+ operation: null,
+ });
+
+ const replacement = connectViewer(store, room, "diagnostic-replacement");
+ complete(router, replacement);
+ expect(router.routeDiagnosticSnapshot(room.roomId).children).toHaveLength(1);
+ router.stopRoom(room.roomId);
+ expect(router.routeDiagnosticSnapshot(room.roomId)).toEqual({
+ children: [],
+ operation: null,
+ });
+
+ complete(router, host);
+ expect(
+ router.routeDiagnosticSnapshot(room.roomId).children.length,
+ ).toBeGreaterThan(0);
+ router.deleteRoom(room.roomId);
+ expect(router.routeDiagnosticSnapshot(room.roomId)).toEqual({
+ children: [],
+ operation: null,
+ });
+ await router.close();
+ });
+
+ it("emits typed exhaustion when reconciliation has no candidate", async () => {
+ const { store, sent, router } = harness(1);
+ const room = await store.createRoom();
+ const host = connectHost(store, room);
+ complete(router, host);
+
+ const first = connectViewer(store, room, "only-slot");
+ complete(router, first);
+ await vi.waitFor(() =>
+ expect(preparedFor(sent, first.sessionId)).toBeDefined(),
+ );
+ const firstPrepare = preparedFor(sent, first.sessionId)!;
+ router.handleRouteReady(first, {
+ type: "route-ready",
+ revision: firstPrepare.revision,
+ phase: "prepare",
+ });
+
+ const blocked = connectViewer(store, room, "no-candidate");
+ complete(router, blocked);
+ await vi.waitFor(() =>
+ expect(
+ sent
+ .get(blocked.sessionId)
+ ?.findLast((message) => message.type === "route-status"),
+ ).toMatchObject({
+ state: "failed",
+ reason: "route-exhausted",
+ }),
+ );
+ await router.close();
+ });
+
});
diff --git a/tests/peer-assisted-benchmark.test.ts b/tests/peer-assisted-benchmark.test.ts
index 4b7e9c1d..ff89ff1e 100644
--- a/tests/peer-assisted-benchmark.test.ts
+++ b/tests/peer-assisted-benchmark.test.ts
@@ -175,13 +175,11 @@ function createObserverHarness(expectedEndpointCap = 2) {
const api = context.__SCREENER_BENCHMARK__ as {
snapshot: () => ObserverSnapshot;
canarySnapshot: () => Record<string, unknown>;
- configureCanary: (value: Record<string, unknown>) => boolean;
};
return {
socket: () => new WebSocketConstructor(),
snapshot: () => structuredClone(api.snapshot()),
canarySnapshot: () => structuredClone(api.canarySnapshot()),
- configureCanary: (value: Record<string, unknown>) => api.configureCanary(value),
};
}
@@ -293,16 +291,6 @@ describe("peer topology loopback configuration", () => {
});
describe("peer topology loopback observations", () => {
- it("suppresses parent proof only through the opt-in injected control", () => {
- const observer = createObserverHarness();
- const socket = observer.socket();
- authenticate(socket);
- expect(observer.configureCanary({ dropParentProof: true })).toBe(true);
- socket.send(JSON.stringify({ type: "parent-edge-quality-evidence" }));
- expect(observer.canarySnapshot()).toMatchObject({ droppedProofs: 1 });
- expect(Object.keys(observer.canarySnapshot())).not.toContain("connectionId");
- });
-
it("counts only active media connections in the requested direction", () => {
const host = page("host", "host", 2, 0);
host.connections[0]!.connectionState = "closed";
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index 06866104..df01c634 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -7,7 +7,6 @@ import {
DEFAULT_VIEWER_DISPLAY_NAME,
MAX_DISPLAY_NAME_CODE_POINTS,
MAX_MEDIA_ROUTE_REVISION,
- MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES,
MAX_SFU_TOKEN_LENGTH,
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
MAX_VIEWER_PASSWORD_LENGTH,
@@ -66,14 +65,6 @@ const qualityEvidence = {
},
} as const;
-const parentEdgeQualityEvidence = {
- type: "parent-edge-quality-evidence",
- viewerPeerId: "viewer_12345678",
- guard: qualityEvidence.guard,
- viewerSequence: qualityEvidence.sequence,
- proof: { kind: "sending", packetsSentDelta: 1_500 },
-} as const;
-
describe("client signaling protocol", () => {
it("keeps executable senders outside the Browser v7 release", () => {
const nativeWire = readFileSync(
@@ -121,6 +112,19 @@ describe("client signaling protocol", () => {
}
});
+ it("accepts only an empty route diagnostic request", () => {
+ expect(
+ clientMessageSchema.safeParse({ type: "request-route-diagnostic" })
+ .success,
+ ).toBe(true);
+ expect(
+ clientMessageSchema.safeParse({
+ type: "request-route-diagnostic",
+ roomId,
+ }).success,
+ ).toBe(false);
+ });
+
it("accepts an atomic room creation profile", () => {
expect(
createRoomRequestSchema.parse({ codeEntryPolicy: "open" }),
@@ -660,63 +664,6 @@ describe("client signaling protocol", () => {
}
});
- it("accepts only strict, bounded parent edge quality proof", () => {
- expect(
- clientMessageSchema.safeParse(parentEdgeQualityEvidence).success,
- ).toBe(true);
- expect(
- Buffer.byteLength(JSON.stringify(parentEdgeQualityEvidence), "utf8"),
- ).toBeLessThanOrEqual(MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES);
- for (const reason of ["cpu", "bandwidth"] as const) {
- expect(
- clientMessageSchema.safeParse({
- ...parentEdgeQualityEvidence,
- proof: {
- kind: "sender-limited",
- packetsSentDelta: 1_500,
- reason,
- },
- }).success,
- ).toBe(true);
- }
-
- for (const invalid of [
- { ...parentEdgeQualityEvidence, roomId },
- { ...parentEdgeQualityEvidence, viewerSequence: -1 },
- {
- ...parentEdgeQualityEvidence,
- proof: { kind: "sending", packetsSentDelta: 0 },
- },
- {
- ...parentEdgeQualityEvidence,
- proof: {
- kind: "remote-loss",
- packetsSentDelta: 1_500,
- remotePacketsLostDelta: null,
- },
- },
- {
- ...parentEdgeQualityEvidence,
- proof: {
- kind: "sender-limited",
- packetsSentDelta: 1_500,
- reason: "other",
- },
- },
- {
- ...parentEdgeQualityEvidence,
- proof: {
- kind: "sender-limited",
- packetsSentDelta: 1_500,
- reason: "cpu",
- score: 1,
- },
- },
- ]) {
- expect(clientMessageSchema.safeParse(invalid).success).toBe(false);
- }
- });
-
it.each([
["video/VP8", null, "max-fr=60; max-fs=8160"],
["video/VP9", "profile-id=2", "max-fs=8160"],
@@ -798,6 +745,134 @@ describe("client signaling protocol", () => {
});
describe("server signaling protocol", () => {
+ it("keeps route status pairings revision-fenced and strict", () => {
+ for (const message of [
+ {
+ type: "route-status",
+ revision: 3,
+ state: "waiting",
+ reason: "sfu-admission",
+ },
+ {
+ type: "route-status",
+ revision: 4,
+ state: "failed",
+ reason: "route-exhausted",
+ },
+ ]) {
+ expect(serverMessageSchema.safeParse(message).success).toBe(true);
+ }
+ for (const message of [
+ {
+ type: "route-status",
+ revision: 3,
+ state: "waiting",
+ reason: "route-exhausted",
+ },
+ {
+ type: "route-status",
+ revision: 3,
+ state: "failed",
+ reason: "sfu-admission",
+ },
+ {
+ type: "route-status",
+ revision: 3,
+ state: "failed",
+ reason: "route-exhausted",
+ retry: true,
+ },
+ ]) {
+ expect(serverMessageSchema.safeParse(message).success).toBe(false);
+ }
+ });
+
+ it("accepts only the privacy-safe two-field route snapshot payload", () => {
+ const message = {
+ type: "route-diagnostic-snapshot",
+ snapshot: {
+ children: [
+ {
+ ordinal: 1,
+ parent: { kind: "host" },
+ effectiveCapacity: 2,
+ childCount: 1,
+ demandAgeMs: 100,
+ queueWaitMs: 10,
+ candidateStartMs: 20,
+ firstDecodedFrameMs: 80,
+ finalMs: 80,
+ finalRoute: "direct",
+ rejectionBucket: "none",
+ },
+ {
+ ordinal: 2,
+ parent: { kind: "viewer", ordinal: 1 },
+ effectiveCapacity: 0,
+ childCount: 0,
+ demandAgeMs: 90,
+ queueWaitMs: null,
+ candidateStartMs: null,
+ firstDecodedFrameMs: null,
+ finalMs: null,
+ finalRoute: "waiting",
+ rejectionBucket: "sfu-admission",
+ },
+ ],
+ operation: {
+ childOrdinal: 2,
+ reason: "join",
+ stage: "admission",
+ cursor: 1,
+ candidateCount: 2,
+ },
+ },
+ } as const;
+ expect(serverMessageSchema.safeParse(message).success).toBe(true);
+ for (const invalid of [
+ {
+ ...message,
+ snapshot: { ...message.snapshot, peerId: "viewer_private_12345678" },
+ },
+ {
+ ...message,
+ snapshot: {
+ ...message.snapshot,
+ children: [
+ {
+ ...message.snapshot.children[0],
+ connectionId: "connection_private_12345678",
+ },
+ ],
+ },
+ },
+ {
+ ...message,
+ snapshot: {
+ ...message.snapshot,
+ children: [
+ message.snapshot.children[0],
+ {
+ ...message.snapshot.children[1],
+ parent: { kind: "viewer", ordinal: 2 },
+ },
+ ],
+ },
+ },
+ {
+ ...message,
+ snapshot: {
+ ...message.snapshot,
+ operation: {
+ ...message.snapshot.operation,
+ rejectionBucket: "raw-error",
+ },
+ },
+ },
+ ]) {
+ expect(serverMessageSchema.safeParse(invalid).success).toBe(false);
+ }
+ });
it("accepts only STUN URLs in the authenticated peer ICE config", () => {
expect(
serverMessageSchema.safeParse({
diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.ts
index 6ec0a330..66457b07 100644
--- a/tests/room-route-controller.test.ts
+++ b/tests/room-route-controller.test.ts
@@ -40,13 +40,14 @@ function addViewer(
routes: RoomRouteController<string>,
peerId: string,
capacity: 0 | 1 | 2 | 3,
+ nowMs?: number,
) {
routes.upsertParticipant({
peerId,
role: "viewer",
sessionId: `${peerId}_session`,
effectiveDownstreamCapacity: capacity,
- });
+ }, nowMs);
}
function cursorGuard(operation: OperationSnapshot): CandidateCursorGuard {
@@ -120,6 +121,264 @@ function peerEdge(
}
describe("RoomRouteController", () => {
+ it("retains one latest timing sample for a 20-Viewer burst", () => {
+ const routes = controller(2);
+ const viewerPeerIds = Array.from(
+ { length: 20 },
+ (_, index) => `burst_${String(index).padStart(2, "0")}_12345678`,
+ );
+ for (const peerId of viewerPeerIds) addViewer(routes, peerId, 2, 0);
+
+ for (const [index, peerId] of viewerPeerIds.entries()) {
+ const operationStartedAtMs = (index + 1) * 10;
+ expect(routes.reconcile(operationStartedAtMs).operation?.childPeerId).toBe(
+ peerId,
+ );
+ commitCurrent(
+ routes,
+ operationStartedAtMs + 1,
+ `${peerId}_connection`,
+ );
+ }
+
+ const snapshot = routes.routeDiagnosticSnapshot(250);
+ expect(snapshot.children).toHaveLength(20);
+ expect(snapshot.children.map((child) => child.queueWaitMs)).toEqual(
+ Array.from({ length: 20 }, (_, index) => (index + 1) * 10),
+ );
+ expect(snapshot.children.every((child) => child.finalRoute === "direct"))
+ .toBe(true);
+ });
+
+ it("projects latest route timing through snapshot-local ordinals", () => {
+ const routes = controller(2);
+ addViewer(routes, A, 1, 100);
+
+ expect(routes.routeDiagnosticSnapshot(150)).toEqual({
+ children: [
+ {
+ ordinal: 1,
+ parent: { kind: "none" },
+ effectiveCapacity: 1,
+ childCount: 0,
+ demandAgeMs: 50,
+ queueWaitMs: null,
+ candidateStartMs: null,
+ firstDecodedFrameMs: null,
+ finalMs: null,
+ finalRoute: "waiting",
+ rejectionBucket: "none",
+ },
+ ],
+ operation: null,
+ });
+
+ const operation = routes.reconcile(160).operation!;
+ expect(routes.routeDiagnosticSnapshot(165).operation).toEqual({
+ childOrdinal: 1,
+ reason: "join",
+ stage: "admission",
+ cursor: 0,
+ candidateCount: operation.candidates.length,
+ });
+ const prepared = beginCandidate(routes, {
+ nowMs: 170,
+ connectionId: "a_connection",
+ reservation: { kind: "direct" },
+ }).operation!;
+ expect(routes.routeDiagnosticSnapshot(180)).toMatchObject({
+ children: [
+ {
+ queueWaitMs: 60,
+ candidateStartMs: 70,
+ firstDecodedFrameMs: null,
+ finalMs: null,
+ },
+ ],
+ operation: { childOrdinal: 1, stage: "first-frame" },
+ });
+ expect(
+ routes.candidateReady(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: prepared.current!.revision,
+ connectionId: "a_connection",
+ },
+ 230,
+ ).accepted,
+ ).toBe(true);
+ const settled = routes.routeDiagnosticSnapshot(240);
+ expect(settled).toMatchObject({
+ children: [
+ {
+ parent: { kind: "host" },
+ queueWaitMs: 60,
+ candidateStartMs: 70,
+ firstDecodedFrameMs: 130,
+ finalMs: 130,
+ finalRoute: "direct",
+ rejectionBucket: "none",
+ },
+ ],
+ operation: null,
+ });
+ expect(JSON.stringify(settled)).not.toContain(A);
+ expect(JSON.stringify(settled)).not.toContain("a_connection");
+
+ expect(
+ routes.invalidateEdge(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ parentSessionId: "host_session",
+ routeRevision: routes.snapshot().revision,
+ connectionId: "a_connection",
+ },
+ 300,
+ ),
+ ).toBe(true);
+ expect(routes.routeDiagnosticSnapshot(320).children[0]).toMatchObject({
+ demandAgeMs: 20,
+ queueWaitMs: null,
+ candidateStartMs: null,
+ firstDecodedFrameMs: null,
+ finalMs: null,
+ finalRoute: "waiting",
+ rejectionBucket: "none",
+ });
+
+ expect(routes.confirmDeparture(A, 330)).toBe(true);
+ expect(routes.routeDiagnosticSnapshot(330)).toEqual({
+ children: [],
+ operation: null,
+ });
+ });
+
+ it("records a bounded candidate failure without retaining route identity", () => {
+ const routes = controller(1);
+ addViewer(routes, A, 0, 0);
+ routes.reconcile(10);
+ const prepared = beginCandidate(routes, {
+ nowMs: 20,
+ connectionId: "failed_candidate",
+ reservation: { kind: "direct" },
+ }).operation!;
+ expect(
+ routes.candidateFailed(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: prepared.current!.revision,
+ connectionId: "failed_candidate",
+ },
+ 30,
+ ),
+ ).toMatchObject({ accepted: true, exhausted: true });
+ expect(routes.routeDiagnosticSnapshot(30).children[0]).toMatchObject({
+ finalMs: 30,
+ finalRoute: "failed",
+ rejectionBucket: "candidate-failed",
+ });
+
+ routes.dispose();
+ expect(routes.routeDiagnosticSnapshot(40)).toEqual({
+ children: [],
+ operation: null,
+ });
+ });
+
+ it("reports a current child that has no usable candidate", () => {
+ const routes = controller(1);
+ addViewer(routes, A, 0);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_connection"));
+ addViewer(routes, B, 0, 0);
+
+ const result = routes.reconcile(10);
+ expect(result.operation).toBeUndefined();
+ expect(result.failedPeerIds).toEqual([B]);
+ expect(routes.routeDiagnosticSnapshot(10).children[1]).toMatchObject({
+ finalMs: 10,
+ finalRoute: "failed",
+ rejectionBucket: "candidate-failed",
+ });
+ });
+
+ it("records SFU admission waiting without advancing the route cursor", () => {
+ const routes = controller(1, { sfuEnabled: true });
+ addViewer(routes, A, 0, 0);
+ const direct = routes.reconcile(10).operation!;
+ expect(direct.candidates.map((candidate) => candidate.tuple.kind)).toEqual([
+ "peer",
+ "sfu",
+ ]);
+ expect(
+ routes.skipCurrentCandidate(
+ cursorGuard(direct),
+ 20,
+ "candidate-failed",
+ ).accepted,
+ ).toBe(true);
+ const sfu = routes.snapshot().operation!;
+ expect(
+ routes.noteCurrentCandidateRejection(
+ cursorGuard(sfu),
+ "sfu-admission",
+ ),
+ ).toBe(true);
+ expect(routes.routeDiagnosticSnapshot(30)).toMatchObject({
+ children: [
+ {
+ finalRoute: "waiting",
+ rejectionBucket: "sfu-admission",
+ },
+ ],
+ operation: {
+ childOrdinal: 1,
+ stage: "admission",
+ cursor: 1,
+ candidateCount: 2,
+ },
+ });
+ });
+
+ it("distinguishes first-frame timeout from the total operation deadline", () => {
+ const routes = controller(1, { sfuEnabled: true });
+ addViewer(routes, A, 0, 0);
+ const direct = routes.reconcile(10).operation!;
+ beginCandidate(routes, {
+ nowMs: 20,
+ connectionId: "silent_direct",
+ reservation: { kind: "direct" },
+ });
+
+ expect(routes.operationExpired(direct.wakeAtMs)).toMatchObject({
+ accepted: true,
+ });
+ expect(routes.routeDiagnosticSnapshot(direct.wakeAtMs)).toMatchObject({
+ children: [
+ {
+ candidateStartMs: null,
+ finalMs: null,
+ finalRoute: "waiting",
+ rejectionBucket: "first-frame-timeout",
+ },
+ ],
+ operation: { cursor: 1, stage: "admission" },
+ });
+
+ const deadline = routes.snapshot().operation!.deadlineAtMs;
+ expect(routes.operationExpired(deadline)).toMatchObject({
+ accepted: true,
+ exhausted: true,
+ });
+ expect(routes.routeDiagnosticSnapshot(deadline).children[0]).toMatchObject({
+ finalMs: deadline,
+ finalRoute: "failed",
+ rejectionBucket: "operation-deadline",
+ });
+ });
+
it.each([1, 2, 3] as const)(
"admits 20 Viewers through one bounded event-driven graph at C=%i",
(capacity) => {
@@ -875,15 +1134,15 @@ describe("RoomRouteController", () => {
routeRevision: 0,
generation: "publication_1",
connectionId: "publication:publication_1",
- })).toBe(true);
+ }, 10)).toBe(true);
routes.touchExternalFacts();
- const operation = routes.reconcile(0).operation!;
+ const operation = routes.reconcile(20).operation!;
expect(operation.candidates[0]).toMatchObject({
tuple: { kind: "sfu", publication: "replace" },
endpointTransition: { kind: "overlap", producerPeerId: HOST },
});
const prepared = beginCandidate(routes, {
- nowMs: 1,
+ nowMs: 21,
connectionId: "a_sfu_2",
publicationGeneration: "publication_2",
publicationConnectionId: "publication_connection_2",
@@ -899,7 +1158,7 @@ describe("RoomRouteController", () => {
childSessionId: `${A}_session`,
revision: prepared.current!.revision,
connectionId: "a_sfu_2",
- }, 2);
+ }, 22);
expect(settled.accepted).toBe(true);
expect(settled.released).toHaveLength(4);
expect(settled.released).toEqual(expect.arrayContaining([
@@ -912,7 +1171,14 @@ describe("RoomRouteController", () => {
publicationGeneration: "publication_2",
});
expect(routes.snapshot().upstreamByViewer.has(B)).toBe(false);
- expect(routes.reconcile(3).operation?.childPeerId).toBe(B);
+ expect(routes.routeDiagnosticSnapshot(22).children[1]).toMatchObject({
+ demandAgeMs: 12,
+ finalRoute: "waiting",
+ });
+ expect(routes.reconcile(23).operation).toMatchObject({
+ childPeerId: B,
+ reason: "edge-unavailable",
+ });
});
it("rebinds direct and SFU media to replacement sessions", () => {
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index e7036ebd..b7f90023 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -407,6 +407,31 @@ describe("WebSocket signaling", () => {
});
});
+ it("serves one current route snapshot only to the authenticated Host", async () => {
+ const harness = await startHarness({ peerAssistedMedia: true });
+ const host = await openClient(harness.webSocketUrl);
+ await authenticate(host, harness.room, "host", "route-diagnostic-host");
+ const viewer = await openClient(harness.webSocketUrl);
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "route-diagnostic-viewer",
+ );
+
+ host.socket.send(JSON.stringify({ type: "request-route-diagnostic" }));
+ expect(await host.inbox.next("route-diagnostic-snapshot")).toMatchObject({
+ snapshot: {
+ children: [{ ordinal: 1, finalRoute: "waiting" }],
+ },
+ });
+
+ viewer.socket.send(JSON.stringify({ type: "request-route-diagnostic" }));
+ expect(await viewer.inbox.next("error")).toMatchObject({
+ code: "FORBIDDEN",
+ });
+ });
+
it("keeps the exact Native Host wire unchanged without a presence opt-in", async () => {
const harness = await startHarness();
const host = await openClient(harness.webSocketUrl);
diff --git a/tests/viewer-quality-evidence.test.ts b/tests/viewer-quality-evidence.test.ts
index bf83afab..ec44ad8e 100644
--- a/tests/viewer-quality-evidence.test.ts
+++ b/tests/viewer-quality-evidence.test.ts
@@ -18,10 +18,6 @@ import {
type ViewerQualityEvidence,
ViewerQualityEvidenceReporter,
} from "../src/client/media/viewer-quality-evidence.ts";
-import {
- ParentEdgeQualityEvidenceReporter,
- parentEdgeQualityEvidenceFromSnapshot,
-} from "../src/client/media/parent-edge-quality-evidence.ts";
import {
EMPTY_METRICS,
type ConnectionMetrics,
@@ -524,96 +520,4 @@ describe("viewer quality evidence", () => {
).toBeNull();
});
- it("builds parent proof only from a current connected send interval", () => {
- const evidence = {
- type: "viewer-quality-evidence",
- viewerPeerId: "viewer_12345678",
- parentPeerId: "host_12345678",
- guard: {
- connectionId: "connection_12345678",
- routeRevision: 4,
- },
- sequence: 7,
- ...qualityEvidenceWindowFromMetrics(receiveMetrics())!,
- } as Extract<ServerMessage, { type: "viewer-quality-evidence" }>;
- const current = {
- ...snapshot(
- evidence.guard.connectionId,
- receiveMetrics({
- sampleWindowMs: 2_000.25,
- intervalPacketsSent: 1_200,
- intervalPacketsLost: 12,
- }),
- ),
- peerId: evidence.viewerPeerId,
- };
- const reporter = new ParentEdgeQualityEvidenceReporter();
-
- expect(reporter.offer(evidence, current)).toEqual({
- type: "parent-edge-quality-evidence",
- viewerPeerId: evidence.viewerPeerId,
- guard: evidence.guard,
- viewerSequence: evidence.sequence,
- proof: {
- kind: "sending",
- packetsSentDelta: 1_200,
- },
- });
- expect(
- reporter.offer({ ...evidence, sequence: evidence.sequence + 1 }, current),
- ).toBeNull();
- expect(
- reporter.offer(
- { ...evidence, sequence: evidence.sequence + 1 },
- {
- ...current,
- metrics: {
- ...current.metrics,
- sampleTimestampMs: current.metrics.sampleTimestampMs! + 0.25,
- },
- },
- ),
- ).toMatchObject({ viewerSequence: evidence.sequence + 1 });
- expect(
- parentEdgeQualityEvidenceFromSnapshot(evidence, {
- ...current,
- metrics: {
- ...current.metrics,
- intervalPacketsSent: 100,
- intervalPacketsLost: 30,
- },
- }),
- ).toMatchObject({
- proof: {
- kind: "remote-loss",
- packetsSentDelta: 100,
- remotePacketsLostDelta: 30,
- },
- });
- for (const reason of ["cpu", "bandwidth"] as const) {
- expect(
- parentEdgeQualityEvidenceFromSnapshot(evidence, {
- ...current,
- metrics: {
- ...current.metrics,
- qualityLimitationReason: reason,
- },
- }),
- ).toMatchObject({
- proof: { kind: "sender-limited", packetsSentDelta: 1_200, reason },
- });
- }
- expect(
- parentEdgeQualityEvidenceFromSnapshot(evidence, {
- ...current,
- connectionId: "connection_replaced_12345678",
- }),
- ).toBeNull();
- expect(
- parentEdgeQualityEvidenceFromSnapshot(evidence, {
- ...current,
- metrics: { ...current.metrics, intervalPacketsSent: null },
- }),
- ).toBeNull();
- });
});