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(media): retry pending host SFU ingress via selected TURN (#115)

AAA0981dafb8789
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index b79ab45b..59c9a6ff 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -82,8 +82,9 @@ and production ordinary peer connections remain STUN-only. The current source
no longer contains the rejected participant-wide
TURN config, issuer, capability, refresh wire, or client propagation. Stale
`PEER_ICE_TURN_*` keys fail startup even when blank. The source candidate now
-implements a complete selected-edge tuple and one post-SFU relay-only rebuild;
-production configures it, but real TURN/media evidence remains open.
+implements a complete selected-edge tuple and one relay-only rebuild for either
+the initial pending Host publication or an active Host/SFU route; production
+configures the tuple, but real TURN/media evidence remains open.
The wire has two explicit edge kinds: `peer-selected` for the last-mile failed
peer edge and `host-sfu-ingress` for a restricted Host-to-SFU retry. Ordinary
Peer ICE remains STUN-only.
@@ -293,13 +294,14 @@ ID allowlist.
8. An active Viewer SFU root may request one fresh short-lived grant. If its next
failure, or the initial SFU prepare, is exhausted, the router grants at most
- one relay-only rebuild of that Viewer's original failed peer edge. An active
+ one relay-only rebuild of that Viewer's original failed peer edge. A
Host-to-SFU route may instead receive one `host-sfu-ingress` relay-only grant
- when the explicit restricted-source decision applies; the grant is bound to
- the host session and publication generation. Failure is
- terminal for that attempt; stop, session replacement, topology revision or a
- new sharing generation clears it, then the existing bounded peer failback
- remains available.
+ for an initial pending publication or an active route. The pending retry is
+ bound to the exact revision, publication/share generations, expected Host
+ session and a server-generated new connection ID. Prepare-ready consumes the
+ attempt; retry failure reports that new ID and restores the unchanged peer
+ baseline. Stop, session replacement, topology revision or a new sharing
+ generation also clears it.
Production logs on 2026-08-20 observed two root participants for about 4.6
seconds and two short Host participants (about 0.46 and 0.27 seconds), all ending
@@ -420,21 +422,20 @@ cannot connect. Source has no
participant-wide TURN path: the rejected candidate is removed and its stale
environment keys fail startup. The selected-edge implementation uses
a short coturn REST bearer and one server-generated connection identity per explicit
-edge kind. `peer-selected` binds the failed parent/Viewer pair; `host-sfu-ingress`
-binds the room, host session, SFU publication generation, and the
-old/new connection identities. The Host client applies that grant only to a
-relay-only LiveKit publisher `RTCConfiguration`. It is configured in production
-but has no real relay-media evidence.
+edge kind. `peer-selected` binds the failed parent/Viewer pair;
+`host-sfu-ingress` binds the room, host session, SFU publication generation, and
+the old/new connection identities. The Host client applies that grant only to a
+relay-only LiveKit publisher `RTCConfiguration`, including during the initial
+pending prepare. Pinned LiveKit client 2.22.0 accepts `rtcConfig` on
+`Room.connect`; its engine clones that override before creating the publisher
+PeerConnection and does not replace explicitly supplied ICE servers. This path
+is configured in production but has no real relay-media evidence.
LiveKit participant-wide embedded/external TURN remains a separate ICE domain.
-### Deferred Gap-Fill And Optimization
+### Deferred Optimization
These items are not current runtime behavior:
-- If the Host cannot reach LiveKit over UDP during the initial pending SFU
- prepare, the current active-route `host-sfu-ingress` retry cannot rescue that
- prepare. A later gap-fill may authorize exactly one generation-bound,
- relay-only retry for that pending publication.
- A room in which the Host and every possible root are restricted may require
several server-fed exceptional edges. Any such extension requires a per-room
selected-relay and central-egress admission cap; it must wait or fail at that
@@ -578,6 +579,8 @@ Negative:
- [LiveKit selective subscription](https://docs.livekit.io/transport/media/subscribe/#selective-subscription)
- [LiveKit track subscription permissions](https://docs.livekit.io/transport/media/publish/#track-permissions)
- [LiveKit client 2.22.0 `prepareConnection` source](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/Room.ts)
+- [LiveKit client 2.22.0 connection options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/options.ts)
+- [LiveKit client 2.22.0 RTC configuration construction](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/RTCEngine.ts)
- [LiveKit JavaScript client usage](https://github.com/livekit/client-sdk-js#usage)
- [LiveKit end-to-end encryption](https://docs.livekit.io/transport/encryption/)
- [TURN, RFC 8656](https://www.rfc-editor.org/rfc/rfc8656.html)
diff --git a/docs/project-memory.md b/docs/project-memory.md
index fbf2404a..eca22a19 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -25,7 +25,7 @@ Last updated: 2026-08-21
- Keep experiments bounded: the standard representation sequence is below; native RTP relay, encoded-object striping, and FEC remain separate.
- ADR-0006's historical browser-bridge canary remains no-go; VP8 stays default. Browser H.264 rendered 298/299; Native WGC/MF rendered 203 with PID/LUID-correlated `VideoEncode`. Downloaded use, multi-viewer/endurance/public proof remain open.
- Mobile Web Host unsupported. Android 14+ source has video and default-off selected-UID playback audio; no mic/system fallback. Device A/V, rotation and SFU remain open. iOS deferred; TV output is P2.
-- ADR-0005 accepts direct/peer UDP, bounded SFU roots, then optional selected-edge TURN. Production enables the one-shot selected-edge tuple after SFU; participant-wide TURN remains rejected and ordinary peer ICE stays STUN-only. No production SFU/TURN media canary has run; latest source has one local SFU/UDP functional proof and TURN remains unverified.
+- ADR-0005 accepts direct/peer UDP, bounded SFU roots, then selected-edge TURN. Source grants one revision/publication/share/session-bound retry to initial or active Host ingress. Production has the tuple but no SFU/TURN media canary; participant-wide TURN stays rejected and ordinary peers stay STUN-only.
- The controller is process-enabled, not room-allowlisted: `PEER_ASSISTED_MEDIA=true` gives every normal room the same direct/peer -> SFU -> selected-edge path with per-room state. Room `1` is historical smoke. Preserve sticky P2P, mobile leaves and break-before-make; recovery gets one attempt per layer (ICE restart, same-parent rebuild, alternate peer, then SFU), never three identical retries.
- C+B quality reparenting is edge-local and cooldown-bound; no score, timer, or global parent penalty.
- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.
@@ -43,12 +43,12 @@ Last updated: 2026-08-21
- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn.
- Production is exact `22119b907d3cf03ce8b06d6fb4596ce1a26fedd7` at `https://share.bonfire.icu`; its 660,626-byte artifact SHA-256 is `3cbd8f6be82fa615fa2861ff1be0eba6c98f3f7d9acb73a0ba5c21a2ff4c661c`. The 2026-08-20T22:17:43Z cutover took 1,696 ms lock/508 ms stop-health/479 ms switch-health. Rollback is exact `fd76277b05d491af8840b28f3132b7ff445d3cbe`.
-- Source is ahead at Android-only exact `b8b6994efe4da3a773e16cec370e2a5ce7cbbf93`; it is not deployed.
+- Source is ahead; Android exact `b8b6994efe4da3a773e16cec370e2a5ce7cbbf93` and pending Host-ingress retry are not deployed.
- The current Screener, LiveKit, coturn, and nginx services are active/running with `NRestarts=0`; local and public health are 200. SQLite v3 is intact with five rooms including room `1`, and the DB owner/mode remain `screener:screener`/0600.
- Production ICE remains ordinary STUN-only. `PEER_ASSISTED_MEDIA=true` enables the controller for every normal room, and selected-edge TURN is configured for the single UDP tuple with TTL 120; the coturn daemon and nginx/LiveKit/firewall/listener baselines were unchanged. No production SFU/TURN media canary or quality claim is implied.
- Production requires the independent site-access secret through `SITE_ACCESS_PASSWORD`. Its stateless cookie authorizes creation/Host and permits code-only Viewer attempts; valid private fragment grants remain direct. Public-watch accepts site access plus code, while private code-only entry additionally requires the room password. The env, endpoint, cookie, and nginx limiter naming migrated atomically; anonymous failures stay neutral, and there are no accounts/JWT/session rows.
- Production uses nginx, Node.js 24.19.0, coturn 4.17.2, and LiveKit 1.13.5 on UDP 7882 (TCP fallback off). Ordinary peer ICE receives no TURN; the selected-edge tuple is configured only for the current controller edge, with no credential pre-advertised to ordinary peers. Coturn retains the old authenticated-relay ports. Services are healthy with zero restarts.
-- ADR-0005 source rejects `PEER_ASSISTED_ROOM_IDS`; `PEER_ASSISTED_MEDIA=true` enables every room, while ordinary peer ICE stays STUN-only. A stale room-ID variable fails startup. `screener-v2` is the only deployed signaling literal; there is no v1 parser or translator.
+- ADR-0005 rejects `PEER_ASSISTED_ROOM_IDS`; `PEER_ASSISTED_MEDIA=true` enables every room and ordinary peers stay STUN-only. Initial or active Host ingress may consume one bound relay-only grant; ready/abort clears it and failure restores peer baseline. Stale room-ID config fails startup; `screener-v2` is the only deployed wire.
- Chrome 151/LiveKit localhost A/B cut failure-to-active/render from 1.481/2.257 seconds to 0.200/0.320; 31 new frames and 25 ms sampling kept host edges at two. It is headless synthetic 720p30 and includes SDK/network prewarm, not public-network evidence.
- Chrome 151 synthetic topology/quality runs kept fanout 2/1 and decoding; one relay close recovered in 5.32 seconds. Control evidence only.
- Deployed Web source uses LiveKit 2.22.0's two-layer `q,h` layout. Local Chrome 151/LiveKit 1.13.5 kept one SFU/UDP root with growing inbound/decoded/rendered counters, clean leaves and no TURN. Production SFU media, zero-child BWE, and calibrated C+B loss remain open.
diff --git a/docs/research/low-server-media-routes.md b/docs/research/low-server-media-routes.md
index d2f28aa3..e7e8639e 100644
--- a/docs/research/low-server-media-routes.md
+++ b/docs/research/low-server-media-routes.md
@@ -199,6 +199,11 @@ SFU, not ordinary peer PCs. Selected-edge coturn uses independent configuration
and credentials. LiveKit TURN cannot rescue an unavailable SFU; the application
controller selects whether independent coturn may rebuild one failed peer edge.
+Pinned client 2.22.0 accepts a per-connect `rtcConfig`; its engine retains
+explicit ICE servers when constructing the publisher PeerConnection. A selected
+Host ingress can therefore supply only its coturn server plus relay policy
+without advertising that credential to ordinary peer PCs.
+
Ordinary peer ICE remains STUN-only. The participant-wide TURN
config, capability and refresh wire are removed; any stale `PEER_ICE_TURN_*`
key, including an empty value, fails startup. Selected-edge TURN is deployed as
@@ -415,6 +420,8 @@ Primary sources checked on 2026-08-19 and 2026-08-21:
and [end-to-end encryption](https://docs.livekit.io/transport/encryption/) -
official behavior and operator-boundary references.
- [LiveKit client 2.22.0 `Room.prepareConnection`](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/Room.ts),
+ [connection options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/options.ts),
+ [RTC configuration construction](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/RTCEngine.ts),
[two-layer RID construction](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/participant/publishUtils.ts),
and [official usage](https://github.com/livekit/client-sdk-js#usage) -
Apache-2.0; API behavior and RID construction were inspected, with no source
diff --git a/docs/status.md b/docs/status.md
index 1cc0823e..cf3e9281 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -5,7 +5,7 @@ Last updated: 2026-08-21
## Phase
Production is exact `22119b907d3cf03ce8b06d6fb4596ce1a26fedd7` at `https://share.bonfire.icu`; its 660,626-byte artifact SHA-256 is `3cbd8f6be82fa615fa2861ff1be0eba6c98f3f7d9acb73a0ba5c21a2ff4c661c`.
-Cutover took 1,696 ms lock/508 ms stop-health. SQLite v3 has five rooms; four services are healthy with zero restarts. Android-only source `b8b6994efe4da3a773e16cec370e2a5ce7cbbf93` is ahead and not deployed.
+Cutover: 1,696 ms lock/508 ms stop-health; SQLite v3/five rooms/four healthy zero-restart services. Android exact `b8b6994efe4da3a773e16cec370e2a5ce7cbbf93` and pending ingress are not deployed.
Ordinary ICE is STUN-only; all rooms use the bounded peer/SFU-UDP controller and selected-edge UDP TTL 120. Room `1` is historical smoke; production SFU/TURN media remains unverified.
Web names/audio hint are deployed. Native WGC/MF/package is source-only; Web defaults VP8.
@@ -36,7 +36,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo
- Native Win11 audio is source-only/default-off: target isolation was 4018x and one Viewer got 495 Opus packets. Download, game sync, Win10, and other routes remain open.
- Access protocol/config/HTTP/storage/SQLite/signaling focused tests pass, including commit-first teardown and v1 rollback.
- Native wire/session tests enforce at most two authoritative children, no presence-created edge, stale-revision ignore, and one bounded unsupported-route failure per revision.
-- Source adds selected Host ingress and peer last-mile for every enabled room; focused routing/config tests pass with Peer ICE STUN-only.
+- Source adds initial/active selected Host ingress and peer last-mile. Focused route/signaling tests pass exactly-once prepare retry, cleanup and rollback with ordinary peers STUN-only; no relay media ran.
- Host names, the window-audio hint, all-room routing, and all-room Host selected ingress are active; the stale restart assertion is historical only.
- Exact `22119b9` passed typecheck, both builds and 30 files/440 tests. Deploy preserved environment, ingress/media/firewall/listener/SQLite hashes, v3/five rooms/room `1`, route settings, services and local/public/route/asset 200s. Site access stayed required, the retired endpoint remained 404, and no TURN/SFU session ran. Rollback is exact `fd76277b05d491af8840b28f3132b7ff445d3cbe`.
@@ -57,7 +57,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo
Run one bounded production room `1` canary that retains UDP, a rendered frame, edge caps, and clean stop. TURN/performance follow later.
Recovery uses one ICE restart, one same-parent rebuild, one alternate peer, then SFU. Next gate exactly-two/Dynacast-off BWE on a zero-child SFU leaf, then root evacuation.
Native WGC/MF passed one-Viewer hardware; package download, Viewer2/FIFO and game A/V remain. Benchmark later.
-Ordinary Peer ICE stays STUN-only. Selected-edge Host ingress still needs one forced-relay canary before a media-success claim.
+Ordinary peers stay STUN-only. Initial/active Host ingress needs forced-relay canaries before any media claim.
ADR-0004 still needs the 30-minute `1/3/5/8` matrix; a separate 20-viewer gate must pass before changing the default eight.
## Blockers And Decisions
diff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.ts
index 9adaf268..87b79553 100644
--- a/src/client/media/host-sfu-route.ts
+++ b/src/client/media/host-sfu-route.ts
@@ -577,9 +577,11 @@ export class HostSfuRoute {
}
if (phase === "prepare") {
if (matchesPlannedRoute || wasActive) {
- // Selected-edge ingress is only issued for an active SFU route.
- // Prepare failures retain the existing null connection contract.
- this.routeFailed(revision, "prepare", null);
+ this.routeFailed(
+ revision,
+ "prepare",
+ slot.selectedEdgeTurn ? slot.connectionId : null,
+ );
}
return;
}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 0e7606ce..26f8fb65 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -951,7 +951,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
if (
peerAssistedRef.current &&
message.hostPeerId === hostPeerIdRef.current &&
- message.revision === activeRouteRevisionRef.current &&
Date.parse(message.expiresAt) > Date.now()
) {
const route = ensureHostSfuRoute(generation);
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index 79b43d63..078d999b 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -27,7 +27,7 @@ import { issueSelectedEdgeTurnCredential } from "./selected-edge-turn.js";
type ErrorCode = Extract<ServerMessage, { type: "error" }>["code"];
-const DEFAULT_SFU_PREPARE_TIMEOUT_MS = 5_000;
+const DEFAULT_SFU_PREPARE_TIMEOUT_MS = 20_000;
const SELECTED_EDGE_TURN_ATTEMPT_TIMEOUT_MS = 30_000;
const VIEWER_QUALITY_BAD_WINDOWS_TO_REASSIGN = 3;
const VIEWER_QUALITY_EVIDENCE_GAP_MS = 5_000;
@@ -45,6 +45,7 @@ interface PendingRoutePreparation {
} | null;
expectedSessionIds: ReadonlyMap<string, string>;
grantsIssued: boolean;
+ hostSfuIngressTurnAttempted: boolean;
timer: NodeJS.Timeout;
}
@@ -730,6 +731,15 @@ export class HybridMediaRouter {
return;
}
+ if (participant.role === "host") {
+ this.markSelectedSfuIngressAnswered(
+ participant.roomId,
+ participant.peerId,
+ participant.sessionId,
+ message.revision,
+ );
+ }
+
controller.ready(participant.peerId, message.revision, "prepare");
this.commitPendingRoute(participant.roomId, message.revision);
}
@@ -771,7 +781,7 @@ export class HybridMediaRouter {
participant.roomId,
participant.peerId,
participant.sessionId,
- active.revision,
+ active,
)
) {
return;
@@ -936,24 +946,51 @@ export class HybridMediaRouter {
) {
return;
}
- if (message.connectionId !== null) {
+ const expectedSessionId = pending.expectedSessionIds.get(participant.peerId);
+ if (!expectedSessionId) {
this.sendError(
participant.sessionId,
"FORBIDDEN",
- "Prepare failures do not identify a peer connection",
+ "Participant is not part of this route plan",
);
return;
}
- const expectedSessionId = pending.expectedSessionIds.get(participant.peerId);
- if (!expectedSessionId) {
+ if (participant.sessionId !== expectedSessionId) {
+ return;
+ }
+ const publicationGeneration = pendingRoute.route.sfu.publicationGeneration;
+ const hostOwnsPendingPublication =
+ participant.role === "host" &&
+ participant.peerId ===
+ this.peerRelayTopology.getHostPeerId(participant.roomId) &&
+ publicationGeneration !== null &&
+ pendingRoute.route.assignments.get(participant.peerId)
+ ?.sfuPublicationGeneration === publicationGeneration;
+ if (message.connectionId !== null) {
+ if (
+ hostOwnsPendingPublication &&
+ this.finishSelectedEdgeTurnFailure(participant, message)
+ ) {
+ return;
+ }
this.sendError(
participant.sessionId,
"FORBIDDEN",
- "Participant is not part of this route plan",
+ "Prepare failure connection is not the selected SFU ingress",
);
return;
}
- if (participant.sessionId !== expectedSessionId) {
+ if (
+ hostOwnsPendingPublication &&
+ (pending.hostSfuIngressTurnAttempted ||
+ this.startSelectedSfuIngressTurn(
+ participant.roomId,
+ participant.peerId,
+ participant.sessionId,
+ pendingRoute.route,
+ pending,
+ ))
+ ) {
return;
}
this.abortPendingRoute(participant.roomId);
@@ -1108,24 +1145,37 @@ export class HybridMediaRouter {
roomId: string,
hostPeerId: string,
hostSessionId: string,
- revision: number,
+ route: RoomMediaRoute,
+ pending?: PendingRoutePreparation,
): boolean {
const config = this.options.selectedEdgeTurn;
const fallback = this.options.sfuFallback;
- const controller = this.mediaRouteControllers.get(roomId);
- const active = controller?.getActiveRoute();
const key = roomId;
+ const currentAttempt = this.selectedSfuIngressAttempts.get(key);
+ if (currentAttempt) {
+ return (
+ currentAttempt.revision === route.revision &&
+ currentAttempt.hostPeerId === hostPeerId &&
+ currentAttempt.hostSessionId === hostSessionId &&
+ currentAttempt.publicationGeneration ===
+ route.sfu.publicationGeneration &&
+ currentAttempt.shareGeneration ===
+ this.options.getShareGeneration(roomId)
+ );
+ }
if (
!config ||
!fallback ||
- !active ||
- active.revision !== revision ||
- this.selectedSfuIngressAttempts.has(key)
+ (pending !== undefined &&
+ (pending.revision !== route.revision ||
+ pending.hostSfuIngressTurnAttempted ||
+ pending.expectedSessionIds.get(hostPeerId) !== hostSessionId))
) {
return false;
}
- const publicationGeneration = active.sfu.publicationGeneration;
- const assignment = active.assignments.get(hostPeerId);
+ const revision = route.revision;
+ const publicationGeneration = route.sfu.publicationGeneration;
+ const assignment = route.assignments.get(hostPeerId);
const host = this.connectedPeer(roomId, hostPeerId);
const shareGeneration = this.options.getShareGeneration(roomId);
if (
@@ -1162,21 +1212,28 @@ export class HybridMediaRouter {
return false;
}
+ const pendingAttempt = pending;
const timer = setTimeout(() => {
const current = this.selectedSfuIngressAttempts.get(key);
- if (
- !current ||
- current.newConnectionId !== newConnectionId ||
- current.answered
- ) {
+ const currentPending =
+ pendingAttempt !== undefined &&
+ this.pendingRoutePreparations.get(key) === pendingAttempt;
+ const currentIngress =
+ current?.newConnectionId === newConnectionId && !current.answered;
+ if (!currentPending && !currentIngress) {
return;
}
- this.selectedSfuIngressAttempts.delete(key);
- this.sendError(
- current.hostSessionId,
- "PEER_NOT_FOUND",
- "Selected SFU relay ingress timed out",
- );
+ if (currentIngress) {
+ this.selectedSfuIngressAttempts.delete(key);
+ this.sendError(
+ current.hostSessionId,
+ "PEER_NOT_FOUND",
+ "Selected SFU relay ingress timed out",
+ );
+ }
+ if (currentPending) {
+ this.abortPendingRoute(key);
+ }
}, SELECTED_EDGE_TURN_ATTEMPT_TIMEOUT_MS);
timer.unref();
const attempt: SelectedSfuIngressAttempt = {
@@ -1191,6 +1248,11 @@ export class HybridMediaRouter {
answered: false,
timer,
};
+ if (pending) {
+ clearTimeout(pending.timer);
+ pending.timer = timer;
+ pending.hostSfuIngressTurnAttempted = true;
+ }
this.selectedSfuIngressAttempts.set(key, attempt);
this.options.sendToSession(hostSessionId, {
type: "selected-edge-turn",
@@ -1222,7 +1284,9 @@ export class HybridMediaRouter {
return;
}
attempt.answered = true;
- clearTimeout(attempt.timer);
+ if (this.pendingRoutePreparations.get(roomId)?.timer !== attempt.timer) {
+ clearTimeout(attempt.timer);
+ }
this.selectedSfuIngressAttempts.delete(roomId);
}
@@ -1237,6 +1301,8 @@ export class HybridMediaRouter {
attempt.hostPeerId !== participant.peerId ||
attempt.hostSessionId !== participant.sessionId ||
attempt.revision !== message.revision ||
+ attempt.shareGeneration !==
+ this.options.getShareGeneration(participant.roomId) ||
attempt.newConnectionId !== message.connectionId
) {
return false;
@@ -1811,6 +1877,7 @@ export class HybridMediaRouter {
: null,
expectedSessionIds,
grantsIssued: false,
+ hostSfuIngressTurnAttempted: false,
timer,
});
void this.issueSfuPrepareGrants(
@@ -1942,6 +2009,11 @@ export class HybridMediaRouter {
}
clearTimeout(pending.timer);
this.pendingRoutePreparations.delete(roomId);
+ const ingress = this.selectedSfuIngressAttempts.get(roomId);
+ if (ingress?.revision === pending.revision) {
+ clearTimeout(ingress.timer);
+ this.selectedSfuIngressAttempts.delete(roomId);
+ }
if (controller.abort(pending.revision)) {
this.broadcastActiveRoute(
roomId,
diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.ts
index 570709eb..4aaff3a8 100644
--- a/tests/route-transition.test.ts
+++ b/tests/route-transition.test.ts
@@ -45,6 +45,24 @@ function sfuConfig(revision: number) {
};
}
+function hostSfuIngressGrant(newConnectionId = "selected-connection-new") {
+ return {
+ type: "selected-edge-turn" as const,
+ edgeKind: "host-sfu-ingress" as const,
+ revision: 1,
+ hostPeerId: "host_12345678",
+ publicationGeneration: "generation-a",
+ oldConnectionId: "generation-a",
+ newConnectionId,
+ expiresAt: "2099-01-01T00:00:00.000Z",
+ iceServer: {
+ urls: ["turn:turn.example.test:3478?transport=udp"] as [string],
+ username: "1787230000:opaque_identity_12345678",
+ credential: "short-lived-credential",
+ },
+ };
+}
+
function createFakePublisher(log: string[], label: string) {
return {
connect: vi.fn(async () => {
@@ -278,21 +296,7 @@ describe("HostSfuRoute", () => {
});
expect(
- route.startSelectedEdgeTurn({
- type: "selected-edge-turn",
- edgeKind: "host-sfu-ingress",
- revision: 1,
- hostPeerId: "host_12345678",
- publicationGeneration: "generation-a",
- oldConnectionId: "generation-a",
- newConnectionId: "selected-connection-new",
- expiresAt: "2030-01-01T00:00:00.000Z",
- iceServer: {
- urls: ["turn:turn.example.test:3478?transport=udp"],
- username: "1787230000:opaque_identity_12345678",
- credential: "short-lived-credential",
- },
- }),
+ route.startSelectedEdgeTurn(hostSfuIngressGrant()),
).toBe(true);
await vi.waitFor(() => expect(publishers).toHaveLength(2));
expect(publishers[1].connect).toHaveBeenCalledWith({
@@ -310,6 +314,49 @@ describe("HostSfuRoute", () => {
},
});
expect(failures).toHaveLength(2);
+ expect(messages).toContainEqual({
+ type: "route-ready",
+ revision: 1,
+ phase: "prepare",
+ });
+ });
+
+ it("identifies a failed selected ingress retry by its new connection", async () => {
+ const messages: ClientMessage[] = [];
+ const publishers: ReturnType<typeof createFakePublisher>[] = [];
+ const route = new HostSfuRoute({
+ getStream: () => ({}) as MediaStream,
+ getProfile: () => QUALITY_PROFILES["720p30"],
+ reconcileChildren: () => undefined,
+ send: (message) => {
+ messages.push(message);
+ return true;
+ },
+ createPublisher: () => {
+ const publisher = createFakePublisher([], `publisher-${publishers.length + 1}`);
+ publisher.connect.mockResolvedValue(false);
+ publishers.push(publisher);
+ return publisher;
+ },
+ });
+
+ route.accept({
+ revision: 1,
+ phase: "prepare",
+ assignment: hostAssignment("generation-a"),
+ });
+ await route.acceptConfig(sfuConfig(1));
+ expect(route.startSelectedEdgeTurn(hostSfuIngressGrant())).toBe(true);
+
+ await vi.waitFor(() => expect(publishers).toHaveLength(2));
+ await vi.waitFor(() =>
+ expect(messages).toContainEqual({
+ type: "route-failed",
+ revision: 1,
+ phase: "prepare",
+ connectionId: "selected-connection-new",
+ }),
+ );
});
it("surfaces a bounded publisher stage after active fallback fails", async () => {
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index cf2f4011..18a89d54 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -4059,6 +4059,200 @@ describe("WebSocket signaling", () => {
});
});
+ it("retries an initial Host SFU prepare through one selected ingress", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ });
+ const prepared = await prepareFallbackForTwoViewers(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-pending-ingress",
+ );
+ const publicationGeneration =
+ prepared.hostPrepare.assignment.sfuPublicationGeneration;
+ expect(publicationGeneration).toEqual(expect.any(String));
+
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: null,
+ }));
+ const grant = await prepared.host.inbox.next("selected-edge-turn");
+ expect(grant).toMatchObject({
+ edgeKind: "host-sfu-ingress",
+ revision: prepared.hostPrepare.revision,
+ hostPeerId: prepared.hostAuth.peerId,
+ publicationGeneration,
+ oldConnectionId: publicationGeneration,
+ newConnectionId: expect.any(String),
+ });
+
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: null,
+ }));
+ await expect(
+ prepared.host.inbox.next("selected-edge-turn", 40),
+ ).rejects.toThrow("Timed out");
+
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ }));
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: null,
+ }));
+ await expect(
+ prepared.host.inbox.next("selected-edge-turn", 40),
+ ).rejects.toThrow("Timed out");
+
+ prepared.failedViewer.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: prepared.rootPrepare.revision,
+ phase: "prepare",
+ }));
+ await expect(
+ nextActiveRouteRevision(prepared.host, prepared.hostPrepare.revision),
+ ).resolves.toMatchObject({
+ assignment: { sfuPublicationGeneration: publicationGeneration },
+ });
+ });
+
+ it("keeps the default prepare open for the initial LiveKit attempt", async () => {
+ vi.useFakeTimers();
+ try {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ });
+ const prepared = await prepareFallbackForTwoViewers(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-pending-deadline",
+ );
+
+ await vi.advanceTimersByTimeAsync(15_000);
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: null,
+ }));
+
+ await expect(
+ prepared.host.inbox.next("selected-edge-turn"),
+ ).resolves.toMatchObject({
+ edgeKind: "host-sfu-ingress",
+ revision: prepared.hostPrepare.revision,
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("replaces the initial deadline with one relay timeout and rollback", async () => {
+ vi.useFakeTimers();
+ try {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ prepareTimeoutMs: 5_000,
+ });
+ const prepared = await prepareFallbackForTwoViewers(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-pending-relay-deadline",
+ );
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: null,
+ }));
+ await prepared.host.inbox.next("selected-edge-turn");
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ const noEarlyRollback = expect(
+ prepared.host.inbox.next("route-update", 1),
+ ).rejects.toThrow("Timed out");
+ await vi.advanceTimersByTimeAsync(1);
+ await noEarlyRollback;
+
+ await vi.advanceTimersByTimeAsync(24_999);
+ await expect(prepared.host.inbox.next("error")).resolves.toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "Selected SFU relay ingress timed out",
+ });
+ await expect(
+ nextActiveRouteAfter(
+ prepared.host,
+ prepared.hostPrepare.revision,
+ ),
+ ).resolves.toMatchObject({
+ revision: prepared.hostPrepare.revision + 1,
+ assignment: { sfuPublicationGeneration: null },
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("rolls back when selected Host prepare ingress also fails", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ });
+ const prepared = await prepareFallbackForTwoViewers(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-pending-failure",
+ );
+
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: null,
+ }));
+ const grant = await prepared.host.inbox.next("selected-edge-turn");
+ if (grant.edgeKind !== "host-sfu-ingress") {
+ throw new Error("expected a Host SFU ingress grant");
+ }
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: grant.newConnectionId,
+ }));
+
+ await expect(prepared.host.inbox.next("error")).resolves.toMatchObject({
+ code: "PEER_NOT_FOUND",
+ });
+ await expect(
+ nextActiveRouteAfter(prepared.host, prepared.hostPrepare.revision),
+ ).resolves.toMatchObject({
+ revision: prepared.hostPrepare.revision + 1,
+ assignment: { sfuPublicationGeneration: null },
+ });
+ prepared.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: prepared.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: grant.newConnectionId,
+ }));
+ await expect(
+ prepared.host.inbox.next("selected-edge-turn", 40),
+ ).rejects.toThrow("Timed out");
+ });
+
it("authorizes a ViewerRelay parent and clears its grant on share stop", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },