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

refactor(route): admit exact TURN allocations (#208)

AAAf733d8f22bc7
diff --git a/.env.example b/.env.example
index db880580..1f3cf149 100644
--- a/.env.example
+++ b/.env.example
@@ -34,11 +34,12 @@ LIVEKIT_API_SECRET=
SFU_INGRESS_CAPACITY=
SFU_EGRESS_CAPACITY=
-# Optional one-shot TURN/UDP transport for one controller-selected edge after
-# peer and SFU recovery are exhausted. Set all three values together.
+# Optional one-shot TURN/UDP transport for a controller-selected edge after
+# peer and SFU recovery are exhausted. Set all four values together.
# SELECTED_EDGE_TURN_URLS=turn:turn.example.com:3478?transport=udp
# SELECTED_EDGE_TURN_SHARED_SECRET=replace-with-32-or-more-independent-random-bytes
# SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS=120
+# SELECTED_EDGE_TURN_ALLOCATION_CAPACITY=replace-with-measured-positive-integer
# Ordinary peer ICE discovery. Production requires at least one STUN URL.
# Separate multiple URLs with commas.
diff --git a/src/client/media/host-provisional-child.ts b/src/client/media/host-provisional-child.ts
index c799cc14..fb157121 100644
--- a/src/client/media/host-provisional-child.ts
+++ b/src/client/media/host-provisional-child.ts
@@ -14,11 +14,62 @@ export interface HostPreparedChildIdentity {
failedConnectionId: string | null;
}
+export interface ActiveSelectedHostChild {
+ peerId: string;
+ connectionId: string;
+ currentRouteRevision: number;
+ pendingCarryRevision: number | null;
+}
+
+export function hostSelectedChildForConnection(
+ children: ReadonlyMap<string, ActiveSelectedHostChild>,
+ peerId: string,
+ connectionId: string,
+): ActiveSelectedHostChild | undefined {
+ const child = children.get(peerId);
+ return child?.connectionId === connectionId ? child : undefined;
+}
+
+export function carryHostSelectedChild(
+ children: Map<string, ActiveSelectedHostChild>,
+ peerId: string,
+ connectionId: string,
+ revision: number,
+): boolean {
+ const child = hostSelectedChildForConnection(
+ children,
+ peerId,
+ connectionId,
+ );
+ if (!child || revision < child.currentRouteRevision) {
+ return false;
+ }
+ child.currentRouteRevision = revision;
+ child.pendingCarryRevision = revision;
+ return true;
+}
+
+export function acceptHostSelectedChildrenRevision(
+ children: Map<string, ActiveSelectedHostChild>,
+ revision: number,
+): string[] {
+ const removedPeerIds: string[] = [];
+ for (const [peerId, child] of children) {
+ if (child.pendingCarryRevision === revision) {
+ child.pendingCarryRevision = null;
+ } else {
+ children.delete(peerId);
+ removedPeerIds.push(peerId);
+ }
+ }
+ return removedPeerIds;
+}
+
interface HostProvisionalInput {
revision: number;
assignment: ParticipantRouteAssignment;
activeChildPeerIds: readonly string[];
- selectedPeerId: string | null;
+ selectedPeerIds: Iterable<string>;
maxMediaEdges: number;
}
@@ -224,9 +275,7 @@ export function plannedHostProvisionalChild(
countEndpointMediaCopies({
childPeerIds: input.assignment.childPeerIds,
publicationGeneration: input.assignment.sfuPublicationGeneration,
- selectedChildPeerIds: input.selectedPeerId
- ? [input.selectedPeerId]
- : [],
+ selectedChildPeerIds: input.selectedPeerIds,
}) > input.maxMediaEdges
) {
return null;
diff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.ts
index 786d95cc..2eb2adcf 100644
--- a/src/client/media/host-sfu-route.ts
+++ b/src/client/media/host-sfu-route.ts
@@ -291,7 +291,6 @@ export class HostSfuRoute {
): boolean {
if (
this.closed ||
- this.active !== null ||
!this.route.acceptsConfig(message.revision) ||
Date.parse(message.expiresAt) <= Date.now()
) {
@@ -302,7 +301,8 @@ export class HostSfuRoute {
if (
!publicationGeneration ||
publicationGeneration !== message.publicationGeneration ||
- message.oldConnectionId !== publicationGeneration
+ message.oldConnectionId !== publicationGeneration ||
+ this.active?.publicationGeneration === publicationGeneration
) {
return false;
}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 97c10ad2..679fc561 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -92,7 +92,11 @@ import {
type HostSfuPublisherSnapshot,
} from "../media/host-sfu-route";
import {
+ acceptHostSelectedChildrenRevision,
+ carryHostSelectedChild,
+ hostSelectedChildForConnection,
HostProvisionalChild,
+ type ActiveSelectedHostChild,
} from "../media/host-provisional-child";
import {
ParentEdgeQualityEvidenceReporter,
@@ -138,12 +142,6 @@ type HostRouteAssignment = Extract<
ServerMessage,
{ type: "route-update" }
>["assignment"];
-interface ActiveSelectedHostChild {
- peerId: string;
- connectionId: string;
- currentRouteRevision: number;
- pendingCarryRevision: number | null;
-}
interface FailedActiveHostChild {
revision: number;
peerId: string;
@@ -284,7 +282,9 @@ 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 selectedHostChildrenRef = useRef(
+ new Map<string, ActiveSelectedHostChild>(),
+ );
const hostProvisionalChildRef = useRef<HostProvisionalChild | null>(null);
const failedActiveHostChildRef = useRef<FailedActiveHostChild | null>(null);
const activeHostChildPeerIdsRef = useRef<string[]>([]);
@@ -424,7 +424,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
peersRef.current.forEach((peer) => peer.dispose());
peersRef.current.clear();
retiredConnectionsRef.current.clear();
- selectedHostChildRef.current = null;
+ selectedHostChildrenRef.current.clear();
hostProvisionalChildRef.current?.discard();
hostProvisionalChildRef.current = null;
failedActiveHostChildRef.current = null;
@@ -541,7 +541,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
peersRef.current.forEach((peer) => peer.dispose());
peersRef.current.clear();
retiredConnectionsRef.current.clear();
- selectedHostChildRef.current = null;
+ selectedHostChildrenRef.current.clear();
hostProvisionalChildRef.current?.discard();
hostProvisionalChildRef.current = null;
failedActiveHostChildRef.current = null;
@@ -908,9 +908,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
retiredConnectionsRef.current.set(peerId, peer.connectionId);
peer.dispose();
}
- if (selectedHostChildRef.current?.peerId === peerId) {
- selectedHostChildRef.current = null;
- }
+ selectedHostChildrenRef.current.delete(peerId);
peersRef.current.delete(peerId);
setPeerSnapshots((current) => {
const next = new Map(current);
@@ -969,7 +967,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
revision,
assignment,
activeChildPeerIds: activeHostChildPeerIdsRef.current,
- selectedPeerId: selectedHostChildRef.current?.peerId ?? null,
+ selectedPeerIds: selectedHostChildrenRef.current.keys(),
maxMediaEdges: MAX_ENDPOINT_MEDIA_CHILDREN,
iceConfig,
stream,
@@ -988,7 +986,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
revision,
assignment,
activeChildPeerIds,
- selectedPeerId: selectedHostChildRef.current?.peerId ?? null,
+ selectedPeerIds: selectedHostChildrenRef.current.keys(),
maxMediaEdges: MAX_ENDPOINT_MEDIA_CHILDREN,
}) ?? { kind: "ordinary" as const };
if (activation.kind === "promote") {
@@ -1038,11 +1036,14 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
}
const reportSelectedTurnFailure = (connectionId: string): void => {
- const selected = selectedHostChildRef.current;
+ const selected = hostSelectedChildForConnection(
+ selectedHostChildrenRef.current,
+ peerId,
+ connectionId,
+ );
if (
!selectedTurn ||
- selected?.peerId !== peerId ||
- selected.connectionId !== connectionId ||
+ !selected ||
!isCurrentGeneration(generation) ||
signalRef.current !== signal
) {
@@ -1166,17 +1167,20 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
failedPrepared?.revision === activeRouteRevisionRef.current
? childPeerIds.filter((peerId) => peerId !== failedPrepared.peerId)
: childPeerIds;
- const selected = selectedHostChildRef.current;
- const selectedIsCurrent =
- selected?.currentRouteRevision === activeRouteRevisionRef.current &&
- peersRef.current.get(selected.peerId)?.connectionId ===
- selected.connectionId;
- const effectiveChildPeerIds = selectedIsCurrent
- ? [...new Set([...authoritativeChildPeerIds, selected.peerId])]
- : authoritativeChildPeerIds;
- if (selected && !selectedIsCurrent) {
- selectedHostChildRef.current = null;
+ const selectedPeerIds: string[] = [];
+ for (const [peerId, selected] of selectedHostChildrenRef.current) {
+ const selectedIsCurrent =
+ selected.currentRouteRevision === activeRouteRevisionRef.current &&
+ peersRef.current.get(peerId)?.connectionId === selected.connectionId;
+ if (selectedIsCurrent) {
+ selectedPeerIds.push(peerId);
+ } else {
+ selectedHostChildrenRef.current.delete(peerId);
+ }
}
+ const effectiveChildPeerIds = [
+ ...new Set([...authoritativeChildPeerIds, ...selectedPeerIds]),
+ ];
reconcileBoundedMediaChildren(
peersRef.current.keys(),
effectiveChildPeerIds,
@@ -1203,9 +1207,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
if (message.type === "authenticated" && message.role === "host") {
discardPreparedHostChild();
failedActiveHostChildRef.current = null;
- const selected = selectedHostChildRef.current;
- if (selected) {
- removePeer(selected.peerId);
+ for (const peerId of [...selectedHostChildrenRef.current.keys()]) {
+ removePeer(peerId);
}
hostPeerIdRef.current = message.peerId;
setViewerAccessUpdating(false);
@@ -1273,17 +1276,17 @@ 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
+ current?.connectionId === message.newConnectionId &&
+ carryHostSelectedChild(
+ selectedHostChildrenRef.current,
+ message.viewerPeerId,
+ message.newConnectionId,
+ message.revision,
+ )
) {
- selected.currentRouteRevision = message.revision;
- selected.pendingCarryRevision = message.revision;
return;
}
const oldConnectionId =
@@ -1299,12 +1302,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
if (current) {
removePeer(message.viewerPeerId);
}
- selectedHostChildRef.current = {
+ selectedHostChildrenRef.current.set(message.viewerPeerId, {
peerId: message.viewerPeerId,
connectionId: message.newConnectionId,
currentRouteRevision: message.revision,
pendingCarryRevision: null,
- };
+ });
void startPeer(message.viewerPeerId, generation, 0, message);
}
return;
@@ -1355,11 +1358,11 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
activatePreparedHostChild(message.revision, message.assignment);
}
if (message.phase === "active") {
- const selected = selectedHostChildRef.current;
- if (selected?.pendingCarryRevision === message.revision) {
- selected.pendingCarryRevision = null;
- } else if (selected) {
- removePeer(selected.peerId);
+ for (const peerId of acceptHostSelectedChildrenRevision(
+ selectedHostChildrenRef.current,
+ message.revision,
+ )) {
+ removePeer(peerId);
}
}
if (
diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.ts
index 0fd4cc5a..aea4cb58 100644
--- a/src/client/webrtc/viewer-relay.ts
+++ b/src/client/webrtc/viewer-relay.ts
@@ -43,7 +43,10 @@ export class ViewerRelay {
private readonly peers = new Map<string, HostPeer>();
private readonly snapshots = new Map<string, PeerSnapshot>();
private readonly retiredConnections = new Map<string, string>();
- private selectedChildConnection: SelectedChildConnection | null = null;
+ private readonly selectedChildConnections = new Map<
+ string,
+ SelectedChildConnection
+ >();
private preparedChild: PreparedChild | null = null;
private failedPreparedChild: FailedPreparedChild | null = null;
private syncQueue = Promise.resolve();
@@ -76,7 +79,7 @@ export class ViewerRelay {
const connectionId =
currentPeer?.connectionId ??
this.retiredConnections.get(message.viewerPeerId);
- const selected = this.selectedChildConnection;
+ const selected = this.selectedChildConnections.get(message.viewerPeerId);
if (
selected?.peerId === message.viewerPeerId &&
selected.connectionId === message.newConnectionId &&
@@ -88,9 +91,6 @@ export class ViewerRelay {
selected.pendingCarryRevision = message.revision;
return true;
}
- const retainedChildPeerIds = selected
- ? this.childPeerIds.filter((peerId) => peerId !== selected.peerId)
- : this.childPeerIds;
if (
this.disposed ||
!stream ||
@@ -98,50 +98,39 @@ export class ViewerRelay {
message.revision !== routeRevision ||
Date.parse(message.expiresAt) <= now ||
connectionId !== message.oldConnectionId ||
- (!retainedChildPeerIds.includes(message.viewerPeerId) &&
- retainedChildPeerIds.length >= MAX_ENDPOINT_MEDIA_CHILDREN)
+ (!this.childPeerIds.includes(message.viewerPeerId) &&
+ this.childPeerIds.length >= MAX_ENDPOINT_MEDIA_CHILDREN)
) {
return false;
}
- if (selected) {
- this.clearSelectedEdgeTurn();
- }
+ this.disposePeer(message.viewerPeerId);
if (!this.childPeerIds.includes(message.viewerPeerId)) {
this.childPeerIds.push(message.viewerPeerId);
}
- this.disposePeer(message.viewerPeerId);
- this.selectedChildConnection = {
+ this.selectedChildConnections.set(message.viewerPeerId, {
peerId: message.viewerPeerId,
connectionId: message.newConnectionId,
revision: message.revision,
pendingCarryRevision: null,
- };
+ });
this.startPeer(message.viewerPeerId, stream, 0, message);
return true;
}
clearSelectedEdgeTurn(): void {
- const selected = this.selectedChildConnection;
- if (!selected) {
- return;
+ for (const peerId of [...this.selectedChildConnections.keys()]) {
+ this.clearSelectedChildConnection(peerId);
}
- this.selectedChildConnection = null;
- this.childPeerIds = this.childPeerIds.filter(
- (peerId) => peerId !== selected.peerId,
- );
- this.disposePeer(selected.peerId);
}
acceptActiveRevision(revision: number): void {
- const selected = this.selectedChildConnection;
- if (!selected) {
- return;
- }
- if (selected.pendingCarryRevision === revision) {
- selected.pendingCarryRevision = null;
- return;
+ for (const [peerId, selected] of [...this.selectedChildConnections]) {
+ if (selected.pendingCarryRevision === revision) {
+ selected.pendingCarryRevision = null;
+ } else {
+ this.clearSelectedChildConnection(peerId);
+ }
}
- this.clearSelectedEdgeTurn();
}
prepareChild(
@@ -249,12 +238,19 @@ export class ViewerRelay {
0,
MAX_ENDPOINT_MEDIA_CHILDREN,
);
- const selectedPeerId = this.selectedChildConnection?.peerId ?? null;
- if (selectedPeerId && !nextChildPeerIds.includes(selectedPeerId)) {
- if (nextChildPeerIds.length >= MAX_ENDPOINT_MEDIA_CHILDREN) {
- nextChildPeerIds.pop();
+ for (const selectedPeerId of this.selectedChildConnections.keys()) {
+ if (!nextChildPeerIds.includes(selectedPeerId)) {
+ if (nextChildPeerIds.length >= MAX_ENDPOINT_MEDIA_CHILDREN) {
+ const removableIndex = nextChildPeerIds.findLastIndex(
+ (peerId) => !this.selectedChildConnections.has(peerId),
+ );
+ if (removableIndex < 0) {
+ continue;
+ }
+ nextChildPeerIds.splice(removableIndex, 1);
+ }
+ nextChildPeerIds.push(selectedPeerId);
}
- nextChildPeerIds.push(selectedPeerId);
}
for (const childPeerId of this.childPeerIds) {
if (!nextChildPeerIds.includes(childPeerId)) {
@@ -264,7 +260,7 @@ export class ViewerRelay {
this.childPeerIds = nextChildPeerIds;
for (const childPeerId of this.childPeerIds) {
const peer = this.peers.get(childPeerId);
- if (childPeerId === selectedPeerId) {
+ if (this.selectedChildConnections.has(childPeerId)) {
continue;
}
if (
@@ -334,7 +330,7 @@ export class ViewerRelay {
return true;
}
const peer = this.peers.get(fromPeerId);
- const selected = this.selectedChildConnection;
+ const selected = this.selectedChildConnections.get(fromPeerId);
if (
!this.childPeerIds.includes(fromPeerId) ||
!peer ||
@@ -401,7 +397,7 @@ export class ViewerRelay {
this.disposed = true;
this.stream = null;
this.discardPreparedChild();
- this.selectedChildConnection = null;
+ this.selectedChildConnections.clear();
this.childPeerIds = [];
this.disposePeers();
}
@@ -580,7 +576,7 @@ export class ViewerRelay {
}
private failSelectedChild(childPeerId: string, connectionId: string): void {
- const selected = this.selectedChildConnection;
+ const selected = this.selectedChildConnections.get(childPeerId);
if (
selected?.peerId !== childPeerId ||
selected.connectionId !== connectionId
@@ -620,10 +616,10 @@ export class ViewerRelay {
const peer = this.peers.get(childPeerId);
if (
peer &&
- this.selectedChildConnection?.peerId === childPeerId &&
- this.selectedChildConnection.connectionId === peer.connectionId
+ this.selectedChildConnections.get(childPeerId)?.connectionId ===
+ peer.connectionId
) {
- this.selectedChildConnection = null;
+ this.selectedChildConnections.delete(childPeerId);
this.childPeerIds = this.childPeerIds.filter(
(peerId) => peerId !== childPeerId,
);
@@ -643,4 +639,14 @@ export class ViewerRelay {
this.events.onUpdate?.(this.getSnapshot());
peer?.dispose();
}
+
+ private clearSelectedChildConnection(childPeerId: string): void {
+ if (!this.selectedChildConnections.delete(childPeerId)) {
+ return;
+ }
+ this.childPeerIds = this.childPeerIds.filter(
+ (peerId) => peerId !== childPeerId,
+ );
+ this.disposePeer(childPeerId);
+ }
}
diff --git a/src/server/app.ts b/src/server/app.ts
index 597ed7b2..9c74a51f 100644
--- a/src/server/app.ts
+++ b/src/server/app.ts
@@ -11,10 +11,14 @@ import {
import { SiteAccess } from "./access-session.js";
import { loadConfig, type ServerConfig } from "./config.js";
import { createIceConfig } from "./ice.js";
-import type { SfuFallbackOptions } from "./hybrid-media-router.js";
+import type {
+ SelectedEdgeTurnOptions,
+ SfuFallbackOptions,
+} from "./hybrid-media-router.js";
import type { SfuTokenIssuer } from "./livekit-token.js";
import type { SfuRoomControl } from "./sfu-room-control.js";
import { SfuResourceAdmission } from "./sfu-resource-admission.js";
+import { TurnAllocationAdmission } from "./turn-allocation-admission.js";
import { RoomDatabase } from "./room-database.js";
import { RoomStore, RoomStoreError } from "./room-store.js";
import { SignalingServer, type SignalingOptions } from "./signaling.js";
@@ -53,6 +57,7 @@ export async function createScreenerServer(
const livekitFallback = config.livekitFallback;
let sfuFallback: SfuFallbackOptions | undefined;
let sfuRoomControl: SfuRoomControl | undefined;
+ let selectedEdgeTurn: SelectedEdgeTurnOptions | undefined;
if (livekitFallback) {
sfuRoomControl =
options.sfuRoomControl ??
@@ -78,6 +83,14 @@ export async function createScreenerServer(
roomControl: sfuRoomControl,
};
}
+ if (config.selectedEdgeTurn) {
+ selectedEdgeTurn = {
+ config: config.selectedEdgeTurn,
+ admission: new TurnAllocationAdmission({
+ capacity: config.selectedEdgeTurn.allocationCapacity,
+ }),
+ };
+ }
const roomStore =
options.roomStore ??
new RoomStore({
@@ -138,7 +151,7 @@ export async function createScreenerServer(
peerAssistedMedia: config.peerAssistedMedia,
endpointMediaCopyCapacity: config.endpointMediaCopyCapacity,
...(sfuFallback ? { sfuFallback } : {}),
- ...(config.selectedEdgeTurn ? { selectedEdgeTurn: config.selectedEdgeTurn } : {}),
+ ...(selectedEdgeTurn ? { selectedEdgeTurn } : {}),
ice: iceOptions,
allowedOrigins: config.allowedOrigins,
siteAccessAtUpgrade: (request) =>
diff --git a/src/server/config.ts b/src/server/config.ts
index 774978e5..7f112acb 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -46,6 +46,7 @@ export interface SelectedEdgeTurnConfig {
urls: readonly [string];
sharedSecret: string;
credentialTtlSeconds: number;
+ allocationCapacity: number;
}
export interface ServerConfig {
@@ -283,6 +284,7 @@ export function parseSelectedEdgeTurn(
const names = [
"SELECTED_EDGE_TURN_URLS", "SELECTED_EDGE_TURN_SHARED_SECRET",
"SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS",
+ "SELECTED_EDGE_TURN_ALLOCATION_CAPACITY",
] as const;
const configuredNames = names.filter((name) => environment[name]?.trim());
if (configuredNames.length === 0) {
@@ -323,6 +325,10 @@ export function parseSelectedEdgeTurn(
MIN_SELECTED_EDGE_TURN_TTL_SECONDS,
MAX_SELECTED_EDGE_TURN_TTL_SECONDS,
),
+ allocationCapacity: parseRequiredPositiveInteger(
+ environment.SELECTED_EDGE_TURN_ALLOCATION_CAPACITY,
+ "SELECTED_EDGE_TURN_ALLOCATION_CAPACITY",
+ ),
};
}
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index fa2699e8..ed02ada2 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -36,7 +36,13 @@ import {
type MediaAssignmentChange,
} from "./peer-relay-topology.js";
import type { RoomStore } from "./room-store.js";
-import { issueSelectedEdgeTurnCredential } from "./selected-edge-turn.js";
+import {
+ issueSelectedEdgeTurnCredential,
+ type HostSfuIngressTurnIdentity,
+ type PeerSelectedEdgeTurnIdentity,
+ type SelectedEdgeTurnIdentity,
+} from "./selected-edge-turn.js";
+import type { TurnAllocationAdmission } from "./turn-allocation-admission.js";
type ErrorCode = Extract<ServerMessage, { type: "error" }>["code"];
@@ -100,6 +106,7 @@ interface SelectedPeerEdgeLease {
viewerPeerId: string;
viewerSessionId: string;
newConnectionId: string;
+ allocationFence: PeerSelectedEdgeTurnIdentity;
grant: Extract<
ServerMessage,
{ type: "selected-edge-turn"; edgeKind: "peer-selected" }
@@ -117,6 +124,7 @@ interface SelectedSfuIngressAttempt {
publicationGeneration: string;
oldConnectionId: string;
newConnectionId: string;
+ allocationFence: HostSfuIngressTurnIdentity;
answered: boolean;
timer: NodeJS.Timeout;
}
@@ -127,6 +135,7 @@ interface ActiveSelectedSfuIngress {
hostSessionId: string;
publicationGeneration: string;
connectionId: string;
+ allocationFence: HostSfuIngressTurnIdentity;
}
interface HealthySfuReselectionProbe {
@@ -214,11 +223,16 @@ export interface SfuFallbackOptions {
hostOfflineCheckMs?: number;
}
+export interface SelectedEdgeTurnOptions {
+ config: SelectedEdgeTurnConfig;
+ admission: TurnAllocationAdmission;
+}
+
export interface HybridMediaRouterOptions {
roomStore: RoomStore;
endpointMediaCopyCapacity: number;
sfuFallback?: SfuFallbackOptions;
- selectedEdgeTurn?: SelectedEdgeTurnConfig;
+ selectedEdgeTurn?: SelectedEdgeTurnOptions;
sendToSession: (sessionId: string, message: ServerMessage) => void;
getConnectionId: (roomId: string, viewerPeerId: string) => string | undefined;
setConnectionId: (roomId: string, viewerPeerId: string, connectionId: string) => void;
@@ -273,7 +287,7 @@ export class HybridMediaRouter {
private readonly consumedSfuRefreshesByRoom = new Map<string, Set<string>>();
private readonly selectedPeerEdgeLeasesByRoom = new Map<
string,
- SelectedPeerEdgeLease
+ Map<string, SelectedPeerEdgeLease>
>();
private readonly selectedSfuIngressAttempts = new Map<
string,
@@ -347,12 +361,16 @@ export class HybridMediaRouter {
clearTimeout(pending.timer);
}
this.pendingRoutePreparations.clear();
- for (const lease of this.selectedPeerEdgeLeasesByRoom.values()) {
- clearTimeout(lease.timer);
+ for (const roomLeases of this.selectedPeerEdgeLeasesByRoom.values()) {
+ for (const lease of roomLeases.values()) {
+ clearTimeout(lease.timer);
+ this.releaseTurnAllocation(lease.allocationFence);
+ }
}
this.selectedPeerEdgeLeasesByRoom.clear();
for (const attempt of this.selectedSfuIngressAttempts.values()) {
clearTimeout(attempt.timer);
+ this.releaseTurnAllocation(attempt.allocationFence);
}
this.selectedSfuIngressAttempts.clear();
for (const deferred of this.deferredHealthySfuReselections.values()) {
@@ -365,7 +383,19 @@ export class HybridMediaRouter {
clearTimeout(check.timer);
}
this.hostOfflineChecks.clear();
+ for (const ingress of this.activeSelectedSfuIngresses.values()) {
+ this.releaseTurnAllocation(ingress.allocationFence);
+ }
this.activeSelectedSfuIngresses.clear();
+ const turnAdmission = this.options.selectedEdgeTurn?.admission;
+ if (turnAdmission) {
+ for (const fence of turnAdmission.beginDrainAll()) {
+ turnAdmission.completeDrain(fence);
+ }
+ if (turnAdmission.usage().allocations !== 0) {
+ throw new Error("TURN allocations were not fully released during shutdown");
+ }
+ }
this.mediaRouteControllers.clear();
this.failedParentPeerIdsByViewer.clear();
this.viewerRouteIntentsByRoom.clear();
@@ -520,15 +550,11 @@ export class HybridMediaRouter {
signalKind: "candidate" | "description";
descriptionType?: "offer" | "answer";
}): boolean | "probe" | undefined {
- const roomLease = this.selectedPeerEdgeLeasesByRoom.get(input.roomId);
- const lease =
- roomLease &&
- ((roomLease.parentPeerId === input.sourcePeerId &&
- roomLease.viewerPeerId === input.targetPeerId) ||
- (roomLease.viewerPeerId === input.sourcePeerId &&
- roomLease.parentPeerId === input.targetPeerId))
- ? roomLease
- : undefined;
+ const lease = this.selectedPeerEdgeLeaseForPeers(
+ input.roomId,
+ input.sourcePeerId,
+ input.targetPeerId,
+ );
if (!lease) {
const pending = this.pendingRoutePreparations.get(input.roomId);
const qualityProbe = pending?.peerQualityReselection;
@@ -602,11 +628,20 @@ export class HybridMediaRouter {
viewerPeerId: string,
connectionId: string,
): void {
- const lease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ const lease = this.selectedPeerEdgeLease(roomId, viewerPeerId);
if (
lease?.viewerPeerId === viewerPeerId &&
lease.newConnectionId === connectionId
) {
+ if (!this.options.selectedEdgeTurn?.admission.commit(lease.allocationFence)) {
+ this.settleSelectedPeerEdgeLease(roomId, viewerPeerId);
+ this.sendError(
+ lease.viewerSessionId,
+ "SERVER_ERROR",
+ "Selected relay edge lost its resource reservation",
+ );
+ return;
+ }
lease.answered = true;
clearTimeout(lease.timer);
this.drainViewerRouteIntents(roomId);
@@ -1318,7 +1353,7 @@ export class HybridMediaRouter {
(message.phase === "prepare" && message.revision === healthyPending?.revision))
) {
this.abortPeerQualityReselectionForHardFailure(participant.roomId);
- this.activeSelectedSfuIngresses.delete(participant.roomId);
+ this.settleActiveSelectedSfuIngress(participant.roomId);
this.failBackToPeerBaseline(participant.roomId);
return;
}
@@ -1367,7 +1402,7 @@ export class HybridMediaRouter {
: message.connectionId === null;
if (activeSfuTransportFailed) {
if (participant.role === "host") {
- this.activeSelectedSfuIngresses.delete(participant.roomId);
+ this.settleActiveSelectedSfuIngress(participant.roomId);
}
this.abortPendingRoute(participant.roomId, undefined, false);
return;
@@ -1698,10 +1733,10 @@ export class HybridMediaRouter {
if (pending?.peerQualityReselection) {
return "quality";
}
- const lease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
- return lease && (!lease.answered || lease.viewerPeerId === viewerPeerId)
- ? "selected"
- : null;
+ const lease = viewerPeerId
+ ? this.selectedPeerEdgeLease(roomId, viewerPeerId)
+ : undefined;
+ return lease ? "selected" : null;
}
private abortPeerQualityReselectionForHardFailure(roomId: string, failedViewerPeerId?: string): void {
@@ -1716,24 +1751,23 @@ export class HybridMediaRouter {
viewerPeerId: string,
requireConsumedSfuRefresh: boolean,
): boolean {
- const config = this.options.selectedEdgeTurn;
+ const config = this.options.selectedEdgeTurn?.config;
+ const admission = this.options.selectedEdgeTurn?.admission;
const controller = this.mediaRouteControllers.get(roomId);
const active = controller?.getActiveRoute();
const intent = this.viewerRouteIntentsByRoom.get(roomId)?.get(viewerPeerId);
- const roomAttempt = this.roomPeerMigrationAttempt(roomId);
+ const roomAttempt = this.roomPeerMigrationAttempt(roomId, viewerPeerId);
if (roomAttempt === "healthy" || roomAttempt === "quality") {
// The room probe already owns recovery, so suppress concurrent failback.
return true;
}
- const roomLease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
- if (roomLease?.viewerPeerId === viewerPeerId) {
+ const roomLease = this.selectedPeerEdgeLease(roomId, viewerPeerId);
+ if (roomLease) {
return true;
}
- if (roomAttempt === "selected" || roomLease) {
- return false;
- }
if (
!config ||
+ !admission ||
!active ||
!intent ||
intent.selectedTurnAttempted ||
@@ -1761,12 +1795,12 @@ export class HybridMediaRouter {
intent.failedParentPeerId,
);
const parentActiveEdges = parentAssignment
- ? countEndpointMediaCopies({
- childPeerIds: parentAssignment.childPeerIds,
- publicationGeneration:
- parentAssignment.sfuPublicationGeneration,
- selectedChildPeerIds: [viewerPeerId],
- })
+ ? this.activeParentMediaEdges(
+ roomId,
+ intent.failedParentPeerId,
+ parentAssignment,
+ [viewerPeerId],
+ )
: Number.POSITIVE_INFINITY;
if (
viewer?.sessionId !== intent.sessionId ||
@@ -1800,31 +1834,36 @@ export class HybridMediaRouter {
intent.selectedTurnAttempted = true;
const newConnectionId = randomBytes(16).toString("base64url");
+ const allocationFence: PeerSelectedEdgeTurnIdentity = {
+ edgeKind: "peer-selected",
+ roomId,
+ shareGeneration,
+ revision: active.revision,
+ parentPeerId: parent.peerId,
+ parentSessionId: parent.sessionId,
+ viewerPeerId,
+ viewerSessionId: viewer.sessionId,
+ oldConnectionId: intent.failedConnectionId,
+ newConnectionId,
+ };
+ if (!admission.reserve(allocationFence)) {
+ return false;
+ }
let credential;
try {
credential = issueSelectedEdgeTurnCredential(
config,
- {
- edgeKind: "peer-selected",
- roomId,
- shareGeneration,
- revision: active.revision,
- parentPeerId: parent.peerId,
- parentSessionId: parent.sessionId,
- viewerPeerId,
- viewerSessionId: viewer.sessionId,
- oldConnectionId: intent.failedConnectionId,
- newConnectionId,
- },
+ allocationFence,
this.options.now?.() ?? Date.now(),
);
} catch {
+ this.releaseTurnAllocation(allocationFence);
console.error("Selected-edge TURN credential issuance failed");
return false;
}
const timer = setTimeout(() => {
- const current = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ const current = this.selectedPeerEdgeLease(roomId, viewerPeerId);
if (
!current ||
current.newConnectionId !== newConnectionId ||
@@ -1832,7 +1871,7 @@ export class HybridMediaRouter {
) {
return;
}
- const settled = this.settleSelectedPeerEdgeLease(roomId);
+ const settled = this.settleSelectedPeerEdgeLease(roomId, viewerPeerId);
if (!settled) {
return;
}
@@ -1864,11 +1903,12 @@ export class HybridMediaRouter {
viewerPeerId,
viewerSessionId: viewer.sessionId,
newConnectionId,
+ allocationFence,
grant: message,
answered: false,
timer,
};
- this.selectedPeerEdgeLeasesByRoom.set(roomId, lease);
+ this.storeSelectedPeerEdgeLease(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);
@@ -1888,7 +1928,8 @@ export class HybridMediaRouter {
route: RoomMediaRoute,
pending?: PendingRoutePreparation,
): boolean {
- const config = this.options.selectedEdgeTurn;
+ const config = this.options.selectedEdgeTurn?.config;
+ const admission = this.options.selectedEdgeTurn?.admission;
const fallback = this.options.sfuFallback;
const key = roomId;
const currentAttempt = this.selectedSfuIngressAttempts.get(key);
@@ -1905,6 +1946,7 @@ export class HybridMediaRouter {
}
if (
!config ||
+ !admission ||
!fallback ||
(pending !== undefined &&
(pending.revision !== route.revision ||
@@ -1927,27 +1969,41 @@ export class HybridMediaRouter {
) {
return false;
}
+ const activeIngress = this.activeSelectedSfuIngresses.get(roomId);
+ if (
+ activeIngress?.hostPeerId === hostPeerId &&
+ activeIngress.hostSessionId === hostSessionId &&
+ activeIngress.shareGeneration === shareGeneration &&
+ activeIngress.publicationGeneration === publicationGeneration
+ ) {
+ return true;
+ }
const oldConnectionId = publicationGeneration;
const newConnectionId = randomBytes(16).toString("base64url");
+ const allocationFence: HostSfuIngressTurnIdentity = {
+ edgeKind: "host-sfu-ingress",
+ roomId,
+ shareGeneration,
+ revision,
+ hostPeerId,
+ hostSessionId,
+ publicationGeneration,
+ oldConnectionId,
+ newConnectionId,
+ };
+ if (!admission.reserve(allocationFence)) {
+ return false;
+ }
let credential;
try {
credential = issueSelectedEdgeTurnCredential(
config,
- {
- edgeKind: "host-sfu-ingress",
- roomId,
- shareGeneration,
- revision,
- hostPeerId,
- hostSessionId,
- publicationGeneration,
- oldConnectionId,
- newConnectionId,
- },
+ allocationFence,
this.options.now?.() ?? Date.now(),
);
} catch {
+ this.releaseTurnAllocation(allocationFence);
console.error("Selected-edge TURN credential issuance failed");
return false;
}
@@ -1964,7 +2020,7 @@ export class HybridMediaRouter {
return;
}
if (currentIngress) {
- this.selectedSfuIngressAttempts.delete(key);
+ this.settleSelectedSfuIngressAttempt(key);
this.sendError(
current.hostSessionId,
"PEER_NOT_FOUND",
@@ -1990,6 +2046,7 @@ export class HybridMediaRouter {
publicationGeneration,
oldConnectionId,
newConnectionId,
+ allocationFence,
answered: false,
timer,
};
@@ -1998,7 +2055,6 @@ export class HybridMediaRouter {
pending.timer = timer;
pending.hostSfuIngressTurnAttempted = true;
}
- this.activeSelectedSfuIngresses.delete(roomId);
this.selectedSfuIngressAttempts.set(key, attempt);
this.options.sendToSession(hostSessionId, {
type: "selected-edge-turn",
@@ -2029,18 +2085,29 @@ export class HybridMediaRouter {
) {
return;
}
+ if (
+ !this.options.selectedEdgeTurn?.admission.commit(
+ attempt.allocationFence,
+ )
+ ) {
+ this.settleSelectedSfuIngressAttempt(roomId);
+ this.sendError(
+ hostSessionId,
+ "SERVER_ERROR",
+ "Selected SFU relay ingress lost its resource reservation",
+ );
+ if (this.pendingRoutePreparations.get(roomId)?.revision === revision) {
+ this.abortPendingRoute(roomId);
+ } else {
+ this.failBackToPeerBaseline(roomId);
+ }
+ return;
+ }
attempt.answered = true;
- if (this.pendingRoutePreparations.get(roomId)?.timer !== attempt.timer) {
- clearTimeout(attempt.timer);
+ if (this.pendingRoutePreparations.get(roomId)?.revision === revision) {
+ return;
}
- this.selectedSfuIngressAttempts.delete(roomId);
- this.activeSelectedSfuIngresses.set(roomId, {
- shareGeneration: attempt.shareGeneration,
- hostPeerId: attempt.hostPeerId,
- hostSessionId: attempt.hostSessionId,
- publicationGeneration: attempt.publicationGeneration,
- connectionId: attempt.newConnectionId,
- });
+ this.promoteSelectedSfuIngressAttempt(roomId, revision);
}
private selectedSfuIngressAttemptIsCurrent(
@@ -2074,8 +2141,46 @@ export class HybridMediaRouter {
this.options.getShareGeneration(participant.roomId) &&
attempt.newConnectionId === message.connectionId
) {
- clearTimeout(attempt.timer);
- this.selectedSfuIngressAttempts.delete(participant.roomId);
+ const pendingRevision = this.pendingRoutePreparations.get(
+ participant.roomId,
+ )?.revision;
+ this.settleSelectedSfuIngressAttempt(participant.roomId);
+ this.sendError(
+ participant.sessionId,
+ "PEER_NOT_FOUND",
+ "Selected SFU relay ingress failed",
+ );
+ if (pendingRevision === message.revision) {
+ this.abortPendingRoute(participant.roomId, undefined, false);
+ } else {
+ this.failBackToPeerBaseline(participant.roomId);
+ }
+ return true;
+ }
+ const activeIngress = this.activeSelectedSfuIngresses.get(
+ participant.roomId,
+ );
+ const activeRoute = this.mediaRouteControllers
+ .get(participant.roomId)
+ ?.getActiveRoute();
+ if (
+ activeIngress?.hostPeerId === participant.peerId &&
+ activeIngress.hostSessionId === participant.sessionId &&
+ activeIngress.connectionId === message.connectionId &&
+ activeIngress.shareGeneration ===
+ this.options.getShareGeneration(participant.roomId) &&
+ activeRoute !== undefined &&
+ activeRoute.sfu.publicationGeneration ===
+ activeIngress.publicationGeneration &&
+ activeRoute.assignments.get(participant.peerId)
+ ?.sfuPublicationGeneration === activeIngress.publicationGeneration &&
+ ((message.phase === "active" &&
+ activeRoute.revision === message.revision) ||
+ (message.phase === "prepare" &&
+ this.pendingRoutePreparations.get(participant.roomId)?.revision ===
+ message.revision))
+ ) {
+ this.settleActiveSelectedSfuIngress(participant.roomId);
this.sendError(
participant.sessionId,
"PEER_NOT_FOUND",
@@ -2088,7 +2193,11 @@ export class HybridMediaRouter {
if (message.connectionId === null) {
return false;
}
- const lease = this.selectedPeerEdgeLeasesByRoom.get(participant.roomId);
+ const lease = this.selectedPeerEdgeLeaseForParticipantConnection(
+ participant.roomId,
+ participant.peerId,
+ message.connectionId,
+ );
const active = this.mediaRouteControllers
.get(participant.roomId)
?.getActiveRoute();
@@ -2114,7 +2223,10 @@ export class HybridMediaRouter {
participant.roomId,
lease.viewerPeerId,
);
- this.settleSelectedPeerEdgeLease(participant.roomId);
+ this.settleSelectedPeerEdgeLease(
+ participant.roomId,
+ lease.viewerPeerId,
+ );
this.sendError(
participant.sessionId,
"PEER_NOT_FOUND",
@@ -2245,8 +2357,7 @@ export class HybridMediaRouter {
for (const [viewerPeerId, intent] of [...intents]) {
if (
- this.selectedPeerEdgeLeasesByRoom.get(roomId)?.viewerPeerId ===
- viewerPeerId
+ this.selectedPeerEdgeLease(roomId, viewerPeerId)
) {
continue;
}
@@ -2429,6 +2540,9 @@ export class HybridMediaRouter {
(intent.sfuAttempts > 0 || intent.unavailableReported) &&
this.startSelectedEdgeTurn(roomId, viewerPeerId, false)
) {
+ if (this.selectedPeerEdgeLease(roomId, viewerPeerId)) {
+ continue;
+ }
return;
}
@@ -2464,7 +2578,7 @@ export class HybridMediaRouter {
!guard ||
!controller ||
controller.getPendingRoute() ||
- this.roomPeerMigrationAttempt(roomId) !== null ||
+ this.roomPeerMigrationAttempt(roomId, viewerPeerId) !== null ||
!active ||
!viewer ||
!shareGeneration ||
@@ -3096,6 +3210,12 @@ export class HybridMediaRouter {
}
supersededSfuFences = result;
}
+ if (
+ pending.hostSfuIngressTurnAttempted &&
+ !this.promoteSelectedSfuIngressAttempt(roomId, revision)
+ ) {
+ throw new Error("Committed SFU route has no selected ingress candidate");
+ }
clearTimeout(pending.timer);
this.pendingRoutePreparations.delete(roomId);
const active = controller.getActiveRoute();
@@ -3196,15 +3316,20 @@ export class HybridMediaRouter {
roomId: string,
parentPeerId: string,
assignment: ParticipantRouteAssignment,
+ additionalSelectedChildPeerIds: readonly string[] = [],
): number {
- const selectedLease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ const selectedChildPeerIds = [
+ ...(this.selectedPeerEdgeLeasesByRoom.get(roomId)?.values() ?? []),
+ ]
+ .filter((lease) => lease.parentPeerId === parentPeerId)
+ .map((lease) => lease.viewerPeerId);
return countEndpointMediaCopies({
childPeerIds: assignment.childPeerIds,
publicationGeneration: assignment.sfuPublicationGeneration,
- selectedChildPeerIds:
- selectedLease?.parentPeerId === parentPeerId
- ? [selectedLease.viewerPeerId]
- : [],
+ selectedChildPeerIds: [
+ ...selectedChildPeerIds,
+ ...additionalSelectedChildPeerIds,
+ ],
});
}
@@ -3262,8 +3387,7 @@ export class HybridMediaRouter {
}
if (participant.role === "viewer") {
return (
- this.selectedPeerEdgeLeasesByRoom.get(participant.roomId)
- ?.viewerPeerId !== participant.peerId &&
+ !this.selectedPeerEdgeLease(participant.roomId, participant.peerId) &&
assignment.upstream.kind === "sfu" &&
active.sfu.rootPeerIds.includes(participant.peerId)
);
@@ -3304,8 +3428,7 @@ export class HybridMediaRouter {
}
const ingress = this.selectedSfuIngressAttempts.get(roomId);
if (ingress?.revision === pending.revision) {
- clearTimeout(ingress.timer);
- this.selectedSfuIngressAttempts.delete(roomId);
+ this.settleSelectedSfuIngressAttempt(roomId);
}
if (controller?.abort(pending.revision)) {
this.broadcastActiveRoute(
@@ -3479,7 +3602,7 @@ export class HybridMediaRouter {
activeIngress.shareGeneration ===
this.options.getShareGeneration(roomId)
) {
- this.activeSelectedSfuIngresses.delete(roomId);
+ this.settleActiveSelectedSfuIngress(roomId);
}
}
try {
@@ -3637,8 +3760,7 @@ export class HybridMediaRouter {
this.reconcileSelectedPeerEdgeLeases(roomId, route);
for (const [key, attempt] of this.selectedSfuIngressAttempts) {
if (attempt.roomId === roomId && attempt.revision !== route.revision) {
- clearTimeout(attempt.timer);
- this.selectedSfuIngressAttempts.delete(key);
+ this.settleSelectedSfuIngressAttempt(key);
}
}
const activeIngress = this.activeSelectedSfuIngresses.get(roomId);
@@ -3653,7 +3775,7 @@ export class HybridMediaRouter {
this.options.getShareGeneration(roomId) !==
activeIngress.shareGeneration)
) {
- this.activeSelectedSfuIngresses.delete(roomId);
+ this.settleActiveSelectedSfuIngress(roomId);
}
this.clearRoomViewerQualityEvidenceStates(roomId);
for (const [peerId, assignment] of route.assignments) {
@@ -3665,6 +3787,54 @@ export class HybridMediaRouter {
this.options.onActiveRouteChanged?.(roomId);
}
+ private selectedPeerEdgeLease(
+ roomId: string,
+ viewerPeerId: string,
+ ): SelectedPeerEdgeLease | undefined {
+ return this.selectedPeerEdgeLeasesByRoom.get(roomId)?.get(viewerPeerId);
+ }
+
+ private selectedPeerEdgeLeaseForPeers(
+ roomId: string,
+ firstPeerId: string,
+ secondPeerId: string,
+ ): SelectedPeerEdgeLease | undefined {
+ const firstAsViewer = this.selectedPeerEdgeLease(roomId, firstPeerId);
+ if (firstAsViewer?.parentPeerId === secondPeerId) {
+ return firstAsViewer;
+ }
+ const secondAsViewer = this.selectedPeerEdgeLease(roomId, secondPeerId);
+ return secondAsViewer?.parentPeerId === firstPeerId
+ ? secondAsViewer
+ : undefined;
+ }
+
+ private selectedPeerEdgeLeaseForParticipantConnection(
+ roomId: string,
+ peerId: string,
+ connectionId: string,
+ ): SelectedPeerEdgeLease | undefined {
+ const viewerLease = this.selectedPeerEdgeLease(roomId, peerId);
+ if (viewerLease?.newConnectionId === connectionId) {
+ return viewerLease;
+ }
+ return [...(this.selectedPeerEdgeLeasesByRoom.get(roomId)?.values() ?? [])]
+ .find(
+ (lease) =>
+ lease.parentPeerId === peerId &&
+ lease.newConnectionId === connectionId,
+ );
+ }
+
+ private storeSelectedPeerEdgeLease(lease: SelectedPeerEdgeLease): void {
+ let roomLeases = this.selectedPeerEdgeLeasesByRoom.get(lease.roomId);
+ if (!roomLeases) {
+ roomLeases = new Map();
+ this.selectedPeerEdgeLeasesByRoom.set(lease.roomId, roomLeases);
+ }
+ roomLeases.set(lease.viewerPeerId, lease);
+ }
+
private selectedPeerEdgeLeaseIsCurrent(
roomId: string,
lease: SelectedPeerEdgeLease,
@@ -3685,12 +3855,11 @@ export class HybridMediaRouter {
? activeParentAssignment?.upstream.kind === "none"
: activeParentAssignment?.upstream.kind === "peer";
const activeParentEdges = activeParentAssignment
- ? countEndpointMediaCopies({
- childPeerIds: activeParentAssignment.childPeerIds,
- publicationGeneration:
- activeParentAssignment.sfuPublicationGeneration,
- selectedChildPeerIds: [lease.viewerPeerId],
- })
+ ? this.activeParentMediaEdges(
+ roomId,
+ lease.parentPeerId,
+ activeParentAssignment,
+ )
: Number.POSITIVE_INFINITY;
return (
route.revision === lease.currentRouteRevision &&
@@ -3716,26 +3885,34 @@ export class HybridMediaRouter {
roomId: string,
route: RoomMediaRoute,
): void {
- const lease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
- if (!lease) {
+ const leases = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ if (!leases) {
return;
}
- lease.currentRouteRevision = route.revision;
- if (!this.selectedPeerEdgeLeaseIsCurrent(roomId, lease, route)) {
- this.settleSelectedPeerEdgeLease(roomId);
+ for (const lease of [...leases.values()].reverse()) {
+ lease.currentRouteRevision = route.revision;
+ if (!this.selectedPeerEdgeLeaseIsCurrent(roomId, lease, route)) {
+ this.settleSelectedPeerEdgeLease(roomId, lease.viewerPeerId);
+ }
}
}
private settleSelectedPeerEdgeLease(
roomId: string,
+ viewerPeerId: string,
excludedPeerId?: string,
): SelectedPeerEdgeLease | undefined {
- const lease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ const roomLeases = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ const lease = roomLeases?.get(viewerPeerId);
if (!lease) {
return undefined;
}
clearTimeout(lease.timer);
- this.selectedPeerEdgeLeasesByRoom.delete(roomId);
+ roomLeases!.delete(viewerPeerId);
+ if (roomLeases!.size === 0) {
+ this.selectedPeerEdgeLeasesByRoom.delete(roomId);
+ }
+ this.releaseTurnAllocation(lease.allocationFence);
const active = this.mediaRouteControllers.get(lease.roomId)?.getActiveRoute();
if (!active) {
@@ -3751,14 +3928,7 @@ export class HybridMediaRouter {
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: active.revision,
- phase: "active",
- assignment,
- });
+ this.sendActiveRouteUpdate(lease.roomId, peerId, active, assignment);
}
}
return lease;
@@ -3774,16 +3944,18 @@ export class HybridMediaRouter {
if (!peer || !assignment) {
return;
}
- const lease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
- if (
- lease &&
- (lease.parentPeerId === peerId || lease.viewerPeerId === peerId) &&
- this.selectedPeerEdgeLeaseIsCurrent(roomId, lease, route)
- ) {
- this.options.sendToSession(peer.sessionId, {
- ...lease.grant,
- revision: route.revision,
- });
+ for (const lease of this.selectedPeerEdgeLeasesByRoom
+ .get(roomId)
+ ?.values() ?? []) {
+ if (
+ (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",
@@ -4076,17 +4248,16 @@ export class HybridMediaRouter {
this.mediaRouteControllers.delete(roomId);
this.clearRoomFailedParents(roomId);
this.viewerRouteIntentsByRoom.delete(roomId);
- const selectedLease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
- if (selectedLease) {
- clearTimeout(selectedLease.timer);
+ const selectedLeases = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ if (selectedLeases) {
+ for (const lease of selectedLeases.values()) {
+ clearTimeout(lease.timer);
+ this.releaseTurnAllocation(lease.allocationFence);
+ }
this.selectedPeerEdgeLeasesByRoom.delete(roomId);
}
- const ingress = this.selectedSfuIngressAttempts.get(roomId);
- if (ingress) {
- clearTimeout(ingress.timer);
- this.selectedSfuIngressAttempts.delete(roomId);
- }
- this.activeSelectedSfuIngresses.delete(roomId);
+ this.settleSelectedSfuIngressAttempt(roomId);
+ this.settleActiveSelectedSfuIngress(roomId);
this.clearDeferredHealthySfuReselection(roomId);
this.consumedSfuRefreshesByRoom.delete(roomId);
this.sfuDisabledRoomIds.delete(roomId);
@@ -4095,24 +4266,84 @@ export class HybridMediaRouter {
this.beginSfuRoomDrain(roomId);
}
+ private settleSelectedSfuIngressAttempt(
+ roomId: string,
+ ): SelectedSfuIngressAttempt | undefined {
+ const attempt = this.selectedSfuIngressAttempts.get(roomId);
+ if (!attempt) {
+ return undefined;
+ }
+ clearTimeout(attempt.timer);
+ this.selectedSfuIngressAttempts.delete(roomId);
+ this.releaseTurnAllocation(attempt.allocationFence);
+ return attempt;
+ }
+
+ private promoteSelectedSfuIngressAttempt(
+ roomId: string,
+ revision: number,
+ ): boolean {
+ const attempt = this.selectedSfuIngressAttempts.get(roomId);
+ if (!attempt || attempt.revision !== revision || !attempt.answered) {
+ return false;
+ }
+ clearTimeout(attempt.timer);
+ this.selectedSfuIngressAttempts.delete(roomId);
+ this.settleActiveSelectedSfuIngress(roomId);
+ this.activeSelectedSfuIngresses.set(roomId, {
+ shareGeneration: attempt.shareGeneration,
+ hostPeerId: attempt.hostPeerId,
+ hostSessionId: attempt.hostSessionId,
+ publicationGeneration: attempt.publicationGeneration,
+ connectionId: attempt.newConnectionId,
+ allocationFence: attempt.allocationFence,
+ });
+ return true;
+ }
+
+ private settleActiveSelectedSfuIngress(
+ roomId: string,
+ ): ActiveSelectedSfuIngress | undefined {
+ const ingress = this.activeSelectedSfuIngresses.get(roomId);
+ if (!ingress) {
+ return undefined;
+ }
+ this.activeSelectedSfuIngresses.delete(roomId);
+ this.releaseTurnAllocation(ingress.allocationFence);
+ return ingress;
+ }
+
+ private releaseTurnAllocation(fence: SelectedEdgeTurnIdentity): boolean {
+ const admission = this.options.selectedEdgeTurn?.admission;
+ if (!admission?.beginDrain(fence)) {
+ return false;
+ }
+ if (!admission.completeDrain(fence)) {
+ throw new Error("TURN allocation drain could not be completed");
+ }
+ return true;
+ }
+
private clearSelectedEdgeTurnsForParticipant(
roomId: string,
peerId: string,
): void {
- const lease = this.selectedPeerEdgeLeasesByRoom.get(roomId);
- if (
- lease &&
- (lease.parentPeerId === peerId || lease.viewerPeerId === peerId)
- ) {
- this.settleSelectedPeerEdgeLease(roomId, peerId);
+ const leases = this.selectedPeerEdgeLeasesByRoom.get(roomId);
+ for (const lease of [...(leases?.values() ?? [])]) {
+ if (lease.parentPeerId === peerId || lease.viewerPeerId === peerId) {
+ this.settleSelectedPeerEdgeLease(
+ roomId,
+ lease.viewerPeerId,
+ peerId,
+ );
+ }
}
const ingress = this.selectedSfuIngressAttempts.get(roomId);
if (ingress?.hostPeerId === peerId) {
- clearTimeout(ingress.timer);
- this.selectedSfuIngressAttempts.delete(roomId);
+ this.settleSelectedSfuIngressAttempt(roomId);
}
if (this.activeSelectedSfuIngresses.get(roomId)?.hostPeerId === peerId) {
- this.activeSelectedSfuIngresses.delete(roomId);
+ this.settleActiveSelectedSfuIngress(roomId);
}
}
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index f8d27e0f..cdfd6ff9 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -27,9 +27,9 @@ import {
RoomStoreError,
type ConnectedPeer,
} from "./room-store.js";
-import type { SelectedEdgeTurnConfig } from "./config.js";
import {
HybridMediaRouter,
+ type SelectedEdgeTurnOptions,
type SfuFallbackOptions,
} from "./hybrid-media-router.js";
import { createIceConfig, type IceConfigOptions } from "./ice.js";
@@ -87,7 +87,7 @@ export interface SignalingOptions {
peerAssistedMedia: boolean;
endpointMediaCopyCapacity: number;
sfuFallback?: SfuFallbackOptions;
- selectedEdgeTurn?: SelectedEdgeTurnConfig;
+ selectedEdgeTurn?: SelectedEdgeTurnOptions;
ice: IceConfigOptions;
allowedOrigins: ReadonlySet<string>;
siteAccessAtUpgrade: (request: IncomingMessage) => boolean;
diff --git a/src/server/turn-allocation-admission.ts b/src/server/turn-allocation-admission.ts
new file mode 100644
index 00000000..1cb4a291
--- /dev/null
+++ b/src/server/turn-allocation-admission.ts
@@ -0,0 +1,214 @@
+import type { SelectedEdgeTurnIdentity } from "./selected-edge-turn.js";
+
+export interface TurnAllocationAdmissionOptions {
+ readonly capacity: number;
+}
+
+export interface TurnAllocationUsage {
+ allocations: number;
+}
+
+export type TurnAllocationState = "reserved" | "committed" | "draining";
+
+interface TurnAllocationEntry {
+ fence: SelectedEdgeTurnIdentity;
+ state: TurnAllocationState;
+}
+
+export class TurnAllocationAdmission {
+ private readonly entries = new Map<string, TurnAllocationEntry>();
+ private readonly allocationIdsByRoom = new Map<string, Set<string>>();
+ private readonly capacity: number;
+
+ constructor(options: TurnAllocationAdmissionOptions) {
+ assertPositiveSafeInteger(options.capacity, "TURN allocation capacity");
+ this.capacity = options.capacity;
+ }
+
+ reserve(fence: SelectedEdgeTurnIdentity): boolean {
+ assertFence(fence);
+ const allocationId = fence.newConnectionId;
+ const existing = this.entries.get(allocationId);
+ if (existing) {
+ return existing.state !== "draining" && sameFence(existing.fence, fence);
+ }
+ if (this.entries.size >= this.capacity) {
+ return false;
+ }
+
+ this.entries.set(allocationId, {
+ fence: cloneFence(fence),
+ state: "reserved",
+ });
+ let roomAllocationIds = this.allocationIdsByRoom.get(fence.roomId);
+ if (!roomAllocationIds) {
+ roomAllocationIds = new Set();
+ this.allocationIdsByRoom.set(fence.roomId, roomAllocationIds);
+ }
+ roomAllocationIds.add(allocationId);
+ return true;
+ }
+
+ commit(fence: SelectedEdgeTurnIdentity): boolean {
+ assertFence(fence);
+ const entry = this.entries.get(fence.newConnectionId);
+ if (!entry || !sameFence(entry.fence, fence)) {
+ return false;
+ }
+ if (entry.state === "committed") {
+ return true;
+ }
+ if (entry.state !== "reserved") {
+ return false;
+ }
+ entry.state = "committed";
+ return true;
+ }
+
+ beginDrain(fence: SelectedEdgeTurnIdentity): boolean {
+ assertFence(fence);
+ const entry = this.entries.get(fence.newConnectionId);
+ if (!entry || !sameFence(entry.fence, fence)) {
+ return false;
+ }
+ entry.state = "draining";
+ return true;
+ }
+
+ completeDrain(fence: SelectedEdgeTurnIdentity): boolean {
+ assertFence(fence);
+ const allocationId = fence.newConnectionId;
+ const entry = this.entries.get(allocationId);
+ if (
+ !entry ||
+ entry.state !== "draining" ||
+ !sameFence(entry.fence, fence)
+ ) {
+ return false;
+ }
+
+ this.entries.delete(allocationId);
+ const roomAllocationIds = this.allocationIdsByRoom.get(fence.roomId);
+ roomAllocationIds?.delete(allocationId);
+ if (roomAllocationIds?.size === 0) {
+ this.allocationIdsByRoom.delete(fence.roomId);
+ }
+ return true;
+ }
+
+ beginDrainRoom(roomId: string): readonly SelectedEdgeTurnIdentity[] {
+ if (!roomId) {
+ throw new Error("TURN allocation room ID is invalid");
+ }
+ const allocationIds = this.allocationIdsByRoom.get(roomId);
+ if (!allocationIds) {
+ return [];
+ }
+ const fences: SelectedEdgeTurnIdentity[] = [];
+ for (const allocationId of allocationIds) {
+ const entry = this.entries.get(allocationId);
+ if (!entry) {
+ throw new Error("TURN allocation room index is inconsistent");
+ }
+ entry.state = "draining";
+ fences.push(cloneFence(entry.fence));
+ }
+ return fences;
+ }
+
+ beginDrainAll(): readonly SelectedEdgeTurnIdentity[] {
+ return [...this.allocationIdsByRoom.keys()].flatMap((roomId) =>
+ this.beginDrainRoom(roomId),
+ );
+ }
+
+ state(fence: SelectedEdgeTurnIdentity): TurnAllocationState | undefined {
+ assertFence(fence);
+ const entry = this.entries.get(fence.newConnectionId);
+ return entry && sameFence(entry.fence, fence) ? entry.state : undefined;
+ }
+
+ usage(): TurnAllocationUsage {
+ return { allocations: this.entries.size };
+ }
+}
+
+function cloneFence(
+ fence: SelectedEdgeTurnIdentity,
+): SelectedEdgeTurnIdentity {
+ return { ...fence };
+}
+
+function sameFence(
+ left: SelectedEdgeTurnIdentity,
+ right: SelectedEdgeTurnIdentity,
+): boolean {
+ if (left.edgeKind !== right.edgeKind) {
+ return false;
+ }
+ if (left.edgeKind === "peer-selected" && right.edgeKind === "peer-selected") {
+ return (
+ left.roomId === right.roomId &&
+ left.shareGeneration === right.shareGeneration &&
+ left.revision === right.revision &&
+ left.parentPeerId === right.parentPeerId &&
+ left.parentSessionId === right.parentSessionId &&
+ left.viewerPeerId === right.viewerPeerId &&
+ left.viewerSessionId === right.viewerSessionId &&
+ left.oldConnectionId === right.oldConnectionId &&
+ left.newConnectionId === right.newConnectionId
+ );
+ }
+ if (
+ left.edgeKind === "host-sfu-ingress" &&
+ right.edgeKind === "host-sfu-ingress"
+ ) {
+ return (
+ left.roomId === right.roomId &&
+ left.shareGeneration === right.shareGeneration &&
+ left.revision === right.revision &&
+ left.hostPeerId === right.hostPeerId &&
+ left.hostSessionId === right.hostSessionId &&
+ left.publicationGeneration === right.publicationGeneration &&
+ left.oldConnectionId === right.oldConnectionId &&
+ left.newConnectionId === right.newConnectionId
+ );
+ }
+ return false;
+}
+
+function assertFence(fence: SelectedEdgeTurnIdentity): void {
+ const commonValues = [
+ fence.roomId,
+ fence.shareGeneration,
+ fence.oldConnectionId,
+ fence.newConnectionId,
+ ];
+ const edgeValues =
+ fence.edgeKind === "peer-selected"
+ ? [
+ fence.parentPeerId,
+ fence.parentSessionId,
+ fence.viewerPeerId,
+ fence.viewerSessionId,
+ ]
+ : [
+ fence.hostPeerId,
+ fence.hostSessionId,
+ fence.publicationGeneration,
+ ];
+ if (
+ commonValues.some((value) => value.length === 0) ||
+ edgeValues.some((value) => value.length === 0) ||
+ !Number.isSafeInteger(fence.revision) ||
+ fence.revision < 0
+ ) {
+ throw new Error("TURN allocation fence is invalid");
+ }
+}
+
+function assertPositiveSafeInteger(value: number, name: string): void {
+ if (!Number.isSafeInteger(value) || value <= 0) {
+ throw new Error(`${name} must be a positive safe integer`);
+ }
+}
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index ccf03cfa..d52921de 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -1005,7 +1005,7 @@ function hostProvisionalInput(
overrides: {
activeChildPeerIds?: string[];
publicationGeneration?: string | null;
- selectedPeerId?: string | null;
+ selectedPeerIds?: readonly string[];
} = {},
) {
return {
@@ -1015,7 +1015,7 @@ function hostProvisionalInput(
overrides.publicationGeneration ?? null,
),
activeChildPeerIds: overrides.activeChildPeerIds ?? [],
- selectedPeerId: overrides.selectedPeerId ?? null,
+ selectedPeerIds: overrides.selectedPeerIds ?? [],
maxMediaEdges: 2,
iceConfig: { iceServers: [] },
stream,
@@ -1104,7 +1104,7 @@ describe("Host provisional child runtime ownership", () => {
revision: 9,
assignment: hostAssignment([]),
activeChildPeerIds: [],
- selectedPeerId: null,
+ selectedPeerIds: [],
maxMediaEdges: 2,
})).toEqual({ kind: "ordinary" });
expect(second.connectionState).toBe("closed");
@@ -1697,6 +1697,158 @@ describe("ViewerRelay downstream ownership", () => {
relay.dispose();
});
+ it("keeps concurrent selected children isolated across carry and failure", async () => {
+ const sendSignal = vi.fn(() => true);
+ const onSelectedEdgeFailed = vi.fn();
+ const relay = new ViewerRelay(
+ { iceServers: [] },
+ QUALITY_PROFILES["720p30"],
+ { sendSignal, onSelectedEdgeFailed },
+ );
+ relay.setChildren(["selected-a", "selected-b"]);
+ relay.setStream(createStream(createTrack("video", "selected-video"), null));
+ await vi.waitFor(() => expect(sendSignal).toHaveBeenCalledTimes(2));
+ const oldConnectionA = relay.getSnapshot("selected-a")!.connectionId;
+ const oldConnectionB = relay.getSnapshot("selected-b")!.connectionId;
+ relay.setChildren([]);
+ expect(FakePeerConnection.activeCount).toBe(0);
+
+ sendSignal.mockClear();
+ const grantA = selectedEdgeTurn(
+ "selected-a",
+ oldConnectionA,
+ "selected-connection-a",
+ );
+ const grantB = selectedEdgeTurn(
+ "selected-b",
+ oldConnectionB,
+ "selected-connection-b",
+ );
+ expect(relay.startSelectedEdgeTurn(grantA, "selected-parent", 7)).toBe(true);
+ expect(relay.startSelectedEdgeTurn(grantB, "selected-parent", 7)).toBe(true);
+ await vi.waitFor(() => expect(sendSignal).toHaveBeenCalledTimes(2));
+ const [selectedConnectionA, selectedConnectionB] =
+ FakePeerConnection.instances.slice(-2);
+ expect(selectedConnectionA).toBeDefined();
+ expect(selectedConnectionB).toBeDefined();
+ expect(FakePeerConnection.activeCount).toBe(2);
+
+ expect(
+ relay.startSelectedEdgeTurn(
+ { ...grantA, revision: 8 },
+ "selected-parent",
+ 7,
+ ),
+ ).toBe(true);
+ expect(
+ relay.startSelectedEdgeTurn(
+ { ...grantB, revision: 8 },
+ "selected-parent",
+ 7,
+ ),
+ ).toBe(true);
+ relay.acceptActiveRevision(8);
+ relay.setChildren([]);
+ expect(selectedConnectionA!.connectionState).not.toBe("closed");
+ expect(selectedConnectionB!.connectionState).not.toBe("closed");
+ expect(FakePeerConnection.activeCount).toBe(2);
+
+ await expect(
+ relay.acceptSignal(
+ "selected-a",
+ {
+ kind: "description",
+ connectionId: "selected-connection-a",
+ description: { type: "answer", sdp: "selected-answer-a" },
+ },
+ 8,
+ ),
+ ).resolves.toBe(true);
+ await expect(
+ relay.acceptSignal(
+ "selected-b",
+ {
+ kind: "description",
+ connectionId: "selected-connection-b",
+ description: { type: "answer", sdp: "selected-answer-b" },
+ },
+ 8,
+ ),
+ ).resolves.toBe(true);
+ expect(selectedConnectionA!.remoteDescription?.sdp).toBe(
+ "selected-answer-a",
+ );
+ expect(selectedConnectionB!.remoteDescription?.sdp).toBe(
+ "selected-answer-b",
+ );
+
+ FakePeerConnection.offersFailing = 1;
+ expect(
+ relay.startSelectedEdgeTurn(
+ {
+ ...selectedEdgeTurn(
+ "selected-a",
+ "selected-connection-a",
+ "selected-connection-a-failed",
+ ),
+ revision: 8,
+ },
+ "selected-parent",
+ 8,
+ ),
+ ).toBe(true);
+ await vi.waitFor(() =>
+ expect(onSelectedEdgeFailed).toHaveBeenCalledWith(
+ "selected-a",
+ "selected-connection-a-failed",
+ 8,
+ ),
+ );
+ expect(selectedConnectionA!.connectionState).toBe("closed");
+ expect(selectedConnectionB!.connectionState).not.toBe("closed");
+ expect(relay.getSnapshot("selected-a")).toBeNull();
+ expect(relay.getSnapshot("selected-b")?.connectionId).toBe(
+ "selected-connection-b",
+ );
+ expect(FakePeerConnection.activeCount).toBe(1);
+ await expect(
+ relay.acceptSignal(
+ "selected-a",
+ {
+ kind: "candidate",
+ connectionId: "selected-connection-a-failed",
+ candidate: null,
+ },
+ 8,
+ ),
+ ).resolves.toBe(false);
+ await expect(
+ relay.acceptSignal(
+ "selected-b",
+ {
+ kind: "candidate",
+ connectionId: "selected-connection-b",
+ candidate: null,
+ },
+ 8,
+ ),
+ ).resolves.toBe(true);
+
+ expect(
+ relay.startSelectedEdgeTurn(
+ { ...grantB, revision: 9 },
+ "selected-parent",
+ 8,
+ ),
+ ).toBe(true);
+ relay.acceptActiveRevision(9);
+ expect(selectedConnectionB!.connectionState).not.toBe("closed");
+ relay.clearSelectedEdgeTurn();
+ expect(selectedConnectionB!.connectionState).toBe("closed");
+ expect(FakePeerConnection.activeCount).toBe(0);
+ relay.dispose();
+ });
+
it("reports a selected child whose relay-only offer fails", async () => {
const onSelectedEdgeFailed = vi.fn();
const relay = new ViewerRelay(
diff --git a/tests/media-copy-accounting.test.ts b/tests/media-copy-accounting.test.ts
index e0eab787..0178969a 100644
--- a/tests/media-copy-accounting.test.ts
+++ b/tests/media-copy-accounting.test.ts
@@ -40,6 +40,30 @@ describe("endpoint media copy accounting", () => {
).toBe(3);
});
+ it.each([
+ [1, null, ["selected-a"]],
+ [2, "publication", ["selected-a"]],
+ [3, "publication", ["selected-a", "selected-b"]],
+ ] as const)(
+ "holds hidden selected carries to endpoint cap %i",
+ (capacity, publicationGeneration, selectedChildPeerIds) => {
+ const atCapacity = countEndpointMediaCopies({
+ childPeerIds: [],
+ publicationGeneration,
+ selectedChildPeerIds,
+ });
+ const overCapacity = countEndpointMediaCopies({
+ childPeerIds: [],
+ publicationGeneration,
+ selectedChildPeerIds: [...selectedChildPeerIds, "selected-overflow"],
+ });
+
+ expect(atCapacity).toBe(capacity);
+ expect(endpointMediaCopyCountFits(atCapacity, capacity)).toBe(true);
+ expect(endpointMediaCopyCountFits(overCapacity, capacity)).toBe(false);
+ },
+ );
+
it.each([
[1, 1, 2],
[2, 2, 3],
diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.ts
index 3e155f04..c1d2da10 100644
--- a/tests/route-transition.test.ts
+++ b/tests/route-transition.test.ts
@@ -10,8 +10,12 @@ import {
} from "../src/client/media/route-transition.ts";
import { HostSfuRoute } from "../src/client/media/host-sfu-route.ts";
import {
+ acceptHostSelectedChildrenRevision,
+ carryHostSelectedChild,
+ hostSelectedChildForConnection,
plannedHostProvisionalChild,
resolveHostPreparedChildActivation,
+ type ActiveSelectedHostChild,
} from "../src/client/media/host-provisional-child.ts";
import { ViewerSfuRoute } from "../src/client/media/viewer-sfu-route.ts";
import { QUALITY_PROFILES } from "../src/client/media/quality.ts";
@@ -56,14 +60,15 @@ function sfuConfig(revision: number) {
function hostSfuIngressGrant(
newConnectionId = "selected-connection-new",
revision = 1,
+ publicationGeneration = "generation-a",
) {
return {
type: "selected-edge-turn" as const,
edgeKind: "host-sfu-ingress" as const,
revision,
hostPeerId: "host_12345678",
- publicationGeneration: "generation-a",
- oldConnectionId: "generation-a",
+ publicationGeneration,
+ oldConnectionId: publicationGeneration,
newConnectionId,
expiresAt: "2099-01-01T00:00:00.000Z",
iceServer: {
@@ -97,13 +102,76 @@ function createFakePublisher(log: string[], label: string) {
}
describe("Host provisional child ownership", () => {
+ it("keeps selected Host children isolated by peer and connection", () => {
+ const selected = new Map<string, ActiveSelectedHostChild>([
+ [
+ "selected-a",
+ {
+ peerId: "selected-a",
+ connectionId: "connection-a",
+ currentRouteRevision: 7,
+ pendingCarryRevision: null,
+ },
+ ],
+ [
+ "selected-b",
+ {
+ peerId: "selected-b",
+ connectionId: "connection-b",
+ currentRouteRevision: 7,
+ pendingCarryRevision: null,
+ },
+ ],
+ ]);
+
+ expect(
+ hostSelectedChildForConnection(
+ selected,
+ "selected-a",
+ "wrong-connection",
+ ),
+ ).toBeUndefined();
+ expect(
+ carryHostSelectedChild(selected, "selected-a", "connection-a", 8),
+ ).toBe(true);
+ expect(
+ carryHostSelectedChild(selected, "selected-b", "connection-b", 8),
+ ).toBe(true);
+ expect(acceptHostSelectedChildrenRevision(selected, 8)).toEqual([]);
+ expect(selected.size).toBe(2);
+
+ const failed = hostSelectedChildForConnection(
+ selected,
+ "selected-a",
+ "connection-a",
+ );
+ expect(failed).toBeDefined();
+ selected.delete(failed!.peerId);
+ expect(selected.has("selected-a")).toBe(false);
+ expect(selected.has("selected-b")).toBe(true);
+
+ selected.set("selected-a", {
+ peerId: "selected-a",
+ connectionId: "connection-a-2",
+ currentRouteRevision: 8,
+ pendingCarryRevision: null,
+ });
+ expect(
+ carryHostSelectedChild(selected, "selected-b", "connection-b", 9),
+ ).toBe(true);
+ expect(acceptHostSelectedChildrenRevision(selected, 9)).toEqual([
+ "selected-a",
+ ]);
+ expect([...selected.keys()]).toEqual(["selected-b"]);
+ });
+
it("admits only one strict child within the physical Host edge budget", () => {
expect(
plannedHostProvisionalChild({
revision: 7,
assignment: hostAssignment(null, ["active-child", "probe-child"]),
activeChildPeerIds: ["active-child"],
- selectedPeerId: null,
+ selectedPeerIds: [],
maxMediaEdges: 2,
}),
).toBe("probe-child");
@@ -112,7 +180,7 @@ describe("Host provisional child ownership", () => {
revision: 7,
assignment: hostAssignment("publication", ["probe-child"]),
activeChildPeerIds: [],
- selectedPeerId: null,
+ selectedPeerIds: [],
maxMediaEdges: 2,
}),
).toBe("probe-child");
@@ -121,7 +189,7 @@ describe("Host provisional child ownership", () => {
revision: 7,
assignment: hostAssignment(null, ["probe-child"]),
activeChildPeerIds: [],
- selectedPeerId: "selected-overlay",
+ selectedPeerIds: ["selected-overlay"],
maxMediaEdges: 2,
}),
).toBe("probe-child");
@@ -133,7 +201,7 @@ describe("Host provisional child ownership", () => {
"probe-child",
]),
activeChildPeerIds: ["active-child"],
- selectedPeerId: null,
+ selectedPeerIds: [],
maxMediaEdges: 2,
}),
).toBeNull();
@@ -142,10 +210,28 @@ describe("Host provisional child ownership", () => {
revision: 7,
assignment: hostAssignment(null, ["active-child", "probe-child"]),
activeChildPeerIds: ["active-child"],
- selectedPeerId: "selected-overlay",
+ selectedPeerIds: ["selected-overlay"],
maxMediaEdges: 2,
}),
).toBeNull();
+ expect(
+ plannedHostProvisionalChild({
+ revision: 7,
+ assignment: hostAssignment(null, ["probe-child"]),
+ activeChildPeerIds: [],
+ selectedPeerIds: ["selected-a", "selected-b"],
+ maxMediaEdges: 3,
+ }),
+ ).toBe("probe-child");
+ expect(
+ plannedHostProvisionalChild({
+ revision: 7,
+ assignment: hostAssignment("publication", ["probe-child"]),
+ activeChildPeerIds: [],
+ selectedPeerIds: ["selected-a", "selected-b"],
+ maxMediaEdges: 3,
+ }),
+ ).toBeNull();
});
it("promotes the exact identity and preserves a failed connection tombstone", () => {
@@ -153,7 +239,7 @@ describe("Host provisional child ownership", () => {
revision: 7,
assignment: hostAssignment(null, ["active-child", "probe-child"]),
activeChildPeerIds: ["active-child"],
- selectedPeerId: null,
+ selectedPeerIds: [],
maxMediaEdges: 2,
};
expect(
@@ -705,6 +791,167 @@ describe("HostSfuRoute", () => {
});
});
+ it("keeps the old publisher until a selected replacement commits", async () => {
+ const messages: ClientMessage[] = [];
+ const publishers: ReturnType<typeof createFakePublisher>[] = [];
+ const route = new HostSfuRoute({
+ getStream: () => ({}) as MediaStream,
+ getProfile: () => QUALITY_PROFILES["720p30"],
+ reconcileChildren: () => undefined,
+ send: (message) => {
+ messages.push(message);
+ return true;
+ },
+ createPublisher: () => {
+ const publisher = createFakePublisher(
+ [],
+ `publisher-${publishers.length + 1}`,
+ );
+ publishers.push(publisher);
+ if (publishers.length === 2) {
+ publisher.connect.mockResolvedValue(false);
+ }
+ return publisher;
+ },
+ });
+ const generationA = hostAssignment("generation-a");
+ route.accept({ revision: 1, phase: "prepare", assignment: generationA });
+ await route.acceptConfig(sfuConfig(1));
+ await route.acceptAndWait({
+ revision: 1,
+ phase: "active",
+ assignment: generationA,
+ });
+ expect(
+ route.startSelectedEdgeTurn(
+ hostSfuIngressGrant("same-generation", 1, "generation-a"),
+ ),
+ ).toBe(false);
+
+ const generationB = hostAssignment("generation-b");
+ route.accept({ revision: 2, phase: "prepare", assignment: generationB });
+ await route.acceptConfig(sfuConfig(2));
+ const selectedB = hostSfuIngressGrant(
+ "selected-generation-b",
+ 2,
+ "generation-b",
+ );
+ expect(route.startSelectedEdgeTurn(selectedB)).toBe(true);
+ await vi.waitFor(() => expect(publishers).toHaveLength(3));
+ expect(publishers[2]?.connect).toHaveBeenCalledWith({
+ url: "wss://sfu.example.test",
+ token: "token-2",
+ rtcConfig: {
+ iceServers: [selectedB.iceServer],
+ iceTransportPolicy: "relay",
+ },
+ });
+ expect(publishers[0]?.deactivate).not.toHaveBeenCalled();
+ expect(publishers[0]?.disconnect).not.toHaveBeenCalled();
+ expect(messages).toContainEqual({
+ type: "route-ready",
+ revision: 2,
+ phase: "prepare",
+ });
+
+ await route.acceptAndWait({
+ revision: 2,
+ phase: "active",
+ assignment: generationB,
+ });
+ expect(publishers[0]?.deactivate).toHaveBeenCalledOnce();
+ expect(publishers[0]?.disconnect).toHaveBeenCalledOnce();
+ expect(publishers[2]?.activate).toHaveBeenCalledOnce();
+ expect(messages).toContainEqual({
+ type: "route-ready",
+ revision: 2,
+ phase: "active",
+ });
+ });
+
+ it("keeps the old publisher through rollback and selected candidate failure", async () => {
+ const messages: ClientMessage[] = [];
+ const publishers: ReturnType<typeof createFakePublisher>[] = [];
+ const failures: Array<() => void> = [];
+ const route = new HostSfuRoute({
+ getStream: () => ({}) as MediaStream,
+ getProfile: () => QUALITY_PROFILES["720p30"],
+ reconcileChildren: () => undefined,
+ send: (message) => {
+ messages.push(message);
+ return true;
+ },
+ createPublisher: (onDisconnected) => {
+ const publisher = createFakePublisher(
+ [],
+ `publisher-${publishers.length + 1}`,
+ );
+ publishers.push(publisher);
+ failures.push(onDisconnected);
+ if (publishers.length === 2 || publishers.length === 4) {
+ publisher.connect.mockResolvedValue(false);
+ }
+ return publisher;
+ },
+ });
+ const generationA = hostAssignment("generation-a");
+ route.accept({ revision: 1, phase: "prepare", assignment: generationA });
+ await route.acceptConfig(sfuConfig(1));
+ await route.acceptAndWait({
+ revision: 1,
+ phase: "active",
+ assignment: generationA,
+ });
+
+ const generationB = hostAssignment("generation-b");
+ route.accept({ revision: 2, phase: "prepare", assignment: generationB });
+ await route.acceptConfig(sfuConfig(2));
+ expect(
+ route.startSelectedEdgeTurn(
+ hostSfuIngressGrant("selected-generation-b", 2, "generation-b"),
+ ),
+ ).toBe(true);
+ await vi.waitFor(() => expect(publishers).toHaveLength(3));
+ expect(publishers[0]?.deactivate).not.toHaveBeenCalled();
+ expect(publishers[0]?.disconnect).not.toHaveBeenCalled();
+
+ await route.acceptAndWait({
+ revision: 3,
+ phase: "active",
+ assignment: generationA,
+ });
+ expect(publishers[2]?.disconnect).toHaveBeenCalledOnce();
+ expect(publishers[0]?.deactivate).not.toHaveBeenCalled();
+ expect(publishers[0]?.disconnect).not.toHaveBeenCalled();
+
+ route.accept({
+ revision: 4,
+ phase: "prepare",
+ assignment: hostAssignment("generation-c"),
+ });
+ await route.acceptConfig(sfuConfig(4));
+ expect(
+ route.startSelectedEdgeTurn(
+ hostSfuIngressGrant("selected-generation-c", 4, "generation-c"),
+ ),
+ ).toBe(true);
+ await vi.waitFor(() => expect(publishers).toHaveLength(5));
+ messages.length = 0;
+ failures[4]?.();
+ expect(messages).toEqual([{
+ type: "route-failed",
+ revision: 4,
+ phase: "prepare",
+ connectionId: "selected-generation-c",
+ }]);
+ await expect(
+ route.updateProfile(QUALITY_PROFILES["1080p30"]),
+ ).resolves.toBe(true);
+ expect(publishers[0]?.updateProfile).toHaveBeenCalledOnce();
+ expect(publishers[0]?.deactivate).not.toHaveBeenCalled();
+ expect(publishers[0]?.disconnect).not.toHaveBeenCalled();
+ });
+
it("identifies a failed selected ingress retry by its new connection", async () => {
const messages: ClientMessage[] = [];
const publishers: ReturnType<typeof createFakePublisher>[] = [];
diff --git a/tests/selected-edge-turn.test.ts b/tests/selected-edge-turn.test.ts
index 5982c7cf..b67b8e47 100644
--- a/tests/selected-edge-turn.test.ts
+++ b/tests/selected-edge-turn.test.ts
@@ -5,6 +5,7 @@ const config = {
urls: ["turn:turn.example.test:3478?transport=udp"] as [string],
sharedSecret: "t".repeat(32),
credentialTtlSeconds: 120,
+ allocationCapacity: 4,
};
const identity = {
edgeKind: "peer-selected" as const,
diff --git a/tests/server-config.test.ts b/tests/server-config.test.ts
index 056d0824..40bf9dff 100644
--- a/tests/server-config.test.ts
+++ b/tests/server-config.test.ts
@@ -35,11 +35,13 @@ describe("server configuration", () => {
SELECTED_EDGE_TURN_URLS: "turn:turn.test:3478?transport=udp",
SELECTED_EDGE_TURN_SHARED_SECRET: "t".repeat(32),
SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS: "120",
+ SELECTED_EDGE_TURN_ALLOCATION_CAPACITY: "4",
};
expect(loadConfig({ ...base, ...turn }).selectedEdgeTurn).toEqual({
urls: [turn.SELECTED_EDGE_TURN_URLS],
sharedSecret: turn.SELECTED_EDGE_TURN_SHARED_SECRET,
credentialTtlSeconds: 120,
+ allocationCapacity: 4,
});
expect(loadConfig({ ...base, ...turn }).stunUrls).toEqual([]);
for (const name of Object.keys(turn)) {
@@ -65,10 +67,31 @@ describe("server configuration", () => {
SELECTED_EDGE_TURN_URLS: url,
SELECTED_EDGE_TURN_SHARED_SECRET: "t".repeat(32),
SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS: "120",
+ SELECTED_EDGE_TURN_ALLOCATION_CAPACITY: "4",
}),
).toThrow("one UDP TURN URL");
});
+ it.each(["0", "-1", "1.5", "9007199254740992"])(
+ "rejects an invalid selected-edge TURN allocation capacity of %s",
+ (capacity) => {
+ expect(() =>
+ loadConfig({
+ PEER_ASSISTED_MEDIA: "true",
+ LIVEKIT_URL: "wss://livekit.test",
+ LIVEKIT_API_KEY: "test-key",
+ LIVEKIT_API_SECRET: "s".repeat(32),
+ ...liveKitAdmission,
+ SELECTED_EDGE_TURN_URLS:
+ "turn:turn.test:3478?transport=udp",
+ SELECTED_EDGE_TURN_SHARED_SECRET: "t".repeat(32),
+ SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS: "120",
+ SELECTED_EDGE_TURN_ALLOCATION_CAPACITY: capacity,
+ }),
+ ).toThrow("SELECTED_EDGE_TURN_ALLOCATION_CAPACITY must be a positive integer");
+ },
+ );
+
it("enables LiveKit fallback only for a complete credential tuple", () => {
const config = loadConfig({
PEER_ASSISTED_MEDIA: "true",
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 06067356..dd194242 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -27,11 +27,13 @@ import type { SfuTokenIssuer } from "../src/server/livekit-token.ts";
import { HybridMediaRouter } from "../src/server/hybrid-media-router.ts";
import { SfuResourceAdmission } from "../src/server/sfu-resource-admission.ts";
import { managedSfuRoomName } from "../src/server/sfu-room-control.ts";
+import { TurnAllocationAdmission } from "../src/server/turn-allocation-admission.ts";
import { FakeSfuRoomControl } from "./fake-sfu-room-control.ts";
const allowedOrigin = "http://allowed.test";
const TEST_SFU_INGRESS_CAPACITY = 10;
const TEST_SFU_EGRESS_CAPACITY = 16;
+const TEST_TURN_ALLOCATION_CAPACITY = 8;
const defaultQualitySettings = {
resolution: "1080p",
maxFramerate: 60,
@@ -148,6 +150,7 @@ interface SignalHarness {
room: CreatedRoom;
database?: RoomDatabase;
sfuAdmission?: SfuResourceAdmission;
+ turnAdmission?: TurnAllocationAdmission;
sfuRoomControl?: FakeSfuRoomControl;
}
@@ -656,6 +659,7 @@ async function startSfuHarness(options: {
roomControl?: FakeSfuRoomControl;
hostOfflineCheckMs?: number;
drainRetryMs?: number;
+ turnAllocationCapacity?: number;
}): Promise<SignalHarness> {
const roomStore = new RoomStore({
ttlMs: 14_400_000,
@@ -677,6 +681,11 @@ async function startSfuHarness(options: {
egressCapacity:
options.sfuEgressCapacity ?? TEST_SFU_EGRESS_CAPACITY,
});
+ const turnAllocationCapacity =
+ options.turnAllocationCapacity ?? TEST_TURN_ALLOCATION_CAPACITY;
+ const turnAdmission = options.selectedEdgeTurn
+ ? new TurnAllocationAdmission({ capacity: turnAllocationCapacity })
+ : undefined;
const sfuRoomControl = options.roomControl ?? new FakeSfuRoomControl();
const signaling = new SignalingServer({
server: httpServer,
@@ -696,9 +705,13 @@ async function startSfuHarness(options: {
...(options.selectedEdgeTurn
? {
selectedEdgeTurn: {
- urls: ["turn:turn.example.test:3478?transport=udp"],
- sharedSecret: "t".repeat(32),
- credentialTtlSeconds: 120,
+ config: {
+ urls: ["turn:turn.example.test:3478?transport=udp"],
+ sharedSecret: "t".repeat(32),
+ credentialTtlSeconds: 120,
+ allocationCapacity: turnAllocationCapacity,
+ },
+ admission: turnAdmission!,
},
}
: {}),
@@ -745,6 +758,7 @@ async function startSfuHarness(options: {
roomStore,
room,
sfuAdmission,
+ turnAdmission,
sfuRoomControl,
};
}
@@ -1185,6 +1199,99 @@ async function activateSingleViewerSfu(
return { ...direct, revision: viewerPrepare.revision };
}
+async function prepareSelectedHostIngressReplacement(
+ harness: SignalHarness,
+ prefix: string,
+) {
+ const active = await activateSingleViewerSfu(
+ harness.webSocketUrl,
+ harness.room,
+ prefix,
+ );
+ active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: active.revision,
+ phase: "active",
+ connectionId: null,
+ }));
+ const activeGrant = await active.host.inbox.next("selected-edge-turn");
+ if (activeGrant.edgeKind !== "host-sfu-ingress") {
+ throw new Error("expected an active Host SFU ingress grant");
+ }
+ active.host.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: active.revision,
+ phase: "active",
+ }));
+ await vi.waitFor(() =>
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 }),
+ );
+ active.viewer.socket.send(JSON.stringify({
+ type: "relay-capacity",
+ downstreamEdges: 0,
+ }));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+ const candidateViewer = await openClient(harness.webSocketUrl);
+ const candidateAuth = peerAssisted(await authenticate(
+ candidateViewer,
+ harness.room,
+ "viewer",
+ `${prefix}-candidate-viewer`,
+ 0,
+ ));
+ expect(candidateAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: active.hostAuth.peerId,
+ });
+ const candidateConnectionId = `${prefix}-candidate-connection`;
+ await sendTestOffer(
+ active.host,
+ candidateViewer,
+ candidateAuth.peerId,
+ candidateConnectionId,
+ );
+ candidateViewer.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: candidateAuth.routeRevision,
+ phase: "active",
+ connectionId: candidateConnectionId,
+ }));
+ const [hostPrepare, activeViewerPrepare, candidatePrepare] =
+ await Promise.all([
+ nextPreparedRoute(active.host),
+ nextPreparedRoute(active.viewer),
+ nextPreparedRoute(candidateViewer),
+ ]);
+ expect(activeViewerPrepare.revision).toBe(hostPrepare.revision);
+ expect(candidatePrepare.revision).toBe(hostPrepare.revision);
+ await Promise.all([
+ active.host.inbox.next("sfu-config"),
+ active.viewer.inbox.next("sfu-config"),
+ candidateViewer.inbox.next("sfu-config"),
+ ]);
+
+ active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: hostPrepare.revision,
+ phase: "prepare",
+ connectionId: null,
+ }));
+ const candidateGrant = await active.host.inbox.next("selected-edge-turn");
+ if (candidateGrant.edgeKind !== "host-sfu-ingress") {
+ throw new Error("expected a pending Host SFU ingress grant");
+ }
+ expect(candidateGrant.newConnectionId).not.toBe(activeGrant.newConnectionId);
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 2 });
+ return {
+ active,
+ activeGrant,
+ candidateGrant,
+ candidateViewer,
+ hostPrepare,
+ };
+}
+
async function prepareSfuHostParentQualityProbe(
harness: SignalHarness,
active: Awaited<ReturnType<typeof activateSingleViewerSfu>>,
@@ -1384,14 +1491,15 @@ async function startPeerSelectedCandidate(
connectionId: string,
) {
failPeerEdgeCandidate(viewer, revision, connectionId);
- const [viewerGrant, parentGrant] = await Promise.all([
- viewer.inbox.next("selected-edge-turn"),
- parent.inbox.next("selected-edge-turn"),
- ]);
- expect(parentGrant).toEqual(viewerGrant);
+ const viewerGrant = await viewer.inbox.next("selected-edge-turn");
if (viewerGrant.edgeKind !== "peer-selected") {
throw new Error("expected a peer-selected grant");
}
+ let parentGrant: Extract<ServerMessage, { type: "selected-edge-turn" }>;
+ do {
+ parentGrant = await parent.inbox.next("selected-edge-turn");
+ } while (parentGrant.newConnectionId !== viewerGrant.newConnectionId);
+ expect(parentGrant).toEqual(viewerGrant);
return viewerGrant;
}
@@ -7347,10 +7455,11 @@ describe("WebSocket signaling", () => {
]);
});
- it("admits only one pending peer-selected TURN attempt per room", async () => {
+ it("admits independent pending peer-selected TURN edges concurrently", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken() { throw new Error("offline"); } },
selectedEdgeTurn: true,
+ turnAllocationCapacity: 2,
});
const peers = await prepareTwoSelectedPeerEdgeCandidates(
harness.webSocketUrl,
@@ -7370,18 +7479,173 @@ describe("WebSocket signaling", () => {
firstGrant.revision,
peers.secondConnectionId,
);
- await expect(
- peers.secondViewer.inbox.next("selected-edge-turn", 40),
- ).rejects.toThrow("Timed out");
- await expect(
- peers.secondParent.inbox.next("selected-edge-turn", 40),
- ).rejects.toThrow("Timed out");
+ const [secondViewerGrant, secondParentGrant] = await Promise.all([
+ peers.secondViewer.inbox.next("selected-edge-turn"),
+ peers.secondParent.inbox.next("selected-edge-turn"),
+ ]);
+ expect(secondViewerGrant).toMatchObject({
+ edgeKind: "peer-selected",
+ viewerPeerId: peers.secondAuth.peerId,
+ parentPeerId: peers.secondParentAuth.peerId,
+ });
+ expect(secondParentGrant.newConnectionId).toBe(
+ secondViewerGrant.newConnectionId,
+ );
+ expect(secondViewerGrant.newConnectionId).not.toBe(
+ firstGrant.newConnectionId,
+ );
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 2 });
+ });
+
+ it.each([1, 2, 3] as const)(
+ "admits %i same-parent selected edges without changing endpoint copy count",
+ async (endpointMediaCopyCapacity) => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken() { throw new Error("offline"); } },
+ selectedEdgeTurn: true,
+ endpointMediaCopyCapacity,
+ turnAllocationCapacity: endpointMediaCopyCapacity,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(await authenticate(
+ host,
+ harness.room,
+ "host",
+ `selected-same-parent-cap-${endpointMediaCopyCapacity}-host`,
+ endpointMediaCopyCapacity,
+ `selected-same-parent-cap-${endpointMediaCopyCapacity}-share`,
+ ));
+ const viewers: Array<{
+ client: TestClient;
+ peerId: string;
+ connectionId: string;
+ }> = [];
+ let revision = hostAuth.routeRevision;
+ for (let index = 0; index < endpointMediaCopyCapacity; index += 1) {
+ const client = await openClient(harness.webSocketUrl);
+ const authenticated = peerAssisted(await authenticate(
+ client,
+ harness.room,
+ "viewer",
+ `selected-same-parent-cap-${endpointMediaCopyCapacity}-viewer-${index}`,
+ 0,
+ ));
+ expect(authenticated.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ revision = authenticated.routeRevision;
+ viewers.push({
+ client,
+ peerId: authenticated.peerId,
+ connectionId:
+ `selected-same-parent-cap-${endpointMediaCopyCapacity}-edge-${index}`,
+ });
+ }
+
+ for (const [index, viewer] of viewers.entries()) {
+ await sendTestOffer(
+ host,
+ viewer.client,
+ viewer.peerId,
+ viewer.connectionId,
+ );
+ const grant = await startPeerSelectedCandidate(
+ viewer.client,
+ host,
+ revision,
+ viewer.connectionId,
+ ).catch((error: unknown) => {
+ throw new Error(
+ `selected edge ${index + 1} of ${endpointMediaCopyCapacity} was not admitted`,
+ { cause: error },
+ );
+ });
+ expect(grant.parentPeerId).toBe(hostAuth.peerId);
+ revision = grant.revision;
+ }
+ expect(harness.turnAdmission?.usage()).toEqual({
+ allocations: endpointMediaCopyCapacity,
+ });
+
+ const overflow = await openClient(harness.webSocketUrl);
+ const overflowAuth = peerAssisted(await authenticate(
+ overflow,
+ harness.room,
+ "viewer",
+ `selected-same-parent-cap-${endpointMediaCopyCapacity}-overflow`,
+ 0,
+ ));
+ expect(overflowAuth.routeAssignment.upstream).toEqual({ kind: "none" });
+ expect(harness.turnAdmission?.usage()).toEqual({
+ allocations: endpointMediaCopyCapacity,
+ });
+ },
+ );
+
+ it("releases every selected allocation when the current share stops", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken() { throw new Error("offline"); } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 2,
+ });
+ const peers = await prepareTwoSelectedPeerEdgeCandidates(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-room-stop",
+ );
+
+ const firstGrant = await startPeerSelectedCandidate(
+ peers.firstViewer,
+ peers.firstParent,
+ peers.revision,
+ peers.firstConnectionId,
+ );
+ await startPeerSelectedCandidate(
+ peers.secondViewer,
+ peers.secondParent,
+ firstGrant.revision,
+ peers.secondConnectionId,
+ );
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 2 });
+
+ peers.host.socket.send(JSON.stringify({ type: "stop-sharing" }));
+ await Promise.all([
+ peers.firstViewer.inbox.next("sharing-stopped"),
+ peers.secondViewer.inbox.next("sharing-stopped"),
+ ]);
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 0 });
});
- it("keeps an answered peer-selected TURN edge inside the room cap", async () => {
+ it("releases selected allocations during graceful shutdown", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken() { throw new Error("offline"); } },
selectedEdgeTurn: true,
+ turnAllocationCapacity: 1,
+ });
+ const peers = await prepareTwoSelectedPeerEdgeCandidates(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-shutdown",
+ );
+ await startPeerSelectedCandidate(
+ peers.firstViewer,
+ peers.firstParent,
+ peers.revision,
+ peers.firstConnectionId,
+ );
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+
+ await runningServer!.close();
+ runningServer = undefined;
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 0 });
+ });
+
+ it("keeps an answered peer-selected edge charged against deployment capacity", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken() { throw new Error("offline"); } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 1,
});
const peers = await prepareTwoSelectedPeerEdgeCandidates(
harness.webSocketUrl,
@@ -7520,6 +7784,7 @@ describe("WebSocket signaling", () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken() { throw new Error("offline"); } },
selectedEdgeTurn: true,
+ turnAllocationCapacity: 1,
});
const peers = await prepareTwoSelectedPeerEdgeCandidates(
harness.webSocketUrl,
@@ -7562,10 +7827,11 @@ describe("WebSocket signaling", () => {
});
});
- it("releases the room cap after the selected edge fails", async () => {
+ it("releases one exact selected edge without affecting a newer edge", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken() { throw new Error("offline"); } },
selectedEdgeTurn: true,
+ turnAllocationCapacity: 1,
});
const peers = await prepareTwoSelectedPeerEdgeCandidates(
harness.webSocketUrl,
@@ -7586,6 +7852,7 @@ describe("WebSocket signaling", () => {
connectionId: firstGrant.newConnectionId,
}));
await peers.firstViewer.inbox.next("error");
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 0 });
const secondGrant = await startPeerSelectedCandidate(
peers.secondViewer,
@@ -7597,12 +7864,141 @@ describe("WebSocket signaling", () => {
edgeKind: "peer-selected",
viewerPeerId: peers.secondAuth.peerId,
});
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+
+ peers.firstParent.inbox.ignore("route-update");
+ peers.firstParent.inbox.ignore("media-assignment");
+ peers.firstParent.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: peers.firstAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: firstGrant.newConnectionId,
+ candidate: null,
+ },
+ }));
+ await peers.firstParent.inbox.expectNone(40);
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
});
- it("releases the room cap when the selected Viewer disconnects", async () => {
+ it("carries a surviving same-parent selected edge before sibling release authority", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken() { throw new Error("offline"); } },
selectedEdgeTurn: true,
+ endpointMediaCopyCapacity: 2,
+ turnAllocationCapacity: 2,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(await authenticate(
+ host,
+ harness.room,
+ "host",
+ "selected-sibling-carry-host",
+ 2,
+ "selected-sibling-carry-share",
+ ));
+ const viewerA = await openClient(harness.webSocketUrl);
+ const viewerAAuth = peerAssisted(await authenticate(
+ viewerA,
+ harness.room,
+ "viewer",
+ "selected-sibling-carry-viewer-a",
+ 0,
+ ));
+ const viewerB = await openClient(harness.webSocketUrl);
+ const viewerBAuth = peerAssisted(await authenticate(
+ viewerB,
+ harness.room,
+ "viewer",
+ "selected-sibling-carry-viewer-b",
+ 0,
+ ));
+ expect(viewerAAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ expect(viewerBAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ await nextActiveRouteRevision(viewerA, viewerBAuth.routeRevision);
+
+ const connectionA = "selected-sibling-carry-connection-a";
+ const connectionB = "selected-sibling-carry-connection-b";
+ await sendTestOffer(host, viewerA, viewerAAuth.peerId, connectionA);
+ await sendTestOffer(host, viewerB, viewerBAuth.peerId, connectionB);
+ const grantA = await startPeerSelectedCandidate(
+ viewerA,
+ host,
+ viewerBAuth.routeRevision,
+ connectionA,
+ );
+ const grantB = await startPeerSelectedCandidate(
+ viewerB,
+ host,
+ grantA.revision,
+ connectionB,
+ );
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 2 });
+
+ const parentAuthority: ServerMessage[] = [];
+ host.socket.on("message", (data) => {
+ const message = decodeServerMessage(data.toString());
+ if (
+ (message.type === "selected-edge-turn" &&
+ message.edgeKind === "peer-selected" &&
+ message.newConnectionId === grantB.newConnectionId) ||
+ (message.type === "route-update" && message.phase === "active")
+ ) {
+ parentAuthority.push(message);
+ }
+ });
+ viewerA.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: grantA.revision,
+ phase: "active",
+ connectionId: grantA.newConnectionId,
+ }));
+ await expect(viewerA.inbox.next("error")).resolves.toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "Selected relay edge failed",
+ });
+ await vi.waitFor(() => expect(parentAuthority).toHaveLength(2));
+ expect(parentAuthority[0]).toMatchObject({
+ type: "selected-edge-turn",
+ revision: grantB.revision,
+ edgeKind: "peer-selected",
+ viewerPeerId: viewerBAuth.peerId,
+ newConnectionId: grantB.newConnectionId,
+ });
+ expect(parentAuthority[1]).toMatchObject({
+ type: "route-update",
+ revision: grantB.revision,
+ phase: "active",
+ });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+
+ host.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerBAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: grantB.newConnectionId,
+ candidate: null,
+ },
+ }));
+ await expect(viewerB.inbox.next("signal")).resolves.toMatchObject({
+ fromPeerId: hostAuth.peerId,
+ payload: { connectionId: grantB.newConnectionId },
+ });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+ });
+
+ it("releases deployment capacity when the selected Viewer disconnects", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken() { throw new Error("offline"); } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 1,
viewerDisconnectGraceMs: 500,
});
const peers = await prepareTwoSelectedPeerEdgeCandidates(
@@ -7643,6 +8039,7 @@ describe("WebSocket signaling", () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken() { throw new Error("offline"); } },
selectedEdgeTurn: true,
+ turnAllocationCapacity: 1,
});
const peers = await prepareTwoSelectedPeerEdgeCandidates(
harness.webSocketUrl,
@@ -7713,10 +8110,11 @@ describe("WebSocket signaling", () => {
});
});
- it("does not count Host SFU ingress against the peer-selected room cap", async () => {
+ it("admits Host ingress and peer-selected edges from one deployment ledger", async () => {
const harness = await startSfuHarness({
tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
selectedEdgeTurn: true,
+ turnAllocationCapacity: 2,
});
const direct = await activateSingleViewerSfu(
harness.webSocketUrl,
@@ -7733,12 +8131,264 @@ describe("WebSocket signaling", () => {
await expect(
direct.host.inbox.next("selected-edge-turn"),
).resolves.toMatchObject({ edgeKind: "host-sfu-ingress" });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
await startPeerSelectedTurn(
direct.viewer,
direct.host,
direct.revision,
);
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 2 });
+ });
+
+ it("keeps active Host ingress charged until its exact transport fails", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 1,
+ });
+ const active = await activateSingleViewerSfu(
+ harness.webSocketUrl,
+ harness.room,
+ "selected-active-ingress-exact-release",
+ );
+
+ active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: active.revision,
+ phase: "active",
+ connectionId: null,
+ }));
+ const grant = await active.host.inbox.next("selected-edge-turn");
+ if (grant.edgeKind !== "host-sfu-ingress") {
+ throw new Error("expected a Host SFU ingress grant");
+ }
+ active.host.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: active.revision,
+ phase: "active",
+ }));
+ await vi.waitFor(() =>
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 }),
+ );
+
+ active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: active.revision,
+ phase: "active",
+ connectionId: null,
+ }));
+ await expect(
+ active.host.inbox.next("selected-edge-turn", 40),
+ ).rejects.toThrow("Timed out");
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+
+ active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: active.revision,
+ phase: "active",
+ connectionId: grant.newConnectionId,
+ }));
+ await expect(active.host.inbox.next("error")).resolves.toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "Selected SFU relay ingress failed",
+ });
+ await expect(
+ nextActiveRouteAfter(active.host, active.revision),
+ ).resolves.toMatchObject({
+ assignment: { sfuPublicationGeneration: null },
+ });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 0 });
+ });
+
+ it("keeps active Host ingress while an answered pending replacement rolls back", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 2,
+ });
+ const replacement = await prepareSelectedHostIngressReplacement(
+ harness,
+ "selected-ingress-rollback",
+ );
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: replacement.hostPrepare.revision,
+ phase: "prepare",
+ }));
+ await vi.waitFor(() =>
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 2 }),
+ );
+ await closeClient(replacement.candidateViewer);
+ const rollback = await nextActiveRouteAfter(
+ replacement.active.host,
+ replacement.hostPrepare.revision,
+ );
+ expect(rollback.assignment.sfuPublicationGeneration).toBe(
+ replacement.activeGrant.publicationGeneration,
+ );
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: rollback.revision,
+ phase: "active",
+ connectionId: replacement.candidateGrant.newConnectionId,
+ }));
+ await expect(
+ replacement.active.host.inbox.next("error"),
+ ).resolves.toMatchObject({ code: "FORBIDDEN" });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+ });
+
+ it("rolls back only the exact failed pending Host ingress candidate", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 2,
+ });
+ const replacement = await prepareSelectedHostIngressReplacement(
+ harness,
+ "selected-ingress-candidate-failure",
+ );
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: replacement.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: replacement.candidateGrant.newConnectionId,
+ }));
+ await expect(
+ replacement.active.host.inbox.next("error"),
+ ).resolves.toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "Selected SFU relay ingress failed",
+ });
+ const rollback = await nextActiveRouteAfter(
+ replacement.active.host,
+ replacement.hostPrepare.revision,
+ );
+ expect(rollback).toMatchObject({
+ revision: replacement.hostPrepare.revision + 1,
+ assignment: {
+ sfuPublicationGeneration:
+ replacement.activeGrant.publicationGeneration,
+ },
+ });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: rollback.revision,
+ phase: "active",
+ connectionId: replacement.candidateGrant.newConnectionId,
+ }));
+ await expect(
+ replacement.active.host.inbox.next("error"),
+ ).resolves.toMatchObject({ code: "FORBIDDEN" });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+ });
+
+ it("preempts a pending replacement when its exact old active ingress fails", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 2,
+ });
+ const replacement = await prepareSelectedHostIngressReplacement(
+ harness,
+ "selected-ingress-active-failure",
+ );
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: replacement.hostPrepare.revision,
+ phase: "prepare",
+ connectionId: replacement.activeGrant.newConnectionId,
+ }));
+ await expect(
+ replacement.active.host.inbox.next("error"),
+ ).resolves.toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "Selected SFU relay ingress failed",
+ });
+ const rollback = await nextActiveRouteAfter(
+ replacement.active.host,
+ replacement.hostPrepare.revision,
+ );
+ expect(rollback.assignment.sfuPublicationGeneration).toBe(
+ replacement.activeGrant.publicationGeneration,
+ );
+ const baseline = await nextActiveRouteAfter(
+ replacement.active.host,
+ rollback.revision,
+ );
+ expect(baseline).toMatchObject({
+ assignment: { sfuPublicationGeneration: null },
+ });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 0 });
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: baseline.revision,
+ phase: "active",
+ connectionId: replacement.candidateGrant.newConnectionId,
+ }));
+ await expect(
+ replacement.active.host.inbox.next("error"),
+ ).resolves.toMatchObject({ code: "FORBIDDEN" });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 0 });
+ });
+
+ it("promotes a pending Host ingress only after the route commits", async () => {
+ const harness = await startSfuHarness({
+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },
+ selectedEdgeTurn: true,
+ turnAllocationCapacity: 2,
+ });
+ const replacement = await prepareSelectedHostIngressReplacement(
+ harness,
+ "selected-ingress-commit",
+ );
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: replacement.hostPrepare.revision,
+ phase: "prepare",
+ }));
+ await vi.waitFor(() =>
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 2 }),
+ );
+ for (const client of [
+ replacement.active.viewer,
+ replacement.candidateViewer,
+ ]) {
+ client.socket.send(JSON.stringify({
+ type: "route-ready",
+ revision: replacement.hostPrepare.revision,
+ phase: "prepare",
+ }));
+ }
+ const committed = await nextActiveRouteRevision(
+ replacement.active.host,
+ replacement.hostPrepare.revision,
+ );
+ expect(committed.assignment.sfuPublicationGeneration).toBe(
+ replacement.candidateGrant.publicationGeneration,
+ );
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
+
+ replacement.active.host.socket.send(JSON.stringify({
+ type: "route-failed",
+ revision: committed.revision,
+ phase: "active",
+ connectionId: replacement.activeGrant.newConnectionId,
+ }));
+ await expect(
+ replacement.active.host.inbox.next("error"),
+ ).resolves.toMatchObject({ code: "FORBIDDEN" });
+ expect(harness.turnAdmission?.usage()).toEqual({ allocations: 1 });
});
it("retries an initial Host SFU prepare through one selected ingress", async () => {
diff --git a/tests/turn-allocation-admission.test.ts b/tests/turn-allocation-admission.test.ts
new file mode 100644
index 00000000..8311b8da
--- /dev/null
+++ b/tests/turn-allocation-admission.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from "vitest";
+
+import type { SelectedEdgeTurnIdentity } from "../src/server/selected-edge-turn.ts";
+import { TurnAllocationAdmission } from "../src/server/turn-allocation-admission.ts";
+
+function peerFence(
+ roomId: string,
+ viewerPeerId: string,
+ newConnectionId = `connection-${roomId}-${viewerPeerId}`,
+): SelectedEdgeTurnIdentity {
+ return {
+ edgeKind: "peer-selected",
+ roomId,
+ shareGeneration: `share-${roomId}`,
+ revision: 3,
+ parentPeerId: `parent-${viewerPeerId}`,
+ parentSessionId: `parent-session-${viewerPeerId}`,
+ viewerPeerId,
+ viewerSessionId: `viewer-session-${viewerPeerId}`,
+ oldConnectionId: `old-${viewerPeerId}`,
+ newConnectionId,
+ };
+}
+
+function ingressFence(roomId: string): SelectedEdgeTurnIdentity {
+ return {
+ edgeKind: "host-sfu-ingress",
+ roomId,
+ shareGeneration: `share-${roomId}`,
+ revision: 4,
+ hostPeerId: `host-${roomId}`,
+ hostSessionId: `host-session-${roomId}`,
+ publicationGeneration: `publication-${roomId}`,
+ oldConnectionId: `publication-${roomId}`,
+ newConnectionId: `ingress-${roomId}`,
+ };
+}
+
+describe("TURN allocation admission", () => {
+ it("admits independent peer and Host-SFU edges up to deployment capacity", () => {
+ const admission = new TurnAllocationAdmission({ capacity: 3 });
+ const first = peerFence("room-a", "viewer-a");
+ const second = peerFence("room-a", "viewer-b");
+ const ingress = ingressFence("room-b");
+
+ expect(admission.reserve(first)).toBe(true);
+ expect(admission.reserve(second)).toBe(true);
+ expect(admission.reserve(ingress)).toBe(true);
+ expect(admission.usage()).toEqual({ allocations: 3 });
+ });
+
+ it("keeps reserve, commit, and drain charged until exact completion", () => {
+ const admission = new TurnAllocationAdmission({ capacity: 1 });
+ const fence = peerFence("room-a", "viewer-a");
+
+ expect(admission.reserve(fence)).toBe(true);
+ expect(admission.reserve(fence)).toBe(true);
+ expect(admission.state(fence)).toBe("reserved");
+ expect(admission.commit(fence)).toBe(true);
+ expect(admission.commit(fence)).toBe(true);
+ expect(admission.state(fence)).toBe("committed");
+ expect(admission.beginDrain(fence)).toBe(true);
+ expect(admission.beginDrain(fence)).toBe(true);
+ expect(admission.state(fence)).toBe("draining");
+ expect(admission.usage()).toEqual({ allocations: 1 });
+ expect(admission.completeDrain(fence)).toBe(true);
+ expect(admission.completeDrain(fence)).toBe(false);
+ expect(admission.usage()).toEqual({ allocations: 0 });
+ });
+
+ it("rejects stale exact identity and allocation ID reuse", () => {
+ const admission = new TurnAllocationAdmission({ capacity: 2 });
+ const current = peerFence("room-a", "viewer-a", "same-connection");
+ const staleRevision = { ...current, revision: current.revision - 1 };
+ const staleGeneration = {
+ ...current,
+ shareGeneration: `${current.shareGeneration}-stale`,
+ };
+ const wrongEdge = peerFence("room-a", "viewer-b", "same-connection");
+
+ expect(admission.reserve(current)).toBe(true);
+ expect(admission.reserve(staleRevision)).toBe(false);
+ expect(admission.reserve(staleGeneration)).toBe(false);
+ expect(admission.reserve(wrongEdge)).toBe(false);
+ expect(admission.commit(staleRevision)).toBe(false);
+ expect(admission.beginDrain(staleGeneration)).toBe(false);
+ expect(admission.beginDrain(wrongEdge)).toBe(false);
+ expect(admission.state(current)).toBe("reserved");
+ expect(admission.usage()).toEqual({ allocations: 1 });
+ expect(admission.beginDrain(current)).toBe(true);
+ expect(admission.completeDrain(current)).toBe(true);
+ expect(admission.usage()).toEqual({ allocations: 0 });
+ });
+
+ it("shares capacity exhaustion between Host ingress and peer edges", () => {
+ const admission = new TurnAllocationAdmission({ capacity: 1 });
+ const first = ingressFence("room-a");
+ const second = peerFence("room-b", "viewer-b");
+
+ expect(admission.reserve(first)).toBe(true);
+ expect(admission.reserve(second)).toBe(false);
+ expect(admission.state(first)).toBe("reserved");
+ expect(admission.state(second)).toBeUndefined();
+ expect(admission.usage()).toEqual({ allocations: 1 });
+ });
+
+ it("returns capacity exhaustion immediately without queueing a retry", () => {
+ const admission = new TurnAllocationAdmission({ capacity: 1 });
+ const active = ingressFence("room-a");
+ const rejected = peerFence("room-b", "viewer-b");
+
+ expect(admission.reserve(active)).toBe(true);
+ expect(admission.reserve(rejected)).toBe(false);
+ expect(admission.beginDrain(active)).toBe(true);
+ expect(admission.completeDrain(active)).toBe(true);
+ expect(admission.state(rejected)).toBeUndefined();
+ expect(admission.usage()).toEqual({ allocations: 0 });
+ expect(admission.reserve(rejected)).toBe(true);
+ });
+
+ it("makes shutdown drain explicit while restart ownership stays process-local", () => {
+ const previousOwner = new TurnAllocationAdmission({ capacity: 2 });
+ const first = peerFence("room-a", "viewer-a");
+ const second = ingressFence("room-b");
+ previousOwner.reserve(first);
+ previousOwner.reserve(second);
+ previousOwner.commit(first);
+
+ const draining = previousOwner.beginDrainAll();
+ expect(draining).toHaveLength(2);
+ expect(previousOwner.usage()).toEqual({ allocations: 2 });
+ const restartedOwner = new TurnAllocationAdmission({ capacity: 2 });
+ expect(restartedOwner.usage()).toEqual({ allocations: 0 });
+
+ for (const fence of draining) {
+ expect(previousOwner.completeDrain(fence)).toBe(true);
+ }
+ expect(previousOwner.usage()).toEqual({ allocations: 0 });
+ });
+});