Spaces:
Running
Running
File size: 5,769 Bytes
8ba64ef 647bbf0 8ba64ef 32f4c77 8ba64ef 32f4c77 8ba64ef 89ef678 32f4c77 89ef678 8ba64ef 89ef678 8ba64ef 32f4c77 8ba64ef 89ef678 8ba64ef 32f4c77 8ba64ef 32f4c77 8ba64ef 89ef678 8ba64ef 89ef678 8ba64ef 32f4c77 89ef678 8ba64ef 647bbf0 8ba64ef 89ef678 8ba64ef 5eff0b7 8ba64ef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | import { v7 as uuidv7 } from "uuid";
import { redis } from "../../infrastructure/redis/redis-client";
import { sendToUser } from "../../infrastructure/ws/session-manager";
import { startPlayerTimer } from "../game/timer";
import {
WsMessageType,
GameStatus,
PLAYER_COLOR,
PlayerInfo,
} from "../../types/types";
import { Keys } from "../../lib/keys";
import { db } from "../../infrastructure/db/db";
import { user } from "../../infrastructure/db/schema";
import { eq } from "drizzle-orm";
const MATCHMAKING_QUEUE_KEY = "matchmaking:queue";
const MATCHMAKING_INFO_KEY = "matchmaking:info";
const CLAIM_OPPONENT_LUA = `
local candidates = redis.call('ZRANGEBYSCORE', KEYS[1], ARGV[1], ARGV[2], 'LIMIT', 0, 2)
for i=1, #candidates do
if candidates[i] ~= ARGV[3] then
redis.call('ZREM', KEYS[1], candidates[i])
return candidates[i]
end
end
return nil
`;
function parseTimeControl(tc: string): { baseMs: number } {
const [minsPart] = tc.split("+");
const mins = parseInt(minsPart ?? "", 10);
if (isNaN(mins)) throw new Error(`Invalid time control: ${tc}`);
return { baseMs: mins * 60 * 1000 };
}
export async function handleJoinQueue(
userId: string,
timeControl: string,
): Promise<void> {
const LOCK_KEY = Keys.lockMatchMaking(userId);
const searchSessionId = uuidv7();
const timestamp = new Date().toISOString().replace("T", " ").replace("Z", "");
const isSearching = await redis.set(
LOCK_KEY,
searchSessionId,
"EX",
60,
"NX",
);
if (!isSearching) {
console.warn(
`[${timestamp}] [Queue] ${userId} already has an active search loop. Ignoring.`,
);
return;
}
try {
const userData = await db.query.user.findFirst({
where: eq(user.id, userId),
});
if (!userData) return;
const rating = userData.rating;
const playerInfo = {
id: userId,
username: userData.username,
rating: userData.rating,
image: userData.image,
};
await redis.hset(MATCHMAKING_INFO_KEY, userId, JSON.stringify(playerInfo));
await redis.zadd(MATCHMAKING_QUEUE_KEY, rating, userId);
const searchTiers = [100, 300, 500, 1000, 1500];
for (const range of searchTiers) {
const stillInQueue = await redis.zscore(MATCHMAKING_QUEUE_KEY, userId);
if (!stillInQueue) return;
const minRating = rating - range;
const maxRating = rating + range;
const opponentId = (await redis.eval(
CLAIM_OPPONENT_LUA,
1,
MATCHMAKING_QUEUE_KEY,
minRating.toString(),
maxRating.toString(),
userId,
)) as string | null;
if (opponentId) {
await redis.zrem(MATCHMAKING_QUEUE_KEY, userId);
const opponentDataStr = await redis.hget(
MATCHMAKING_INFO_KEY,
opponentId,
);
const opponentInfo = opponentDataStr
? JSON.parse(opponentDataStr)
: {
id: opponentId,
username: "Unknown",
rating: 1200,
image: null,
};
await redis.hdel(MATCHMAKING_INFO_KEY, userId, opponentId);
await createNewMatch(playerInfo, opponentInfo, timeControl);
return;
}
await new Promise((resolve) => setTimeout(resolve, 10000));
}
const finalLock = await redis.get(LOCK_KEY);
if (finalLock === searchSessionId) {
const finalCheck = await redis.zrem(MATCHMAKING_QUEUE_KEY, userId);
if (finalCheck) {
await redis.hdel(MATCHMAKING_INFO_KEY, userId);
await sendToUser(userId, {
type: WsMessageType.MATCHMAKING_TIMEOUT,
payload: { message: "No suitable opponent found. Try again?" },
});
}
}
} finally {
const currentLock = await redis.get(LOCK_KEY);
if (currentLock === searchSessionId) {
await redis.del(LOCK_KEY);
}
}
}
export async function handleLeaveQueue(userId: string): Promise<void> {
await redis.zrem(MATCHMAKING_QUEUE_KEY, userId);
await redis.hdel(MATCHMAKING_INFO_KEY, userId);
await redis.del(Keys.lockMatchMaking(userId));
}
export async function createNewMatch(
player1: PlayerInfo,
player2: PlayerInfo,
timeControl: string,
forceP1White?: boolean,
): Promise<void> {
const gameId = uuidv7();
const initialFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
const { baseMs } = parseTimeControl(timeControl);
const now = Date.now();
const isP1White =
forceP1White !== undefined ? forceP1White : Math.random() > 0.5;
const whiteUser = isP1White ? player1 : player2;
const blackUser = isP1White ? player2 : player1;
await redis.hset(Keys.game(gameId), {
whiteUser: JSON.stringify({ ...whiteUser, timeLeftMs: baseMs }),
blackUser: JSON.stringify({ ...blackUser, timeLeftMs: baseMs }),
fen: initialFen,
pgn: "",
status: GameStatus.IN_PROGRESS,
turn: PLAYER_COLOR.WHITE,
timeControl,
lastMoveTimestamp: now,
});
console.log(
`[Game] Started | ID: ${gameId} | ${whiteUser.id} (W) vs ${blackUser.id} (B)`,
);
await Promise.all([
redis.del(Keys.lockMatchMaking(whiteUser.id)),
redis.del(Keys.lockMatchMaking(blackUser.id)),
redis.set(Keys.userActiveGame(whiteUser.id), gameId),
redis.set(Keys.userActiveGame(blackUser.id), gameId),
]);
const payloadBase = {
gameId,
fen: initialFen,
timeControl,
white: whiteUser,
black: blackUser,
};
await Promise.all([
sendToUser(whiteUser.id, {
type: WsMessageType.GAME_STARTED,
payload: { ...payloadBase, color: "white" },
}),
sendToUser(blackUser.id, {
type: WsMessageType.GAME_STARTED,
payload: { ...payloadBase, color: "black" },
}),
]);
await startPlayerTimer(gameId, whiteUser.id, baseMs);
}
|