File size: 5,053 Bytes
3ed1fc7
8ba64ef
5eff0b7
8ba64ef
5eff0b7
8ba64ef
 
 
5eff0b7
 
8ba64ef
3ed1fc7
 
 
8ba64ef
 
 
 
5eff0b7
8ba64ef
 
 
 
5eff0b7
 
8ba64ef
 
 
 
 
 
 
5eff0b7
 
8ba64ef
 
3ed1fc7
8ba64ef
 
5eff0b7
3ed1fc7
8ba64ef
 
5eff0b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ed1fc7
5eff0b7
 
8ba64ef
 
 
 
5eff0b7
 
 
 
 
 
 
 
 
8ba64ef
 
5eff0b7
8ba64ef
 
5eff0b7
8ba64ef
 
 
 
 
5eff0b7
8ba64ef
5eff0b7
8ba64ef
 
5eff0b7
 
 
 
8ba64ef
5eff0b7
 
8ba64ef
5eff0b7
 
 
 
 
8ba64ef
5eff0b7
8ba64ef
5eff0b7
 
 
 
8ba64ef
5eff0b7
 
 
8ba64ef
5eff0b7
 
8ba64ef
 
 
 
 
 
5eff0b7
8ba64ef
 
5eff0b7
 
 
 
8ba64ef
5eff0b7
8ba64ef
5eff0b7
8ba64ef
5eff0b7
 
 
 
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
import { Queue, Worker, ConnectionOptions } from "bullmq";
import { redis } from "../../infrastructure/redis/redis-client";
import { broadcastGameUpdate } from "../../infrastructure/ws/session-manager";
import { Keys } from "../../lib/keys";
import { GameStatus, WsMessageType } from "../../types/types";
import { flushGameToDatabase } from "./storage";

const TIMER_QUEUE_NAME = "game-timers";
const ABANDONMENT_QUEUE_NAME = "game-abandonment";
const DISCONNECT_GRACE_MS = 5000;

export const timerQueue = new Queue(TIMER_QUEUE_NAME, {
  connection: redis as unknown as ConnectionOptions,
});

export const timerWorker = new Worker(
  TIMER_QUEUE_NAME,
  async (job) => {
    const { gameId, winnerId } = job.data as {
      gameId: string;
      winnerId: string;
    };
    const gameState = await redis.hgetall(Keys.game(gameId));

    if (!gameState || gameState.status !== GameStatus.IN_PROGRESS) return;

    const timeoutPayload = {
      type: WsMessageType.GAME_OVER,
      payload: { status: GameStatus.TIME_OUT, reason: "timeout", winnerId },
    };

    await Promise.all([
      broadcastGameUpdate(gameId, timeoutPayload),
      flushGameToDatabase(gameId, GameStatus.TIME_OUT, winnerId),
    ]);
  },
  { connection: redis as unknown as ConnectionOptions },
);

export const abandonmentQueue = new Queue(ABANDONMENT_QUEUE_NAME, {
  connection: redis as unknown as ConnectionOptions,
});

export const abandonmentWorker = new Worker(
  ABANDONMENT_QUEUE_NAME,
  async (job) => {
    const { gameId } = job.data as { gameId: string };
    const gameKey = Keys.game(gameId);
    const gameState = await redis.hgetall(gameKey);

    if (!gameState || gameState.status !== GameStatus.IN_PROGRESS) return;

    const whiteUser = JSON.parse(gameState.whiteUser);
    const blackUser = JSON.parse(gameState.blackUser);

    const moveTimes: number[] = JSON.parse(gameState.moveTimes || "[]");
    const isAbort = moveTimes.length < 2;
    const winnerId = isAbort
      ? undefined
      : gameState.whiteDisconnectedAt
        ? blackUser.id
        : whiteUser.id;

    const gameOverPayload = {
      type: WsMessageType.GAME_OVER,
      payload: { status: GameStatus.ABANDONED, winnerId, reason: "abandoned" },
    };

    await broadcastGameUpdate(gameId, gameOverPayload);
    await flushGameToDatabase(gameId, GameStatus.ABANDONED, winnerId);
  },
  { connection: redis as unknown as ConnectionOptions },
);

export async function startPlayerTimer(
  gameId: string,
  opponentId: string,
  timeLeftMs: number,
) {
  const safeDelay = isNaN(timeLeftMs) ? 0 : Math.max(0, Math.floor(timeLeftMs));

  if (isNaN(timeLeftMs)) {
    console.error(
      `[Timer Critical] Received NaN for timeLeftMs in game ${gameId}. Opponent: ${opponentId}`,
    );
  }

  await timerQueue.add(
    "timeout",
    { gameId, winnerId: opponentId },
    {
      jobId: Keys.timerJob(gameId),
      delay: safeDelay,
      removeOnComplete: true,
      removeOnFail: true,
    },
  );
}
export async function cancelTimer(gameId: string) {
  const job = await timerQueue.getJob(Keys.timerJob(gameId));
  if (job) await job.remove();
}

export async function startReconnectTimer(gameId: string, userId: string) {
  const gameKey = Keys.game(gameId);
  const gameState = await redis.hgetall(gameKey);
  if (!gameState || !gameState.whiteUser) return;

  const whiteUser = JSON.parse(gameState.whiteUser);
  const color = whiteUser.id === userId ? "white" : "black";

  const isNewDisconnect = await redis.hsetnx(
    gameKey,
    `${color}DisconnectedAt`,
    Date.now(),
  );

  if (isNewDisconnect === 0) return;

  await broadcastGameUpdate(gameId, {
    type: "PLAYER_DISCONNECTED",
    payload: { color, userId },
  });

  await abandonmentQueue.add(
    "abandon-check",
    { gameId },
    {
      jobId: `abandonment_${gameId}`,
      delay: DISCONNECT_GRACE_MS,
      removeOnComplete: true,
      removeOnFail: true,
    },
  );
}

export async function cancelReconnectTimer(gameId: string, userId: string) {
  const gameKey = Keys.game(gameId);
  const gameState = await redis.hgetall(gameKey);
  if (!gameState || !gameState.whiteUser) return;

  const whiteUser = JSON.parse(gameState.whiteUser);
  const color = whiteUser.id === userId ? "white" : "black";

  const deletedCount = await redis.hdel(gameKey, `${color}DisconnectedAt`);

  if (deletedCount === 0) return;

  await broadcastGameUpdate(gameId, {
    type: "PLAYER_RECONNECTED",
    payload: { color, userId },
  });

  const job = await abandonmentQueue.getJob(`abandonment_${gameId}`);
  if (job) await job.remove();
}

export async function cancelAbandonmentJob(gameId: string): Promise<void> {
  const jobId = `abandonment_${gameId}`;
  const job = await abandonmentQueue.getJob(jobId);

  if (job) {
    try {
      const isActive = await job.isActive();

      if (!isActive) {
        await job.remove();
      }
    } catch (err) {
      console.warn(
        `[Timer] Could not remove locked job ${jobId}:`,
        err instanceof Error ? err.message : err,
      );
    }
  }
}