-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
1533 lines (1328 loc) · 45.3 KB
/
index.js
File metadata and controls
1533 lines (1328 loc) · 45.3 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Fastify from "fastify";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
import { instrument } from "@socket.io/admin-ui";
import jwt from "jsonwebtoken";
import fastifyEnv from "@fastify/env";
import cors from "@fastify/cors";
import fastifyStatic from "@fastify/static";
import fastifyRedis from "@fastify/redis";
import fastifyPostgres from "@fastify/postgres";
// import fastifyRabbit from "fastify-rabbitmq";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import crypto from "node:crypto";
const SELECTION_TIMEOUT = 10 * 1000; // 선택 만료 시간: 10초
const RESERVATION_STATUS_INTERVAL = 1 * 1000; // 좌석 예매 현황 불러오는 주기: 1초
const PAYMENT_TIMEOUT = 60 * 1000; // 결제 만료 시간: 1분 (테스트용)
const schema = {
type: "object",
required: [
"PORT",
"JWT_SECRET",
"JWT_SECRET_FOR_ENTRANCE",
"CACHE_HOST",
"CACHE_PORT",
"DB_URL",
// "MQ_URL",
],
properties: {
PORT: {
type: "string",
},
JWT_SECRET: {
type: "string",
},
JWT_SECRET_FOR_ENTRANCE: {
type: "string",
},
CACHE_HOST: {
type: "string",
},
CACHE_PORT: {
type: "integer",
},
DB_URL: {
type: "string",
},
// MQ_URL: {
// type: "string",
// },
},
};
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const fastify = Fastify({
logger: true,
});
await fastify.register(fastifyEnv, {
schema,
dotenv: true,
});
await fastify.register(cors, {
origin: "*",
});
await fastify.register(fastifyRedis, {
host: fastify.config.CACHE_HOST,
port: fastify.config.CACHE_PORT,
family: 4,
});
await fastify.register(fastifyPostgres, {
connectionString: fastify.config.DB_URL,
});
// await fastify.register(fastifyRabbit, {
// connection: fastify.config.MQ_URL,
// });
await fastify.register(fastifyStatic, {
root: join(__dirname, "dist"),
prefix: "/admin",
redirect: true,
});
fastify.get("/reservation", async (request, reply) => {
return reply.sendFile("reservation.html");
});
fastify.get("/liveness", (request, reply) => {
reply.send({ status: "ok", message: "The server is alive." });
});
fastify.get("/readiness", async (request, reply) => {
try {
let redisStatus = { status: "disconnected", message: "" };
let dbStatus = { status: "disconnected", message: "" };
// let rabbitStatus = { status: "disconnected", message: "" };
// Redis 상태 확인
try {
const pingResult = await fastify.redis.ping();
if (pingResult === "PONG") {
redisStatus = { status: "connected", message: "Redis is available." };
} else {
redisStatus.message = "Redis responded, but not with 'PONG'.";
}
} catch (error) {
redisStatus.message = `Redis connection failed: ${error.message}`;
}
// PostgreSQL 상태 확인
let client;
try {
client = await fastify.pg.connect();
if (client) {
dbStatus = {
status: "connected",
message: "PostgreSQL is connected and responsive.",
};
client.release(); // 연결 반환
}
} catch (error) {
dbStatus.message = `PostgreSQL connection failed: ${error.message}`;
}
// RabbitMQ 상태 확인
// try {
// if (fastify.rabbitmq.ready) {
// rabbitStatus = {
// status: "connected",
// message: "RabbitMQ is connected and operational.",
// };
// } else {
// rabbitStatus.message = "RabbitMQ is not connected.";
// }
// } catch (error) {
// rabbitStatus.message = `RabbitMQ connection check failed: ${error.message}`;
// }
// 모든 상태가 정상일 때
if (
redisStatus.status === "connected" &&
dbStatus.status === "connected"
// rabbitStatus.status === "connected"
) {
reply.send({
status: "ok",
message: "The server is ready.",
redis: redisStatus,
database: dbStatus,
// rabbitmq: rabbitStatus,
});
} else {
// 하나라도 비정상일 때
reply.status(500).send({
status: "error",
message: "The server is not fully ready. See details below.",
redis: redisStatus,
database: dbStatus,
// rabbitmq: rabbitStatus,
});
}
} catch (unexpectedError) {
// 예기치 못한 오류 처리
fastify.log.error(
"Readiness check encountered an unexpected error:",
unexpectedError
);
reply.status(500).send({
status: "error",
message: "Unexpected error occurred during readiness check.",
error: unexpectedError.message,
});
}
});
// 이벤트에 대한 모든 구역 정보를 가져오는 함수
async function getAreasForRoom(eventId) {
// PostgreSQL 쿼리 실행
const query = `
SELECT
area.id,
area.label,
area.svg,
area.price
FROM area
WHERE area."eventId" = $1
AND area."deletedAt" IS NULL;
`;
const params = [eventId];
const { rows } = await fastify.pg.query(query, params);
// 구역 정보를 반환
return rows;
}
async function getSeatsForArea(eventDateId, areaId) {
// PostgreSQL 쿼리 실행
const query = `
SELECT
seat.id AS seat_id,
seat.cx,
seat.cy,
seat.row,
seat.number,
seat."areaId" AS area_id,
reservation.id AS reservation_id,
eventDate.id AS event_date_id,
eventDate.date,
"order"."userId" AS reserved_user_id
FROM seat
LEFT JOIN reservation ON reservation."seatId" = seat.id AND reservation."canceledAt" IS NULL AND reservation."deletedAt" IS NULL
LEFT JOIN event_date AS eventDate ON reservation."eventDateId" = eventDate.id
LEFT JOIN "order" ON reservation."orderId" = "order".id AND "order"."canceledAt" IS NULL AND "order"."deletedAt" IS NULL
WHERE seat."areaId" = $1
AND (eventDate.id = $2 OR eventDate.id IS NULL);
`;
const params = [areaId, eventDateId];
const { rows } = await fastify.pg.query(query, params);
// 데이터 가공
const seatMap = new Map();
rows.forEach((row) => {
if (!seatMap.has(row.seat_id)) {
seatMap.set(row.seat_id, {
id: row.seat_id,
cx: row.cx,
cy: row.cy,
row: row.row,
number: row.number,
area_id: row.area_id,
selectedBy: null,
reservedUserId: row.reserved_user_id || null, // 예약된 유저 ID
updatedAt: null, // 초기 상태
expirationTime: null, // 초기 상태
});
}
});
return Array.from(seatMap.values());
}
// Redis에서 구역 정보를 저장
// async function setAreaDataInRedis(roomName, areaData) {
// await fastify.redis.set(`areaData:${roomName}`, JSON.stringify(areaData));
// }
// 구역 별 예약 상태를 Redis에 저장
async function updateAreaInRedis(roomName, areaId, area) {
await fastify.redis.hset(`areas:${roomName}`, areaId, JSON.stringify(area));
}
// Redis에서 구역 별 예약 상태 가져오기
async function getAreaFromRedis(roomName, areaId) {
const areaData = await fastify.redis.hget(`areas:${roomName}`, areaId);
return areaData ? JSON.parse(areaData) : null;
}
// Redis에서 모든 구역 가져오기
async function getAllAreasFromRedis(roomName) {
const areasData = await fastify.redis.hgetall(`areas:${roomName}`);
const areas = [];
for (const areaId in areasData) {
areas.push(JSON.parse(areasData[areaId]));
}
return areas;
}
// Redis에서 좌석 정보를 구역 별로 저장
// async function setSeatDataInRedis(areaName, seatData) {
// await fastify.redis.set(`seatData:${areaName}`, JSON.stringify(seatData));
// }
// 좌석 선택 상태를 Redis에 저장
async function updateSeatInRedis(areaName, seatId, seat) {
await fastify.redis.hset(`seats:${areaName}`, seatId, JSON.stringify(seat));
}
// Redis에서 좌석 선택 상태 가져오기
async function getSeatFromRedis(areaName, seatId) {
const seatData = await fastify.redis.hget(`seats:${areaName}`, seatId);
return seatData ? JSON.parse(seatData) : null;
}
// Redis에서 특정 구역의 모든 좌석 가져오기
async function getAllSeatsFromRedis(areaName) {
const seatsData = await fastify.redis.hgetall(`seats:${areaName}`);
const seats = [];
for (const seatId in seatsData) {
seats.push(JSON.parse(seatsData[seatId]));
}
return seats;
}
// 좌석 선택 만료를 Redis에서 설정
async function setSeatExpirationInRedis(areaName, seatId) {
// 만료 시간을 설정하여 키를 설정
await fastify.redis.set(
`timer:${areaName}:${seatId}`,
"active",
"PX",
SELECTION_TIMEOUT
);
}
// Redis에서 좌석 선택 만료 확인
async function isSeatExpired(areaName, seatId) {
const status = await fastify.redis.exists(`timer:${areaName}:${seatId}`);
return !status; // 존재하지 않으면 만료됨
}
// 새로운 Order를 Redis에 임시 저장
async function createOrderInRedis(areaName, seatIds, userId, eventDateId) {
let id = crypto.randomUUID();
const orderStatus = "pending"; // 초기 상태
const createdAt = new Date().toISOString();
// Redis에 Order 데이터 저장
await fastify.redis.hset(
`order:${areaName}`,
id,
JSON.stringify({ userId, eventDateId, seatIds, orderStatus, createdAt })
);
return id;
}
async function updateOrderInRedis(areaName, orderId) {
try {
// Redis에서 주문 데이터를 가져옴
const orderData = await getOrderFromRedis(areaName, orderId);
// 주문 데이터가 존재하지 않는 경우 예외 처리
if (!orderData) {
throw new Error(
`Order not found in Redis for area: ${areaName}, orderId: ${orderId}`
);
}
// 상태 업데이트
orderData.orderStatus = "completed";
// 업데이트된 데이터를 Redis에 저장
await fastify.redis.hset(
`order:${areaName}`,
orderId,
JSON.stringify(orderData)
);
// 업데이트 결과 확인
const updatedRedisOrder = await getOrderFromRedis(areaName, orderId);
return updatedRedisOrder;
} catch (error) {
console.error("Error updating order in Redis:", error);
throw error; // 예외를 호출자로 전달
}
}
// Redis에서 임시 주문 정보 가져오기
async function getOrderFromRedis(areaName, orderId) {
const orderData = await fastify.redis.hget(`order:${areaName}`, orderId);
return orderData ? JSON.parse(orderData) : null;
}
// 주문 결제 만료를 Redis에서 설정
async function setPaymentExpirationInRedis(areaName, orderId) {
// 만료 시간을 설정하여 키를 설정
await fastify.redis.set(
`paymentTimer:${areaName}:${orderId}`,
"active",
"PX",
PAYMENT_TIMEOUT
);
}
// // Redis에서 주문 결제 만료 확인
// async function isPaymentExpired(areaName, orderId) {
// const status = await fastify.redis.exists(`paymentTimer:${areaName}:${orderId}`);
// return !status; // 존재하지 않으면 만료됨
// }
async function validateToken(token) {
const status = await fastify.redis.get(`token:${token}`);
if (status === "issued") {
await fastify.redis.del(`token:${token}`); // 토큰 사용 완료 처리
return true;
}
return false;
}
// Redis Keyspace Notifications를 위한 Subscriber 설정
const redisSubscriber = fastify.redis.duplicate();
// await redisSubscriber.connect();
// Redis Keyspace Notifications 설정
await redisSubscriber.config("SET", "notify-keyspace-events", "Ex");
// 만료 이벤트 패턴 구독
const pattern = `__keyevent@${fastify.redis.options.db || 0}__:expired`;
redisSubscriber.psubscribe(pattern, (err, count) => {
if (err) {
fastify.log.error("Failed to subscribe to pattern:", err);
} else {
fastify.log.info(
`Successfully subscribed to pattern: ${pattern}, subscription count: ${count}`
);
}
});
// 패턴 메시지 이벤트 리스너 설정
redisSubscriber.on("pmessage", async (pattern, channel, message) => {
const keyParts = message.split(":");
const keyType = keyParts[0];
if (keyType === "timer") {
const areaName = keyParts[1];
const seatId = keyParts[2];
await handleExpirationEvent(areaName, seatId);
} else if (keyType === "paymentTimer") {
const areaName = keyParts[1];
const orderId = keyParts[2];
const orderData = await getOrderFromRedis(areaName, orderId);
if (orderData && orderData.orderStatus === "pending") {
for (const seatId of orderData.seatIds) {
await handleExpirationEvent(areaName, seatId);
}
}
await fastify.redis.hdel(`order:${areaName}`, orderId);
}
});
// Redis 잠금을 사용하여 이벤트 중복 방지
const handleExpirationEvent = async (areaName, seatId) => {
const lockKey = `lock:seat:${areaName}:${seatId}`;
// 잠금을 설정하고 기존에 잠금이 없었을 경우에만 처리
const lockAcquired = await fastify.redis.set(
lockKey,
"locked",
"NX",
"EX",
10
);
if (!lockAcquired) {
fastify.log.info(`Another process is already handling this: ${lockKey}`);
return; // 다른 프로세스가 이미 처리 중
}
try {
// 좌석 정보 처리 로직
const seat = await getSeatFromRedis(areaName, seatId);
if (seat) {
seat.selectedBy = null;
seat.updatedAt = new Date().toISOString();
seat.expirationTime = null;
seat.reservedUserId = null;
await updateSeatInRedis(areaName, seatId, seat);
io.to(areaName).emit("seatsSelected", [
{
seatId: seat.id,
selectedBy: null,
updatedAt: seat.updatedAt,
expirationTime: null,
reservedUserId: null,
},
]);
fastify.log.info(
`Selection for seat ${seatId} has expired (area: ${areaName}).`
);
}
} finally {
// 잠금 해제
await fastify.redis.del(lockKey);
}
};
const pubClient = fastify.redis.duplicate();
const subClient = fastify.redis.duplicate();
const io = new Server(fastify.server, {
cors: {
origin: "*",
methods: "*",
credentials: true,
},
transports: ["websocket"],
adapter: createAdapter(pubClient, subClient),
});
instrument(io, {
auth: {
type: "basic",
username: "admin",
password: "$2a$10$QWUn5UhhE3eSAu2a95fVn.PRVaamlJlJBMeT7viIrvgvfCOeUIV2W",
},
mode: "development",
});
// Redis 기반 유저 수 가져오기 함수
async function getRoomUserCount(roomName) {
const maxRetries = 30;
let delay = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
// const sockets = await io.in(roomName).fetchSockets(); // 모든 노드에서 룸에 속한 소켓 ID 가져오기
const count = await fastify.redis.get(`room:${roomName}:count`);
return parseInt(count || "0"); // 소켓 수 반환
} catch (err) {
console.error(
`Timeout reached, retrying (attempt ${attempt}/${maxRetries})...`
);
await new Promise((resolve) => {
delay = decorrelatedJitter(100, 60000, delay);
setTimeout(resolve, delay);
});
}
}
}
async function decrementRoomCount(room) {
const decrementScript = `
local key = KEYS[1]
local value = redis.call("GET", key)
if value and tonumber(value) > 0 then
return redis.call("DECR", key)
else
return 0
end
`;
const key = `room:${room}:count`;
const count = await fastify.redis.eval(decrementScript, 1, key);
return parseInt(count || "0");
}
function decorrelatedJitter(baseDelay, maxDelay, previousDelay) {
if (!previousDelay) {
previousDelay = baseDelay;
}
return Math.min(
maxDelay,
Math.random() * (previousDelay * 3 - baseDelay) + baseDelay
);
}
io.use(async (socket, next) => {
const token = socket.handshake.auth.token;
if (!token) {
return next(new Error("Authentication error"));
}
if (!(await validateToken(token))) {
return next(new Error("Authentication error 2"));
}
try {
const decoded = jwt.verify(token, fastify.config.JWT_SECRET_FOR_ENTRANCE);
socket.data.user = decoded;
next();
} catch (err) {
return next(new Error("Authentication error"));
}
});
// const roomIntervals = {};
io.on("connection", (socket) => {
fastify.log.info(`New client connected: ${socket.id}`);
// 클라이언트가 room 정보를 전달
socket.on("joinRoom", async ({ eventId, eventDateId }) => {
if (!eventId || !eventDateId) {
socket.emit("error", { message: "Invalid room parameters." });
return;
}
// room 이름 생성 (eventId와 eventDateId 조합)
const roomName = `${eventId}_${eventDateId}`;
try {
// Room 접속자가 최대치를 초과하면 연결 거부
// if (currentConnections >= MAX_ROOM_CONNECTIONS) {
// socket.emit("error", {
// message: `Room ${roomName} is full. Maximum connections reached.`,
// });
// return;
// }
// 클라이언트를 해당 room에 추가
socket.join(roomName);
const currentConnections = await fastify.redis.incr(
`room:${roomName}:count`
);
fastify.log.info(
`Client ${socket.id} joined room: ${roomName}. Current connections: ${currentConnections + 1}`
);
// 구역 정보 가져오기
let areas = await getAllAreasFromRedis(roomName);
if (areas.length === 0) {
// Redis에 구역 정보가 없으면 DB에서 가져오기
areas = await getAreasForRoom(eventId, eventDateId); // DB에서 가져오기
// Redis에 구역 정보 저장
for (const area of areas) {
await updateAreaInRedis(roomName, area.id, area);
}
// await setAreaDataInRedis(roomName, areas);
}
// 클라이언트에게 데이터 전송
socket.emit("roomJoined", {
message: `You have joined the room: ${roomName}`,
areas,
});
// startReservationStatusInterval(eventId, eventDateId);
const jwtToken = jwt.sign(
{
jti: crypto.randomUUID(),
sub: "scheduling",
eventId,
eventDateId,
},
fastify.config.JWT_SECRET,
{
expiresIn: 600, // 10분
}
);
await fetch(
"https://socketing.hjyoon.me/scheduling/seat/reservation/statistic",
{
method: "POST",
headers: {
Authorization: `Bearer ${jwtToken}`, // JWT 토큰 추가
},
}
);
} catch (error) {
fastify.log.error(`Error fetching data for room ${roomName}:`, error);
socket.emit("error", {
message: "Failed to fetch room data.",
});
}
});
socket.on("joinArea", async ({ eventId, eventDateId, areaId }) => {
if (!eventId || !eventDateId || !areaId) {
socket.emit("error", { message: "Invalid area parameters." });
return;
}
const areaName = `${eventId}_${eventDateId}_${areaId}`;
try {
// 클라이언트를 해당 area에 추가
socket.join(areaName);
fastify.log.info(`Client ${socket.id} joined area: ${areaName}.`);
// 좌석 정보 가져오기
let seats = await getAllSeatsFromRedis(areaName);
if (seats.length === 0) {
// Redis에 좌석 정보가 없으면 DB에서 가져오기
seats = await getSeatsForArea(eventDateId, areaId); // DB에서 가져오기
// Redis에 좌석 정보 저장
for (const seat of seats) {
await updateSeatInRedis(areaName, seat.id, seat);
}
// await setSeatDataInRedis(areaName, seats);
}
// 클라이언트에게 데이터 전송
socket.emit("areaJoined", {
message: `You have joined the area: ${areaName}`,
seats,
});
} catch (error) {
fastify.log.error(`Error fetching data for area ${areaName}:`, error);
socket.emit("error", {
message: "Failed to fetch area data.",
});
}
});
// 좌석 선택 처리 (단일 및 연석)
socket.on(
"selectSeats",
async ({ seatId, eventId, eventDateId, areaId, numberOfSeats = 1 }) => {
const areaName = `${eventId}_${eventDateId}_${areaId}`;
// Redis에서 모든 좌석 정보 조회
const allSeats = await getAllSeatsFromRedis(areaName);
// 이전에 선택한 좌석들을 찾고 취소
await releaseSeats(socket.id, allSeats, areaName);
// 선택하려는 좌석 찾기
const selectedSeat = allSeats.find((s) => s.id === seatId);
if (!selectedSeat) {
socket.emit("error", { message: "Invalid seat ID." });
return;
}
const seatsToSelect = [];
if (numberOfSeats === 1) {
// 단일 좌석 선택
// 이미 예매된 좌석인지 확인
if (selectedSeat.reservedUserId) {
socket.emit("error", {
message: `Seat ${selectedSeat.id} is reserved and cannot be selected.`,
});
return;
}
// 이미 다른 유저가 선택한 좌석인지 확인
const expired = await isSeatExpired(areaName, selectedSeat.id);
if (selectedSeat.selectedBy && !expired) {
socket.emit("error", {
message: `Seat ${selectedSeat.id} is already selected by another user.`,
});
return;
}
seatsToSelect.push(selectedSeat);
} else {
// 연석 선택
const adjacentSeats = findAdjacentSeats(
allSeats,
selectedSeat,
numberOfSeats
);
// 가능한 좌석이 요청한 좌석 수보다 적으면 리턴
if (adjacentSeats.length < numberOfSeats) {
socket.emit("error", {
message: "Not enough adjacent seats available",
});
return;
}
seatsToSelect.push(...adjacentSeats);
}
const currentTime = new Date().toISOString();
const result = [];
for (const seat of seatsToSelect) {
// 선택될 좌석 상태 변경
seat.selectedBy = socket.id;
seat.updatedAt = currentTime;
seat.expirationTime = new Date(
Date.now() + SELECTION_TIMEOUT
).toISOString();
// Redis 업데이트
await updateSeatInRedis(areaName, seat.id, seat);
await setSeatExpirationInRedis(areaName, seat.id);
result.push({
seatId: seat.id,
selectedBy: socket.id,
updatedAt: currentTime,
expirationTime: seat.expirationTime,
});
fastify.log.info(`Seat ${seat.id} selected by ${socket.id}`);
}
// 같은 room의 유저들에게 상태 변경 브로드캐스트
io.to(areaName).emit("seatsSelected", result);
}
);
socket.on(
"reserveSeats",
async ({ seatIds, eventId, eventDateId, areaId, userId }) => {
const roomName = `${eventId}_${eventDateId}`;
const areaName = `${eventId}_${eventDateId}_${areaId}`;
const seatsToReserve = [];
const broadcastUpdates = [];
const seatIdsToReserve = [];
try {
if (!Array.isArray(seatIds) || seatIds.length === 0) {
socket.emit("error", { message: "Invalid seat IDs." });
return;
}
for (const seatId of seatIds) {
// Redis에서 좌석 정보 조회
let seat = await getSeatFromRedis(areaName, seatId);
if (!seat) {
fastify.log.warn(`Invalid seat ID: ${seatId}`);
socket.emit("error", { message: `Invalid seat ID: ${seatId}.` });
return;
}
// 좌석이 이미 예약되었는지 확인
if (seat.reservedUserId) {
socket.emit("error", {
message: `Seat ${seat.id} is reserved and cannot be selected.`,
});
return;
}
// 이미 다른 유저가 선택한 좌석인지 확인
const expired = await isSeatExpired(areaName, seat.id);
if (
seat.selectedBy !== null &&
seat.selectedBy !== socket.id &&
!expired
) {
socket.emit("error", {
message: `Seat ${seat.id} is already selected by another user.`,
});
return;
}
const currentTime = new Date().toISOString();
// 좌석 상태 업데이트
seat.reservedUserId = userId;
seat.selectedBy = null;
seat.updatedAt = currentTime;
seat.expirationTime = null;
// Redis 업데이트
await updateSeatInRedis(areaName, seatId, seat);
fastify.log.info(
`Seat ${seatId} will be reserved by ${socket.id} in area ${areaName}`
);
await fastify.redis.del(`timer:${areaName}:${seatId}`); // seat expiration timer 삭제
seatsToReserve.push(seat);
seatIdsToReserve.push(seat.id);
// 브로드캐스트 업데이트에 추가
broadcastUpdates.push({
seatId: seat.id,
selectedBy: seat.selectedBy,
updatedAt: seat.updatedAt,
expirationTime: seat.expirationTime,
reservedUserId: seat.reservedUserId,
});
}
} catch (error) {
fastify.log.error(
`Failed to process seat ${seat.id}: ${error.message}`
);
socket.emit("error", {
message: `Failed to process seat ${seat.id}: ${error.message}`,
});
}
let orderId;
try {
orderId = await createOrderInRedis(
areaName,
seatIdsToReserve,
userId,
eventDateId
);
await setPaymentExpirationInRedis(areaName, orderId);
const order = await getOrderFromRedis(areaName, orderId);
const selectedArea = await getAreaFromRedis(roomName, areaId);
const area = {
id: selectedArea.id,
label: selectedArea.label,
price: selectedArea.price,
};
const expirationTime = new Date(
Date.now() + PAYMENT_TIMEOUT
).toISOString();
const reservationData = {
id: orderId,
createdAt: order.createdAt,
expirationTime: expirationTime,
seats: seatsToReserve,
area: area,
};
// 클라이언트에게 주문 정보 전달
socket.emit("orderMade", { data: reservationData });
} catch (error) {
fastify.log.error(`Failed to prepare order data: ${error.message}`);
socket.emit("error", {
message: `Failed to prepare order data: ${error.message}`,
});
}
// 같은 room의 유저들에게 상태 변경 브로드캐스트
if (broadcastUpdates.length > 0) {
io.to(areaName).emit("seatsSelected", broadcastUpdates);
}
}
);
socket.on(
"requestOrder",
async ({
userId,
orderId,
paymentMethod,
eventId,
eventDateId,
areaId,
}) => {
if (
!userId ||
!orderId ||
!paymentMethod ||
!eventId ||
!eventDateId ||
!areaId
) {
socket.emit("error", { message: "Invalid requestOrder parameters." });
return;
}
const areaName = `${eventId}_${eventDateId}_${areaId}`;
const redisOrderData = await getOrderFromRedis(areaName, orderId);
if (!redisOrderData) {
socket.emit("error", { message: "Invalid cache requestOrderData" });
return;
}
const client = await fastify.pg.connect();
try {
await client.query("BEGIN");
// 사용자 검증
const userResult = await client.query(
`SELECT * FROM "user" WHERE id = $1`,
[userId]
);
const user = userResult.rows[0];
if (!user) {
throw { code: "USER_NOT_FOUND", message: "User not found." };
}
// EventDate 및 Event 검증
const eventResult = await client.query(
`
SELECT
ed.id AS "eventDateId",
ed.date AS "eventDate",
e.id AS "eventId",
e.title AS "eventTitle",
e.place AS "eventPlace",
e.cast AS "eventCast",
e.thumbnail AS "eventThumbnail",
e."ageLimit" AS "eventAgeLimit"
FROM event_date ed
INNER JOIN event e ON ed."eventId" = e.id
WHERE ed.id = $1
`,
[eventDateId]
);
// 결과 처리
const event = eventResult.rows[0];
if (!event) {
throw {
code: "EVENT_DATE_NOT_FOUND",
message: "Event date not found.",
};
}
const seatIds = redisOrderData.seatIds;
const seatResult = await client.query(
`
SELECT
s.*,
a.id AS "areaId",
a.label AS "areaLabel",
a.price AS "areaPrice"
FROM seat s
INNER JOIN area a ON s."areaId" = a.id
WHERE s.id = ANY($1::uuid[])
`,
[seatIds]