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. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

fix(media): demote corroborated relay parents (#164)

AAA0a5c21025f82
diff --git a/.env.example b/.env.example
index 3fb4ae6a..359656de 100644
--- a/.env.example
+++ b/.env.example
@@ -19,6 +19,8 @@ MAX_VIEWERS_PER_ROOM=8
# Bounded standard-WebRTC relay/SFU controller for every room when true.
# Keep false outside measured tests.
PEER_ASSISTED_MEDIA=false
+# Per-endpoint peer upload budget. Default 2; explicit range 1-3.
+MAX_PEER_RELAY_DOWNSTREAM_EDGES=2
# Optional automatic SFU fallback capacity. Set PEER_ASSISTED_MEDIA=true and
# supply all three values together; leaving them empty keeps LiveKit completely
@@ -49,3 +51,4 @@ STUN_URLS=
# LIVEKIT_API_KEY=replace-with-a-livekit-api-key
# LIVEKIT_API_SECRET=replace-with-at-least-32-independent-random-bytes
# MAX_SFU_ROOTS_PER_ROOM=2
+# MAX_PEER_RELAY_DOWNSTREAM_EDGES=2
diff --git a/AGENTS.md b/AGENTS.md
index 585d21c7..054ab8cd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,7 +7,7 @@
- Keep media distributed and automatic. Use centralized services for rooms, authentication, signaling, STUN, observability, and bounded SFU-root capacity. TURN is an optional authenticated selected-edge compatibility transport, disabled unless explicitly configured; it is not a media topology.
- Let viewers join from a normal desktop or mobile browser without installing the sender application.
- STUN is required. The target ladder is direct/peer UDP, then an SFU/UDP virtual parent feeding at most two roots, then optional authenticated selected-edge TURN, followed by a clear bounded failure. Ordinary peer edges must not receive TURN candidates by default. HTTPS/WSS remains TLS/TCP and is independent of this media-transport policy.
-- Every non-server endpoint stays within its advertised relay capacity and the deployment hard ceiling; an upstream receive edge does not consume this upload budget. The current ordinary Web release tier is uniformly two without UA- or visibility-based policy, and actual edge failure returns to the bounded route-reselection path. A later accepted tier may use evidence-driven discrete `0/1/2/3` capacity under a server ceiling and cooldown; it must not infer capacity from device identity. Central media normally serves at most two roots; extra server-fed exceptional viewers require an explicit deployment egress/admission cap and must never create unbounded fanout.
+- Every non-server endpoint stays within its advertised relay capacity and the deployment hard ceiling; an upstream receive edge does not consume this upload budget. The deployment cap defaults to two and may be explicitly set from one through three without UA- or visibility-based policy; actual edge failure returns to the bounded route-reselection path. Dynamic evidence-driven capacity remains future work and must not infer capacity from device identity. Central media normally serves at most two roots; extra server-fed exceptional viewers require an explicit deployment egress/admission cap and must never create unbounded fanout.
- Treat a web client as the initial delivery target. A packaged desktop sender or native capture helper is a later optimization, not an assumed requirement.
- Do not silently change the product into an always-SFU conferencing system. An SFU is a virtual parent for one or two necessary roots whose peer descendants remain distributed; record any broader topology change as an ADR with measured justification.
@@ -64,6 +64,8 @@
- Keep changes scoped and preserve unrelated user work.
- Prefer the smallest proven extension point; do not add speculative frameworks, hooks, or abstractions without a current consumer.
- Add automated tests in proportion to behavioral risk. Block the current phase on P0 security, privacy, irreversible data, authorization, generation, bounded-resource, and rollback failures, plus P1 failures of the milestone's core user path. Record or cover P2/P3 rare environments, diagnostic detail, and minor UI edges cheaply without turning them into canary blockers unless they can cause P0 harm. Use high-repeat race runs only for a reproduced concurrency failure. For realtime media changes, also document the manual network and browser matrix used.
+- Use independent review for routing or protocol state machines, security/privacy boundaries, large features, and milestone integration. Narrow changes should normally close with focused tests plus the relevant typecheck/build; do not start a separate reviewer for every small feature.
+- Treat `docs/status.md` as a current index, not an archive. When it approaches its budget, remove completed or stale facts that Git history already owns; move still-relevant detail to the owning requirement, ADR, research, or deployment document and leave a short link or index entry. Create a scoped second-level status document only when no existing owner fits; never micro-compress prose merely to satisfy the byte gate.
- Batch validation by risk and phase: run narrow checks while iterating, and run expensive full suites, browser matrices, endurance tests, or deployment checks only at an acceptance boundary or when a relevant change invalidates prior evidence. Documentation-only or unrelated changes do not invalidate media-path evidence.
- Use comments for non-obvious rationale, invariants, protocol constraints, and workarounds; do not narrate obvious code.
- Use WebRTC statistics and reproducible measurements for latency, bitrate, candidate type, packet loss, encode time, and quality limitations. Do not claim performance from assumptions alone.
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index 679f665d..21dbf440 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -127,18 +127,23 @@ server currently retries a failed edge through the deterministic peer topology;
only an exhausted peer route can request an SFU branch root. The target keeps
healthy routes sticky but may select SFU directly when admission has no eligible
peer path. Optional TURN is controller-selected only after that SFU/UDP attempt
-fails. The authorization must bind the current room/share generation, viewer and
-parent sessions, route revision, and replaced/new connection identities; stale,
-replayed, participant-wide, or unselected attempts fail closed. Coturn still
+fails. The authorization binds the room/share generation, viewer and parent
+sessions, grant revision, and replaced/new connection identities. After answer,
+the signed grant revision stays immutable while the controller tracks the current
+route revision separately. An unrelated route revision may carry the exact edge
+only while its sessions, topology, share generation, and parent downstream
+budget remain current; carry authority must precede the active route update.
+Stale, replayed, participant-wide, over-budget, or unselected attempts fail closed. Coturn still
validates only HMAC and expiry, so application generation checks, short TTL,
one-use state, fanout, and quotas bound the bearer. LiveKit publisher/subscriber
ICE remains a separate participant-wide domain.
Every viewer starts with zero relay capacity for each authenticated session. A
-peer-assisted Web client then explicitly advertises two downstream edges; there
-is no UA-, device-, or visibility-based branch. The controller accepts bounded
-capacity values from zero through two for admission and recovery. Withdrawing
-capacity does not proactively migrate an otherwise healthy existing edge.
+peer-assisted client advertises its absolute ability of three downstream edges;
+there is no UA-, device-, or visibility-based branch. The controller clamps the
+advertisement to `MAX_PEER_RELAY_DOWNSTREAM_EDGES`, which defaults to two and
+accepts one through three. Withdrawing capacity does not proactively migrate an
+otherwise healthy existing edge.
The source now implements one narrow admission exception to sticky assignment.
On an active peer-only route with no SFU publication or pending prepare, a
@@ -338,7 +343,12 @@ change or the current share stops. A new sharing generation starts from the
cheapest available UDP route. The controller does not continuously rebalance
healthy media. The bounded quality candidate changes only the Viewer-rooted
subtree whose current parent-to-child edge produced three consecutive hard-bad
-windows; it does not withdraw that parent's global relay capacity.
+windows. One confirmed child remains edge-local. Two distinct confirmed
+children under the same Viewer parent session and share generation within five
+seconds temporarily make that parent relay-ineligible (effective capacity zero)
+for 30 seconds; its advertised capacity is unchanged. The triggering edge still
+follows its own intent: relative FPS is peer-only, while severe evidence retains
+the ordinary peer, SFU, selected-edge TURN, then bounded-failure ladder.
The authenticated standby is not a transport: it has no grant and never joins a
room. During route prepare the current implementation warms only an unpublishing/unsubscribed
@@ -611,10 +621,9 @@ boundary is actually configured and the UI must not claim E2EE.
## Acceptance Gates
-- Every non-server endpoint stays at or below two active downstream media edges
- across prepare, commit, rollback, reconnect, and stale-message sequences;
- the current Web candidate uses the same two-child bound and never admits a
- third edge.
+- Every non-server endpoint stays at or below the configured one-through-three
+ downstream edge budget across prepare, commit, rollback, reconnect, and
+ stale-message sequences; production keeps the default two.
- Only necessary roots or explicitly admitted exceptional viewers receive SFU
media and the configured central egress budget is never exceeded.
- A reliable SFU root continues to serve bounded peer descendants. Normal
diff --git a/docs/deployment.md b/docs/deployment.md
index 5f7a83f3..240b50f9 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -235,6 +235,7 @@ To make automatic SFU fallback capacity available, add the complete tuple:
```dotenv
PEER_ASSISTED_MEDIA=true
+MAX_PEER_RELAY_DOWNSTREAM_EDGES=2
LIVEKIT_URL=wss://share.example.com
LIVEKIT_API_KEY=<GENERATED_LIVEKIT_API_KEY>
LIVEKIT_API_SECRET=<INDEPENDENT_SECRET_OF_AT_LEAST_32_BYTES>
@@ -283,6 +284,11 @@ Omit the database path to keep random temporary rooms; `ROOM_TTL_SECONDS`
applies only to those rooms.
`MAX_VIEWERS_PER_ROOM` defaults to 8 and accepts 1 through 16. It is an admission
limit, not evidence that the publisher can sustain that many streams.
+`MAX_PEER_RELAY_DOWNSTREAM_EDGES` defaults to 2 and accepts 1 through 3. It is
+the hard per-endpoint peer upload budget; an active Host SFU publication also
+uses one Host edge. Web and Native advertise an absolute ability of three, but
+the server always clamps assignments to this deployment value. It does not
+change the separate SFU root limit.
The three `LIVEKIT_*` values must either all be absent or all be present, and a
complete tuple requires `PEER_ASSISTED_MEDIA=true`. An empty tuple keeps the
diff --git a/docs/project-memory.md b/docs/project-memory.md
index 956da3d8..f47e8ea5 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -8,7 +8,7 @@ Last updated: 2026-08-22
- Browser first. Viewers use desktop/mobile Web; an optional sender requires a proven browser capability gap.
- Use a small central service for access, rooms, signaling, deterministic topology, STUN, observability, and bounded SFU-root capacity.
- Minimize server bandwidth. Ordinary peer ICE is STUN-only. Failure tries restart, rebuild, alternate peer and bounded SFU/UDP roots; only then may the controller authorize short-lived TURN for one selected exceptional edge before clear failure. TURN is transport, not topology.
-- The current release budget is two downstream edges per non-server node, including ordinary Web relays; upstream receive is free and UA/visibility do not change it. SFU normally feeds one or two roots that retain peer descendants; separately capped server edges may serve exceptional viewers that cannot attach behind a healthy root. A future evidence-driven tier may change the ceiling only through the owning requirement and design.
+- Production keeps two downstream edges per non-server node; source exposes a deployment cap defaulting to two with an explicit one-through-three range. Upstream receive is free and UA/visibility do not change it. SFU normally feeds one or two roots that retain peer descendants; its root cap remains separate. Dynamic evidence-driven capacity still requires its own acceptance.
- Two-tree packet/layer striping may reduce endpoint upload toward one stream bitrate, but needs a bounded multi-parent, loss, sync, churn, and latency experiment; it is not in the current full-stream chains.
- Direct/peer keeps per-PC stock GCC. Active SFU publishes exactly `q,h` at a `HIGH` ceiling; built-in BWE may forward `LOW`. The zero-descendant quality/resource gate is next; if it passes, no app media selector is built. Explicit quality, manual activation, and custom/native remain fallbacks.
- A later explicit quality fallback evacuates children under a generation guard first. Autonomous BWE enters `suspect`; confirmation evacuates children, and no confirmed `FALLBACK` parent remains. Root-with-children impact is a default-on gate; capacity returns after longer recovery plus cooldown. Self-report alone never triggers it.
@@ -28,7 +28,7 @@ Last updated: 2026-08-22
- Mobile endpoints are Web Viewer-only. Current Android/iOS browsers do not expose Web Host capture; AirPlay/system mirroring is Viewer-local output.
- ADR-0005: direct/peer UDP -> bounded SFU roots -> selected-edge TURN. The deployed controller caps pending/answered `peer-selected` at one per room; Host ingress is independent. A pre-`ecc794d` exact-source/production-media canary proves active Host ingress only. Ordinary peers stay STUN-only.
- `PEER_ASSISTED_MEDIA=true` covers all rooms. One-root healthy-SFU MBB is deployed with retained parent, media proof, Host2/browser1 overlap, cooldown and fresh two-window proof; it excludes `peer-selected`. Active-SFU loss uses normal recovery; the manual control keeps its route: peer restarts its edge, SFU reauthenticates signaling and rebuilds that subscriber. Capacity `0 -> 1`, multi-root/browser gates remain open.
-- C+B reparenting stays edge-local: severe uses fallback; relative relay FPS uses fresh parent evidence and peers only. No scoring or global penalty.
+- C+B stays edge-local: severe keeps its fallback ladder; relative relay FPS uses fresh parent evidence and peers only. Two confirmed children under one Viewer relay/session/share within 5s pause its eligibility for 30s and peer-only evacuate its children; no score.
- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.
- Treat settings as ceilings and degradation as unclassified. Use correlated Host A+B/Viewer C and one-variable evidence; never force AV1, infer by UA, or create a composite score.
- Screen audio: Web capture requests speech processing off and ideal stereo; peer answers use `stereo=1;maxaveragebitrate=128000`; SFU uses 128 kbps stereo/`forceStereo`, DTX off, RED retained. Proof open; no audio UI; voice and Native stay separate.
@@ -51,7 +51,7 @@ Last updated: 2026-08-22
- Production keeps ordinary ICE STUN-only, SFU roots <=2, selected-edge UDP TTL 120, and one pending/answered `peer-selected` attempt per room excluding Host ingress. This rollout ran no browser/media/SFU/TURN/performance canary; earlier exact-`16f6eab` evidence proves active Host ingress only.
- Production requires independent `SITE_ACCESS_PASSWORD`: its stateless cookie authorizes creation/Host and code-only Viewer attempts; private grants stay direct, while public/private code entry needs site access alone/plus room password. Env/endpoint/cookie/nginx naming migrated atomically; failures remain neutral; there are no accounts/JWT/session rows. Local `gate:access-privacy` proves fragment isolation, site/grant transport-log absence, and raw room-password SQLite absence; room-password WebSocket/log ingress and live/headful evidence remain open.
- 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 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. Web and source-only Native use the single deployed `screener-v4` authentication wire; Native does not subscribe to Web presence.
+- 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. Production uses `screener-v4`; current Web and source-only Native move atomically to `screener-v5` for the bounded cap3 wire. Native does not subscribe to Web presence.
- Defaults are balanced with automatic codec; clarity/fluid and H.264/VP8 remain explicit. Codec is locked during a share. Web SFU uses LiveKit 2.22.0 `q,h`; SFU/UDP and selected-TURN work; BWE, Host A+B and production remain open.
- Chrome 151 five-Viewer 720p30 cap2 evidence: Host/relay fanout two; both relay children +80 decoded frames/~1.1 MB; every Viewer decoded; clean stop. Functional only; resource and heterogeneous-network behavior remain open.
@@ -68,7 +68,7 @@ These are measurement gates, not performance claims.
- Sustainable count by hardware, quality, network, and route: finish instrumented `1/3/5/8`, then pass a 20-viewer matrix before changing the accepted target default to 20.
- Whether ADR-0004 passes re-encoding, depth-three/eight-viewer latency, reparenting, silent-partition, and representative resource gates.
-- Selected-edge: active Host-ingress function passes; initial ingress, `peer-selected`, expiry/failure, mobile, resource and bandwidth gates remain. The bearer is non-revocable until expiry; performance follows later and Media TCP is out.
+- Selected-edge: Host ingress works; initial ingress, `peer-selected`, expiry/failure, mobile/resource/bandwidth gates remain. Coturn bearer lasts to expiry; the app lease ends on edge/session/share/budget loss. Media TCP is out.
- Exact mobile Viewer lifecycle behavior across autoplay, rotation, iOS lock-screen/page reclamation, background reconnection and network changes.
- Project license and distribution model, which determines whether GPL/AGPL sources can move beyond study-only use.
- Initial deployment regions and expected mainland China, Hong Kong, and overseas network mix.
diff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.md
index 1654c73b..43eeacb5 100644
--- a/docs/research/advanced-peer-distribution.md
+++ b/docs/research/advanced-peer-distribution.md
@@ -201,7 +201,10 @@ less than two-thirds of that actual inbound FPS. The configured FPS ceiling is
not evidence. `sending`, either report alone, and healthy or ambiguous pairs
reset or do not advance the streak.
It holds at most one pending/streak state per connected Viewer and one room
-cooldown, with no timer, weighted score or global parent-capacity decision.
+cooldown, with no timer or weighted score. One confirmed child event stays
+edge-local. A separate bounded corroboration can suspend one Viewer relay's
+server-owned eligibility only after two distinct children confirm under the
+same parent session and share within five seconds.
The conservative Viewer C hard predicates are: freeze duration at least half
of the one-to-five-second window; positive received-packet delta with zero
@@ -245,16 +248,19 @@ five-second gap and 30-second
cooldown are falsifiable candidate constants for production calibration, not
standards-derived or claimed optimum values.
-The correlated pair can therefore attribute a problem only to the current
-parent-to-child edge generation. It cannot prove that the parent is globally
-bad: the remote-loss value is that child's RTCP report and
-`qualityLimitationReason` belongs to one outbound video stream. LiveKit's pinned
-server implementation deliberately reduces published-track and subscribed-
-downtrack quality to a participant-wide minimum; that aggregate is useful for
-conferencing UI but is not a directional P2P parent score. Screener consequently
-excludes only the affected edge parent. Alternate-parent selection remains
-deterministic breadth-first; preferring recent healthy candidates over unknown
-candidates is a later make-before-break slice, not a score in this correction.
+One correlated pair still attributes a problem only to its current
+parent-to-child edge generation: remote loss comes from that child and
+`qualityLimitationReason` belongs to one outbound stream. Screener therefore
+keeps a single event edge-local. Two independently confirmed current children
+within five seconds are instead treated as bounded corroboration to pause that
+Viewer parent's relay eligibility for 30 seconds, not as proof of device-wide
+quality or a numeric score. The client-advertised capacity remains intact; new
+capacity messages cannot override the server-owned pause. Existing children
+try deterministic peer reassignment and keep their old edge when none exists;
+the parent keeps its upstream and the pause itself never starts SFU or TURN.
+Host parents are excluded, while expiry, a new parent session or a new share
+restores eligibility. Alternate-parent selection remains breadth-first;
+preferring recent healthy candidates remains a later make-before-break slice.
With host and current browser-relay degree two, deterministic breadth-first
assignment keeps eight viewers to depth three. A tree for `N` viewers
diff --git a/docs/status.md b/docs/status.md
index 6be56883..eaab3b71 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -17,10 +17,11 @@ Parallel flagship work; use minimum relevant checks and rollback proof. Target-d
- Capture precedes rooms; source/quality changes and AV pause preserve peers. Defaults are balanced and automatic codec; clarity/fluid plus H.264/VP8 stay explicit, with codec locked during a share. Browser degradation and Host SFU A+B remain open.
- Deployed `screener-v4` admits private fragment grants directly; code-only Viewers need site access, and private rooms additionally need their password. Credentials remain unstored. Web presence fields remain opt-in and Native does not subscribe to them.
- Deployed UI has nickname editing, room entry, Viewer roster, duplicate-only ID suffixes, pause notice, and session-bound SFU first-media truth that clears on track/route/session loss. P2P/SFU/TURN labels require evidence. Guarded relay evidence reaches opted-in Web Host rosters without Host-local transport claims or false parent-edge proof.
-- Native v4 is source-only (memory rooms, 300s reclaim); it does not subscribe to Web presence, follows authenticated direct-child assignments up to two, and fails unsupported SFU/selected ingress boundedly.
-- Production roots/Web relay <=2; Viewer upstream1, child3 rejected. One-root healthy-SFU MBB is deployed/media-unverified; source defers one cooldown ready for expiry reproof. Capacity `0 -> 1`, multi-root and browser gates remain open. Room `1` is historical; HTTPS/WSS is TLS/TCP.
+- Native v4 is source-only (memory rooms, 300s reclaim); it does not subscribe to Web presence, accepts the shared absolute three-child bound, and fails unsupported SFU/selected ingress boundedly. Production still clamps to two.
+- Production roots/Web relay <=2; Viewer upstream1. Source parameterizes endpoint cap at default2/range1-3 while SFU roots remain <=2; production stays2. One-root healthy-SFU MBB is deployed/media-unverified; source defers one cooldown ready for expiry reproof. Capacity `0 -> 1`, multi-root and browser gates remain open. Room `1` is historical; HTTPS/WSS is TLS/TCP.
- After an answer, a generation-bound 15s initial-connect deadline enters ICE restart; success/replacement/disposal cancels it. It is deployed but not mobile-verified.
-- C+B reparenting remains uncalibrated. Production compares relay-child FPS with fresh parent input and tries peers only; no candidate keeps the old edge. Admission rescue stays deterministic.
+- C+B is uncalibrated. Production compares relay-child FPS with fresh parent input and tries peers only. Source lets two confirmed children pause one Viewer relay for 30s and peer-only reassign its children; no candidate keeps old edges. Not deployed; admission rescue remains deterministic.
+- Source-only `screener-v5` selected-TURN work separates immutable grant revision from current route authority and parameterizes endpoint cap default2/range1-3: unrelated revisions may carry only the same in-budget edge, while topology/session/share/budget loss revokes it before active authority. Browser and production proof remain open.
## Verified Evidence
diff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
index 7b6ac825..c99f3b7a 100644
--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
@@ -104,7 +104,7 @@ Web Host 在 `authenticate` 中显式发送 `viewerPresence: true` capability,
## 信令协议
-WebSocket 使用无 query/fragment 的同源 `/signal`。upgrade 只记录 site-access cookie 是否有效;连接后五秒内第一条消息必须是 `screener-v4` 的房间级 `authenticate`。Host 消息携带 room、role、内部 Host token 与 clientId,并由 socket state 复核 site access;Web Host 可选发 `viewerPasswordSettings: true` capability,source-only Native 使用同一 wire 版本但不发送该 capability,也不接收密码设置或 presence 新消息。Viewer 消息携带 room、role、clientId,以及 private room 的 Viewer grant 或当前尝试的房间密码。服务端设置 64 KiB `maxPayload`、关闭 `perMessageDeflate`,并以 ping/pong 清理失效连接。单进程固定限制 2048 条总连接和 256 条未鉴权连接,容量在 upgrade 前预留,超限直接返回 HTTP 503 并销毁 socket。
+WebSocket 使用无 query/fragment 的同源 `/signal`。upgrade 只记录 site-access cookie 是否有效;连接后五秒内第一条消息必须是 `screener-v5` 的房间级 `authenticate`。Host 消息携带 room、role、内部 Host token 与 clientId,并由 socket state 复核 site access;Web Host 可选发 `viewerPasswordSettings: true` capability,source-only Native 使用同一 wire 版本但不发送该 capability,也不接收密码设置或 presence 新消息。Viewer 消息携带 room、role、clientId,以及 private room 的 Viewer grant 或当前尝试的房间密码。服务端设置 64 KiB `maxPayload`、关闭 `perMessageDeflate`,并以 ping/pong 清理失效连接。单进程固定限制 2048 条总连接和 256 条未鉴权连接,容量在 upgrade 前预留,超限直接返回 HTTP 503 并销毁 socket。
主要消息:
@@ -182,7 +182,7 @@ SFU publisher 使用 pinned SDK 的 `AudioPresets.musicHighQualityStereo`、`for
质量自适应采用 ADR-0007 的 built-in-first 路径隔离双表示,而不是全房间按最差链路降档。Direct/peer 保留每条 PeerConnection 的 stock WebRTC GCC。每条 SFU path 从 `HIGH` ceiling 开始;优先发布共享 `HIGH+LOW` 并让 LiveKit BWE 独立降层和恢复。若该 gate 通过,Screener 不实现媒体层 selector。应用证据只决定下述 parent/leaf 拓扑资格与诊断。`LOW` 可以常驻;关闭空闲层只是资源优化。active representation/layer 数量硬限制为二,不能按 viewer 增长。标准浏览器不保证跨 PeerConnection 共用一个物理编码器,inactive 层也不保证释放 GPU;实际层数、实例数、CPU/GPU、游戏 FPS/p1 low、区间 encode cost、上传与释放行为必须实测。若没有合格 hardware/power-efficient 路径或额外表示破坏游戏/上传预算,则 fail closed,保留健康路径并明确显示弱路径降级或失败。
-应用只为拓扑资格维护 `HIGH`/`FALLBACK` 两个 durable states;`suspect` 是采样中的候选而不是第三种媒体模式。连续窗口确认 `FALLBACK` 后撤销 parent capacity,更长稳定窗口和 cooldown 后才恢复。它不命令正常的 LiveKit/WebRTC 媒体层,也不把 RTT、CPU、码率、设备信息压成综合分数。具体窗口和阈值由真实质量矩阵确定。
+单个三窗确认的 C+B 事件仍是 edge-local:`severe` 进入原 fallback ladder,`relative-fps` 只尝试 peer。若同一 Viewer parent peer/session/share 在五秒内由两个不同 child 分别确认任一类型,服务端把该 parent 的独立 `relayEligible` 暂停 30 秒,使拓扑有效容量为零但保留客户端广告值;后续 capacity 广播不能绕过。Host 不参与,parent 自身 upstream/观看和无可替代 peer 的旧 child edge 均保留;有 peer 的当前 children 各自重选,退位不创建 SFU/TURN intent。到期惰性恢复,parent 新 session 或新分享立即恢复,stop/delete/disconnect 清理状态。该离散资格不命令 LiveKit/WebRTC 媒体层,也不把 RTT、CPU、码率、设备信息压成综合分数;窗口仍需真实质量矩阵校准。
状态决策必须关联同一时间区间和媒体代次的三段证据:
@@ -240,10 +240,11 @@ fail-fast,绝不作为 alias。
Controller 先完成一次 ICE restart、一次同 parent rebuild、一个 alternate peer,随后
准备最多两个 SFU/UDP roots;只有该 edge 仍无法通过 SFU/UDP 时,才生成一次
selected-edge TURN attempt。该 attempt 必须同时绑定 room/share generation、viewer
-与 parent session、route revision、replaced connection 和 server-generated next
+与 parent session、签发时 route revision、replaced connection 和 server-generated next
connection identity;parent 与 child 只为该新 PC 协同重建,Viewer 使用 relay-only
-配置。pending 超时、失败或代次变化清理 attempt;answer 后 attempt 变为已使用并仅为
-该 edge 保留信令 owner,直到失败或 generation/session/topology/room cleanup。普通 PC、其他 edge、
+配置。pending 超时、失败或绑定变化清理 attempt;answer 后签发 revision 保持不可改写,
+controller 另持 current route revision。只有 exact edge/session/share 与 parent downstream
+budget 仍成立时才先发 carry、再发新的 active authority;否则撤销该 edge owner。普通 PC、其他 edge、
Source-only Native 与 authenticated snapshot 继续 STUN-only。凭据不进入 URL、日志、browser
storage、room row 或 SQLite。
@@ -343,7 +344,7 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
- RoomStore 的随机临时房间、TTL、Host token/Viewer grant 摘要验证、private/public policy、grant 到期/跨房拒绝、rotate/revoke 强撤销、停止分享等待、Viewer 上限和超额拒绝;
- SQLite 房间库从 `1` 自增、重启恢复、v1/v2 -> v3 单事务迁移、nullable 32-byte grant 与 48-byte password material CHECK、畸形值 fail-closed、rotate/revoke/password 写失败原子性和数据最小化;数据库路径无 site access 时启动失败;
- STUN/TURN UDP URL 严格校验、生产 STUN 必需、selected-edge tuple 完整性/TTL/secret 独立性、issuer HMAC/expiry/opaque tag、当前 route/session/revision/old-new connection generation 与 one-use rebuild guard,以及 ordinary peer、未命中房间和 Native 的 STUN-only isolation;LiveKit `sfu-config` 保持独立边界;
-- 单一 `screener-v4` 信令 literal、v3 旧页面 mismatch 的一次性刷新终态,以及协议非法 JSON、未知消息、错误方向、跨房间目标和 payload 限制;
+- 单一 `screener-v5` 信令 literal、v3 旧页面 mismatch 的一次性刷新终态,以及协议非法 JSON、未知消息、错误方向、跨房间目标和 payload 限制;
- 质量协议的 host 授权、严格字段与数值范围、last-wins、当前/未来 relay、已配置 SFU 和普通 P2P wire 兼容;sender 的四字段 requested/applied 读回、拒绝与持续受限提示;screen audio SDP helper 覆盖 CRLF、existing/missing fmtp、unknown key preservation、幂等、payload number、rejected/non-audio,以及 empty/no-Opus/ambiguous/parser 异常原对象 fallback,`ViewerPeer` 覆盖 initial/restart/rebuild 时同一结果的 local/signaling 一致性,SFU publisher 精确断言 high-quality stereo/forceStereo/DTX 且不覆盖 RED;
- HTTP/WS 集成:nginx per-source site-access `limit_req` 与统一错误不泄露 secret,应用不建立 IP limiter 状态;Viewer 可在 Origin/容量门下 upgrade;Host 首条鉴权同时要求 upgrade-captured site access 与 Host token,Viewer 要么持 exact-room grant,要么先有 site access 再按 room policy;site-access cookie 不绕过 private grant/password,grant/password 不能建房、取得 Host 或跨房。覆盖 fragment/sessionStorage/replaceState、无 site access 的 public/password code-only 统一拒绝、通过 site access 后的 public/password 进入、不含明文于 URL/浏览器持久存储/SQLite/log、Native capability isolation,以及 rotate/revoke 后 grace/route 清理、旧 Viewer/上游媒体边关闭和 reconnect 拒绝;
- 客户端策略与 stats 解析:会话替换不重连,ordinary ICE、LiveKit 与 selected-edge TURN protocol 分离,远端 TURN transport 保持未知;
@@ -398,9 +399,9 @@ STUN-only;只有 controller-selected edge 可接收一次短期 grant。该边
所有边都继续使用标准 WebRTC。每名 viewer 播放收到的 remote `MediaStream`,并把同一组 remote tracks 加入最多两个 child 各自独立的 `RTCPeerConnection`。该路径会逐跳解码并为每个 outbound sender 重编码;实验必须记录每层 encode time、CPU/GPU、`qualityLimitationReason`、帧率、分辨率和延迟,不能称为 zero-copy 或 shared encode。
-固定 `2` 是当前上线档而非永久产品上限;后续统一 evidence-driven controller 可在独立验收后使用离散 `0/1/2/3`,不按 device/UA 分支,并由持续 sender bitrate、`availableOutgoingBitrate`、区间 encode time、`qualityLimitationReason`、loss/RTT 健康窗、server deployment hard ceiling 与 cooldown 共同限界。本次 slice 不实现该动态控制。H.264、hardware encode 或 shared encode 可降低编码成本或同观感码率,但每个 child 的网络副本仍独立存在。
+部署参数 `MAX_PEER_RELAY_DOWNSTREAM_EDGES` 默认 `2`、允许 `1/2/3`,统一约束 Host、Viewer、SFU publication 与 selected-edge overlay;客户端绝对能力为三,服务端按部署值钳制,SFU root 预算仍独立最多二。动态 evidence-driven capacity 仍须独立验收,不按 device/UA 分支,并由持续 sender bitrate、`availableOutgoingBitrate`、区间 encode time、`qualityLimitationReason`、loss/RTT 健康窗与 cooldown 共同限界。H.264、hardware encode 或 shared encode 可降低编码成本或同观感码率,但每个 child 的网络副本仍独立存在。
-Peer-assisted 信令只接受一个严格对象:`resolution` 为 `720p | 1080p | 1440p`,`maxFramerate` 为 15 至 60 的整数,`maxBitrate` 为 2,000,000 至 12,000,000 的整数,`degradationPreference` 为 `maintain-resolution | balanced | maintain-framerate`,可选 `videoCodec` 为 `automatic | h264 | vp8`,其余字段和越界值拒绝。服务端用房间内存 Map 保存完整设置,默认 1080p60、8 Mbps、`balanced`、`automatic`,不写 SQLite;停止分享时保留,房间被放弃或过期时删除。只有 peer-assisted host 可更新,鉴权快照和在线广播携带同一设置;本 wire 由 `screener-v4` 隔离旧页面,普通 P2P 严格鉴权结构不变。SFU publisher 复用同一设置。
+Peer-assisted 信令只接受一个严格对象:`resolution` 为 `720p | 1080p | 1440p`,`maxFramerate` 为 15 至 60 的整数,`maxBitrate` 为 2,000,000 至 12,000,000 的整数,`degradationPreference` 为 `maintain-resolution | balanced | maintain-framerate`,可选 `videoCodec` 为 `automatic | h264 | vp8`,其余字段和越界值拒绝。服务端用房间内存 Map 保存完整设置,默认 1080p60、8 Mbps、`balanced`、`automatic`,不写 SQLite;停止分享时保留,房间被放弃或过期时删除。只有 peer-assisted host 可更新,鉴权快照和在线广播携带同一设置;本 wire 由 `screener-v5` 隔离旧页面,普通 P2P 严格鉴权结构不变。SFU publisher 复用同一设置。
Viewer 在处理 peer-assisted 鉴权快照时先更新 `ViewerRelay` 的 desired settings,再应用拓扑分配;同一个串行队列协调 remote stream、当前 child 更新和以后重建的 child,因此它们读取同一最新目标。每个 `HostPeer` 也把初始 sender 配置、`replaceStream()` 和 `updateProfile()` 放进同一 sender-mutation queue;desired settings 在入队前同步更新,已排队操作执行时读取最新值,使快速连续修改保持 last-wins,而不增加版本号或确认协议。这里同步的是浏览器 sender 的目标上限,不是实际分辨率、帧率、码率或 shared encoding 的性能保证。
diff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
index a76e9925..a6019fdb 100644
--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
@@ -26,7 +26,7 @@
- [ ] 一对多观看:当前安全默认上限为 8、可配置范围为 1 至 16;自动分布式拓扑验收后,同一 release 将默认值和上限改为 20。当前 PoC 的逐观看者连接是测量基线,不再是超过两名观看者时的目标拓扑;未通过 20 人门禁时继续明确拒绝超额加入。
- [ ] 端点 fanout 硬上限:任一非服务器端点任何时刻最多维护两条 active downstream media edges,包括加入、断线、换父和恢复过程;上游接收不计入这项上传预算。普通 Web relay 统一声明最多两个 child,不按 UA、设备类型或页面可见性另建容量策略;实际 edge 失败进入同一有界换父路径。第三名及后续观看者由系统自动分配给通过验收的 peer-assisted 拓扑,不能隐藏地回退为 Host 第三条连接。没有可行 peer path 时,SFU 作为主要中央兜底 virtual parent 正常向一至两个必要 roots 送流;媒体到达 root 后其余可行观看者仍优先沿受限 peer descendants 扩散。多个无法挂到健康 root 的极端 viewer 可成为额外 server-fed 例外,但必须受显式中央 egress/admission 上限约束,不能无界整房 fanout。TURN 只作为可选的极端网络 transport 兼容层,不定义房间拓扑。
- [ ] P2P 优先:每条逻辑媒体边的 ICE 必须先尝试直接 UDP 路径,服务器不得默认中转可直连的媒体。一个或两个观看者优先直接连接分享端;更多观看者的 peer-assisted 行为须先通过 ADR-0004 的实验门槛。
-- [ ] NAT 与传输兜底:STUN 必须可用,所有 ordinary peer `RTCPeerConnection` 只接收 STUN ICE servers。PC 失败后按一次 ICE restart、一次同 parent rebuild、一个 alternate peer、再 SFU/UDP virtual parent 的顺序恢复,任一步成功即停止;只有该 edge 的 SFU/UDP 也失败后,controller 才可授权一次短期 authenticated selected-edge TURN/UDP rebuild。授权必须绑定当前 room/share generation、viewer/parent session、route revision 与 old/new connection identity,成功、失败、超时或代次变化即消费;同一房间同时 pending 或 active 的 `peer-selected` attempt 总数最多为一,`host-sfu-ingress` 使用独立状态且不占该 last-mile 名额。不得按 participant、房间或普通 peer PC 下发,source-only Native 保持 STUN-only。凭据不进入 URL、日志、浏览器持久化或 SQLite。Coturn 只验证 HMAC 与 expiry,应用必须重验 edge 代次并用短 TTL、one-use state 与 quota 限界。媒体路径保持 UDP-only;全部 UDP 路径耗尽后明确失败。HTTPS/WSS 仍独立使用 TLS/TCP。
+- [ ] NAT 与传输兜底:STUN 必须可用,所有 ordinary peer `RTCPeerConnection` 只接收 STUN ICE servers。PC 失败后按一次 ICE restart、一次同 parent rebuild、一个 alternate peer、再 SFU/UDP virtual parent 的顺序恢复,任一步成功即停止;只有该 edge 的 SFU/UDP 也失败后,controller 才可授权一次短期 authenticated selected-edge TURN/UDP rebuild。授权必须绑定 room/share generation、viewer/parent session、签发时 route revision 与 old/new connection identity;answer 后只在 exact edge/session/share 与 parent downstream budget 仍成立时跨无关 route revision carry,且 carry 必须先于新 active authority。失败、超时或任一绑定/预算失效即撤销;同一房间同时 pending 或 active 的 `peer-selected` attempt 总数最多为一,`host-sfu-ingress` 使用独立状态且不占该 last-mile 名额。不得按 participant、房间或普通 peer PC 下发,source-only Native 保持 STUN-only。凭据不进入 URL、日志、浏览器持久化或 SQLite。Coturn 只验证 HMAC 与 expiry,应用必须重验 edge 代次并用短 TTL、one-use state 与 quota 限界。媒体路径保持 UDP-only;全部 UDP 路径耗尽后明确失败。HTTPS/WSS 仍独立使用 TLS/TCP。
- [ ] 质量控制:保留 1080p60(8 Mbps)、1080p30(5 Mbps)、720p30(3 Mbps)三档推荐上限,三档与高级设置初始值统一采用 `balanced`(平衡)与 `automatic`(自动编码),`maintain-resolution`(清晰优先)、`maintain-framerate`(流畅优先)和 H.264/VP8 保留为显式选择;分享期间可直接换档或应用有界高级设置,不重新选择来源或重建健康连接,codec 在直播中锁定并于下一次分享生效。Peer-assisted relay 与已配置的 SFU 必须接收同一个严格校验的房间级权威设置,覆盖当前和以后建立的 sender;普通 P2P 信令结构保持不变。任何设置都只是浏览器上限和偏好,具体降级由浏览器决定;必须读回实际 sender 参数并通过 stats 观测结果、显示参数拒绝、改写和持续受限原因。不做自定义动态 FPS、综合评分或周期性全房间调档。
- [ ] 路径隔离双表示:direct/peer 继续使用每条 PeerConnection 独立的 stock WebRTC GCC,不把任何 viewer 反馈合成全房目标。每条 SFU path 从 `HIGH` ceiling 开始;优先用 pinned LiveKit 2.22.0/1.13.5 的标准两层 screen-share simulcast,在 Dynacast off 下常驻 exactly `HIGH+LOW`,让内建 per-subscriber BWE 独立降层和恢复。若该 gate 通过,Screener 不实现媒体层 selector。首 gate 使用 zero-descendant SFU leaf;root-with-children 的自动 downshift 与有界迁移是 default-on 前独立硬门。只有内建选择不满足门槛时才用标准 subscriber quality 显式限制,常驻成本不合格时再测标准 sender 手动启停。`LOW` 停编只是资源优化;active representation/layer 硬上限为二,禁止按 viewer 增长。必须实测实际接收层、硬件编码证据、游戏 FPS/p1 low、CPU/GPU、区间 encode cost、上传和分层 bytes。当前 Web P2P simulcast 缺少 receiver 选 RID 和跨 PeerConnection shared-encode 契约;当前 Web/LiveKit SVC 也缺少 direct/peer 独立选层与可移植硬件保证,且 pinned screen share 强制三层 temporal-only `L1T3`,二者按现契约静态 no-go。全部标准路径失败后才考虑 custom/native dual encode。没有合格 hardware/power-efficient 路径或额外表示破坏游戏/上传预算时 fail closed:保护健康路径并明确显示弱路径降级或不可用。
- [ ] 路径级质量状态:应用的 `HIGH`/`FALLBACK` 非对称窗口只决定拓扑资格和诊断,不命令正常的媒体层切换,也不计算综合分数。SFU BWE downshift 先进入 `suspect`;多个连续窗口的 sender/viewer 关联证据确认 `FALLBACK` 后,应用不得稳定保留该 parent,并把 downstream capacity 降为 0。计划或显式质量 fallback 仅是内建路径失败后的候选:已有 children 时先在 connection/assignment generation guard 下全部迁走,失败或代次过期则保持原 assignment/quality。Autonomous downshift 无法 packet-level 预先迁移,default-on 前必须验收 descendants 的短暂影响。只有更长的稳定恢复窗口和 cooldown 后才能重新声明 relay capacity。Viewer 请求必须鉴权、限频、去重,并由 sender 的 GCC/Transport-CC、实际码率、RTT、丢包、重传、编码限制、协商 codec/profile/parameters 与 viewer 解码、丢帧、冻结证据交叉验证;不能仅凭自报生效,也不得上传 raw SDP、candidate 地址或原始设备/网络标识。
@@ -41,7 +41,7 @@
- [ ] 私密房间双入口:private room 接受现有 `/r/{code}#v={grant}` 合法邀请直接进入,或“站点访问 + 房间号 + 该房间观看密码”。没有 grant 的 `/join` 或 `/r/{code}` 先显示明确标为“站点访问”的整站验证,通过后才显示明确标为“加入房间”的当前房间密码输入;有效 site-access cookie 直接跳过第一步,但两类密码不得复用、代填或互相替代。Host 可设置、轮换或移除房间观看密码。密码接受 1 至 64 个可见 ASCII 字符;异步 scrypt 全局最多执行 2 个、等待 16 个派生。站点口令和房间密码都不得进入 URL/query/storage/log/SQLite;不存在、错误密码、队满和正确密码后的满房都返回通用结果。
-- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。合格父节点构成网状候选关系,但实际媒体保持无环且每个 Viewer 只有一个 active upstream;加入、容量变化、掉线和当前边失败触发有界重选,切换重叠必须受现有边预算与当前代媒体证据约束,不做常驻多源分片。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
+- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。合格父节点构成网状候选关系,但实际媒体保持无环且每个 Viewer 只有一个 active upstream;加入、容量变化、掉线和当前边失败触发有界重选,切换重叠必须受现有边预算与当前代媒体证据约束,不做常驻多源分片。一个 child 的已确认 C+B 质量事件仍只处理该 edge;只有同一 Viewer parent peer/session/share 在五秒内收到两个不同 child 各自三窗确认的 `severe` 或 `relative-fps`,服务端才把该 parent 的独立 relay 资格暂停 30 秒,使有效容量为零但不覆盖客户端广告。Host 不退位,parent 的上游观看不变;当前 children 只尝试其他 peer,无候选时保留旧边,退位本身不得准备 SFU/TURN。新 parent session、新分享或 30 秒到期立即/惰性恢复资格。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
- [ ] 质量控制扩展:推荐档位仍是默认入口;“高级视频设置”只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling、清晰/平衡/流畅三种偏好,以及 `自动 | H.264 | VP8` 编码选择;初始值采用 `balanced` 与 `automatic`,其余偏好和编码保留为显式选择。视频档位在直播中显式应用;codec 直播中锁定并于下一次分享生效,避免滑杆产生连续控制流量。本期不重命名该区域,也不增加音频 UI:屏幕音频固定使用一个媒体默认,所有实际浏览器 sender 请求并读回 128 kbps ceiling,DTX 关闭,Web peer 与 SFU 都显式允许 Opus stereo 并协商 128 kbps maximum average bitrate;实际码率仍由浏览器拥塞控制和 stats 决定。Peer 只在唯一明确的 active Opus audio 上做结构化、幂等的 Viewer answer `stereo=1;maxaveragebitrate=128000` 变换;非目标形态或 parser/writer 异常必须原样保留浏览器 answer,不得阻断可继续的 mono/video edge。不得用宽泛字符串/正则改 SDP,也不得改写浏览器协商的 FEC。SFU 使用 pinned SDK 的 128 kbps high-quality stereo preset、`forceStereo = true`、`dtx = false`,并保留 pinned room default `red = true`。不得暴露声道、采样率、codec、任意码率、stereo、DTX、RED 或 FEC 控件。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。未来 microphone voice 若进入范围,必须是独立 track/处理链,不能把 AEC/降噪/DTX 套到电影或游戏音频。
- [ ] SFU 质量设置生命周期:直播中修改档位时,浏览器 sender 的 applied readback、LiveKit `LocalVideoTrack` 保存的 degradation preference、track restart options 与 `LocalTrackPublication` 的 republish options 必须作为同一次串行操作更新;任一步失败恢复旧 sender 与旧 SDK 保存态,旧 publication generation 不得回写当前状态。LiveKit full reconnect/republish 不得恢复初次发布的旧偏好。该修复不改变 codec、码率上限、层数或路由,也不能单独解释即时低帧。
- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。
diff --git a/native/sender/internal/app/server_test.go b/native/sender/internal/app/server_test.go
index 669bcba4..21e2f061 100644
--- a/native/sender/internal/app/server_test.go
+++ b/native/sender/internal/app/server_test.go
@@ -632,7 +632,7 @@ func newAppRemoteServer(t *testing.T, terminal chan<- []byte) *httptest.Server {
if _, _, err = connection.Read(request.Context()); err != nil {
return
}
- authenticated := []byte(`{"type":"authenticated","protocol":"screener-v4","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":[],"iceConfig":{"iceServers":[]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678"}`)
+ authenticated := []byte(`{"type":"authenticated","protocol":"screener-v5","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":[],"iceConfig":{"iceServers":[]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678"}`)
if err = connection.Write(request.Context(), websocket.MessageText, authenticated); err != nil {
return
}
@@ -688,7 +688,7 @@ func newDelayedAppRemoteServer(
<-releaseAuthentication
writeContext, cancelWrite := context.WithTimeout(context.Background(), time.Second)
defer cancelWrite()
- _ = connection.Write(writeContext, websocket.MessageText, []byte(`{"type":"authenticated","protocol":"screener-v4","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":[],"iceConfig":{"iceServers":[]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678"}`))
+ _ = connection.Write(writeContext, websocket.MessageText, []byte(`{"type":"authenticated","protocol":"screener-v5","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":[],"iceConfig":{"iceServers":[]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678"}`))
})
return server
}
diff --git a/native/sender/internal/remote/session.go b/native/sender/internal/remote/session.go
index 99963ac3..03946e3c 100644
--- a/native/sender/internal/remote/session.go
+++ b/native/sender/internal/remote/session.go
@@ -24,7 +24,7 @@ import (
)
const (
- maxHostEdges = 2
+ maxHostEdges = 3
maxRemoteResponse = 64 << 10
remoteRequestTimeout = 10 * time.Second
signalWriteTimeout = 5 * time.Second
diff --git a/native/sender/internal/remote/wire.go b/native/sender/internal/remote/wire.go
index 6cb91dc4..febc4257 100644
--- a/native/sender/internal/remote/wire.go
+++ b/native/sender/internal/remote/wire.go
@@ -16,7 +16,7 @@ import (
)
const (
- signalingProtocol = "screener-v4"
+ signalingProtocol = "screener-v5"
maxProtocolViewers = 16
maxRouteRevision = int64(1<<53 - 1)
maxSignalSDPBytes = 48 << 10
diff --git a/native/sender/internal/remote/wire_test.go b/native/sender/internal/remote/wire_test.go
index cda9dc78..602201bc 100644
--- a/native/sender/internal/remote/wire_test.go
+++ b/native/sender/internal/remote/wire_test.go
@@ -6,9 +6,9 @@ import (
"testing"
)
-const validHostAuthenticated = `{"type":"authenticated","protocol":"screener-v4","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":[],"iceConfig":{"iceServers":[{"urls":["stun:example.test"]}]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678"}`
+const validHostAuthenticated = `{"type":"authenticated","protocol":"screener-v5","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":[],"iceConfig":{"iceServers":[{"urls":["stun:example.test"]}]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678"}`
-const validPeerAssistedHostAuthenticated = `{"type":"authenticated","protocol":"screener-v4","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":["viewer-1","viewer-2"],"iceConfig":{"iceServers":[{"urls":["stun:example.test"]}]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678","mediaMode":"peer-assisted","mediaAssignment":{"parentPeerId":null,"childPeerIds":["viewer-1","viewer-2"]},"routeRevision":7,"routeAssignment":{"upstream":{"kind":"none"},"childPeerIds":["viewer-1","viewer-2"],"sfuPublicationGeneration":null},"qualitySettings":{"resolution":"1080p","maxFramerate":60,"maxBitrate":8000000,"degradationPreference":"maintain-resolution","videoCodec":"automatic"}}`
+const validPeerAssistedHostAuthenticated = `{"type":"authenticated","protocol":"screener-v5","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":["viewer-1","viewer-2","viewer-3"],"iceConfig":{"iceServers":[{"urls":["stun:example.test"]}]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678","mediaMode":"peer-assisted","mediaAssignment":{"parentPeerId":null,"childPeerIds":["viewer-1","viewer-2","viewer-3"]},"routeRevision":7,"routeAssignment":{"upstream":{"kind":"none"},"childPeerIds":["viewer-1","viewer-2","viewer-3"],"sfuPublicationGeneration":null},"qualitySettings":{"resolution":"1080p","maxFramerate":60,"maxBitrate":8000000,"degradationPreference":"maintain-resolution","videoCodec":"automatic"}}`
func TestMarshalHostSignalShapes(t *testing.T) {
mid := "0"
@@ -69,15 +69,15 @@ func TestDecodePeerAssistedHostAuthentication(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if !message.PeerAssisted || message.RouteRevision != 7 || len(message.MediaAssignment.ChildPeerIDs) != 2 {
+ if !message.PeerAssisted || message.RouteRevision != 7 || len(message.MediaAssignment.ChildPeerIDs) != 3 {
t.Fatalf("peer-assisted authentication = %+v", message)
}
}
func TestDecodePeerAssistedHostAuthenticationRejectsInvalidAuthority(t *testing.T) {
tests := map[string]func(map[string]any){
- "third-child": func(message map[string]any) {
- children := []any{"viewer-1", "viewer-2", "viewer-3"}
+ "fourth-child": func(message map[string]any) {
+ children := []any{"viewer-1", "viewer-2", "viewer-3", "viewer-4"}
message["mediaAssignment"].(map[string]any)["childPeerIds"] = children
message["routeAssignment"].(map[string]any)["childPeerIds"] = children
},
diff --git a/scripts/check-project-state.ps1 b/scripts/check-project-state.ps1
index d22ec358..70821003 100644
--- a/scripts/check-project-state.ps1
+++ b/scripts/check-project-state.ps1
@@ -25,10 +25,10 @@ $statusBytes = (Get-Item docs/status.md).Length
if ($agentLines -gt 200) {
throw "AGENTS.md exceeds the 200-line context budget: $agentLines lines"
}
-if ($memoryLines -gt 200 -or $memoryBytes -gt 12000) {
+if ($memoryLines -gt 200 -or $memoryBytes -gt 16000) {
throw "docs/project-memory.md exceeds its budget: $memoryLines lines, $memoryBytes bytes"
}
-if ($statusLines -gt 120 -or $statusBytes -gt 8000) {
+if ($statusLines -gt 120 -or $statusBytes -gt 12000) {
throw "docs/status.md exceeds its budget: $statusLines lines, $statusBytes bytes"
}
diff --git a/scripts/check-project-state.sh b/scripts/check-project-state.sh
index 853d4c56..9b9c2af1 100755
--- a/scripts/check-project-state.sh
+++ b/scripts/check-project-state.sh
@@ -23,12 +23,12 @@ if [ "$agent_lines" -gt 200 ]; then
exit 1
fi
-if [ "$memory_lines" -gt 200 ] || [ "$memory_bytes" -gt 12000 ]; then
+if [ "$memory_lines" -gt 200 ] || [ "$memory_bytes" -gt 16000 ]; then
echo "docs/project-memory.md exceeds its budget: $memory_lines lines, $memory_bytes bytes" >&2
exit 1
fi
-if [ "$status_lines" -gt 120 ] || [ "$status_bytes" -gt 8000 ]; then
+if [ "$status_lines" -gt 120 ] || [ "$status_bytes" -gt 12000 ]; then
echo "docs/status.md exceeds its budget: $status_lines lines, $status_bytes bytes" >&2
exit 1
fi
diff --git a/src/client/media/relay-capability.ts b/src/client/media/relay-capability.ts
index 557589bd..fc53aa2d 100644
--- a/src/client/media/relay-capability.ts
+++ b/src/client/media/relay-capability.ts
@@ -1,4 +1,7 @@
-import type { ClientMessage } from "../../shared/protocol";
+import {
+ MAX_PEER_RELAY_DOWNSTREAM_EDGES,
+ type ClientMessage,
+} from "../../shared/protocol";
type RelayCapacityMessage = Extract<
ClientMessage,
@@ -13,6 +16,6 @@ export function relayCapacityMessageForBrowser(
}
return {
type: "relay-capacity",
- downstreamEdges: 2,
+ downstreamEdges: MAX_PEER_RELAY_DOWNSTREAM_EDGES,
};
}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 8abb9052..3a7bad47 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -117,6 +117,12 @@ type SelectedEdgeTurn = Extract<
ServerMessage,
{ type: "selected-edge-turn"; edgeKind: "peer-selected" }
>;
+interface ActiveSelectedHostChild {
+ peerId: string;
+ connectionId: string;
+ currentRouteRevision: number;
+ pendingCarryRevision: number | null;
+}
interface CaptureDetails {
resolution: string;
@@ -251,6 +257,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const iceConfigRef = useRef<IceConfig | null>(null);
const peersRef = useRef(new Map<string, HostPeer>());
const retiredConnectionsRef = useRef(new Map<string, string>());
+ const selectedHostChildRef = useRef<ActiveSelectedHostChild | null>(null);
const hostPeerIdRef = useRef<string | null>(null);
const viewerQualityEvidenceRef = useRef(
new Map<string, ViewerQualityEvidence>(),
@@ -347,6 +354,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
peersRef.current.forEach((peer) => peer.dispose());
peersRef.current.clear();
retiredConnectionsRef.current.clear();
+ selectedHostChildRef.current = null;
hostPeerIdRef.current = null;
viewerQualityEvidenceTimersRef.current.forEach((timer) =>
window.clearTimeout(timer),
@@ -450,6 +458,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
peersRef.current.forEach((peer) => peer.dispose());
peersRef.current.clear();
retiredConnectionsRef.current.clear();
+ selectedHostChildRef.current = null;
hostPeerIdRef.current = null;
void hostSfuRouteRef.current?.disconnect();
hostSfuRouteRef.current = null;
@@ -761,6 +770,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
retiredConnectionsRef.current.set(peerId, peer.connectionId);
peer.dispose();
}
+ if (selectedHostChildRef.current?.peerId === peerId) {
+ selectedHostChildRef.current = null;
+ }
peersRef.current.delete(peerId);
setPeerSnapshots((current) => {
const next = new Map(current);
@@ -794,6 +806,25 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
return;
}
+ const reportSelectedTurnFailure = (connectionId: string): void => {
+ const selected = selectedHostChildRef.current;
+ if (
+ !selectedTurn ||
+ selected?.peerId !== peerId ||
+ selected.connectionId !== connectionId ||
+ !isCurrentGeneration(generation) ||
+ signalRef.current !== signal
+ ) {
+ return;
+ }
+ signal.send({
+ type: "route-failed",
+ revision: selected.currentRouteRevision,
+ phase: "active",
+ connectionId,
+ });
+ };
+
let peer: HostPeer;
peer = new HostPeer(
peerId,
@@ -811,6 +842,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
peersRef.current.get(peerId) === peer
) {
if (selectedTurn && snapshot.connectionState === "failed") {
+ reportSelectedTurnFailure(peer.connectionId);
removePeer(peerId);
return;
}
@@ -827,6 +859,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
started = await peer.start();
} catch (error) {
if (peersRef.current.get(peerId) === peer) {
+ reportSelectedTurnFailure(peer.connectionId);
removePeer(peerId);
}
throw error;
@@ -835,6 +868,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
return;
}
+ reportSelectedTurnFailure(peer.connectionId);
removePeer(peerId);
if (selectedTurn || !isCurrentGeneration(generation) || attempt >= 1) {
return;
@@ -896,9 +930,20 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
childPeerIds: string[],
generation: number,
): void {
+ const selected = selectedHostChildRef.current;
+ const selectedIsCurrent =
+ selected?.currentRouteRevision === activeRouteRevisionRef.current &&
+ peersRef.current.get(selected.peerId)?.connectionId ===
+ selected.connectionId;
+ const effectiveChildPeerIds = selectedIsCurrent
+ ? [...new Set([...childPeerIds, selected.peerId])]
+ : childPeerIds;
+ if (selected && !selectedIsCurrent) {
+ selectedHostChildRef.current = null;
+ }
reconcileBoundedMediaChildren(
peersRef.current.keys(),
- childPeerIds,
+ effectiveChildPeerIds,
MAX_HOST_MEDIA_CHILDREN,
removePeer,
(peerId) => {
@@ -920,6 +965,10 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
return;
}
if (message.type === "authenticated" && message.role === "host") {
+ const selected = selectedHostChildRef.current;
+ if (selected) {
+ removePeer(selected.peerId);
+ }
hostPeerIdRef.current = message.peerId;
setViewerAccessUpdating(false);
clearAllViewerQualityEvidence();
@@ -982,6 +1031,19 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
return;
}
const current = peersRef.current.get(message.viewerPeerId);
+ const selected = selectedHostChildRef.current;
+ if (
+ peerAssistedRef.current &&
+ message.parentPeerId === hostPeerIdRef.current &&
+ selected?.peerId === message.viewerPeerId &&
+ selected.connectionId === message.newConnectionId &&
+ current?.connectionId === selected.connectionId &&
+ message.revision >= selected.currentRouteRevision
+ ) {
+ selected.currentRouteRevision = message.revision;
+ selected.pendingCarryRevision = message.revision;
+ return;
+ }
const oldConnectionId =
current?.connectionId ??
retiredConnectionsRef.current.get(message.viewerPeerId);
@@ -995,6 +1057,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
if (current) {
removePeer(message.viewerPeerId);
}
+ selectedHostChildRef.current = {
+ peerId: message.viewerPeerId,
+ connectionId: message.newConnectionId,
+ currentRouteRevision: message.revision,
+ pendingCarryRevision: null,
+ };
void startPeer(message.viewerPeerId, generation, 0, message);
}
return;
@@ -1039,6 +1107,14 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
}
if (message.type === "route-update") {
if (peerAssistedRef.current) {
+ if (message.phase === "active") {
+ const selected = selectedHostChildRef.current;
+ if (selected?.pendingCarryRevision === message.revision) {
+ selected.pendingCarryRevision = null;
+ } else if (selected) {
+ removePeer(selected.peerId);
+ }
+ }
if (
message.phase === "active" &&
message.revision !== activeRouteRevisionRef.current
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index b537d55d..47c4a747 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -69,6 +69,7 @@ import type {
import {
limitMediaAssignment,
MAX_VIEWER_MEDIA_CHILDREN,
+ retainSelectedMediaParent,
viewerRestartMessage,
viewerSignalMessage,
} from "../webrtc/media-assignment";
@@ -88,6 +89,11 @@ type SelectedEdgeTurn = Extract<
ServerMessage,
{ type: "selected-edge-turn"; edgeKind: "peer-selected" }
>;
+interface ActiveSelectedEdgeTurn {
+ grant: SelectedEdgeTurn;
+ currentRouteRevision: number;
+ pendingCarryRevision: number | null;
+}
interface SfuUpstreamState {
connectionState: "connected" | "reconnecting";
metrics: ConnectionMetrics | null;
@@ -230,7 +236,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
parentPeerId: string;
connectionId: string;
} | null = null;
- let selectedEdgeTurn: SelectedEdgeTurn | null = null;
+ let selectedEdgeTurn: ActiveSelectedEdgeTurn | null = null;
const messageAuthority = new ViewerMessageAuthority();
let sfuStandbyPrewarmer: SfuStandbyPrewarmer | null = null;
let relayChildEvidenceCurrent: ViewerQualityEvidence | null = null;
@@ -362,6 +368,20 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
payload,
})
: false,
+ onSelectedEdgeFailed: (
+ _childPeerId,
+ connectionId,
+ revision,
+ ) => {
+ if (active && peerAssisted) {
+ signal.send({
+ type: "route-failed",
+ revision,
+ phase: "active",
+ connectionId,
+ });
+ }
+ },
onUpdate: (snapshot) => {
if (active) {
setRelaySnapshot(snapshot);
@@ -682,7 +702,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
const peer = new ViewerPeer(
selectedEdgeTurn
- ? { iceServers: [selectedEdgeTurn.iceServer] }
+ ? { iceServers: [selectedEdgeTurn.grant.iceServer] }
: currentIceConfig,
{
sendSignal: (targetPeerId, payload) =>
@@ -760,12 +780,12 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
return true;
}
if (
- selectedEdgeTurn?.parentPeerId === parentPeerId &&
- selectedEdgeTurn.newConnectionId === connectionId
+ selectedEdgeTurn?.grant.parentPeerId === parentPeerId &&
+ selectedEdgeTurn.grant.newConnectionId === connectionId
) {
signal.send({
type: "route-failed",
- revision: selectedEdgeTurn.revision,
+ revision: selectedEdgeTurn.currentRouteRevision,
phase: "active",
connectionId,
});
@@ -792,7 +812,12 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
authorityToken: number,
): Promise<void> {
if (message.type === "authenticated") {
+ const hadSelectedUpstream = selectedEdgeTurn !== null;
selectedEdgeTurn = null;
+ if (hadSelectedUpstream) {
+ clearUpstreamState();
+ }
+ viewerRelay?.clearSelectedEdgeTurn();
viewerAuthenticated = true;
setAccessState("ready");
setViewerPasswordDraft("");
@@ -907,6 +932,16 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
);
return;
}
+ if (
+ selectedEdgeTurn?.grant.parentPeerId === message.parentPeerId &&
+ selectedEdgeTurn.grant.viewerPeerId === message.viewerPeerId &&
+ selectedEdgeTurn.grant.newConnectionId === message.newConnectionId &&
+ message.revision >= selectedEdgeTurn.currentRouteRevision
+ ) {
+ selectedEdgeTurn.currentRouteRevision = message.revision;
+ selectedEdgeTurn.pendingCarryRevision = message.revision;
+ return;
+ }
if (
message.revision !== currentRouteRevision ||
Date.parse(message.expiresAt) <= Date.now()
@@ -922,7 +957,11 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
) {
return;
}
- selectedEdgeTurn = message;
+ selectedEdgeTurn = {
+ grant: message,
+ currentRouteRevision: message.revision,
+ pendingCarryRevision: null,
+ };
clearViewerSfuRoute();
clearUpstreamState();
acceptAssignedRoute(message.revision, {
@@ -938,17 +977,43 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
if (message.type === "route-update") {
if (peerAssisted) {
- if (message.phase === "active") {
- if (message.revision !== currentRouteRevision) {
- viewerRelay?.clearSelectedEdgeTurn();
- }
- if (selectedEdgeTurn?.revision !== message.revision) {
- selectedEdgeTurn = null;
+ if (
+ message.phase === "active" &&
+ message.revision >= currentRouteRevision
+ ) {
+ viewerRelay?.acceptActiveRevision(message.revision);
+ if (selectedEdgeTurn) {
+ if (
+ selectedEdgeTurn.pendingCarryRevision === message.revision
+ ) {
+ selectedEdgeTurn.pendingCarryRevision = null;
+ } else {
+ selectedEdgeTurn = null;
+ clearUpstreamState();
+ }
}
if (message.revision !== currentRouteRevision) {
clearRelayChildEvidence();
}
currentRouteRevision = message.revision;
+ if (selectedEdgeTurn) {
+ applyMediaAssignment(
+ {
+ parentPeerId: selectedEdgeTurn.grant.parentPeerId,
+ childPeerIds: message.assignment.childPeerIds,
+ },
+ true,
+ );
+ acceptAssignedRoute(
+ message.revision,
+ {
+ kind: "peer",
+ peerId: selectedEdgeTurn.grant.parentPeerId,
+ },
+ "active",
+ );
+ return;
+ }
}
const result = ensureViewerSfuRoute().accept(message);
if (result !== "stale") {
@@ -973,7 +1038,15 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
if (message.type === "media-assignment") {
if (peerAssisted && !viewerSfuRoute) {
- applyMediaAssignment(message.mediaAssignment);
+ applyMediaAssignment(
+ selectedEdgeTurn
+ ? retainSelectedMediaParent(
+ message.mediaAssignment,
+ selectedEdgeTurn.grant.parentPeerId,
+ )
+ : message.mediaAssignment,
+ selectedEdgeTurn !== null,
+ );
}
return;
}
@@ -1046,6 +1119,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
return;
}
if (message.type === "sharing-stopped") {
+ selectedEdgeTurn = null;
setSfuStandbyUrl(null);
setAssignedRoute(null);
currentHostOnline = false;
diff --git a/src/client/webrtc/media-assignment.ts b/src/client/webrtc/media-assignment.ts
index b50b4977..8d32f358 100644
--- a/src/client/webrtc/media-assignment.ts
+++ b/src/client/webrtc/media-assignment.ts
@@ -3,9 +3,10 @@ import type {
MediaAssignment,
SignalPayload,
} from "../../shared/protocol";
+import { MAX_PEER_RELAY_DOWNSTREAM_EDGES } from "../../shared/protocol";
-export const MAX_HOST_MEDIA_CHILDREN = 2;
-export const MAX_VIEWER_MEDIA_CHILDREN = 2;
+export const MAX_HOST_MEDIA_CHILDREN = MAX_PEER_RELAY_DOWNSTREAM_EDGES;
+export const MAX_VIEWER_MEDIA_CHILDREN = MAX_PEER_RELAY_DOWNSTREAM_EDGES;
export function limitMediaAssignment(
assignment: MediaAssignment,
@@ -17,6 +18,16 @@ export function limitMediaAssignment(
};
}
+export function retainSelectedMediaParent(
+ assignment: MediaAssignment,
+ parentPeerId: string,
+): MediaAssignment {
+ return {
+ parentPeerId,
+ childPeerIds: assignment.childPeerIds,
+ };
+}
+
export function reconcileBoundedMediaChildren(
currentPeerIds: Iterable<string>,
nextChildPeerIds: readonly string[],
diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.ts
index f66376ab..1cd65e42 100644
--- a/src/client/webrtc/viewer-relay.ts
+++ b/src/client/webrtc/viewer-relay.ts
@@ -11,6 +11,11 @@ import { MAX_VIEWER_MEDIA_CHILDREN } from "./media-assignment";
interface ViewerRelayEvents {
sendSignal: (peerId: string, payload: SignalPayload) => boolean;
onUpdate?: (snapshot: PeerSnapshot | null) => void;
+ onSelectedEdgeFailed?: (
+ childPeerId: string,
+ connectionId: string,
+ revision: number,
+ ) => void;
}
type SelectedEdgeTurn = Extract<
ServerMessage,
@@ -20,6 +25,7 @@ interface SelectedChildConnection {
peerId: string;
connectionId: string;
revision: number;
+ pendingCarryRevision: number | null;
}
export class ViewerRelay {
@@ -60,6 +66,17 @@ export class ViewerRelay {
currentPeer?.connectionId ??
this.retiredConnections.get(message.viewerPeerId);
const selected = this.selectedChildConnection;
+ if (
+ selected?.peerId === message.viewerPeerId &&
+ selected.connectionId === message.newConnectionId &&
+ currentPeer?.connectionId === selected.connectionId &&
+ message.parentPeerId === parentPeerId &&
+ message.revision >= selected.revision
+ ) {
+ selected.revision = message.revision;
+ selected.pendingCarryRevision = message.revision;
+ return true;
+ }
const retainedChildPeerIds = selected
? this.childPeerIds.filter((peerId) => peerId !== selected.peerId)
: this.childPeerIds;
@@ -86,6 +103,7 @@ export class ViewerRelay {
peerId: message.viewerPeerId,
connectionId: message.newConnectionId,
revision: message.revision,
+ pendingCarryRevision: null,
};
this.startPeer(message.viewerPeerId, stream, 0, message);
return true;
@@ -103,6 +121,18 @@ export class ViewerRelay {
this.disposePeer(selected.peerId);
}
+ acceptActiveRevision(revision: number): void {
+ const selected = this.selectedChildConnection;
+ if (!selected) {
+ return;
+ }
+ if (selected.pendingCarryRevision === revision) {
+ selected.pendingCarryRevision = null;
+ return;
+ }
+ this.clearSelectedEdgeTurn();
+ }
+
setChildren(childPeerIds: readonly string[]): void {
if (this.disposed) {
return;
@@ -330,7 +360,7 @@ export class ViewerRelay {
snapshot.connectionId === peer.connectionId
) {
if (selectedTurn && snapshot.connectionState === "failed") {
- this.disposePeer(childPeerId);
+ this.failSelectedChild(childPeerId, peer.connectionId);
return;
}
this.snapshots.set(childPeerId, {
@@ -352,6 +382,10 @@ export class ViewerRelay {
if (started || this.peers.get(childPeerId) !== peer) {
return;
}
+ if (selectedTurn) {
+ this.failSelectedChild(childPeerId, peer.connectionId);
+ return;
+ }
this.disposePeer(childPeerId);
if (
!selectedTurn &&
@@ -367,6 +401,22 @@ export class ViewerRelay {
});
}
+ private failSelectedChild(childPeerId: string, connectionId: string): void {
+ const selected = this.selectedChildConnection;
+ if (
+ selected?.peerId !== childPeerId ||
+ selected.connectionId !== connectionId
+ ) {
+ return;
+ }
+ this.events.onSelectedEdgeFailed?.(
+ childPeerId,
+ connectionId,
+ selected.revision,
+ );
+ this.disposePeer(childPeerId);
+ }
+
private disposePeers(): void {
for (const childPeerId of [...this.peers.keys()]) {
this.disposePeer(childPeerId);
diff --git a/src/server/app.ts b/src/server/app.ts
index 8f1679fc..e0ecc71d 100644
--- a/src/server/app.ts
+++ b/src/server/app.ts
@@ -111,6 +111,7 @@ export async function createScreenerServer(
server: httpServer,
roomStore,
peerAssistedMedia: config.peerAssistedMedia,
+ maxPeerRelayDownstreamEdges: config.maxPeerRelayDownstreamEdges,
...(sfuFallback ? { sfuFallback } : {}),
...(config.selectedEdgeTurn ? { selectedEdgeTurn: config.selectedEdgeTurn } : {}),
ice: iceOptions,
diff --git a/src/server/config.ts b/src/server/config.ts
index 7a0ccdea..36ea590b 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -1,5 +1,7 @@
import {
+ DEFAULT_PEER_RELAY_DOWNSTREAM_EDGES,
MAX_ICE_SERVER_URLS,
+ MAX_PEER_RELAY_DOWNSTREAM_EDGES,
MAX_VIEWERS_PER_ROOM_LIMIT,
stunUrlSchema,
turnUrlSchema,
@@ -55,6 +57,7 @@ export interface ServerConfig {
maxRooms: number;
maxViewersPerRoom: number;
peerAssistedMedia: boolean;
+ maxPeerRelayDownstreamEdges: number;
livekitFallback?: LiveKitFallbackConfig;
selectedEdgeTurn?: SelectedEdgeTurnConfig;
stunUrls: readonly string[];
@@ -334,6 +337,13 @@ export function loadConfig(
false,
"PEER_ASSISTED_MEDIA",
);
+ const maxPeerRelayDownstreamEdges = parseBoundedInteger(
+ environment.MAX_PEER_RELAY_DOWNSTREAM_EDGES,
+ DEFAULT_PEER_RELAY_DOWNSTREAM_EDGES,
+ "MAX_PEER_RELAY_DOWNSTREAM_EDGES",
+ 1,
+ MAX_PEER_RELAY_DOWNSTREAM_EDGES,
+ );
const livekitFallback = parseLiveKitFallback(environment, nodeEnv);
const selectedEdgeTurn = parseSelectedEdgeTurn(environment);
@@ -403,6 +413,7 @@ export function loadConfig(
maxRooms: parsePositiveInteger(environment.MAX_ROOMS, 1_000, "MAX_ROOMS"),
maxViewersPerRoom,
peerAssistedMedia,
+ maxPeerRelayDownstreamEdges,
livekitFallback,
selectedEdgeTurn,
stunUrls,
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index 2f093875..3439b791 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -62,15 +62,19 @@ interface ViewerRouteIntent {
qualityGuard?: QualityRouteIntentGuard;
}
-interface SelectedEdgeTurnAttempt {
+interface SelectedPeerEdgeLease {
roomId: string;
- revision: number;
+ currentRouteRevision: number;
shareGeneration: string;
parentPeerId: string;
parentSessionId: string;
viewerPeerId: string;
viewerSessionId: string;
newConnectionId: string;
+ grant: Extract<
+ ServerMessage,
+ { type: "selected-edge-turn"; edgeKind: "peer-selected" }
+ >;
answered: boolean;
timer: NodeJS.Timeout;
}
@@ -144,6 +148,14 @@ interface ViewerQualityEvidenceState {
} | null;
}
+interface RelayParentQualityState {
+ parentSessionId: string;
+ shareGeneration: string;
+ lastChildPeerId: string;
+ lastConfirmedAtMs: number;
+ quarantinedUntilMs: number | null;
+}
+
interface ForwardedViewerQualityEvidence {
roomId: string;
viewerSessionId: string;
@@ -172,6 +184,7 @@ export interface SfuFallbackOptions {
export interface HybridMediaRouterOptions {
roomStore: RoomStore;
+ maxPeerRelayDownstreamEdges: RelayDownstreamEdges;
sfuFallback?: SfuFallbackOptions;
selectedEdgeTurn?: SelectedEdgeTurnConfig;
sendToSession: (sessionId: string, message: ServerMessage) => void;
@@ -206,7 +219,7 @@ export interface AuthenticatedRouteParticipant {
}
export class HybridMediaRouter {
- private readonly peerRelayTopology = new PeerRelayTopology();
+ private readonly peerRelayTopology: PeerRelayTopology;
private readonly mediaRouteControllers = new Map<
string,
MediaRouteController
@@ -224,9 +237,9 @@ export class HybridMediaRouter {
Map<string, ViewerRouteIntent>
>();
private readonly consumedSfuRefreshesByRoom = new Map<string, Set<string>>();
- private readonly selectedEdgeTurnAttempts = new Map<
+ private readonly selectedPeerEdgeLeases = new Map<
string,
- SelectedEdgeTurnAttempt
+ SelectedPeerEdgeLease
>();
private readonly selectedSfuIngressAttempts = new Map<
string,
@@ -257,8 +270,12 @@ export class HybridMediaRouter {
string,
DeferredHealthySfuReselection
>();
+ private readonly relayParentQualityStates = new Map<string, RelayParentQualityState>();
constructor(private readonly options: HybridMediaRouterOptions) {
+ this.peerRelayTopology = new PeerRelayTopology(
+ options.maxPeerRelayDownstreamEdges,
+ );
const fallback = options.sfuFallback;
if (options.selectedEdgeTurn && !fallback) {
throw new Error("Selected-edge TURN requires SFU fallback");
@@ -284,10 +301,10 @@ export class HybridMediaRouter {
clearTimeout(pending.timer);
}
this.pendingRoutePreparations.clear();
- for (const attempt of this.selectedEdgeTurnAttempts.values()) {
- clearTimeout(attempt.timer);
+ for (const lease of this.selectedPeerEdgeLeases.values()) {
+ clearTimeout(lease.timer);
}
- this.selectedEdgeTurnAttempts.clear();
+ this.selectedPeerEdgeLeases.clear();
for (const attempt of this.selectedSfuIngressAttempts.values()) {
clearTimeout(attempt.timer);
}
@@ -308,10 +325,18 @@ export class HybridMediaRouter {
this.viewerQualityEvidenceStates.clear();
this.heldQualityParentExclusionsByViewer.clear();
this.roomQualityMigrationCooldownUntilMs.clear();
+ this.relayParentQualityStates.clear();
}
connectParticipant(input: AuthenticatedRouteParticipant): HybridAuthenticationState {
+ // A selected transport is bound to both authenticated sessions. A client
+ // may replace its WebSocket without changing the stable peer id or route.
+ this.clearSelectedEdgeTurnsForParticipant(
+ input.roomId,
+ input.peerId,
+ );
this.clearRoomViewerQualityEvidenceStates(input.roomId);
+ this.refreshRelayParentQualityStates(input.roomId);
this.clearHeldQualityParentExclusion(input.roomId, input.peerId);
this.clearSfuRefreshesForPeer(input.roomId, input.peerId);
if (input.role === "viewer") {
@@ -415,15 +440,15 @@ export class HybridMediaRouter {
}): boolean | undefined {
const sourceKey = viewerConnectionKey(input.roomId, input.sourcePeerId);
const targetKey = viewerConnectionKey(input.roomId, input.targetPeerId);
- const attempt =
- this.selectedEdgeTurnAttempts.get(sourceKey)?.parentPeerId ===
+ const lease =
+ this.selectedPeerEdgeLeases.get(sourceKey)?.parentPeerId ===
input.targetPeerId
- ? this.selectedEdgeTurnAttempts.get(sourceKey)
- : this.selectedEdgeTurnAttempts.get(targetKey)?.parentPeerId ===
+ ? this.selectedPeerEdgeLeases.get(sourceKey)
+ : this.selectedPeerEdgeLeases.get(targetKey)?.parentPeerId ===
input.sourcePeerId
- ? this.selectedEdgeTurnAttempts.get(targetKey)
+ ? this.selectedPeerEdgeLeases.get(targetKey)
: undefined;
- if (!attempt) {
+ if (!lease) {
const pending = this.pendingRoutePreparations.get(input.roomId);
const probe = pending?.healthyReselection;
const parentToRoot = probe?.parentPeerId === input.sourcePeerId &&
@@ -443,21 +468,23 @@ export class HybridMediaRouter {
(input.signalKind === "candidate" ||
(rootToParent && input.descriptionType === "answer"));
}
- const parentToViewer = input.sourcePeerId === attempt.parentPeerId;
- const currentRoute = this.mediaRouteControllers.get(input.roomId)?.getActiveRoute();
+ const parentToViewer = input.sourcePeerId === lease.parentPeerId;
+ const currentRoute = this.mediaRouteControllers
+ .get(input.roomId)
+ ?.getActiveRoute();
return Boolean(
- input.connectionId === attempt.newConnectionId &&
- currentRoute?.revision === attempt.revision &&
- this.options.getShareGeneration(input.roomId) ===
- attempt.shareGeneration &&
+ currentRoute &&
+ input.connectionId === lease.newConnectionId &&
+ currentRoute.revision === lease.currentRouteRevision &&
+ this.selectedPeerEdgeLeaseIsCurrent(input.roomId, lease, currentRoute) &&
((parentToViewer &&
- input.sourceSessionId === attempt.parentSessionId &&
- input.targetSessionId === attempt.viewerSessionId) ||
+ input.sourceSessionId === lease.parentSessionId &&
+ input.targetSessionId === lease.viewerSessionId) ||
(!parentToViewer &&
- input.sourceSessionId === attempt.viewerSessionId &&
- input.targetSessionId === attempt.parentSessionId)) &&
+ input.sourceSessionId === lease.viewerSessionId &&
+ input.targetSessionId === lease.parentSessionId)) &&
(input.signalKind === "candidate" ||
- (!attempt.answered &&
+ (!lease.answered &&
((parentToViewer && input.descriptionType === "offer") ||
(!parentToViewer && input.descriptionType === "answer"))))
);
@@ -468,12 +495,13 @@ export class HybridMediaRouter {
viewerPeerId: string,
connectionId: string,
): void {
- const attempt = this.selectedEdgeTurnAttempts.get(
+ const lease = this.selectedPeerEdgeLeases.get(
viewerConnectionKey(roomId, viewerPeerId),
);
- if (attempt?.newConnectionId === connectionId) {
- attempt.answered = true;
- clearTimeout(attempt.timer);
+ if (lease?.newConnectionId === connectionId) {
+ lease.answered = true;
+ clearTimeout(lease.timer);
+ this.drainViewerRouteIntents(roomId);
}
}
@@ -653,16 +681,7 @@ export class HybridMediaRouter {
correlatedAtMs: now,
framesPerSecond: pending.evidence.metrics.framesPerSecond,
};
- const cooldownUntil = this.roomQualityMigrationCooldownUntilMs.get(roomId);
- if (cooldownUntil !== undefined && now < cooldownUntil) {
- state.badWindowCount = 0;
- state.badWindowKind = null;
- state.lastCorrelatedAtMs = now;
- return;
- }
- if (cooldownUntil !== undefined) {
- this.roomQualityMigrationCooldownUntilMs.delete(roomId);
- }
+ this.refreshRelayParentQualityStates(roomId, now);
const existingIntent = this.viewerRouteIntentsByRoom
.get(roomId)
?.get(viewerPeerId);
@@ -702,6 +721,29 @@ export class HybridMediaRouter {
return;
}
+ const relayParentBadEvent = this.handleRelayParentBadEvent(
+ roomId,
+ edge.parentPeerId,
+ parentSessionId,
+ viewerPeerId,
+ badWindowKind!,
+ now,
+ );
+ if (relayParentBadEvent === "trigger-moved") {
+ this.viewerQualityEvidenceStates.delete(connectionKey);
+ return;
+ }
+ const cooldownUntil = this.roomQualityMigrationCooldownUntilMs.get(roomId);
+ if (cooldownUntil !== undefined && now < cooldownUntil) {
+ if (relayParentBadEvent === null) {
+ state.badWindowCount = 0;
+ state.badWindowKind = null;
+ return;
+ }
+ } else if (cooldownUntil !== undefined) {
+ this.roomQualityMigrationCooldownUntilMs.delete(roomId);
+ }
+
let roomIntents = this.viewerRouteIntentsByRoom.get(roomId);
if (!roomIntents) {
roomIntents = new Map();
@@ -715,6 +757,8 @@ export class HybridMediaRouter {
excludedParents.add(edge.parentPeerId);
roomIntents.set(viewerPeerId, {
failedParentPeerId: edge.parentPeerId,
+ failedParentSessionId: parentSessionId,
+ failedConnectionId: evidence.guard.connectionId,
sessionId: viewerSessionId,
sfuAttempts: 0,
unavailableReported: false,
@@ -779,6 +823,7 @@ export class HybridMediaRouter {
if (participant.role !== "viewer") {
return;
}
+ this.refreshRelayParentQualityStates(participant.roomId);
let advertised = this.relayCapacitySessionsByRoom.get(participant.roomId);
if (!advertised) {
advertised = new Map();
@@ -811,6 +856,8 @@ export class HybridMediaRouter {
this.clearChangedConnectionIds(participant.roomId, changes);
this.reconcileMediaRoute(participant.roomId);
this.sendMediaAssignmentChanges(participant.roomId, changes);
+ } else if (active) {
+ this.reconcileSelectedPeerEdgeLeases(participant.roomId, active);
}
const assignment = this.mediaRouteControllers
.get(participant.roomId)
@@ -855,7 +902,7 @@ export class HybridMediaRouter {
participant.role !== "viewer" ||
!controller ||
controller.getPendingRoute() ||
- this.roomPeerMigrationAttempt(roomId) !== null ||
+ this.roomPeerMigrationAttempt(roomId, participant.peerId) !== null ||
active?.revision !== revision ||
active.sfu.rootPeerIds.length !== 1 ||
active.sfu.rootPeerIds[0] !== participant.peerId ||
@@ -898,7 +945,9 @@ export class HybridMediaRouter {
const activeParent = active.assignments.get(parentPeerId);
const capacity = Math.min(
this.peerRelayTopology.getDownstreamCapacity(roomId, parentPeerId),
- parentPeerId === hostPeerId ? 2 : 1,
+ parentPeerId === hostPeerId
+ ? this.options.maxPeerRelayDownstreamEdges
+ : 1,
);
if (
!host ||
@@ -919,6 +968,7 @@ export class HybridMediaRouter {
hostPeerId,
null,
[],
+ this.options.maxPeerRelayDownstreamEdges,
);
const rootAssignment = assignments.get(participant.peerId)!;
const parentAssignment = assignments.get(parentPeerId)!;
@@ -1168,6 +1218,12 @@ export class HybridMediaRouter {
this.handlePrepareRouteFailed(participant, message);
return;
}
+ if (
+ message.connectionId !== null &&
+ this.finishSelectedEdgeTurnFailure(participant, message)
+ ) {
+ return;
+ }
const controller = this.mediaRouteControllers.get(participant.roomId);
const active = controller?.getActiveRoute();
if (!controller || !active || active.revision !== message.revision) {
@@ -1212,9 +1268,6 @@ export class HybridMediaRouter {
this.failBackToPeerBaseline(participant.roomId);
return;
}
- if (this.finishSelectedEdgeTurnFailure(participant, message)) {
- return;
- }
if (participant.role !== "viewer") {
this.sendError(
participant.sessionId,
@@ -1288,6 +1341,10 @@ export class HybridMediaRouter {
) {
pending.qualityIntent.takenOverByRouteFailure = true;
}
+ existingIntent.failedParentSessionId = this.connectedPeer(
+ participant.roomId, assignment.upstream.peerId,
+ )?.sessionId;
+ existingIntent.failedConnectionId = message.connectionId;
existingIntent.qualityGuard.exclusionOwnedByQuality = false;
existingIntent.qualityGuard = undefined;
}
@@ -1437,12 +1494,15 @@ export class HybridMediaRouter {
private roomPeerMigrationAttempt(
roomId: string,
+ viewerPeerId?: string,
): "healthy" | "selected" | null {
if (this.pendingRoutePreparations.get(roomId)?.healthyReselection) {
return "healthy";
}
- return [...this.selectedEdgeTurnAttempts.values()].some(
- (attempt) => attempt.roomId === roomId,
+ return [...this.selectedPeerEdgeLeases.values()].some(
+ (lease) =>
+ lease.roomId === roomId &&
+ (!lease.answered || lease.viewerPeerId === viewerPeerId),
)
? "selected"
: null;
@@ -1463,10 +1523,15 @@ export class HybridMediaRouter {
// The healthy probe already owns recovery, so suppress active-route failback.
return true;
}
- if (this.selectedEdgeTurnAttempts.has(key)) {
+ if (this.selectedPeerEdgeLeases.has(key)) {
return true;
}
- if (roomAttempt === "selected") {
+ if (
+ roomAttempt === "selected" ||
+ [...this.selectedPeerEdgeLeases.values()].some(
+ (lease) => lease.roomId === roomId,
+ )
+ ) {
return false;
}
if (
@@ -1487,18 +1552,27 @@ export class HybridMediaRouter {
const parent = this.connectedPeer(roomId, intent.failedParentPeerId);
const shareGeneration = this.options.getShareGeneration(roomId);
const parentAssignment = active.assignments.get(intent.failedParentPeerId);
- const parentChildLimit = this.peerRelayTopology.getDownstreamCapacity(
- roomId,
- intent.failedParentPeerId,
- );
+ const parentChildLimit =
+ this.peerRelayTopology.getAdvertisedDownstreamCapacity(
+ roomId,
+ intent.failedParentPeerId,
+ );
+ const selectedOverlayEdges = parentAssignment?.childPeerIds.includes(
+ viewerPeerId,
+ )
+ ? 0
+ : 1;
+ const parentActiveEdges = parentAssignment
+ ? parentAssignment.childPeerIds.length +
+ (parentAssignment.sfuPublicationGeneration ? 1 : 0) +
+ selectedOverlayEdges
+ : Number.POSITIVE_INFINITY;
if (
viewer?.sessionId !== intent.sessionId ||
parent?.sessionId !== intent.failedParentSessionId ||
!parentAssignment ||
- (parentAssignment.childPeerIds.length +
- (parentAssignment.sfuPublicationGeneration ? 1 : 0) >=
- parentChildLimit &&
- !parentAssignment.childPeerIds.includes(viewerPeerId)) ||
+ parentChildLimit === 0 ||
+ parentActiveEdges > parentChildLimit ||
!shareGeneration
) {
return false;
@@ -1548,7 +1622,7 @@ export class HybridMediaRouter {
}
const timer = setTimeout(() => {
- const current = this.selectedEdgeTurnAttempts.get(key);
+ const current = this.selectedPeerEdgeLeases.get(key);
if (
!current ||
current.newConnectionId !== newConnectionId ||
@@ -1556,38 +1630,43 @@ export class HybridMediaRouter {
) {
return;
}
- this.selectedEdgeTurnAttempts.delete(key);
+ const settled = this.settleSelectedPeerEdgeLease(key);
+ if (!settled) {
+ return;
+ }
this.sendError(
- current.viewerSessionId,
+ settled.viewerSessionId,
"PEER_NOT_FOUND",
"Selected relay edge timed out",
);
+ this.drainViewerRouteIntents(roomId);
}, SELECTED_EDGE_TURN_ATTEMPT_TIMEOUT_MS);
timer.unref();
- const attempt: SelectedEdgeTurnAttempt = {
- roomId,
+ const message: Extract<ServerMessage, { type: "selected-edge-turn" }> = {
+ type: "selected-edge-turn",
+ edgeKind: "peer-selected",
revision: active.revision,
+ parentPeerId: parent.peerId,
+ viewerPeerId,
+ oldConnectionId: intent.failedConnectionId,
+ newConnectionId,
+ expiresAt: credential.expiresAt,
+ iceServer: credential.iceServer,
+ };
+ const lease: SelectedPeerEdgeLease = {
+ roomId,
+ currentRouteRevision: active.revision,
shareGeneration,
parentPeerId: parent.peerId,
parentSessionId: parent.sessionId,
viewerPeerId,
viewerSessionId: viewer.sessionId,
newConnectionId,
+ grant: message,
answered: false,
timer,
};
- this.selectedEdgeTurnAttempts.set(key, attempt);
- const message: Extract<ServerMessage, { type: "selected-edge-turn" }> = {
- type: "selected-edge-turn",
- edgeKind: "peer-selected",
- revision: attempt.revision,
- parentPeerId: attempt.parentPeerId,
- viewerPeerId,
- oldConnectionId: intent.failedConnectionId,
- newConnectionId,
- expiresAt: credential.expiresAt,
- iceServer: credential.iceServer,
- };
+ this.selectedPeerEdgeLeases.set(key, lease);
// Queue the Viewer grant first. Any parent offer is handled on a later
// event-loop turn, so the Viewer's socket observes this grant first.
this.options.sendToSession(viewer.sessionId, message);
@@ -1764,46 +1843,72 @@ export class HybridMediaRouter {
if (participant.role === "host" && message.connectionId !== null) {
const attempt = this.selectedSfuIngressAttempts.get(participant.roomId);
if (
- !attempt ||
- attempt.hostPeerId !== participant.peerId ||
- attempt.hostSessionId !== participant.sessionId ||
- attempt.revision !== message.revision ||
- attempt.shareGeneration !==
- this.options.getShareGeneration(participant.roomId) ||
- attempt.newConnectionId !== message.connectionId
+ 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;
+ clearTimeout(attempt.timer);
+ this.selectedSfuIngressAttempts.delete(participant.roomId);
+ this.sendError(
+ participant.sessionId,
+ "PEER_NOT_FOUND",
+ "Selected SFU relay ingress failed",
+ );
+ this.failBackToPeerBaseline(participant.roomId);
+ return true;
}
- clearTimeout(attempt.timer);
- this.selectedSfuIngressAttempts.delete(participant.roomId);
- this.sendError(
- participant.sessionId,
- "PEER_NOT_FOUND",
- "Selected SFU relay ingress failed",
- );
- this.failBackToPeerBaseline(participant.roomId);
- return true;
}
- if (participant.role !== "viewer" || message.connectionId === null) {
+ if (message.connectionId === null) {
return false;
}
- const key = viewerConnectionKey(participant.roomId, participant.peerId);
- const attempt = this.selectedEdgeTurnAttempts.get(key);
+ let key = viewerConnectionKey(participant.roomId, participant.peerId);
+ let lease = this.selectedPeerEdgeLeases.get(key);
if (
- !attempt ||
- attempt.viewerSessionId !== participant.sessionId ||
- attempt.revision !== message.revision ||
- attempt.newConnectionId !== message.connectionId
+ !lease ||
+ lease.viewerPeerId !== participant.peerId ||
+ lease.viewerSessionId !== participant.sessionId
+ ) {
+ const parentEntry = [...this.selectedPeerEdgeLeases].find(
+ ([, candidate]) =>
+ candidate.roomId === participant.roomId &&
+ candidate.parentPeerId === participant.peerId &&
+ candidate.parentSessionId === participant.sessionId,
+ );
+ if (parentEntry) {
+ [key, lease] = parentEntry;
+ }
+ }
+ const active = this.mediaRouteControllers
+ .get(participant.roomId)
+ ?.getActiveRoute();
+ const participantOwnsLease =
+ (lease?.viewerPeerId === participant.peerId &&
+ lease.viewerSessionId === participant.sessionId) ||
+ (lease?.parentPeerId === participant.peerId &&
+ lease.parentSessionId === participant.sessionId);
+ if (
+ !lease ||
+ !active ||
+ !participantOwnsLease ||
+ lease.newConnectionId !== message.connectionId ||
+ !this.selectedPeerEdgeLeaseIsCurrent(
+ participant.roomId,
+ lease,
+ active,
+ )
) {
return false;
}
- clearTimeout(attempt.timer);
- this.selectedEdgeTurnAttempts.delete(key);
+ this.settleSelectedPeerEdgeLease(key);
this.sendError(
participant.sessionId,
"PEER_NOT_FOUND",
"Selected relay edge failed",
);
+ this.drainViewerRouteIntents(participant.roomId);
return true;
}
@@ -1826,6 +1931,7 @@ export class HybridMediaRouter {
hostPeerId,
null,
[],
+ this.options.maxPeerRelayDownstreamEdges,
);
const revision = controller.reconcileBaseline({
assignments,
@@ -1860,6 +1966,7 @@ export class HybridMediaRouter {
hostPeerId,
null,
[],
+ this.options.maxPeerRelayDownstreamEdges,
);
const revision = controller.reconcileBaseline({
assignments,
@@ -1908,6 +2015,7 @@ export class HybridMediaRouter {
}
private drainViewerRouteIntents(roomId: string): void {
+ this.refreshRelayParentQualityStates(roomId);
this.enqueueUnassignedViewerIntents(roomId);
const pending = this.pendingRoutePreparations.get(roomId);
if (pending) {
@@ -1921,10 +2029,18 @@ export class HybridMediaRouter {
}
const intents = this.viewerRouteIntentsByRoom.get(roomId);
if (!intents) {
+ this.evacuateQuarantinedRelayParents(roomId);
return;
}
for (const [viewerPeerId, intent] of [...intents]) {
+ if (
+ this.selectedPeerEdgeLeases.has(
+ viewerConnectionKey(roomId, viewerPeerId),
+ )
+ ) {
+ continue;
+ }
if (
intent.qualityGuard &&
!this.qualityIntentIsCurrent(roomId, viewerPeerId, intent)
@@ -2128,6 +2244,9 @@ export class HybridMediaRouter {
if (intents.size === 0) {
this.viewerRouteIntentsByRoom.delete(roomId);
}
+ if (this.roomPeerMigrationAttempt(roomId) !== "selected") {
+ this.evacuateQuarantinedRelayParents(roomId);
+ }
}
private qualityIntentIsCurrent(
@@ -2340,7 +2459,8 @@ export class HybridMediaRouter {
if (
rootPeerIds.length > fallback.maxRoots ||
!host ||
- host.childPeerIds.length + 1 > 2
+ host.childPeerIds.length + 1 >
+ this.options.maxPeerRelayDownstreamEdges
) {
this.sendError(
sourceSessionId,
@@ -2860,6 +2980,7 @@ export class HybridMediaRouter {
hostPeerId,
previousSfu?.publicationGeneration ?? null,
rootPeerIds,
+ this.options.maxPeerRelayDownstreamEdges,
);
if (!controller && initialRevision === 0 && assignments.size > 1) {
initialRevision = 1;
@@ -2868,6 +2989,7 @@ export class HybridMediaRouter {
if (!controller) {
controller = new MediaRouteController({
hostPeerId,
+ maxEndpointMediaEdges: this.options.maxPeerRelayDownstreamEdges,
assignments,
revision: initialRevision,
sfuPublicationGeneration:
@@ -2900,6 +3022,11 @@ export class HybridMediaRouter {
controller.getActiveRoute(),
excludedPeerId,
);
+ } else {
+ this.reconcileSelectedPeerEdgeLeases(
+ roomId,
+ controller.getActiveRoute(),
+ );
}
return controller;
}
@@ -2909,12 +3036,7 @@ export class HybridMediaRouter {
route: RoomMediaRoute,
excludedPeerId?: string,
): void {
- for (const [key, attempt] of this.selectedEdgeTurnAttempts) {
- if (attempt.roomId === roomId && attempt.revision !== route.revision) {
- clearTimeout(attempt.timer);
- this.selectedEdgeTurnAttempts.delete(key);
- }
- }
+ this.reconcileSelectedPeerEdgeLeases(roomId, route);
for (const [key, attempt] of this.selectedSfuIngressAttempts) {
if (attempt.roomId === roomId && attempt.revision !== route.revision) {
clearTimeout(attempt.timer);
@@ -2940,17 +3062,133 @@ export class HybridMediaRouter {
if (peerId === excludedPeerId) {
continue;
}
- const peer = this.connectedPeer(roomId, peerId);
- if (peer) {
- this.options.sendToSession(peer.sessionId, {
+ this.sendActiveRouteUpdate(roomId, peerId, route, assignment);
+ }
+ this.options.onActiveRouteChanged?.(roomId);
+ }
+
+ private selectedPeerEdgeLeaseIsCurrent(
+ roomId: string,
+ lease: SelectedPeerEdgeLease,
+ route: RoomMediaRoute,
+ ): boolean {
+ const viewerAssignment = this.peerRelayTopology.getAssignment(
+ roomId,
+ lease.viewerPeerId,
+ );
+ const parentAssignment = this.peerRelayTopology.getAssignment(
+ roomId,
+ lease.parentPeerId,
+ );
+ const activeParentAssignment = route.assignments.get(lease.parentPeerId);
+ const selectedOverlayEdges =
+ activeParentAssignment?.childPeerIds.includes(lease.viewerPeerId) === true
+ ? 0
+ : 1;
+ const activeParentEdges = activeParentAssignment
+ ? activeParentAssignment.childPeerIds.length +
+ (activeParentAssignment.sfuPublicationGeneration ? 1 : 0) +
+ selectedOverlayEdges
+ : Number.POSITIVE_INFINITY;
+ return (
+ route.revision === lease.currentRouteRevision &&
+ this.options.getShareGeneration(roomId) === lease.shareGeneration &&
+ this.connectedPeer(roomId, lease.parentPeerId)?.sessionId ===
+ lease.parentSessionId &&
+ this.options.roomStore.getConnectedViewer(roomId, lease.viewerPeerId)
+ ?.sessionId === lease.viewerSessionId &&
+ viewerAssignment?.parentPeerId === lease.parentPeerId &&
+ parentAssignment?.childPeerIds.includes(lease.viewerPeerId) === true &&
+ activeParentEdges <=
+ this.peerRelayTopology.getAdvertisedDownstreamCapacity(
+ roomId,
+ lease.parentPeerId,
+ )
+ );
+ }
+
+ private reconcileSelectedPeerEdgeLeases(
+ roomId: string,
+ route: RoomMediaRoute,
+ ): void {
+ for (const [key, lease] of this.selectedPeerEdgeLeases) {
+ if (lease.roomId !== roomId) {
+ continue;
+ }
+ lease.currentRouteRevision = route.revision;
+ if (this.selectedPeerEdgeLeaseIsCurrent(roomId, lease, route)) {
+ continue;
+ }
+ this.settleSelectedPeerEdgeLease(key);
+ }
+ }
+
+ private settleSelectedPeerEdgeLease(
+ key: string,
+ excludedPeerId?: string,
+ ): SelectedPeerEdgeLease | undefined {
+ const lease = this.selectedPeerEdgeLeases.get(key);
+ if (!lease) {
+ return undefined;
+ }
+ clearTimeout(lease.timer);
+ this.selectedPeerEdgeLeases.delete(key);
+
+ const active = this.mediaRouteControllers.get(lease.roomId)?.getActiveRoute();
+ if (!active) {
+ return lease;
+ }
+ for (const [peerId, sessionId] of [
+ [lease.parentPeerId, lease.parentSessionId],
+ [lease.viewerPeerId, lease.viewerSessionId],
+ ] as const) {
+ if (peerId === excludedPeerId) {
+ continue;
+ }
+ const participant = this.connectedPeer(lease.roomId, peerId);
+ const assignment = active.assignments.get(peerId);
+ if (participant?.sessionId === sessionId && assignment) {
+ // No carry grant precedes this duplicate authority, so the client
+ // closes the selected transport even when the route revision is equal.
+ this.options.sendToSession(sessionId, {
type: "route-update",
- revision: route.revision,
+ revision: active.revision,
phase: "active",
assignment,
});
}
}
- this.options.onActiveRouteChanged?.(roomId);
+ return lease;
+ }
+
+ private sendActiveRouteUpdate(
+ roomId: string,
+ peerId: string,
+ route: RoomMediaRoute,
+ assignment = route.assignments.get(peerId),
+ ): void {
+ const peer = this.connectedPeer(roomId, peerId);
+ if (!peer || !assignment) {
+ return;
+ }
+ for (const lease of this.selectedPeerEdgeLeases.values()) {
+ if (
+ lease.roomId === roomId &&
+ (lease.parentPeerId === peerId || lease.viewerPeerId === peerId) &&
+ this.selectedPeerEdgeLeaseIsCurrent(roomId, lease, route)
+ ) {
+ this.options.sendToSession(peer.sessionId, {
+ ...lease.grant,
+ revision: route.revision,
+ });
+ }
+ }
+ this.options.sendToSession(peer.sessionId, {
+ type: "route-update",
+ revision: route.revision,
+ phase: "active",
+ assignment,
+ });
}
private clearChangedRouteConnectionIds(
@@ -3014,12 +3252,12 @@ export class HybridMediaRouter {
const parent = this.connectedPeer(roomId, parentPeerId);
const parentAssignment = active?.assignments.get(parentPeerId);
if (parent && parentAssignment && active) {
- this.options.sendToSession(parent.sessionId, {
- type: "route-update",
- revision: active.revision,
- phase: "active",
- assignment: parentAssignment,
- });
+ this.sendActiveRouteUpdate(
+ roomId,
+ parentPeerId,
+ active,
+ parentAssignment,
+ );
this.options.sendToSession(parent.sessionId, {
type: "media-assignment",
mediaAssignment: mediaAssignmentFromParticipantRoute(parentAssignment),
@@ -3075,10 +3313,10 @@ export class HybridMediaRouter {
this.mediaRouteControllers.delete(roomId);
this.clearRoomFailedParents(roomId);
this.viewerRouteIntentsByRoom.delete(roomId);
- for (const [key, attempt] of this.selectedEdgeTurnAttempts) {
- if (attempt.roomId === roomId) {
- clearTimeout(attempt.timer);
- this.selectedEdgeTurnAttempts.delete(key);
+ for (const [key, lease] of this.selectedPeerEdgeLeases) {
+ if (lease.roomId === roomId) {
+ clearTimeout(lease.timer);
+ this.selectedPeerEdgeLeases.delete(key);
}
}
const ingress = this.selectedSfuIngressAttempts.get(roomId);
@@ -3092,19 +3330,19 @@ export class HybridMediaRouter {
this.sfuDisabledRoomIds.delete(roomId);
this.clearRoomViewerQualityEvidenceStates(roomId);
this.roomQualityMigrationCooldownUntilMs.delete(roomId);
+ this.refreshRelayParentQualityStates(roomId, Number.MAX_SAFE_INTEGER);
}
private clearSelectedEdgeTurnsForParticipant(
roomId: string,
peerId: string,
): void {
- for (const [key, attempt] of this.selectedEdgeTurnAttempts) {
+ for (const [key, lease] of [...this.selectedPeerEdgeLeases]) {
if (
- attempt.roomId === roomId &&
- (attempt.parentPeerId === peerId || attempt.viewerPeerId === peerId)
+ lease.roomId === roomId &&
+ (lease.parentPeerId === peerId || lease.viewerPeerId === peerId)
) {
- clearTimeout(attempt.timer);
- this.selectedEdgeTurnAttempts.delete(key);
+ this.settleSelectedPeerEdgeLease(key, peerId);
}
}
const ingress = this.selectedSfuIngressAttempts.get(roomId);
@@ -3196,7 +3434,10 @@ export class HybridMediaRouter {
viewer?.sessionId !== deferred.rootSessionId ||
!controller ||
controller.getPendingRoute() ||
- this.roomPeerMigrationAttempt(participant.roomId) !== null ||
+ this.roomPeerMigrationAttempt(
+ participant.roomId,
+ participant.peerId,
+ ) !== null ||
active?.revision !== deferred.activeRevision ||
active.sfu.publicationGeneration !== deferred.publicationGeneration ||
active.sfu.rootPeerIds.length !== 1 ||
@@ -3209,12 +3450,12 @@ export class HybridMediaRouter {
}
// Duplicate authority asks the Viewer for fresh media proof.
- this.options.sendToSession(deferred.rootSessionId, {
- type: "route-update",
- revision: active.revision,
- phase: "active",
+ this.sendActiveRouteUpdate(
+ participant.roomId,
+ deferred.rootPeerId,
+ active,
assignment,
- });
+ );
};
this.deferredHealthySfuReselections.set(participant.roomId, deferred);
schedule(cooldownUntil - now);
@@ -3242,10 +3483,131 @@ export class HybridMediaRouter {
}
}
+ private handleRelayParentBadEvent(
+ roomId: string,
+ parentPeerId: string,
+ parentSessionId: string,
+ childPeerId: string,
+ badWindowKind: ViewerQualityBadWindowKind,
+ now: number,
+ ): ViewerQualityBadWindowKind | "trigger-moved" | null {
+ const shareGeneration = this.options.getShareGeneration(roomId);
+ if (
+ !shareGeneration ||
+ this.options.roomStore.getConnectedViewer(roomId, parentPeerId)
+ ?.sessionId !== parentSessionId
+ ) {
+ return null;
+ }
+ const key = viewerConnectionKey(roomId, parentPeerId);
+ const previous = this.relayParentQualityStates.get(key);
+ if (previous?.quarantinedUntilMs == null) {
+ if (
+ !previous ||
+ previous.lastChildPeerId === childPeerId ||
+ now - previous.lastConfirmedAtMs > VIEWER_QUALITY_EVIDENCE_GAP_MS
+ ) {
+ this.relayParentQualityStates.set(key, {
+ parentSessionId,
+ shareGeneration,
+ lastChildPeerId: childPeerId,
+ lastConfirmedAtMs: now,
+ quarantinedUntilMs: null,
+ });
+ return null;
+ }
+ previous.lastChildPeerId = childPeerId;
+ previous.lastConfirmedAtMs = now;
+ previous.quarantinedUntilMs =
+ now + VIEWER_QUALITY_REASSIGN_COOLDOWN_MS;
+ this.peerRelayTopology.setViewerRelayEligible(roomId, parentPeerId, false);
+ }
+ if (
+ badWindowKind === "relative-fps" &&
+ !this.pendingRoutePreparations.has(roomId)
+ ) {
+ this.evacuateRelayParentChildren(roomId, parentPeerId);
+ }
+ return this.resolveActivePeerEdge(roomId, childPeerId)?.parentPeerId ===
+ parentPeerId
+ ? badWindowKind
+ : "trigger-moved";
+ }
+
+ private evacuateRelayParentChildren(
+ roomId: string,
+ parentPeerId: string,
+ ): void {
+ const childPeerIds =
+ this.peerRelayTopology.getAssignment(roomId, parentPeerId)?.childPeerIds ?? [];
+ for (const childPeerId of childPeerIds) {
+ const failedParents = this.failedParentPeerIdsByViewer.get(
+ viewerConnectionKey(roomId, childPeerId),
+ );
+ const excludedParents = new Set(failedParents);
+ excludedParents.add(parentPeerId);
+ const changes = this.peerRelayTopology.reassignViewer(
+ roomId, childPeerId, this.connectedPeerIds(roomId), excludedParents,
+ MAX_PEER_RELAY_DEPTH,
+ );
+ if (!changes) continue;
+ this.clearChangedConnectionIds(roomId, changes);
+ this.reconcileMediaRoute(roomId);
+ this.sendMediaAssignmentChanges(roomId, changes);
+ }
+ }
+
+ private evacuateQuarantinedRelayParents(roomId: string): void {
+ const prefix = `${roomId}:`;
+ for (const [key, state] of this.relayParentQualityStates) {
+ if (key.startsWith(prefix) && state.quarantinedUntilMs !== null) {
+ this.evacuateRelayParentChildren(roomId, key.slice(prefix.length));
+ }
+ }
+ }
+
+ private refreshRelayParentQualityStates(
+ roomId: string,
+ currentTime = this.options.now?.() ?? Date.now(),
+ ): void {
+ if (!Number.isFinite(currentTime)) return;
+ const prefix = `${roomId}:`;
+ const shareGeneration = this.options.getShareGeneration(roomId);
+ for (const [key, state] of this.relayParentQualityStates) {
+ if (!key.startsWith(prefix)) continue;
+ const parentPeerId = key.slice(prefix.length);
+ const identityCurrent =
+ state.parentSessionId ===
+ this.options.roomStore.getConnectedViewer(roomId, parentPeerId)
+ ?.sessionId && state.shareGeneration === shareGeneration;
+ const active =
+ state.quarantinedUntilMs === null
+ ? currentTime - state.lastConfirmedAtMs <=
+ VIEWER_QUALITY_EVIDENCE_GAP_MS
+ : currentTime < state.quarantinedUntilMs;
+ if (
+ identityCurrent &&
+ currentTime >= state.lastConfirmedAtMs &&
+ active
+ ) {
+ continue;
+ }
+ if (state.quarantinedUntilMs !== null) {
+ this.peerRelayTopology.setViewerRelayEligible(roomId, parentPeerId, true);
+ }
+ this.relayParentQualityStates.delete(key);
+ }
+ }
+
private clearViewerQualityStateForParticipant(
roomId: string,
peerId: string,
): void {
+ const relayParentKey = viewerConnectionKey(roomId, peerId);
+ if (this.relayParentQualityStates.get(relayParentKey)?.quarantinedUntilMs != null) {
+ this.peerRelayTopology.setViewerRelayEligible(roomId, peerId, true);
+ }
+ this.relayParentQualityStates.delete(relayParentKey);
this.clearHeldQualityParentExclusion(roomId, peerId);
const intents = this.viewerRouteIntentsByRoom.get(roomId);
for (const [viewerPeerId, intent] of [...(intents ?? [])]) {
@@ -3372,6 +3734,7 @@ function participantRoutesFromTopology(
hostPeerId: string,
publicationGeneration: string | null,
requestedRootPeerIds: readonly string[],
+ maxHostMediaEdges: number,
): Map<string, ParticipantRouteAssignment> {
// Keep the peer tree intact underneath the active SFU overlay so prepare
// aborts and one-shot failback never need to reconstruct a lost baseline.
@@ -3412,8 +3775,9 @@ function participantRoutesFromTopology(
}
const host = assignments.get(hostPeerId);
if (host && rootPeerIds.length > 0) {
- const directChildPeerIds = host.childPeerIds.slice(0, 1);
- for (const suppressedPeerId of host.childPeerIds.slice(1)) {
+ const directChildLimit = Math.max(0, maxHostMediaEdges - 1);
+ const directChildPeerIds = host.childPeerIds.slice(0, directChildLimit);
+ for (const suppressedPeerId of host.childPeerIds.slice(directChildLimit)) {
const suppressed = assignments.get(suppressedPeerId);
if (suppressed?.upstream.kind === "peer") {
assignments.set(suppressedPeerId, {
diff --git a/src/server/media-route-controller.ts b/src/server/media-route-controller.ts
index 581c60da..d1ccf6cb 100644
--- a/src/server/media-route-controller.ts
+++ b/src/server/media-route-controller.ts
@@ -1,5 +1,7 @@
import {
+ DEFAULT_PEER_RELAY_DOWNSTREAM_EDGES,
MAX_MEDIA_ROUTE_REVISION,
+ MAX_PEER_RELAY_DOWNSTREAM_EDGES,
MAX_VIEWERS_PER_ROOM_LIMIT,
participantRouteAssignmentSchema,
sfuPublicationGenerationSchema,
@@ -32,6 +34,7 @@ export interface MediaRouteControllerOptions {
revision?: number;
sfuPublicationGeneration?: string | null;
sfuRootPeerIds?: readonly string[];
+ maxEndpointMediaEdges?: number;
}
export interface PrepareMediaRouteInput {
@@ -58,9 +61,19 @@ export class MediaRouteController {
private pendingRoute: StoredPendingRoute | undefined;
private latestRevision: number;
private readonly hostPeerId: string;
+ private readonly maxEndpointMediaEdges: number;
constructor(options: MediaRouteControllerOptions) {
this.hostPeerId = options.hostPeerId;
+ this.maxEndpointMediaEdges =
+ options.maxEndpointMediaEdges ?? DEFAULT_PEER_RELAY_DOWNSTREAM_EDGES;
+ if (
+ !Number.isSafeInteger(this.maxEndpointMediaEdges) ||
+ this.maxEndpointMediaEdges < 1 ||
+ this.maxEndpointMediaEdges > MAX_PEER_RELAY_DOWNSTREAM_EDGES
+ ) {
+ throw new Error("Endpoint media edge budget is invalid");
+ }
const revision = options.revision ?? 0;
assertRevision(revision);
this.activeRoute = createRoute(
@@ -69,6 +82,7 @@ export class MediaRouteController {
options.sfuPublicationGeneration ?? null,
options.sfuRootPeerIds ?? [],
this.hostPeerId,
+ this.maxEndpointMediaEdges,
);
this.latestRevision = revision;
}
@@ -102,6 +116,7 @@ export class MediaRouteController {
: input.sfuPublicationGeneration,
input.sfuRootPeerIds ?? this.activeRoute.sfu.rootPeerIds,
this.hostPeerId,
+ this.maxEndpointMediaEdges,
);
if (hasSameTopology(route, this.activeRoute)) {
return undefined;
@@ -124,6 +139,7 @@ export class MediaRouteController {
input.sfuPublicationGeneration ?? null,
input.sfuRootPeerIds ?? [],
this.hostPeerId,
+ this.maxEndpointMediaEdges,
);
const expectedParticipantIds = new Set(input.expectedParticipantIds);
if (expectedParticipantIds.size > MAX_PARTICIPANTS_PER_ROOM) {
@@ -191,7 +207,7 @@ export class MediaRouteController {
hostActiveMediaEdges(): number {
const edgeCount = hostMediaEdges(this.activeRoute, this.hostPeerId);
- if (edgeCount > 2) {
+ if (edgeCount > this.maxEndpointMediaEdges) {
throw new Error("Host active media edge budget exceeded");
}
return edgeCount;
@@ -211,6 +227,7 @@ function createRoute(
publicationGeneration: string | null,
rootPeerIds: readonly string[],
hostPeerId: string,
+ maxEndpointMediaEdges: number,
): RoomMediaRoute {
assertRevision(revision);
if (
@@ -236,13 +253,14 @@ function createRoute(
rootPeerIds: [...rootPeerIds],
},
};
- assertRouteInvariants(route, hostPeerId);
+ assertRouteInvariants(route, hostPeerId, maxEndpointMediaEdges);
return route;
}
function assertRouteInvariants(
route: RoomMediaRoute,
hostPeerId: string,
+ maxEndpointMediaEdges: number,
): void {
const hostAssignment = route.assignments.get(hostPeerId);
if (!hostAssignment) {
@@ -272,6 +290,9 @@ function assertRouteInvariants(
}
for (const [peerId, assignment] of route.assignments) {
+ if (assignment.childPeerIds.length > maxEndpointMediaEdges) {
+ throw new Error("Participant active media edge budget exceeded");
+ }
if (
peerId !== hostPeerId &&
assignment.sfuPublicationGeneration !== null
@@ -316,7 +337,7 @@ function assertRouteInvariants(
}
assertAcyclicPeerEdges(route.assignments);
- if (hostMediaEdges(route, hostPeerId) > 2) {
+ if (hostMediaEdges(route, hostPeerId) > maxEndpointMediaEdges) {
throw new Error("Host active media edge budget exceeded");
}
}
diff --git a/src/server/peer-relay-topology.ts b/src/server/peer-relay-topology.ts
index fb129de6..c7850ad0 100644
--- a/src/server/peer-relay-topology.ts
+++ b/src/server/peer-relay-topology.ts
@@ -2,6 +2,10 @@ import type {
MediaAssignment,
RelayDownstreamEdges,
} from "../shared/protocol.js";
+import {
+ DEFAULT_PEER_RELAY_DOWNSTREAM_EDGES,
+ MAX_PEER_RELAY_DOWNSTREAM_EDGES,
+} from "../shared/protocol.js";
export interface MediaAssignmentChange {
peerId: string;
@@ -20,11 +24,13 @@ interface RelayViewer {
parentPeerId: string | null;
childPeerIds: string[];
downstreamEdges: RelayDownstreamEdges;
+ relayEligible: boolean;
}
interface RelayRoom {
hostPeerId?: string;
hostChildPeerIds: string[];
+ maxDownstreamEdges: RelayDownstreamEdges;
viewers: Map<string, RelayViewer>;
nextOrder: number;
}
@@ -32,6 +38,19 @@ interface RelayRoom {
export class PeerRelayTopology {
private readonly rooms = new Map<string, RelayRoom>();
+ constructor(
+ private readonly maxDownstreamEdges: RelayDownstreamEdges =
+ DEFAULT_PEER_RELAY_DOWNSTREAM_EDGES,
+ ) {
+ if (
+ !Number.isSafeInteger(maxDownstreamEdges) ||
+ maxDownstreamEdges < 1 ||
+ maxDownstreamEdges > MAX_PEER_RELAY_DOWNSTREAM_EDGES
+ ) {
+ throw new Error("Peer relay downstream limit is invalid");
+ }
+ }
+
setHost(
roomId: string,
hostPeerId: string,
@@ -73,6 +92,7 @@ export class PeerRelayTopology {
parentPeerId: null,
childPeerIds: [],
downstreamEdges: 0,
+ relayEligible: true,
});
room.nextOrder += 1;
} else {
@@ -100,8 +120,12 @@ export class PeerRelayTopology {
}
const before = snapshot(room);
+ const boundedDownstreamEdges = Math.min(
+ downstreamEdges,
+ this.maxDownstreamEdges,
+ );
const previousDownstreamEdges = viewer.downstreamEdges;
- viewer.downstreamEdges = downstreamEdges;
+ viewer.downstreamEdges = boundedDownstreamEdges;
for (const [candidatePeerId, candidate] of orderedViewers(room)) {
if (candidate.parentPeerId === null) {
this.assignViewer(room, candidatePeerId, connectedPeerIds);
@@ -110,7 +134,7 @@ export class PeerRelayTopology {
if (
options.rescueUnassignedRelay &&
previousDownstreamEdges === 0 &&
- downstreamEdges > 0
+ boundedDownstreamEdges > 0
) {
this.rescueUnassignedRelay(room, peerId, connectedPeerIds);
}
@@ -191,6 +215,25 @@ export class PeerRelayTopology {
return room ? downstreamCapacity(room, peerId) : 0;
}
+ getAdvertisedDownstreamCapacity(
+ roomId: string,
+ peerId: string,
+ ): RelayDownstreamEdges {
+ const room = this.rooms.get(roomId);
+ return room ? advertisedDownstreamCapacity(room, peerId) : 0;
+ }
+
+ setViewerRelayEligible(
+ roomId: string,
+ peerId: string,
+ eligible: boolean,
+ ): void {
+ const viewer = this.rooms.get(roomId)?.viewers.get(peerId);
+ if (viewer) {
+ viewer.relayEligible = eligible;
+ }
+ }
+
getHostPeerId(roomId: string): string | undefined {
return this.rooms.get(roomId)?.hostPeerId;
}
@@ -258,6 +301,7 @@ export class PeerRelayTopology {
if (!room) {
room = {
hostChildPeerIds: [],
+ maxDownstreamEdges: this.maxDownstreamEdges,
viewers: new Map(),
nextOrder: 0,
};
@@ -325,7 +369,7 @@ export class PeerRelayTopology {
!connectedPeerIds.has(peerId) ||
candidate.parentPeerId !== null ||
candidate.childPeerIds.length !== 0 ||
- candidate.downstreamEdges === 0 ||
+ downstreamCapacity(room, peerId) === 0 ||
room.hostChildPeerIds.length !== downstreamCapacity(room, hostPeerId)
) {
return;
@@ -337,7 +381,7 @@ export class PeerRelayTopology {
connectedPeerIds.has(childPeerId) &&
child?.parentPeerId === hostPeerId &&
child.childPeerIds.length === 0 &&
- child.downstreamEdges === 0
+ downstreamCapacity(room, childPeerId) === 0
);
});
if (!leafPeerId) {
@@ -426,9 +470,18 @@ function findReassignmentParent(
function downstreamCapacity(
room: RelayRoom,
peerId: string,
+): RelayDownstreamEdges {
+ return room.hostPeerId === peerId || room.viewers.get(peerId)?.relayEligible
+ ? advertisedDownstreamCapacity(room, peerId)
+ : 0;
+}
+
+function advertisedDownstreamCapacity(
+ room: RelayRoom,
+ peerId: string,
): RelayDownstreamEdges {
return room.hostPeerId === peerId
- ? 2
+ ? room.maxDownstreamEdges
: (room.viewers.get(peerId)?.downstreamEdges ?? 0);
}
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index 1c0ad4be..3ad09570 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -82,6 +82,7 @@ export interface SignalingOptions {
server: HttpServer;
roomStore: RoomStore;
peerAssistedMedia: boolean;
+ maxPeerRelayDownstreamEdges: number;
sfuFallback?: SfuFallbackOptions;
selectedEdgeTurn?: SelectedEdgeTurnConfig;
ice: IceConfigOptions;
@@ -155,6 +156,7 @@ export class SignalingServer {
if (options.peerAssistedMedia) {
this.hybridMediaRouter = new HybridMediaRouter({
roomStore: options.roomStore,
+ maxPeerRelayDownstreamEdges: options.maxPeerRelayDownstreamEdges,
sfuFallback: options.sfuFallback,
selectedEdgeTurn: options.selectedEdgeTurn,
sendToSession: (sessionId, message) =>
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index c1df3314..b58fbd97 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -5,7 +5,7 @@ import { isCanonicalVideoCodecEvidence } from "./video-codec-evidence.js";
export const MAX_VIEWERS_PER_ROOM_LIMIT = 16;
export const MAX_PARTICIPANTS_PER_ROOM_LIMIT = MAX_VIEWERS_PER_ROOM_LIMIT + 1;
export const MAX_SIGNAL_BYTES = 64 * 1024;
-export const SIGNALING_PROTOCOL = "screener-v4";
+export const SIGNALING_PROTOCOL = "screener-v5";
export const ROOM_CODE_LENGTH = 12;
export const MAX_MEDIA_ROUTE_REVISION = Number.MAX_SAFE_INTEGER;
export const MAX_SFU_TOKEN_LENGTH = 8 * 1024;
@@ -195,11 +195,13 @@ export const DEFAULT_QUALITY_SETTINGS = {
videoCodec: "automatic",
} as const satisfies QualitySettings;
-export const relayDownstreamEdgesSchema = z.union([
- z.literal(0),
- z.literal(1),
- z.literal(2),
-]);
+export const DEFAULT_PEER_RELAY_DOWNSTREAM_EDGES = 2;
+export const MAX_PEER_RELAY_DOWNSTREAM_EDGES = 3;
+export const relayDownstreamEdgesSchema = z
+ .number()
+ .int()
+ .min(0)
+ .max(MAX_PEER_RELAY_DOWNSTREAM_EDGES);
export type RelayDownstreamEdges = z.infer<typeof relayDownstreamEdgesSchema>;
function isValidStunUrl(value: string): boolean {
@@ -336,7 +338,9 @@ export type SignalPayload = z.infer<typeof signalPayloadSchema>;
export const mediaAssignmentSchema = z
.object({
parentPeerId: opaqueIdSchema.nullable(),
- childPeerIds: z.array(opaqueIdSchema).max(2),
+ childPeerIds: z
+ .array(opaqueIdSchema)
+ .max(MAX_PEER_RELAY_DOWNSTREAM_EDGES),
})
.strict();
export type MediaAssignment = z.infer<typeof mediaAssignmentSchema>;
@@ -357,7 +361,7 @@ export const participantRouteAssignmentSchema = z
upstream: mediaRouteUpstreamSchema,
childPeerIds: z
.array(opaqueIdSchema)
- .max(2)
+ .max(MAX_PEER_RELAY_DOWNSTREAM_EDGES)
.refine((peerIds) => new Set(peerIds).size === peerIds.length),
sfuPublicationGeneration: sfuPublicationGenerationSchema.nullable(),
})
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index 34e8dc3f..88a5ca56 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -635,7 +635,7 @@ describe("client signaling recovery policy", () => {
Object.defineProperty(authenticated, "data", {
value: JSON.stringify({
type: "authenticated",
- protocol: "screener-v4",
+ protocol: "screener-v5",
role: "viewer",
peerId: "viewer_12345678",
roomExpiresAt: null,
@@ -714,7 +714,7 @@ describe("client signaling recovery policy", () => {
JSON.parse(String(sockets[0]!.send.mock.calls[0]![0])),
).toMatchObject({
type: "authenticate",
- protocol: "screener-v4",
+ protocol: "screener-v5",
});
const message = new Event("message");
Object.defineProperty(message, "data", { value: payload });
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index d13ab01a..e9884881 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -964,7 +964,7 @@ describe("HostPeer source replacement", () => {
});
describe("ViewerRelay downstream ownership", () => {
- it("reconciles two children without ever opening a third edge", async () => {
+ it("reconciles three children without ever opening a fourth edge", async () => {
const targets: string[] = [];
const relay = new ViewerRelay(
{ iceServers: [] },
@@ -978,18 +978,22 @@ describe("ViewerRelay downstream ownership", () => {
);
const firstVideo = createTrack("video", "first-video");
const firstAudio = createTrack("audio", "first-audio");
- relay.setChildren(["child-a", "child-b", "ignored-third"]);
+ relay.setChildren(["child-a", "child-b", "child-c", "ignored-fourth"]);
relay.setStream(createStream(firstVideo, firstAudio));
await vi.waitFor(() =>
- expect(new Set(targets)).toEqual(new Set(["child-a", "child-b"])),
+ expect(new Set(targets)).toEqual(
+ new Set(["child-a", "child-b", "child-c"]),
+ ),
);
- const [childAConnection, childBConnection] =
+ const [childAConnection, childBConnection, childCConnection] =
FakePeerConnection.instances;
expect(childAConnection).toBeDefined();
expect(childBConnection).toBeDefined();
+ expect(childCConnection).toBeDefined();
childAConnection!.connectionState = "connected";
childBConnection!.connectionState = "connected";
+ childCConnection!.connectionState = "connected";
const retiredConnectionId = relay.getSnapshot("child-a")!.connectionId;
const nextVideo = createTrack("video", "next-video");
@@ -1000,15 +1004,18 @@ describe("ViewerRelay downstream ownership", () => {
expect(childBConnection!.senders[0]?.track).toBe(nextVideo);
expect(childAConnection!.senders[1]?.track).toBe(nextAudio);
expect(childBConnection!.senders[1]?.track).toBe(nextAudio);
+ expect(childCConnection!.senders[0]?.track).toBe(nextVideo);
+ expect(childCConnection!.senders[1]?.track).toBe(nextAudio);
});
- relay.setChildren(["child-b", "child-c"]);
- await vi.waitFor(() => expect(targets).toContain("child-c"));
+ relay.setChildren(["child-b", "child-c", "child-d"]);
+ await vi.waitFor(() => expect(targets).toContain("child-d"));
expect(childAConnection!.connectionState).toBe("closed");
expect(childBConnection!.connectionState).toBe("connected");
- expect(FakePeerConnection.activeCount).toBe(2);
- expect(FakePeerConnection.peakActiveCount).toBe(2);
- expect(targets).not.toContain("ignored-third");
+ expect(childCConnection!.connectionState).toBe("connected");
+ expect(FakePeerConnection.activeCount).toBe(3);
+ expect(FakePeerConnection.peakActiveCount).toBe(3);
+ expect(targets).not.toContain("ignored-fourth");
await relay.acceptSignal("stale-child", {
kind: "description",
@@ -1017,16 +1024,15 @@ describe("ViewerRelay downstream ownership", () => {
}, 7);
await relay.recover("stale-child", "stale-connection", true);
await relay.recover("child-c", "wrong-connection", true);
- expect(FakePeerConnection.activeCount).toBe(2);
- const childCConnection = FakePeerConnection.latest!;
+ expect(FakePeerConnection.activeCount).toBe(3);
const childCConnectionId = relay.getSnapshot("child-c")!.connectionId;
await relay.recover("child-c", childCConnectionId, true);
await vi.waitFor(() =>
expect(FakePeerConnection.latest).not.toBe(childCConnection),
);
expect(childBConnection!.connectionState).toBe("connected");
- expect(FakePeerConnection.activeCount).toBe(2);
- expect(FakePeerConnection.peakActiveCount).toBe(2);
+ expect(FakePeerConnection.activeCount).toBe(3);
+ expect(FakePeerConnection.peakActiveCount).toBe(3);
expect(
relay.startSelectedEdgeTurn(
@@ -1039,8 +1045,8 @@ describe("ViewerRelay downstream ownership", () => {
7,
),
).toBe(false);
- expect(FakePeerConnection.activeCount).toBe(2);
- expect(FakePeerConnection.peakActiveCount).toBe(2);
+ expect(FakePeerConnection.activeCount).toBe(3);
+ expect(FakePeerConnection.peakActiveCount).toBe(3);
relay.dispose();
});
@@ -1102,6 +1108,16 @@ describe("ViewerRelay downstream ownership", () => {
iceTransportPolicy: "relay",
}]);
const selectedConnection = FakePeerConnection.latest!;
+ expect(
+ relay.startSelectedEdgeTurn(
+ { ...selectedGrant, revision: 8 },
+ "selected-parent",
+ 7,
+ ),
+ ).toBe(true);
+ expect(FakePeerConnection.latest).toBe(selectedConnection);
+ expect(sendSignal).toHaveBeenCalledOnce();
+ relay.acceptActiveRevision(8);
relay.setChildren(["sibling-child"]);
expect(selectedConnection.connectionState).not.toBe("closed");
expect(siblingConnection.connectionState).toBe("connected");
@@ -1116,7 +1132,7 @@ describe("ViewerRelay downstream ownership", () => {
kind: "candidate",
connectionId: "selected-connection-new",
candidate: pendingCandidate,
- }, 7),
+ }, 8),
).resolves.toBe(true);
expect(selectedConnection.addedIceCandidates).toEqual([]);
await expect(
@@ -1124,7 +1140,7 @@ describe("ViewerRelay downstream ownership", () => {
kind: "description",
connectionId: "selected-connection-new",
description: { type: "answer", sdp: "selected-answer" },
- }, 7),
+ }, 8),
).resolves.toBe(true);
expect(selectedConnection.remoteDescription?.type).toBe("answer");
expect(selectedConnection.addedIceCandidates).toEqual([pendingCandidate]);
@@ -1133,7 +1149,7 @@ describe("ViewerRelay downstream ownership", () => {
kind: "candidate",
connectionId: "selected-connection-new",
candidate: null,
- }, 7),
+ }, 8),
).resolves.toBe(true);
expect(selectedConnection.addedIceCandidates).toEqual([
pendingCandidate,
@@ -1144,24 +1160,27 @@ describe("ViewerRelay downstream ownership", () => {
kind: "candidate",
connectionId: "selected-connection-new",
candidate: null,
- }, 6),
+ }, 7),
).resolves.toBe(false);
await expect(
relay.acceptSignal("selected-child", {
kind: "candidate",
connectionId: oldConnectionId,
candidate: null,
- }, 7),
+ }, 8),
).resolves.toBe(false);
expect(
relay.startSelectedEdgeTurn(
- selectedEdgeTurn(
- "selected-child",
- "selected-connection-new",
- "selected-connection-replacement",
- ),
+ {
+ ...selectedEdgeTurn(
+ "selected-child",
+ "selected-connection-new",
+ "selected-connection-replacement",
+ ),
+ revision: 9,
+ },
"selected-parent",
- 7,
+ 9,
),
).toBe(true);
await vi.waitFor(() => expect(sendSignal).toHaveBeenCalledTimes(2));
@@ -1170,20 +1189,57 @@ describe("ViewerRelay downstream ownership", () => {
expect(replacementConnection.connectionState).not.toBe("closed");
expect(FakePeerConnection.activeCount).toBe(2);
expect(FakePeerConnection.peakActiveCount).toBe(2);
- relay.clearSelectedEdgeTurn();
+ relay.acceptActiveRevision(9);
expect(replacementConnection.connectionState).toBe("closed");
await expect(
relay.acceptSignal("selected-child", {
kind: "candidate",
connectionId: "selected-connection-replacement",
candidate: null,
- }, 7),
+ }, 9),
).resolves.toBe(false);
expect(FakePeerConnection.activeCount).toBe(1);
expect(FakePeerConnection.peakActiveCount).toBe(2);
relay.dispose();
});
+ it("reports a selected child whose relay-only offer fails", async () => {
+ const onSelectedEdgeFailed = vi.fn();
+ const relay = new ViewerRelay(
+ { iceServers: [] },
+ QUALITY_PROFILES["720p30"],
+ { sendSignal: () => true, onSelectedEdgeFailed },
+ );
+ relay.setChildren(["selected-child"]);
+ relay.setStream(createStream(createTrack("video", "selected-video"), null));
+ await vi.waitFor(() => expect(relay.getSnapshot()).not.toBeNull());
+ const oldConnectionId = relay.getSnapshot()!.connectionId;
+ relay.setChildren([]);
+ FakePeerConnection.offersFailing = 1;
+
+ expect(
+ relay.startSelectedEdgeTurn(
+ selectedEdgeTurn(
+ "selected-child",
+ oldConnectionId,
+ "selected-failed-connection",
+ ),
+ "selected-parent",
+ 7,
+ ),
+ ).toBe(true);
+ await vi.waitFor(() =>
+ expect(onSelectedEdgeFailed).toHaveBeenCalledWith(
+ "selected-child",
+ "selected-failed-connection",
+ 7,
+ ),
+ );
+ expect(relay.getSnapshot("selected-child")).toBeNull();
+ expect(FakePeerConnection.latest?.connectionState).toBe("closed");
+ relay.dispose();
+ });
+
it("exposes a defensive snapshot of current downstream send metrics", async () => {
const relay = new ViewerRelay(
{ iceServers: [] },
diff --git a/tests/media-assignment.test.ts b/tests/media-assignment.test.ts
index 3da2a0fe..af2cd425 100644
--- a/tests/media-assignment.test.ts
+++ b/tests/media-assignment.test.ts
@@ -6,6 +6,7 @@ import {
MAX_HOST_MEDIA_CHILDREN,
MAX_VIEWER_MEDIA_CHILDREN,
reconcileBoundedMediaChildren,
+ retainSelectedMediaParent,
viewerRestartMessage,
viewerSignalMessage,
} from "../src/client/webrtc/media-assignment.ts";
@@ -23,7 +24,9 @@ describe("peer-assisted client assignment", () => {
childPeerIds: [
"child_12345678",
"child_abcdefgh",
+ "child_qwertyui",
"child_12345678",
+ "child_overflow",
],
};
@@ -31,13 +34,21 @@ describe("peer-assisted client assignment", () => {
limitMediaAssignment(assignment, MAX_HOST_MEDIA_CHILDREN),
).toEqual({
parentPeerId: "parent_12345678",
- childPeerIds: ["child_12345678", "child_abcdefgh"],
+ childPeerIds: [
+ "child_12345678",
+ "child_abcdefgh",
+ "child_qwertyui",
+ ],
});
expect(
limitMediaAssignment(assignment, MAX_VIEWER_MEDIA_CHILDREN),
).toEqual({
parentPeerId: "parent_12345678",
- childPeerIds: ["child_12345678", "child_abcdefgh"],
+ childPeerIds: [
+ "child_12345678",
+ "child_abcdefgh",
+ "child_qwertyui",
+ ],
});
});
@@ -56,9 +67,25 @@ describe("peer-assisted client assignment", () => {
"remove:old-child",
"start:kept-child",
"start:new-child",
+ "start:overflow-child",
]);
});
+ it("updates selected Viewer children without replacing its retained parent", () => {
+ expect(
+ retainSelectedMediaParent(
+ {
+ parentPeerId: null,
+ childPeerIds: ["new-child_12345678"],
+ },
+ "selected-parent_12345678",
+ ),
+ ).toEqual({
+ parentPeerId: "selected-parent_12345678",
+ childPeerIds: ["new-child_12345678"],
+ });
+ });
+
it("leaves ordinary viewer signaling untargeted", () => {
expect(viewerSignalMessage(false, "host_12345678", offer)).toEqual({
type: "signal",
diff --git a/tests/media-route-controller.test.ts b/tests/media-route-controller.test.ts
index cb9dbc73..cabb178f 100644
--- a/tests/media-route-controller.test.ts
+++ b/tests/media-route-controller.test.ts
@@ -10,6 +10,8 @@ const HOST = "host_12345678";
const DIRECT_ROOT = "viewer_direct_12345678";
const SFU_ROOT_A = "viewer_sfu_a_12345678";
const SFU_ROOT_B = "viewer_sfu_b_12345678";
+const THIRD_CHILD = "viewer_third_12345678";
+const FOURTH_CHILD = "viewer_fourth_12345678";
const GENERATION_A = "generation_a_12345678";
const GENERATION_B = "generation_b_12345678";
@@ -216,7 +218,7 @@ describe("MediaRouteController", () => {
expect(routes.hostActiveMediaEdges()).toBe(2);
});
- it("rejects host fanout above two and inconsistent SFU ownership", () => {
+ it("rejects host fanout above the configured two and inconsistent SFU ownership", () => {
const tooManyHostEdges = new Map(hybridPlan().assignments);
tooManyHostEdges.set(
HOST,
@@ -277,6 +279,64 @@ describe("MediaRouteController", () => {
).toThrow("SFU roots and publication generation must be active together");
});
+ it("supports an explicit three-edge endpoint budget without admitting four", () => {
+ const threeHostChildren = new Map<string, ParticipantRouteAssignment>([
+ [
+ HOST,
+ assignment(
+ { kind: "none" },
+ [DIRECT_ROOT, SFU_ROOT_A, THIRD_CHILD],
+ ),
+ ],
+ [DIRECT_ROOT, assignment({ kind: "peer", peerId: HOST })],
+ [SFU_ROOT_A, assignment({ kind: "peer", peerId: HOST })],
+ [THIRD_CHILD, assignment({ kind: "peer", peerId: HOST })],
+ ]);
+ const expanded = new MediaRouteController({
+ hostPeerId: HOST,
+ assignments: threeHostChildren,
+ maxEndpointMediaEdges: 3,
+ });
+ expect(expanded.hostActiveMediaEdges()).toBe(3);
+
+ const viewerWithThreeChildren = new Map<string, ParticipantRouteAssignment>([
+ [HOST, assignment({ kind: "none" }, [DIRECT_ROOT])],
+ [
+ DIRECT_ROOT,
+ assignment(
+ { kind: "peer", peerId: HOST },
+ [SFU_ROOT_A, SFU_ROOT_B, THIRD_CHILD],
+ ),
+ ],
+ [SFU_ROOT_A, assignment({ kind: "peer", peerId: DIRECT_ROOT })],
+ [SFU_ROOT_B, assignment({ kind: "peer", peerId: DIRECT_ROOT })],
+ [THIRD_CHILD, assignment({ kind: "peer", peerId: DIRECT_ROOT })],
+ ]);
+ expect(() => controller(viewerWithThreeChildren)).toThrow(
+ "Participant active media edge budget exceeded",
+ );
+
+ const fourHostEdges = new Map(threeHostChildren);
+ fourHostEdges.set(
+ HOST,
+ assignment(
+ { kind: "none" },
+ [DIRECT_ROOT, SFU_ROOT_A, THIRD_CHILD],
+ GENERATION_A,
+ ),
+ );
+ fourHostEdges.set(FOURTH_CHILD, assignment({ kind: "sfu" }));
+ expect(() =>
+ new MediaRouteController({
+ hostPeerId: HOST,
+ assignments: fourHostEdges,
+ maxEndpointMediaEdges: 3,
+ sfuPublicationGeneration: GENERATION_A,
+ sfuRootPeerIds: [FOURTH_CHILD],
+ }),
+ ).toThrow("Host active media edge budget exceeded");
+ });
+
it("rejects reciprocal peer cycles", () => {
const assignments = new Map<string, ParticipantRouteAssignment>([
[HOST, assignment({ kind: "none" })],
diff --git a/tests/peer-relay-topology.test.ts b/tests/peer-relay-topology.test.ts
index f51b9f94..0d8c255a 100644
--- a/tests/peer-relay-topology.test.ts
+++ b/tests/peer-relay-topology.test.ts
@@ -197,6 +197,60 @@ describe("PeerRelayTopology", () => {
expect(topology.getAssignment("room", "viewer-d")?.parentPeerId).toBeNull();
});
+ it("keeps server relay ineligibility separate from advertised capacity", () => {
+ const topology = new PeerRelayTopology();
+ const peers = connected("host", "relay", "sibling", "child", "pending");
+ topology.setHost("room", "host", peers);
+ topology.addViewer("room", "relay", peers);
+ topology.addViewer("room", "sibling", peers);
+ topology.setViewerRelayCapacity("room", "relay", 1, peers);
+ topology.addViewer("room", "child", peers);
+
+ topology.setViewerRelayEligible("room", "relay", false);
+ expect(topology.getDownstreamCapacity("room", "relay")).toBe(0);
+ expect(topology.getAdvertisedDownstreamCapacity("room", "relay")).toBe(1);
+ expect(topology.getAssignment("room", "child")?.parentPeerId).toBe("relay");
+ expect(
+ topology.setViewerRelayCapacity("room", "relay", 2, peers),
+ ).toEqual([]);
+ expect(topology.getAdvertisedDownstreamCapacity("room", "relay")).toBe(2);
+ topology.addViewer("room", "pending", peers);
+ expect(topology.getAssignment("room", "pending")?.parentPeerId).toBeNull();
+
+ topology.setViewerRelayEligible("room", "relay", true);
+ topology.setViewerRelayCapacity("room", "relay", 2, peers);
+ expect(topology.getAssignment("room", "pending")?.parentPeerId).toBe(
+ "relay",
+ );
+ topology.setViewerRelayEligible("room", "host", false);
+ expect(topology.getDownstreamCapacity("room", "host")).toBe(2);
+ });
+
+ it("clamps advertisements to the deployment limit and can opt into three", () => {
+ const peers = connected("host", "relay");
+ const defaultTopology = new PeerRelayTopology();
+ defaultTopology.setHost("default", "host", peers);
+ defaultTopology.addViewer("default", "relay", peers);
+ defaultTopology.setViewerRelayCapacity("default", "relay", 3, peers);
+ expect(
+ defaultTopology.getAdvertisedDownstreamCapacity("default", "host"),
+ ).toBe(2);
+ expect(
+ defaultTopology.getAdvertisedDownstreamCapacity("default", "relay"),
+ ).toBe(2);
+
+ const expandedTopology = new PeerRelayTopology(3);
+ expandedTopology.setHost("expanded", "host", peers);
+ expandedTopology.addViewer("expanded", "relay", peers);
+ expandedTopology.setViewerRelayCapacity("expanded", "relay", 3, peers);
+ expect(
+ expandedTopology.getAdvertisedDownstreamCapacity("expanded", "host"),
+ ).toBe(3);
+ expect(
+ expandedTopology.getAdvertisedDownstreamCapacity("expanded", "relay"),
+ ).toBe(3);
+ });
+
it("does not reassign a failed edge through a viewer leaf", () => {
const topology = new PeerRelayTopology();
const peers = connected("host", "viewer-a", "viewer-b", "viewer-c");
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index a2aede69..a5c981c1 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -516,6 +516,12 @@ describe("client signaling protocol", () => {
type: "relay-capacity",
downstreamEdges: 3,
}).success,
+ ).toBe(true);
+ expect(
+ clientMessageSchema.safeParse({
+ type: "relay-capacity",
+ downstreamEdges: 4,
+ }).success,
).toBe(false);
expect(
clientMessageSchema.safeParse({
@@ -934,7 +940,8 @@ describe("server signaling protocol", () => {
childPeerIds: [
"viewer_12345678",
"viewer_87654321",
- "viewer_overflow",
+ "viewer_third_1234",
+ "viewer_overflow_1",
],
},
}).success,
@@ -1015,7 +1022,8 @@ describe("server signaling protocol", () => {
childPeerIds: [
"child_12345678",
"child_87654321",
- "child_overflow",
+ "child_third_1234",
+ "child_overflow_1",
],
}).success,
).toBe(false);
diff --git a/tests/relay-capability.test.ts b/tests/relay-capability.test.ts
index 14ec2d53..79d4bc26 100644
--- a/tests/relay-capability.test.ts
+++ b/tests/relay-capability.test.ts
@@ -5,10 +5,10 @@ import {
} from "../src/client/media/relay-capability.ts";
describe("browser relay capability", () => {
- it("allows two downstream edges on a peer-assisted Web viewer", () => {
+ it("advertises the bounded browser maximum to a peer-assisted server", () => {
expect(relayCapacityMessageForBrowser(true)).toEqual({
type: "relay-capacity",
- downstreamEdges: 2,
+ downstreamEdges: 3,
});
});
diff --git a/tests/server-config.test.ts b/tests/server-config.test.ts
index 56742421..596ed746 100644
--- a/tests/server-config.test.ts
+++ b/tests/server-config.test.ts
@@ -12,6 +12,7 @@ describe("server configuration", () => {
expect(config.stunUrls).toEqual([]);
expect(config.maxViewersPerRoom).toBe(8);
expect(config.peerAssistedMedia).toBe(false);
+ expect(config.maxPeerRelayDownstreamEdges).toBe(2);
expect(config.livekitFallback).toBeUndefined();
expect(config.selectedEdgeTurn).toBeUndefined();
});
@@ -216,6 +217,28 @@ describe("server configuration", () => {
);
});
+ it.each(["1", "2", "3"])(
+ "accepts a bounded peer relay downstream limit of %s",
+ (maxPeerRelayDownstreamEdges) => {
+ expect(
+ loadConfig({
+ MAX_PEER_RELAY_DOWNSTREAM_EDGES: maxPeerRelayDownstreamEdges,
+ }).maxPeerRelayDownstreamEdges,
+ ).toBe(Number(maxPeerRelayDownstreamEdges));
+ },
+ );
+
+ it.each(["0", "4", "1.5"])(
+ "rejects an invalid peer relay downstream limit of %s",
+ (maxPeerRelayDownstreamEdges) => {
+ expect(() =>
+ loadConfig({
+ MAX_PEER_RELAY_DOWNSTREAM_EDGES: maxPeerRelayDownstreamEdges,
+ }),
+ ).toThrow("MAX_PEER_RELAY_DOWNSTREAM_EDGES");
+ },
+ );
+
it("enables the hybrid controller for every room when selected", () => {
expect(loadConfig({ PEER_ASSISTED_MEDIA: "true" }).peerAssistedMedia).toBe(
true,
diff --git a/tests/server-http.test.ts b/tests/server-http.test.ts
index 63b54e32..a8f99b32 100644
--- a/tests/server-http.test.ts
+++ b/tests/server-http.test.ts
@@ -43,6 +43,7 @@ function testConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {
maxRooms: 10,
maxViewersPerRoom: 8,
peerAssistedMedia: false,
+ maxPeerRelayDownstreamEdges: 2,
stunUrls: [],
...overrides,
};
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 4ab7f5b2..9babd99b 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -152,6 +152,7 @@ function testConfig(): ServerConfig {
maxRooms: 10,
maxViewersPerRoom: 8,
peerAssistedMedia: false,
+ maxPeerRelayDownstreamEdges: 2,
stunUrls: [],
};
}
@@ -282,22 +283,46 @@ async function correlateParentEdgeQualityEvidence(
return viewerEvidence;
}
+async function sendTestOffer(
+ source: TestClient,
+ target: TestClient,
+ targetPeerId: string,
+ connectionId: string,
+) {
+ source.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId,
+ payload: {
+ kind: "description",
+ connectionId,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ return target.inbox.next("signal");
+}
+
async function startRelayRelativeFpsFixture(
prefix: string,
now: () => number,
options: {
- alternateRelayCapacity?: 0 | 1;
+ alternateRelayCapacity?: 0 | 1 | 2;
+ issueSfuToken?: (peerId: string) => Promise<string>;
onSfuTokenIssue?: () => void;
+ secondChild?: boolean;
+ selectedEdgeTurn?: boolean;
sfu?: boolean;
} = {},
) {
const harness = options.sfu
- ? await startSfuHarness({
+ ? await startSfuHarness({
now,
+ selectedEdgeTurn: options.selectedEdgeTurn,
tokenIssuer: {
issueToken: async ({ peerId }) => {
options.onSfuTokenIssue?.();
- return `token-${peerId}`;
+ return options.issueSfuToken?.(peerId) ?? `token-${peerId}`;
},
},
})
@@ -308,7 +333,13 @@ async function startRelayRelativeFpsFixture(
);
const parent = await openClient(harness.webSocketUrl);
const parentAuth = peerAssisted(
- await authenticate(parent, harness.room, "viewer", `${prefix}-parent`, 1),
+ await authenticate(
+ parent,
+ harness.room,
+ "viewer",
+ `${prefix}-parent`,
+ options.secondChild ? 2 : 1,
+ ),
);
const alternate = await openClient(harness.webSocketUrl);
const alternateAuth = peerAssisted(
@@ -324,6 +355,20 @@ async function startRelayRelativeFpsFixture(
const childAuth = peerAssisted(
await authenticate(child, harness.room, "viewer", `${prefix}-child`, 0),
);
+ const secondChild = options.secondChild
+ ? await openClient(harness.webSocketUrl)
+ : undefined;
+ const secondChildAuth = secondChild
+ ? peerAssisted(
+ await authenticate(
+ secondChild,
+ harness.room,
+ "viewer",
+ `${prefix}-second-child`,
+ 0,
+ ),
+ )
+ : undefined;
expect(parentAuth.routeAssignment.upstream).toEqual({
kind: "peer",
peerId: hostAuth.peerId,
@@ -336,34 +381,31 @@ async function startRelayRelativeFpsFixture(
kind: "peer",
peerId: parentAuth.peerId,
});
+ expect(secondChildAuth?.routeAssignment.upstream).toEqual(
+ secondChildAuth
+ ? { kind: "peer", peerId: parentAuth.peerId }
+ : undefined,
+ );
+ const routeRevision = secondChildAuth?.routeRevision ?? childAuth.routeRevision;
+ if (secondChildAuth) {
+ await nextActiveRouteRevision(child, routeRevision);
+ }
const parentConnectionId = `${prefix}_parent_connection`;
- host.socket.send(
- JSON.stringify({
- type: "signal",
- targetPeerId: parentAuth.peerId,
- payload: {
- kind: "description",
- connectionId: parentConnectionId,
- description: { type: "offer", sdp: "v=0\r\n" },
- },
- }),
- );
- await parent.inbox.next("signal");
+ await sendTestOffer(host, parent, parentAuth.peerId, parentConnectionId);
const childConnectionId = `${prefix}_child_connection`;
- parent.socket.send(
- JSON.stringify({
- type: "signal",
- targetPeerId: childAuth.peerId,
- payload: {
- kind: "description",
- connectionId: childConnectionId,
- description: { type: "offer", sdp: "v=0\r\n" },
- },
- }),
- );
- await child.inbox.next("signal");
+ await sendTestOffer(parent, child, childAuth.peerId, childConnectionId);
+
+ const secondChildConnectionId = `${prefix}_second_child_connection`;
+ if (secondChild && secondChildAuth) {
+ await sendTestOffer(
+ parent,
+ secondChild,
+ secondChildAuth.peerId,
+ secondChildConnectionId,
+ );
+ }
return {
alternate,
@@ -377,20 +419,24 @@ async function startRelayRelativeFpsFixture(
parent,
parentAuth,
parentConnectionId,
- routeRevision: childAuth.routeRevision,
+ routeRevision,
+ secondChild,
+ secondChildAuth,
+ secondChildConnectionId,
};
}
async function correlateRelayParentInboundFps(
fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
framesPerSecond: number,
+ sequence = 0,
) {
fixture.parent.socket.send(
JSON.stringify(
viewerQualityEvidenceWithMetrics(
fixture.parentConnectionId,
fixture.routeRevision,
- 0,
+ sequence,
{ framesPerSecond },
),
),
@@ -418,11 +464,13 @@ async function correlateRelayChildFps(
fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
sequence: number,
framesPerSecond: number,
+ child = fixture.child,
+ connectionId = fixture.childConnectionId,
) {
- fixture.child.socket.send(
+ child.socket.send(
JSON.stringify(
viewerQualityEvidenceWithMetrics(
- fixture.childConnectionId,
+ connectionId,
fixture.routeRevision,
sequence,
{ framesPerSecond },
@@ -437,6 +485,83 @@ async function correlateRelayChildFps(
await new Promise<void>((resolve) => setTimeout(resolve, 0));
}
+async function confirmRelayChildRelativeFps(
+ fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
+ child: TestClient,
+ connectionId: string,
+ advanceWindow: () => void,
+) {
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ await correlateRelayChildFps(
+ fixture,
+ sequence,
+ 10,
+ child,
+ connectionId,
+ );
+ if (sequence < 2) advanceWindow();
+ }
+}
+
+async function confirmRelayParentChildRelativeFps(
+ fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
+ childIndex: 0 | 1,
+ advanceWindow: () => void,
+) {
+ const child = childIndex === 0 ? fixture.child : fixture.secondChild!;
+ const connectionId = childIndex === 0
+ ? fixture.childConnectionId
+ : fixture.secondChildConnectionId;
+ await correlateRelayParentInboundFps(fixture, 30, childIndex);
+ await confirmRelayChildRelativeFps(
+ fixture,
+ child,
+ connectionId,
+ advanceWindow,
+ );
+}
+
+async function confirmRelayChildSevere(
+ fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
+ child: TestClient,
+ connectionId: string,
+ advanceWindow: () => void,
+) {
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ child.socket.send(JSON.stringify(viewerQualityEvidenceWithMetrics(
+ connectionId,
+ fixture.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ )));
+ await correlateParentEdgeQualityEvidence(fixture.parent);
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ if (sequence < 2) advanceWindow();
+ }
+}
+
+async function reconnectRelayQualityEdges(
+ fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
+ suffix: string,
+) {
+ const secondChild = fixture.secondChild!;
+ const secondChildAuth = fixture.secondChildAuth!;
+ fixture.parentConnectionId = `${suffix}_parent_connection`;
+ await sendTestOffer(
+ fixture.host,
+ fixture.parent,
+ fixture.parentAuth.peerId,
+ fixture.parentConnectionId,
+ );
+ fixture.secondChildConnectionId = `${suffix}_second_child_connection`;
+ await sendTestOffer(
+ fixture.parent,
+ secondChild,
+ secondChildAuth.peerId,
+ fixture.secondChildConnectionId,
+ );
+}
+
async function startSfuHarness(options: {
tokenIssuer: SfuTokenIssuer;
selectedEdgeTurn?: boolean;
@@ -465,6 +590,7 @@ async function startSfuHarness(options: {
server: httpServer,
roomStore,
peerAssistedMedia: true,
+ maxPeerRelayDownstreamEdges: 2,
sfuFallback: {
url: "wss://sfu.example.test",
tokenIssuer: options.tokenIssuer,
@@ -3293,117 +3419,595 @@ describe("WebSocket signaling", () => {
expect(issuedSfuTokens).toBeGreaterThan(0);
});
- it("does not apply relative-FPS reparenting to a Host-direct edge", async () => {
- let now = 150_000;
- const harness = await startHarness({
- peerAssistedMedia: true,
- now: () => now,
+ it("keeps severe SFU fallback when the second child quarantines a relay", async () => {
+ let now = 142_000;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relay_parent_second_severe",
+ () => now,
+ { alternateRelayCapacity: 0, secondChild: true, sfu: true },
+ );
+ const advanceWindow = () => {
+ now += 2_000;
+ };
+ await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);
+ await confirmRelayChildSevere(
+ fixture,
+ fixture.secondChild!,
+ fixture.secondChildConnectionId,
+ advanceWindow,
+ );
+
+ const prepare = await nextPreparedRoute(fixture.secondChild!);
+ expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });
+ expect(await fixture.secondChild!.inbox.next("sfu-config")).toMatchObject({
+ revision: prepare.revision,
});
- const host = await openClient(harness.webSocketUrl);
- const hostAuth = peerAssisted(
- await authenticate(host, harness.room, "host", "relative_host_direct_host"),
+ });
+
+ it("gives a severe trigger the sole alternate before evacuating siblings", async () => {
+ let now = 144_000;
+ let issuedSfuTokens = 0;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relay_parent_severe_peer_first",
+ () => now,
+ {
+ alternateRelayCapacity: 0,
+ onSfuTokenIssue: () => {
+ issuedSfuTokens += 1;
+ },
+ secondChild: true,
+ sfu: true,
+ },
);
- const viewer = await openClient(harness.webSocketUrl);
- const viewerAuth = peerAssisted(
- await authenticate(
- viewer,
- harness.room,
- "viewer",
- "relative_host_direct_viewer",
- 0,
- ),
+ const advanceWindow = () => {
+ now += 2_000;
+ };
+ await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);
+ fixture.alternate.socket.send(JSON.stringify({
+ type: "relay-capacity",
+ downstreamEdges: 1,
+ }));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ await confirmRelayChildSevere(
+ fixture,
+ fixture.secondChild!,
+ fixture.secondChildConnectionId,
+ advanceWindow,
);
- const alternate = await openClient(harness.webSocketUrl);
- const alternateAuth = peerAssisted(
- await authenticate(
- alternate,
- harness.room,
- "viewer",
- "relative_host_direct_alternate",
- 1,
- ),
+
+ const triggerMoved = await nextActiveRouteAfter(
+ fixture.secondChild!,
+ fixture.routeRevision,
);
- await nextActiveRouteRevision(viewer, alternateAuth.routeRevision);
- expect(viewerAuth.routeAssignment.upstream).toEqual({
+ expect(triggerMoved.assignment.upstream).toEqual({
kind: "peer",
- peerId: hostAuth.peerId,
+ peerId: fixture.alternateAuth.peerId,
});
- host.socket.send(
- JSON.stringify({
- type: "signal",
- targetPeerId: viewerAuth.peerId,
- payload: {
- kind: "description",
- connectionId: "relative_host_direct_connection",
- description: { type: "offer", sdp: "v=0\r\n" },
+ const siblingStayed = await nextActiveRouteRevision(
+ fixture.child,
+ triggerMoved.revision,
+ );
+ expect(siblingStayed.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.parentAuth.peerId,
+ });
+ expect(issuedSfuTokens).toBe(0);
+ });
+
+ it("keeps quarantine stable while severe fallback waits on selected TURN", async () => {
+ let now = 144_500;
+ let releaseTokens!: () => void;
+ let markTokenStarted!: () => void;
+ const tokenBarrier = new Promise<void>((resolve) => {
+ releaseTokens = resolve;
+ });
+ const tokenStarted = new Promise<void>((resolve) => {
+ markTokenStarted = resolve;
+ });
+ const fixture = await startRelayRelativeFpsFixture(
+ "relay_parent_severe_selected_turn",
+ () => now,
+ {
+ alternateRelayCapacity: 0,
+ issueSfuToken: async () => {
+ markTokenStarted();
+ await tokenBarrier;
+ throw new Error("offline");
},
- }),
+ secondChild: true,
+ selectedEdgeTurn: true,
+ sfu: true,
+ },
);
- await viewer.inbox.next("signal");
- for (let sequence = 0; sequence < 3; sequence += 1) {
- viewer.socket.send(
- JSON.stringify(
- viewerQualityEvidenceWithMetrics(
- "relative_host_direct_connection",
- alternateAuth.routeRevision,
- sequence,
- { framesPerSecond: 10 },
- ),
- ),
- );
- await correlateParentEdgeQualityEvidence(host);
+ const advanceWindow = () => {
now += 2_000;
- }
- await expect(viewer.inbox.next("route-update", 40)).rejects.toThrow(
- "Timed out",
+ };
+ await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);
+ await confirmRelayChildSevere(
+ fixture,
+ fixture.secondChild!,
+ fixture.secondChildConnectionId,
+ advanceWindow,
+ );
+ await tokenStarted;
+
+ const takeoverConnectionId = "relay_parent_selected_turn_takeover";
+ await sendTestOffer(
+ fixture.parent,
+ fixture.secondChild!,
+ fixture.secondChildAuth!.peerId,
+ takeoverConnectionId,
);
+ fixture.secondChild!.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: fixture.routeRevision,
+ phase: "active",
+ connectionId: takeoverConnectionId,
+ }));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ releaseTokens();
+
+ const [viewerGrant, parentGrant] = await Promise.all([
+ fixture.secondChild!.inbox.next("selected-edge-turn"),
+ fixture.parent.inbox.next("selected-edge-turn"),
+ ]);
+ expect(parentGrant).toEqual(viewerGrant);
+ expect(viewerGrant).toMatchObject({
+ parentPeerId: fixture.parentAuth.peerId,
+ viewerPeerId: fixture.secondChildAuth!.peerId,
+ oldConnectionId: takeoverConnectionId,
+ });
+ await Promise.all([
+ nextActiveRouteRevision(fixture.child, viewerGrant.revision),
+ nextActiveRouteRevision(fixture.secondChild!, viewerGrant.revision),
+ ]);
+
+ fixture.alternate.socket.send(JSON.stringify({
+ type: "relay-capacity",
+ downstreamEdges: 1,
+ }));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ await Promise.all([
+ expect(fixture.child.inbox.next("route-update", 40)).rejects.toThrow(
+ "Timed out",
+ ),
+ expect(fixture.secondChild!.inbox.next("route-update", 40)).rejects.toThrow(
+ "Timed out",
+ ),
+ ]);
});
- it("requires fresh correlated inbound FPS from the relay parent", async () => {
- let now = 170_000;
+ it("quarantines a relay only after two children and restores it lazily", async () => {
+ let now = 145_000;
+ let issuedSfuTokens = 0;
const fixture = await startRelayRelativeFpsFixture(
- "relative_parent_freshness",
+ "relay_parent_quarantine",
() => now,
+ {
+ alternateRelayCapacity: 0,
+ onSfuTokenIssue: () => {
+ issuedSfuTokens += 1;
+ },
+ secondChild: true,
+ sfu: true,
+ },
);
- for (let sequence = 0; sequence < 3; sequence += 1) {
- await correlateRelayChildFps(fixture, sequence, 10);
- now += 2_000;
- }
- await expect(
- fixture.child.inbox.next("route-update", 40),
- ).rejects.toThrow("Timed out");
+ const secondChild = fixture.secondChild!;
- await correlateRelayParentInboundFps(fixture, 30);
- now += 5_001;
- for (let sequence = 3; sequence < 6; sequence += 1) {
- await correlateRelayChildFps(fixture, sequence, 10);
+ const advanceWindow = () => {
now += 2_000;
- }
- await expect(
- fixture.child.inbox.next("route-update", 40),
- ).rejects.toThrow("Timed out");
- });
+ };
+ await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);
+ await confirmRelayParentChildRelativeFps(fixture, 1, advanceWindow);
- it.each(["connection", "revision", "session"] as const)(
- "rejects relative FPS after the relay parent's %s identity changes",
- async (changedIdentity) => {
- let now = 180_000;
- const prefix = `relative_parent_${changedIdentity}`;
- const fixture = await startRelayRelativeFpsFixture(prefix, () => now);
- await correlateRelayParentInboundFps(fixture, 30);
- let routeRevision = fixture.routeRevision;
+ expect(issuedSfuTokens).toBe(0);
+ expect(await sendTestOffer(
+ fixture.parent,
+ secondChild,
+ fixture.secondChildAuth!.peerId,
+ "relay_parent_quarantine_still_active",
+ )).toMatchObject({
+ fromPeerId: fixture.parentAuth.peerId,
+ });
- if (changedIdentity === "connection") {
- fixture.host.socket.send(
- JSON.stringify({
- type: "signal",
- targetPeerId: fixture.parentAuth.peerId,
- payload: {
- kind: "description",
- connectionId: `${prefix}_replacement_connection`,
- description: { type: "offer", sdp: "v=0\r\n" },
- },
- }),
+ fixture.child.socket.close();
+ await new Promise<void>((resolve) => setTimeout(resolve, 70));
+ fixture.parent.socket.send(
+ JSON.stringify({ type: "relay-capacity", downstreamEdges: 2 }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ const pending = await openClient(fixture.harness.webSocketUrl);
+ const pendingAuth = peerAssisted(
+ await authenticate(
+ pending,
+ fixture.harness.room,
+ "viewer",
+ "relay-parent-quarantine-pending",
+ 0,
+ ),
+ );
+ expect(pendingAuth.routeAssignment.upstream).toEqual({ kind: "none" });
+
+ now += 30_001;
+ fixture.parent.socket.send(
+ JSON.stringify({ type: "relay-capacity", downstreamEdges: 2 }),
+ );
+ const restored = await nextActiveRouteAfter(
+ pending,
+ pendingAuth.routeRevision,
+ );
+ expect(restored.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.parentAuth.peerId,
+ });
+ });
+
+ it("keeps room cooldown when quarantine has no alternate", async () => {
+ let now = 180_000;
+ let issuedSfuTokens = 0;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relay_parent_peer_only",
+ () => now,
+ {
+ alternateRelayCapacity: 1,
+ onSfuTokenIssue: () => {
+ issuedSfuTokens += 1;
+ },
+ secondChild: true,
+ sfu: true,
+ },
+ );
+ const secondChild = fixture.secondChild!;
+
+ const advanceWindow = () => {
+ now += 2_000;
+ };
+ await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);
+ const firstMoved = await nextActiveRouteAfter(
+ fixture.child,
+ fixture.routeRevision,
+ );
+ expect(firstMoved.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.alternateAuth.peerId,
+ });
+ fixture.routeRevision = firstMoved.revision;
+ const secondAtFirstMove = await nextActiveRouteRevision(
+ secondChild,
+ firstMoved.revision,
+ );
+ expect(secondAtFirstMove.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.parentAuth.peerId,
+ });
+ await confirmRelayParentChildRelativeFps(fixture, 1, advanceWindow);
+ await expect(secondChild.inbox.next("route-update", 40)).rejects.toThrow(
+ "Timed out",
+ );
+
+ for (let sequence = 2; sequence < 5; sequence += 1) {
+ fixture.parent.socket.send(JSON.stringify(viewerQualityEvidenceWithMetrics(
+ fixture.parentConnectionId,
+ fixture.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ )));
+ await correlateParentEdgeQualityEvidence(fixture.host);
+ now += 2_000;
+ }
+ expect(issuedSfuTokens).toBe(0);
+ await expect(
+ fixture.parent.inbox.next("sfu-config", 40),
+ ).rejects.toThrow("Timed out");
+ });
+
+ it("defers quarantine evacuation until a pending severe SFU prepare commits", async () => {
+ let now = 200_000;
+ let releaseTokens!: () => void;
+ let markTokenStarted!: () => void;
+ const tokenBarrier = new Promise<void>((resolve) => {
+ releaseTokens = resolve;
+ });
+ const tokenStarted = new Promise<void>((resolve) => {
+ markTokenStarted = resolve;
+ });
+ const fixture = await startRelayRelativeFpsFixture(
+ "relay_parent_pending_severe",
+ () => now,
+ {
+ alternateRelayCapacity: 0,
+ issueSfuToken: async (peerId) => {
+ markTokenStarted();
+ await tokenBarrier;
+ return `token-${peerId}`;
+ },
+ secondChild: true,
+ sfu: true,
+ },
+ );
+ const advanceWindow = () => {
+ now += 2_000;
+ };
+ await confirmRelayChildSevere(
+ fixture,
+ fixture.child,
+ fixture.childConnectionId,
+ advanceWindow,
+ );
+ await tokenStarted;
+
+ fixture.alternate.socket.send(JSON.stringify({
+ type: "relay-capacity",
+ downstreamEdges: 2,
+ }));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ await confirmRelayChildSevere(
+ fixture,
+ fixture.secondChild!,
+ fixture.secondChildConnectionId,
+ advanceWindow,
+ );
+ releaseTokens();
+
+ const [hostPrepare, parentPrepare, childPrepare] = await Promise.all([
+ nextPreparedRoute(fixture.host),
+ nextPreparedRoute(fixture.parent),
+ nextPreparedRoute(fixture.child),
+ ]);
+ await Promise.all([
+ fixture.host.inbox.next("sfu-config"),
+ fixture.parent.inbox.next("sfu-config"),
+ fixture.child.inbox.next("sfu-config"),
+ ]);
+ expect(parentPrepare.revision).toBe(childPrepare.revision);
+ expect(hostPrepare.revision).toBe(childPrepare.revision);
+ for (const client of [fixture.host, fixture.parent, fixture.child]) {
+ client.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: childPrepare.revision,
+ phase: "prepare",
+ }));
+ }
+
+ const childActive = await nextActiveRouteRevision(
+ fixture.child,
+ childPrepare.revision,
+ );
+ expect(childActive.assignment.upstream).toEqual({ kind: "sfu" });
+ const siblingMoved = await nextActiveRouteAfter(
+ fixture.secondChild!,
+ childPrepare.revision,
+ );
+ expect(siblingMoved.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.alternateAuth.peerId,
+ });
+ });
+
+ it("does not combine confirmed child events across the five-second gap", async () => {
+ let now = 220_000;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relay_parent_stale_gap",
+ () => now,
+ { alternateRelayCapacity: 0, secondChild: true },
+ );
+ const secondChild = fixture.secondChild!;
+
+ const advanceWindow = () => {
+ now += 2_000;
+ };
+ await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);
+ now += 5_001;
+ fixture.alternate.socket.send(
+ JSON.stringify({ type: "relay-capacity", downstreamEdges: 2 }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ await confirmRelayParentChildRelativeFps(fixture, 1, advanceWindow);
+
+ const secondMoved = await nextActiveRouteAfter(
+ secondChild,
+ fixture.routeRevision,
+ );
+ expect(secondMoved.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.alternateAuth.peerId,
+ });
+ const firstStayed = await nextActiveRouteRevision(
+ fixture.child,
+ secondMoved.revision,
+ );
+ expect(firstStayed.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.parentAuth.peerId,
+ });
+ });
+
+ it.each(["session", "share"] as const)(
+ "does not combine confirmed children across a new parent %s",
+ async (boundary) => {
+ let now = boundary === "session" ? 250_000 : 280_000;
+ const prefix = `relay_parent_stale_${boundary}`;
+ const fixture = await startRelayRelativeFpsFixture(prefix, () => now, {
+ alternateRelayCapacity: 0,
+ secondChild: true,
+ });
+ const secondChild = fixture.secondChild!;
+
+ const advanceWindow = () => {
+ now += 2_000;
+ };
+ await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);
+
+ if (boundary === "session") {
+ const replacement = await openClient(fixture.harness.webSocketUrl);
+ const replacementAuth = peerAssisted(
+ await authenticate(
+ replacement,
+ fixture.harness.room,
+ "viewer",
+ `${prefix}-parent`,
+ 2,
+ ),
+ );
+ expect(replacementAuth.peerId).toBe(fixture.parentAuth.peerId);
+ fixture.parent = replacement;
+ fixture.parentAuth = replacementAuth;
+ fixture.routeRevision = replacementAuth.routeRevision;
+ } else {
+ const replacement = await openClient(fixture.harness.webSocketUrl);
+ const replacementAuth = peerAssisted(
+ await authenticate(
+ replacement,
+ fixture.harness.room,
+ "host",
+ `${prefix}-host`,
+ 1,
+ `${prefix}-next-share`,
+ ),
+ );
+ expect(replacementAuth.peerId).toBe(fixture.hostAuth.peerId);
+ fixture.host = replacement;
+ fixture.hostAuth = replacementAuth;
+ fixture.routeRevision = replacementAuth.routeRevision;
+ }
+ await reconnectRelayQualityEdges(fixture, `${prefix}_replacement`);
+ fixture.alternate.socket.send(
+ JSON.stringify({ type: "relay-capacity", downstreamEdges: 2 }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ await confirmRelayParentChildRelativeFps(fixture, 1, advanceWindow);
+
+ const secondMoved = await nextActiveRouteAfter(
+ secondChild,
+ fixture.routeRevision,
+ );
+ expect(secondMoved.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.alternateAuth.peerId,
+ });
+ const firstChildSignal = await sendTestOffer(
+ fixture.parent,
+ fixture.child,
+ fixture.childAuth.peerId,
+ `${prefix}_first_child_still_active`,
+ );
+ expect(firstChildSignal).toMatchObject({
+ fromPeerId: fixture.parentAuth.peerId,
+ });
+ },
+ );
+
+ it("does not apply relative-FPS reparenting to a Host-direct edge", async () => {
+ let now = 150_000;
+ const harness = await startHarness({
+ peerAssistedMedia: true,
+ now: () => now,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "relative_host_direct_host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "relative_host_direct_viewer",
+ 0,
+ ),
+ );
+ const alternate = await openClient(harness.webSocketUrl);
+ const alternateAuth = peerAssisted(
+ await authenticate(
+ alternate,
+ harness.room,
+ "viewer",
+ "relative_host_direct_alternate",
+ 1,
+ ),
+ );
+ await nextActiveRouteRevision(viewer, alternateAuth.routeRevision);
+ expect(viewerAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "relative_host_direct_connection",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await viewer.inbox.next("signal");
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ viewer.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "relative_host_direct_connection",
+ alternateAuth.routeRevision,
+ sequence,
+ { framesPerSecond: 10 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(host);
+ now += 2_000;
+ }
+ await expect(viewer.inbox.next("route-update", 40)).rejects.toThrow(
+ "Timed out",
+ );
+ });
+
+ it("requires fresh correlated inbound FPS from the relay parent", async () => {
+ let now = 170_000;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relative_parent_freshness",
+ () => now,
+ );
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ await correlateRelayChildFps(fixture, sequence, 10);
+ now += 2_000;
+ }
+ await expect(
+ fixture.child.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+
+ await correlateRelayParentInboundFps(fixture, 30);
+ now += 5_001;
+ for (let sequence = 3; sequence < 6; sequence += 1) {
+ await correlateRelayChildFps(fixture, sequence, 10);
+ now += 2_000;
+ }
+ await expect(
+ fixture.child.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+ });
+
+ it.each(["connection", "revision", "session"] as const)(
+ "rejects relative FPS after the relay parent's %s identity changes",
+ async (changedIdentity) => {
+ let now = 180_000;
+ const prefix = `relative_parent_${changedIdentity}`;
+ const fixture = await startRelayRelativeFpsFixture(prefix, () => now);
+ await correlateRelayParentInboundFps(fixture, 30);
+ let routeRevision = fixture.routeRevision;
+
+ if (changedIdentity === "connection") {
+ fixture.host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: fixture.parentAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: `${prefix}_replacement_connection`,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
);
await fixture.parent.inbox.next("signal");
} else if (changedIdentity === "revision") {
@@ -5679,13 +6283,13 @@ describe("WebSocket signaling", () => {
await expect(
direct.viewer.inbox.next("route-update", 40),
).rejects.toThrow("Timed out");
- direct.viewer.socket.send(JSON.stringify({
+ direct.host.socket.send(JSON.stringify({
type: "route-failed",
revision: direct.revision,
phase: "active",
connectionId: viewerGrant.newConnectionId,
}));
- expect((await direct.viewer.inbox.next("error")).code).toBe("PEER_NOT_FOUND");
+ expect((await direct.host.inbox.next("error")).code).toBe("PEER_NOT_FOUND");
await expect(
direct.viewer.inbox.next("selected-edge-turn", 40),
).rejects.toThrow("Timed out");
@@ -5750,7 +6354,7 @@ describe("WebSocket signaling", () => {
"selected-room-pending-cap",
);
- await startPeerSelectedTurn(
+ const firstGrant = await startPeerSelectedTurn(
peers.failedViewer,
peers.secondRoot,
peers.revision,
@@ -5762,6 +6366,13 @@ describe("WebSocket signaling", () => {
).resolves.toMatchObject({
assignment: { upstream: { kind: "peer" } },
});
+ const carry = await peers.secondRoot.inbox.next("selected-edge-turn");
+ expect(carry).toMatchObject({
+ parentPeerId: firstGrant.parentPeerId,
+ viewerPeerId: firstGrant.viewerPeerId,
+ oldConnectionId: firstGrant.oldConnectionId,
+ newConnectionId: firstGrant.newConnectionId,
+ });
await expect(
peers.secondRoot.inbox.next("selected-edge-turn", 40),
).rejects.toThrow("Timed out");
@@ -5805,16 +6416,160 @@ describe("WebSocket signaling", () => {
await peers.secondRoot.inbox.next("signal");
await failActiveSfuRoot(peers.secondRoot, peers.revision);
- await expect(
- nextActiveRouteAfter(peers.secondRoot, peers.revision),
- ).resolves.toMatchObject({
+ const routeAfterFailure = await nextActiveRouteAfter(
+ peers.secondRoot,
+ peers.revision,
+ );
+ expect(routeAfterFailure).toMatchObject({
assignment: { upstream: { kind: "peer" } },
});
+ const carry = await peers.secondRoot.inbox.next("selected-edge-turn");
+ expect(carry).toMatchObject({
+ revision: routeAfterFailure.revision,
+ parentPeerId: grant.parentPeerId,
+ viewerPeerId: grant.viewerPeerId,
+ oldConnectionId: grant.oldConnectionId,
+ newConnectionId: grant.newConnectionId,
+ });
await expect(
peers.secondRoot.inbox.next("selected-edge-turn", 40),
).rejects.toThrow("Timed out");
});
+ it("revokes a Host selected overlay before another child exceeds cap two", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ });
+ const active = await activateSingleViewerSfu(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-host-overlay-budget",
+ );
+ const grant = await startPeerSelectedTurn(
+ active.viewer,
+ active.host,
+ active.revision,
+ );
+ expect(grant.parentPeerId).toBe(active.hostAuth.peerId);
+ active.host.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: active.viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: grant.newConnectionId,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }));
+ await active.viewer.inbox.next("signal");
+ active.viewer.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: active.hostAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: grant.newConnectionId,
+ description: { type: "answer", sdp: "v=0\r\n" },
+ },
+ }));
+ await active.host.inbox.next("signal");
+
+ const sibling = await openClient(harness.webSocketUrl);
+ const siblingAuth = peerAssisted(
+ await authenticate(
+ sibling,
+ harness.room,
+ "viewer",
+ "selected-host-overlay-budget-sibling",
+ 0,
+ ),
+ );
+ const [hostRoute, selectedViewerRoute] = await Promise.all([
+ nextActiveRouteRevision(active.host, siblingAuth.routeRevision),
+ nextActiveRouteRevision(active.viewer, siblingAuth.routeRevision),
+ ]);
+ expect(hostRoute.assignment.childPeerIds).toContain(siblingAuth.peerId);
+ expect(hostRoute.assignment.sfuPublicationGeneration).not.toBeNull();
+ expect(
+ hostRoute.assignment.childPeerIds.length +
+ (hostRoute.assignment.sfuPublicationGeneration ? 1 : 0),
+ ).toBe(2);
+ expect(selectedViewerRoute.assignment.upstream).toEqual({ kind: "sfu" });
+ await Promise.all([
+ expect(
+ active.host.inbox.next("selected-edge-turn", 40),
+ ).rejects.toThrow("Timed out"),
+ expect(
+ active.viewer.inbox.next("selected-edge-turn", 40),
+ ).rejects.toThrow("Timed out"),
+ ]);
+ active.host.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: active.viewerAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: grant.newConnectionId,
+ candidate: null,
+ },
+ }));
+ expect((await active.host.inbox.next("error")).code).toBe("FORBIDDEN");
+ });
+
+ it("revokes a selected lease when its parent withdraws relay capacity", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ });
+ const peers = await activateTwoFailedViewerSfuRoots(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-parent-capacity-withdrawal",
+ );
+ const firstGrant = await startPeerSelectedTurn(
+ peers.failedViewer,
+ peers.secondRoot,
+ peers.revision,
+ );
+
+ peers.secondRoot.socket.send(JSON.stringify({
+ type: "relay-capacity",
+ downstreamEdges: 0,
+ }));
+ const [viewerAuthority, parentAuthority] = await Promise.all([
+ peers.failedViewer.inbox.next("route-update"),
+ peers.secondRoot.inbox.next("route-update"),
+ ]);
+ expect(viewerAuthority).toMatchObject({
+ revision: peers.revision,
+ phase: "active",
+ });
+ expect(parentAuthority).toMatchObject({
+ revision: peers.revision,
+ phase: "active",
+ });
+ peers.secondRoot.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: peers.failedAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: firstGrant.newConnectionId,
+ candidate: null,
+ },
+ }));
+ expect((await peers.secondRoot.inbox.next("error")).code).toBe("FORBIDDEN");
+
+ await failActiveSfuRoot(peers.secondRoot, peers.revision);
+ const [secondGrant, hostGrant] = await Promise.all([
+ peers.secondRoot.inbox.next("selected-edge-turn"),
+ peers.host.inbox.next("selected-edge-turn"),
+ ]);
+ expect(hostGrant).toEqual(secondGrant);
+ expect(secondGrant).toMatchObject({
+ edgeKind: "peer-selected",
+ parentPeerId: peers.hostAuth.peerId,
+ viewerPeerId: peers.secondRootAuth.peerId,
+ });
+ });
+
it("releases the room cap after the selected edge fails", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
@@ -5882,6 +6637,60 @@ describe("WebSocket signaling", () => {
});
});
+ it("releases a selected edge when its Viewer session is replaced", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ });
+ const peers = await activateTwoFailedViewerSfuRoots(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-viewer-session-replacement",
+ );
+ const firstGrant = await startPeerSelectedTurn(
+ peers.failedViewer,
+ peers.secondRoot,
+ peers.revision,
+ );
+
+ const replacement = await openClient(harness.webSocketUrl);
+ const replacementAuth = peerAssisted(
+ await authenticate(
+ replacement,
+ harness.room,
+ "viewer",
+ "selected-viewer-session-replacement-second-viewer",
+ ),
+ );
+ expect(replacementAuth.peerId).toBe(peers.failedAuth.peerId);
+ await expect(peers.secondRoot.inbox.next("route-update")).resolves.toMatchObject({
+ revision: replacementAuth.routeRevision,
+ phase: "active",
+ });
+ peers.secondRoot.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: replacementAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: firstGrant.newConnectionId,
+ candidate: null,
+ },
+ }));
+ expect((await peers.secondRoot.inbox.next("error")).code).toBe("FORBIDDEN");
+
+ await failActiveSfuRoot(peers.secondRoot, replacementAuth.routeRevision);
+ const [secondGrant, hostGrant] = await Promise.all([
+ peers.secondRoot.inbox.next("selected-edge-turn"),
+ peers.host.inbox.next("selected-edge-turn"),
+ ]);
+ expect(hostGrant).toEqual(secondGrant);
+ if (secondGrant.edgeKind !== "peer-selected") {
+ throw new Error("Expected a selected peer edge grant");
+ }
+ expect(secondGrant.viewerPeerId).toBe(peers.secondRootAuth.peerId);
+ expect(secondGrant.newConnectionId).not.toBe(firstGrant.newConnectionId);
+ });
+
it("allows selected TURN for Host SFU ingress outside historical room 1", async () => {
const harness = await startSfuHarness({
persistent: true,
@@ -6132,7 +6941,7 @@ describe("WebSocket signaling", () => {
).rejects.toThrow("Timed out");
});
- it("authorizes a ViewerRelay parent and clears its grant on share stop", async () => {
+ it("carries a ViewerRelay selected edge across an unrelated revision", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
selectedEdgeTurn: true,
@@ -6219,25 +7028,95 @@ describe("WebSocket signaling", () => {
},
}));
await prepared.rootViewer.inbox.next("signal");
- const reconnectedSibling = await openClient(harness.webSocketUrl);
- const reconnectedSiblingAuth = peerAssisted(
+ const parentAuthorityOrder: Array<{
+ type: "selected-edge-turn" | "route-update";
+ revision: number;
+ }> = [];
+ prepared.rootViewer.socket.on("message", (data) => {
+ const message = decodeServerMessage(data.toString());
+ if (
+ (message.type === "selected-edge-turn" &&
+ message.edgeKind === "peer-selected" &&
+ message.newConnectionId === childGrant.newConnectionId) ||
+ (message.type === "route-update" && message.phase === "active")
+ ) {
+ parentAuthorityOrder.push({
+ type: message.type,
+ revision: message.revision,
+ });
+ }
+ });
+ const expectCarryBeforeRoute = (revision: number): void => {
+ const events = parentAuthorityOrder.filter(
+ (event) => event.revision === revision,
+ );
+ expect(events.length).toBeGreaterThan(0);
+ expect(events.length % 2).toBe(0);
+ for (let index = 0; index < events.length; index += 2) {
+ expect(events[index]).toEqual({
+ type: "selected-edge-turn",
+ revision,
+ });
+ expect(events[index + 1]).toEqual({ type: "route-update", revision });
+ }
+ };
+ const unrelatedViewer = await openClient(harness.webSocketUrl);
+ const unrelatedViewerAuth = peerAssisted(
await authenticate(
- reconnectedSibling,
+ unrelatedViewer,
harness.room,
"viewer",
- "selected-viewer-parent-root-sibling-client",
+ "selected-viewer-parent-unrelated-client",
0,
),
);
- expect(reconnectedSiblingAuth.routeRevision).toBe(childGrant.revision);
- expect(
- await nextActiveRouteRevision(
- prepared.rootViewer,
- childGrant.revision,
+ expect(unrelatedViewerAuth.routeRevision).toBeGreaterThan(
+ childGrant.revision,
+ );
+ const parentAfterUnrelatedJoin = await nextActiveRouteRevision(
+ prepared.rootViewer,
+ unrelatedViewerAuth.routeRevision,
+ );
+ expect(parentAfterUnrelatedJoin.revision).toBeGreaterThan(
+ childGrant.revision,
+ );
+ const [childCarry, parentCarry] = await Promise.all([
+ prepared.failedViewer.inbox.next("selected-edge-turn"),
+ prepared.rootViewer.inbox.next("selected-edge-turn"),
+ ]);
+ expect(parentCarry).toEqual(childCarry);
+ expect(childCarry).toMatchObject({
+ revision: parentAfterUnrelatedJoin.revision,
+ parentPeerId: childGrant.parentPeerId,
+ viewerPeerId: childGrant.viewerPeerId,
+ oldConnectionId: childGrant.oldConnectionId,
+ newConnectionId: childGrant.newConnectionId,
+ iceServer: childGrant.iceServer,
+ });
+ expectCarryBeforeRoute(parentAfterUnrelatedJoin.revision);
+ parentAuthorityOrder.length = 0;
+ const replacementSibling = await openClient(harness.webSocketUrl);
+ const replacementSiblingAuth = peerAssisted(
+ await authenticate(
+ replacementSibling,
+ harness.room,
+ "viewer",
+ "selected-viewer-parent-root-sibling-client",
+ 0,
),
- ).toMatchObject({
- assignment: { childPeerIds: [reconnectedSiblingAuth.peerId] },
- });
+ );
+ let sameRevisionCarry;
+ do {
+ sameRevisionCarry = await prepared.rootViewer.inbox.next(
+ "selected-edge-turn",
+ );
+ } while (sameRevisionCarry.revision !== replacementSiblingAuth.routeRevision);
+ expect(sameRevisionCarry.newConnectionId).toBe(childGrant.newConnectionId);
+ await nextActiveRouteRevision(
+ prepared.rootViewer,
+ replacementSiblingAuth.routeRevision,
+ );
+ expectCarryBeforeRoute(replacementSiblingAuth.routeRevision);
prepared.rootViewer.socket.send(JSON.stringify({
type: "signal",
targetPeerId: prepared.failedAuth.peerId,
@@ -6255,11 +7134,16 @@ describe("WebSocket signaling", () => {
candidate: { candidate: "candidate-after-sibling-reconnect" },
},
});
- prepared.host.socket.send(JSON.stringify({
- type: "stop-sharing",
- shareGeneration: "selected-viewer-parent-share",
+ prepared.rootViewer.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: replacementSiblingAuth.routeRevision,
+ phase: "active",
+ connectionId: childGrant.newConnectionId,
}));
- await prepared.failedViewer.inbox.next("sharing-stopped");
+ await expect(prepared.rootViewer.inbox.next("error")).resolves.toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "Selected relay edge failed",
+ });
prepared.rootViewer.socket.send(JSON.stringify({
type: "signal",
targetPeerId: prepared.failedAuth.peerId,