Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

♻️ refactor: consolidate shuffle deck into shared utility with mutex protection

Anderson Firmino02ccb35e8093
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts
index c1c093b161..6c4c44b44a 100644
--- a/open-sse/services/combo.ts
+++ b/open-sse/services/combo.ts
@@ -9,6 +9,7 @@ import { recordComboRequest, getComboMetrics } from "./comboMetrics.ts";
import { resolveComboConfig, getDefaultComboConfig } from "./comboConfig.ts";
import * as semaphore from "./rateLimitSemaphore.ts";
import { getCircuitBreaker } from "../../src/shared/utils/circuitBreaker";
+import { fisherYatesShuffle, getNextFromDeck } from "../../src/shared/utils/shuffleDeck";
import { parseModel } from "./model.ts";
// Status codes that should mark semaphore + record circuit breaker failures
@@ -150,53 +151,8 @@ function orderModelsForWeightedFallback(models, selectedModel) {
return [selected, ...rest].filter(Boolean).map((e) => e.model);
}
-/**
- * Fisher-Yates shuffle (in-place)
- * @param {Array} arr
- * @returns {Array} The shuffled array
- */
-function shuffleArray(arr) {
- for (let i = arr.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- [arr[i], arr[j]] = [arr[j], arr[i]];
- }
- return arr;
-}
-
-// ─── Strict-Random: Shuffle Deck for Combos ──────────────────────────────────
-// Keyed by combo name — persists across requests, resets on server restart.
-const comboShuffleDecks = new Map();
-
-/**
- * Returns the next model ID from a shuffle deck for the given combo.
- * Uses each model exactly once per cycle before reshuffling (Fisher-Yates).
- * Guarantees the last model of the previous cycle is not the first of the next.
- */
-function getNextModelFromDeck(comboName, modelIds) {
- if (modelIds.length === 0) return "";
- if (modelIds.length === 1) return modelIds[0];
-
- const deck = comboShuffleDecks.get(comboName);
- const idsKey = [...modelIds].sort().join(",");
-
- // If deck exists, is for the same model set, and is not exhausted — advance
- if (deck && deck.idsKey === idsKey && deck.index < deck.order.length) {
- const id = deck.order[deck.index];
- comboShuffleDecks.set(comboName, { ...deck, index: deck.index + 1 });
- return id;
- }
-
- // Reshuffle — ensure last of previous cycle is not first of new cycle
- const lastId = deck && deck.idsKey === idsKey ? deck.order[deck.order.length - 1] : undefined;
- let newOrder = shuffleArray([...modelIds]);
- if (lastId !== undefined && newOrder[0] === lastId && newOrder.length > 1) {
- const swapIdx = Math.floor(Math.random() * (newOrder.length - 1)) + 1;
- [newOrder[0], newOrder[swapIdx]] = [newOrder[swapIdx], newOrder[0]];
- }
-
- comboShuffleDecks.set(comboName, { order: newOrder, index: 1, idsKey });
- return newOrder[0];
-}
+// shuffleArray and getNextModelFromDeck moved to src/shared/utils/shuffleDeck.ts
+// combo.ts now uses the shared, mutex-protected getNextFromDeck with "combo:" namespace.
/**
* Sort models by pricing (cheapest first) for cost-optimized strategy
@@ -323,7 +279,7 @@ export async function handleComboChat({
// Apply strategy-specific ordering
if (strategy === "strict-random") {
- const selectedId = getNextModelFromDeck(combo.name, orderedModels);
+ const selectedId = await getNextFromDeck(`combo:${combo.name}`, orderedModels);
// Put selected model first so the fallback loop tries it first
const rest = orderedModels.filter((m) => m !== selectedId);
orderedModels = [selectedId, ...rest];
@@ -332,7 +288,7 @@ export async function handleComboChat({
`Strict-random deck: ${selectedId} selected (${orderedModels.length} models)`
);
} else if (strategy === "random") {
- orderedModels = shuffleArray([...orderedModels]);
+ orderedModels = fisherYatesShuffle([...orderedModels]);
log.info("COMBO", `Random shuffle: ${orderedModels.length} models`);
} else if (strategy === "least-used") {
orderedModels = sortModelsByUsage(orderedModels, combo.name);
diff --git a/src/shared/utils/shuffleDeck.ts b/src/shared/utils/shuffleDeck.ts
new file mode 100644
index 0000000000..39d4371392
--- /dev/null
+++ b/src/shared/utils/shuffleDeck.ts
@@ -0,0 +1,145 @@
+/**
+ * Shared shuffle deck utility — Fisher-Yates shuffle with anti-repeat guarantee.
+ * Used by both combo model rotation and credential connection selection.
+ *
+ * Thread-safe: each deck namespace gets its own promise-based mutex to prevent
+ * race conditions when concurrent requests hit the same deck simultaneously.
+ */
+
+// ─── Types ──────────────────────────────────────────────────────────────────
+
+interface ShuffleDeck {
+ order: readonly string[];
+ index: number;
+ idsKey: string;
+}
+
+// ─── State ──────────────────────────────────────────────────────────────────
+
+const decks = new Map<string, ShuffleDeck>();
+const mutexes = new Map<string, Promise<void>>();
+
+// ─── Fisher-Yates Shuffle ───────────────────────────────────────────────────
+
+/**
+ * Fisher-Yates shuffle — returns a new shuffled copy of the array.
+ * Does NOT mutate the original.
+ */
+export function fisherYatesShuffle<T>(arr: readonly T[]): T[] {
+ const result = [...arr];
+ for (let i = result.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ const tmp = result[i];
+ result[i] = result[j];
+ result[j] = tmp;
+ }
+ return result;
+}
+
+// ─── Deck Operations ────────────────────────────────────────────────────────
+
+/**
+ * Get next item from a namespaced shuffle deck.
+ *
+ * - Namespace isolates decks (e.g. "combo:myCombo" vs "conn:openai").
+ * - Uses each item exactly once per cycle before reshuffling.
+ * - Guarantees the last item of a cycle is not the first of the next.
+ * - Resets deck when the item set changes (detected via sorted key).
+ * - Serialized per namespace via promise-based mutex (no race conditions).
+ */
+export async function getNextFromDeck(
+ namespace: string,
+ itemIds: readonly string[]
+): Promise<string> {
+ if (itemIds.length === 0) return "";
+ if (itemIds.length === 1) return itemIds[0];
+
+ // Acquire per-namespace mutex
+ const currentMutex = mutexes.get(namespace) ?? Promise.resolve();
+ let resolveMutex: (() => void) | undefined;
+ mutexes.set(
+ namespace,
+ new Promise<void>((resolve) => {
+ resolveMutex = resolve;
+ })
+ );
+
+ try {
+ await currentMutex;
+
+ const idsKey = [...itemIds].sort().join(",");
+ const existing = decks.get(namespace);
+
+ // If deck exists, same item set, and not exhausted — advance
+ if (existing && existing.idsKey === idsKey && existing.index < existing.order.length) {
+ const id = existing.order[existing.index];
+ decks.set(namespace, { ...existing, index: existing.index + 1 });
+ return id;
+ }
+
+ // Reshuffle — ensure last of previous cycle is not first of new cycle
+ const lastUsedId =
+ existing && existing.idsKey === idsKey && existing.order.length > 0
+ ? existing.order[existing.order.length - 1]
+ : undefined;
+
+ const newOrder = fisherYatesShuffle(itemIds);
+
+ if (lastUsedId !== undefined && newOrder[0] === lastUsedId && newOrder.length > 1) {
+ const swapIdx = 1 + Math.floor(Math.random() * (newOrder.length - 1));
+ const tmp = newOrder[0];
+ newOrder[0] = newOrder[swapIdx];
+ newOrder[swapIdx] = tmp;
+ }
+
+ decks.set(namespace, { order: newOrder, index: 1, idsKey });
+ return newOrder[0];
+ } finally {
+ resolveMutex?.();
+ }
+}
+
+// ─── Sync version (backwards compat for non-concurrent callers) ─────────────
+
+/**
+ * Synchronous version of getNextFromDeck — NO mutex protection.
+ * Only safe when the caller already holds a mutex (e.g. auth.ts getProviderCredentials).
+ */
+export function getNextFromDeckSync(namespace: string, itemIds: readonly string[]): string {
+ if (itemIds.length === 0) return "";
+ if (itemIds.length === 1) return itemIds[0];
+
+ const idsKey = [...itemIds].sort().join(",");
+ const existing = decks.get(namespace);
+
+ if (existing && existing.idsKey === idsKey && existing.index < existing.order.length) {
+ const id = existing.order[existing.index];
+ decks.set(namespace, { ...existing, index: existing.index + 1 });
+ return id;
+ }
+
+ const lastUsedId =
+ existing && existing.idsKey === idsKey && existing.order.length > 0
+ ? existing.order[existing.order.length - 1]
+ : undefined;
+
+ const newOrder = fisherYatesShuffle(itemIds);
+
+ if (lastUsedId !== undefined && newOrder[0] === lastUsedId && newOrder.length > 1) {
+ const swapIdx = 1 + Math.floor(Math.random() * (newOrder.length - 1));
+ const tmp = newOrder[0];
+ newOrder[0] = newOrder[swapIdx];
+ newOrder[swapIdx] = tmp;
+ }
+
+ decks.set(namespace, { order: newOrder, index: 1, idsKey });
+ return newOrder[0];
+}
+
+// ─── Test helpers ───────────────────────────────────────────────────────────
+
+/** Reset all decks — for testing only. */
+export function _resetAllDecks(): void {
+ decks.clear();
+ mutexes.clear();
+}
diff --git a/src/sse/services/auth.ts b/src/sse/services/auth.ts
index 31288a33bd..6bd77dc8d8 100644
--- a/src/sse/services/auth.ts
+++ b/src/sse/services/auth.ts
@@ -15,6 +15,7 @@ import {
lockModel,
} from "@omniroute/open-sse/services/accountFallback.ts";
import * as log from "../utils/logger";
+import { fisherYatesShuffle, getNextFromDeckSync } from "@/shared/utils/shuffleDeck";
type JsonRecord = Record<string, unknown>;
@@ -87,72 +88,10 @@ let selectionMutex = Promise.resolve();
// unavailable in parallel, which was the root cause of cascading 502 lockouts.
const markMutexes = new Map<string, Promise<void>>();
-// ─── Strict-Random: Shuffle Deck ─────────────────────────────────────────────
-interface ShuffleDeck {
- order: readonly string[];
- index: number;
-}
-
-const shuffleDecks = new Map<string, ShuffleDeck>();
-
-/**
- * Fisher-Yates shuffle — returns a new shuffled copy of the array.
- */
-export function fisherYatesShuffle<T>(arr: readonly T[]): T[] {
- const result = [...arr];
- for (let i = result.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- const tmp = result[i];
- result[i] = result[j];
- result[j] = tmp;
- }
- return result;
-}
-
-/**
- * Get next connection ID from the shuffle deck for the given provider.
- * - If the deck is valid and not exhausted, returns the next ID and advances the index.
- * - If exhausted or invalid (connection list changed), reshuffles.
- * - On reshuffle, guarantees the last ID of the previous cycle is not the first of the new one.
- */
-export function getNextFromDeck(provider: string, connectionIds: readonly string[]): string {
- if (connectionIds.length === 0) return "";
- if (connectionIds.length === 1) return connectionIds[0];
-
- const existing = shuffleDecks.get(provider);
-
- // Check if deck is still valid (same set of connection IDs)
- const deckValid =
- existing !== undefined &&
- existing.order.length === connectionIds.length &&
- existing.order.every((id) => connectionIds.includes(id));
-
- if (deckValid && existing.index < existing.order.length) {
- const id = existing.order[existing.index];
- shuffleDecks.set(provider, { order: existing.order, index: existing.index + 1 });
- return id;
- }
-
- // Need to reshuffle — remember the last used ID to avoid repeating it first
- const lastUsedId =
- existing !== undefined && existing.order.length > 0
- ? existing.order[Math.min(existing.index, existing.order.length) - 1]
- : undefined;
-
- let newOrder = fisherYatesShuffle(connectionIds);
-
- // If the first of the new cycle equals the last of the previous, swap it away
- if (lastUsedId !== undefined && newOrder[0] === lastUsedId && newOrder.length > 1) {
- // Pick a random position > 0 and swap
- const swapIdx = 1 + Math.floor(Math.random() * (newOrder.length - 1));
- const tmp = newOrder[0];
- newOrder[0] = newOrder[swapIdx];
- newOrder[swapIdx] = tmp;
- }
-
- shuffleDecks.set(provider, { order: newOrder, index: 1 });
- return newOrder[0];
-}
+// Strict-Random shuffle deck moved to src/shared/utils/shuffleDeck.ts
+// auth.ts uses getNextFromDeckSync (already inside selectionMutex).
+// Re-export for backwards compat with existing test imports.
+export { fisherYatesShuffle, getNextFromDeckSync as getNextFromDeck };
/**
* Get provider credentials from localDb
@@ -394,7 +333,7 @@ export async function getProviderCredentials(
} else if (strategy === "strict-random") {
// Strict Random: shuffle deck — uses each account once before reshuffling
const ids = orderedConnections.map((c) => c.id);
- const selectedId = getNextFromDeck(provider, ids);
+ const selectedId = getNextFromDeckSync(`conn:${provider}`, ids);
connection = orderedConnections.find((c) => c.id === selectedId) || orderedConnections[0];
} else {
// Default: fill-first (already sorted by priority in getProviderConnections)