refactor: simplify connection selection with linear scan

This commit is contained in:
Mohamed Boudra
2026-03-13 13:44:25 +07:00
parent 7f69166e97
commit a495138374
+23 -30
View File
@@ -15,6 +15,14 @@ export type SelectBestConnectionInput = {
probeByConnectionId: Map<string, ConnectionProbeState>; probeByConnectionId: Map<string, ConnectionProbeState>;
}; };
function getAvailableLatency(input: {
connectionId: string;
probeByConnectionId: Map<string, ConnectionProbeState>;
}): number | null {
const probe = input.probeByConnectionId.get(input.connectionId);
return probe?.status === "available" ? probe.latencyMs : null;
}
export function selectBestConnection( export function selectBestConnection(
input: SelectBestConnectionInput input: SelectBestConnectionInput
): string | null { ): string | null {
@@ -23,37 +31,22 @@ export function selectBestConnection(
return null; return null;
} }
const available = candidates let bestConnectionId: string | null = null;
.map((candidate, index) => ({ candidate, index })) let bestLatency: number | null = null;
.filter(({ candidate }) => {
const probe = probeByConnectionId.get(candidate.connectionId); for (const candidate of candidates) {
return probe?.status === "available"; const latencyMs = getAvailableLatency({
connectionId: candidate.connectionId,
probeByConnectionId,
}); });
if (latencyMs === null) {
const byLatency = (left: { candidate: ConnectionCandidate; index: number }, right: { candidate: ConnectionCandidate; index: number }) => { continue;
const leftProbe = probeByConnectionId.get(left.candidate.connectionId); }
const rightProbe = probeByConnectionId.get(right.candidate.connectionId); if (bestLatency === null || latencyMs < bestLatency) {
bestConnectionId = candidate.connectionId;
const leftLatency = bestLatency = latencyMs;
leftProbe && leftProbe.status === "available" }
? leftProbe.latencyMs
: Number.POSITIVE_INFINITY;
const rightLatency =
rightProbe && rightProbe.status === "available"
? rightProbe.latencyMs
: Number.POSITIVE_INFINITY;
if (leftLatency === rightLatency) {
return left.index - right.index;
}
return leftLatency - rightLatency;
};
if (available.length === 0) {
return null;
} }
const sorted = available.sort(byLatency); return bestConnectionId;
return sorted[0]!.candidate.connectionId;
} }