-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue-refresh-test.js
More file actions
567 lines (500 loc) · 20.1 KB
/
Copy pathqueue-refresh-test.js
File metadata and controls
567 lines (500 loc) · 20.1 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
import ws from 'k6/ws';
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Counter, Trend, Rate } from 'k6/metrics';
// ==================== 설정 ====================
const QUEUE_URL = 'http://localhost:8085'; // Queue 서버
const WS_BASE = 'ws://localhost:8087/ws'; // RealTime 서버
const PERFORMANCE_ID = 1;
const OPTION_ID = 1;
const TOTAL_SEATS = 98;
const ALL_SEATS = Array.from({ length: TOTAL_SEATS }, (_, i) => i + 1);
const MAX_VUS = __ENV.MAX_VUS ? parseInt(__ENV.MAX_VUS) : 100;
const WAIT_POLL_MS = __ENV.WAIT_POLL_MS ? parseInt(__ENV.WAIT_POLL_MS) : 1000;
const WAIT_MAX_MS = __ENV.WAIT_MAX_MS ? parseInt(__ENV.WAIT_MAX_MS) : 30000;
const LOG_EVERY = __ENV.LOG_EVERY ? parseInt(__ENV.LOG_EVERY) : 10;
// QueueToken TTL = 서버 ACTIVE_USER_TIMEOUT (5분)
const QUEUE_TOKEN_TTL_MS = __ENV.QUEUE_TOKEN_TTL_MS ? parseInt(__ENV.QUEUE_TOKEN_TTL_MS) : 300000;
// ==================== 사용자 행동 패턴 확률 ====================
// 잡아두고 결제하는 사람 (선택 후 끝까지 보유)
const PATTERN_HOLD = 0.35;
// 고민하다가 바꾸는 사람 (선택 → 취소 → 재선택 반복)
const PATTERN_CHANGE_MIND = 0.30;
// 빠르게 여러번 바꾸는 사람 (좌석 비교)
const PATTERN_COMPARE = 0.20;
// 구경만 하다 나가는 사람 (선택 안하거나 늦게)
const PATTERN_BROWSE = 0.15;
// ==================== 메트릭 ====================
const queueJoined = new Counter('queue_joined');
const queueJoinFailed = new Counter('queue_join_failed');
const tokenIssued = new Counter('token_issued');
const tokenFailed = new Counter('token_failed');
const tokenExpired = new Counter('token_expired');
const queueToTokenTime = new Trend('queue_to_token_ms');
const reentryCount = new Counter('queue_reentry');
const seatRequests = new Counter('seat_requests');
const seatSecured = new Counter('seat_secured');
const seatDenied = new Counter('seat_denied');
const seatReleased = new Counter('seat_released');
const secureRate = new Rate('seat_secure_rate');
const responseTime = new Trend('seat_response_ms');
const raceSameSeat = new Counter('race_same_seat');
const raceLost = new Counter('race_lost');
const wsConnectFailed = new Counter('ws_connect_failed');
const totalSessions = new Counter('total_sessions');
// ==================== 시나리오 ====================
export const options = {
scenarios: {
queue_refresh: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '10s', target: Math.floor(MAX_VUS * 0.25) },
{ duration: '10s', target: Math.floor(MAX_VUS * 0.5) },
{ duration: '10s', target: MAX_VUS },
{ duration: '5m', target: MAX_VUS }, // QueueToken TTL(5분) 동안 유지
{ duration: '10s', target: 0 },
],
},
},
};
// ==================== 헬퍼 ====================
function randomString(length) {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
function sockjsSend(socket, data) {
socket.send(JSON.stringify([data]));
}
function createStompFrame(command, headers = {}, body = '') {
let frame = command + '\n';
for (const [key, value] of Object.entries(headers)) {
frame += `${key}:${value}\n`;
}
frame += '\n' + body + '\0';
return frame;
}
function parseStompFrame(data) {
let content = data;
if (data.startsWith('a[')) {
try {
const arr = JSON.parse(data.substring(1));
content = arr[0] || '';
} catch (e) { content = data; }
}
const nullIndex = content.indexOf('\0');
const frameContent = nullIndex !== -1 ? content.substring(0, nullIndex) : content;
const lines = frameContent.split('\n');
const command = lines[0];
const headers = {};
let bodyStartIndex = 1;
for (let i = 1; i < lines.length; i++) {
if (lines[i] === '') { bodyStartIndex = i + 1; break; }
const ci = lines[i].indexOf(':');
if (ci !== -1) headers[lines[i].substring(0, ci)] = lines[i].substring(ci + 1);
}
const body = lines.slice(bodyStartIndex).join('\n');
return { command, headers, body };
}
function pickRandomSeats(count, unavailable) {
const available = ALL_SEATS.filter((id) => !unavailable.has(id));
for (let i = available.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[available[i], available[j]] = [available[j], available[i]];
}
return available.slice(0, Math.min(count, available.length));
}
function maybeLog(message) {
if (__ITER % LOG_EVERY === 0) {
console.log(message);
}
}
function parseQueueStatus(body) {
if (!body) return null;
const tokenMatch = body.match(/"queueToken"\s*:\s*"([^"]+)"/);
const statusMatch = body.match(/"status"\s*:\s*"([A-Z_]+)"/);
const rankMatch = body.match(/"rank"\s*:\s*(\d+)/);
if (!statusMatch) return null;
return {
status: statusMatch[1],
queueToken: tokenMatch ? tokenMatch[1] : null,
rank: rankMatch ? parseInt(rankMatch[1]) : null,
};
}
// 사용자 행동 패턴 결정
function pickUserPattern() {
const roll = Math.random();
if (roll < PATTERN_HOLD) return 'hold';
if (roll < PATTERN_HOLD + PATTERN_CHANGE_MIND) return 'change_mind';
if (roll < PATTERN_HOLD + PATTERN_CHANGE_MIND + PATTERN_COMPARE) return 'compare';
return 'browse';
}
// ==================== 대기열 진입 ====================
function joinQueueAndWait(userId) {
const queueStart = Date.now();
const joinRes = http.post(
`${QUEUE_URL}/api/queue/in`,
JSON.stringify({ performanceId: PERFORMANCE_ID, optionId: OPTION_ID }),
{
headers: {
'Content-Type': 'application/json',
'X-User-Id': userId.toString(),
},
timeout: '10s',
}
);
if (joinRes.status !== 200) {
queueJoinFailed.add(1);
console.log(`[VU ${__VU}] 대기열 등록 실패: ${joinRes.status}`);
return null;
}
queueJoined.add(1);
const pollStart = Date.now();
while (Date.now() - pollStart < WAIT_MAX_MS) {
const res = http.get(
`${QUEUE_URL}/api/queue/status?performanceId=${PERFORMANCE_ID}&optionId=${OPTION_ID}`,
{
headers: {
'X-User-Id': userId.toString(),
'Accept': 'text/event-stream',
},
timeout: '5s',
}
);
if (res.error) {
maybeLog(`[VU ${__VU}] status poll error: ${res.error}`);
sleep(WAIT_POLL_MS / 1000);
continue;
}
const parsed = parseQueueStatus(res.body || '');
if (parsed) {
maybeLog(`[VU ${__VU}] status=${parsed.status} rank=${parsed.rank ?? 'N/A'}`);
if (parsed.status === 'ISSUED' && parsed.queueToken) {
queueToTokenTime.add(Date.now() - queueStart);
tokenIssued.add(1);
console.log(`[VU ${__VU}] 토큰 발급 완료: ${parsed.queueToken.substring(0, 8)}...`);
return parsed.queueToken;
}
}
sleep(WAIT_POLL_MS / 1000);
}
tokenFailed.add(1);
console.log(`[VU ${__VU}] 토큰 발급 실패 (대기 타임아웃)`);
return null;
}
// ==================== 좌석 선택 (QueueToken TTL 기반) ====================
function seatSelection(userId, queueToken) {
totalSessions.add(1);
const pattern = pickUserPattern();
const sessionStart = Date.now();
const serverId = Math.floor(Math.random() * 1000);
const sessionId = randomString(8);
const url = `${WS_BASE}/${serverId}/${sessionId}/websocket?performanceId=${PERFORMANCE_ID}&optionId=${OPTION_ID}&queueToken=${queueToken}`;
let gotTokenExpired = false;
const res = ws.connect(url, {}, function (socket) {
let subId = 0;
let stompConnected = false;
let initReceived = false;
let fallbackLockScheduled = false;
const occupied = new Set();
const sold = new Set();
const myLocked = new Set();
let lockSentTime = 0;
let actionCount = 0;
// 패턴별 설정
let maxActions, selectDelay, releaseChance, reSelectDelay;
switch (pattern) {
case 'hold':
// 바로 선택하고 끝까지 보유 (결제 의지 높음)
maxActions = 2;
selectDelay = 1 + Math.random() * 3; // 1~4초 후 선택
releaseChance = 0.05; // 거의 취소 안함
reSelectDelay = 0;
break;
case 'change_mind':
// 선택 → 고민 → 취소 → 다시 선택 반복
maxActions = 8 + Math.floor(Math.random() * 6); // 8~13회
selectDelay = 2 + Math.random() * 5; // 2~7초 후 선택
releaseChance = 0.6; // 높은 취소율
reSelectDelay = 3 + Math.random() * 10; // 3~13초 고민
break;
case 'compare':
// 빠르게 좌석 비교 (선택/취소 반복)
maxActions = 15 + Math.floor(Math.random() * 10); // 15~24회
selectDelay = 0.5 + Math.random() * 1.5; // 0.5~2초
releaseChance = 0.7; // 매우 높은 취소율
reSelectDelay = 0.5 + Math.random() * 2; // 빠른 재선택
break;
case 'browse':
// 구경만 하다가 늦게 선택하거나 안함
maxActions = 1 + Math.floor(Math.random() * 2);
selectDelay = 20 + Math.random() * 40; // 20~60초 후에야 선택
releaseChance = 0.3;
reSelectDelay = 0;
break;
}
socket.on('open', () => {});
// QueueToken TTL 기반 타임아웃: 서버에서 TOKEN_EXPIRED가 오면 끝나지만
// 혹시 메시지가 안오면 TTL 시간 + 여유 10초 후 강제 종료
socket.setTimeout(function () {
maybeLog(`[VU ${__VU}] QueueToken TTL 도달, 세션 종료 (pattern=${pattern})`);
if (myLocked.size > 0) {
sockjsSend(socket, createStompFrame('SEND', {
'destination': '/app/seats/release',
'content-type': 'application/json',
}, JSON.stringify({
performanceId: PERFORMANCE_ID,
optionId: OPTION_ID,
seatIds: [...myLocked],
})));
seatReleased.add(myLocked.size);
sleep(0.2);
}
if (stompConnected) {
sockjsSend(socket, createStompFrame('DISCONNECT', {}));
}
socket.close();
}, QUEUE_TOKEN_TTL_MS + 10000);
socket.on('message', (data) => {
if (data === 'o') {
sockjsSend(socket, createStompFrame('CONNECT', {
'accept-version': '1.2',
'heart-beat': '10000,10000',
}));
return;
}
if (data === 'h' || data.startsWith('c[') || !data.startsWith('a[')) return;
const frame = parseStompFrame(data);
if (frame.command === 'CONNECTED') {
stompConnected = true;
sockjsSend(socket, createStompFrame('SUBSCRIBE', {
'id': `sub-${subId++}`, 'destination': '/user/queue/seats',
}));
sockjsSend(socket, createStompFrame('SUBSCRIBE', {
'id': `sub-${subId++}`,
'destination': `/topic/seats.${PERFORMANCE_ID}.${OPTION_ID}`,
}));
sockjsSend(socket, createStompFrame('SEND', {
'destination': '/app/seats/init',
'content-type': 'application/json',
}, '{}'));
if (!fallbackLockScheduled) {
fallbackLockScheduled = true;
socket.setTimeout(function () {
if (!initReceived) {
maybeLog(`[VU ${__VU}] no INITIAL_STATE, fallback doLock()`);
doLock(socket);
}
}, 1500);
}
}
if (frame.command !== 'MESSAGE') return;
let msg;
try { msg = JSON.parse(frame.body); } catch (e) { return; }
// 좌석 상태 업데이트
if (msg.type === 'SEAT_LOCKED' && msg.seatIds) msg.seatIds.forEach((id) => occupied.add(id));
if (msg.type === 'SEAT_RELEASED' && msg.seatIds) msg.seatIds.forEach((id) => occupied.delete(id));
if (msg.type === 'SEAT_EXPIRED' && msg.seatIds) msg.seatIds.forEach((id) => { occupied.delete(id); myLocked.delete(id); });
// 초기 상태 수신 → 패턴에 따라 행동 시작
if (msg.type === 'INITIAL_STATE') {
initReceived = true;
if (msg.occupiedSeats) msg.occupiedSeats.forEach((id) => occupied.add(id));
if (msg.soldSeats) msg.soldSeats.forEach((id) => sold.add(id));
if (msg.myLockedSeats) msg.myLockedSeats.forEach((id) => myLocked.add(id));
// 패턴별 첫 행동까지 대기 시간
sleep(selectDelay);
doLock(socket);
}
// 선점 성공
if (msg.type === 'LOCK_SUCCESS') {
responseTime.add(Date.now() - lockSentTime);
seatSecured.add(1);
secureRate.add(true);
if (msg.seatIds) msg.seatIds.forEach((id) => myLocked.add(id));
actionCount++;
if (actionCount < maxActions) {
// 취소할지 결정
if (Math.random() < releaseChance) {
sleep(reSelectDelay || (1 + Math.random() * 5));
doRelease(socket);
sleep(0.5 + Math.random() * 2);
doLock(socket);
} else {
// 보유 유지, 다음 행동까지 대기
sleep(5 + Math.random() * 15);
if (actionCount < maxActions) {
doLock(socket);
}
}
}
// maxActions 도달하면 그냥 보유한 채로 토큰 만료까지 대기
}
// 선점 실패 → 즉시 다른 좌석 재시도
if (msg.type === 'LOCK_FAILED') {
responseTime.add(Date.now() - lockSentTime);
seatDenied.add(1);
secureRate.add(false);
raceLost.add(1);
actionCount++;
if (actionCount < maxActions) {
sleep(0.2 + Math.random() * 0.5);
doLock(socket);
}
}
// QueueToken 만료 → 세션 종료 (서버가 TTL 만료를 알려줌)
if (msg.type === 'TOKEN_EXPIRED') {
tokenExpired.add(1);
console.log(`[VU ${__VU}] QueueToken 만료 (pattern=${pattern}, actions=${actionCount})`);
gotTokenExpired = true;
if (stompConnected) {
sockjsSend(socket, createStompFrame('DISCONNECT', {}));
}
socket.close();
}
});
function doLock(sock) {
const unavailable = new Set([...occupied, ...sold, ...myLocked]);
const count = Math.ceil(Math.random() * 4);
let targets = pickRandomSeats(count, unavailable);
// 경쟁: 30% 확률로 이미 점유된 좌석에 락 시도 (실제 사용자처럼 동시 클릭)
if (targets.length === 0 || Math.random() < 0.3) {
const contestable = [...occupied].filter((id) => !myLocked.has(id) && !sold.has(id));
if (contestable.length > 0) {
targets = [contestable[Math.floor(Math.random() * contestable.length)]];
raceSameSeat.add(1);
} else if (targets.length === 0) {
return;
}
}
seatRequests.add(1);
maybeLog(`[VU ${__VU}] [${pattern}] lock seats=${targets.join(',')}`);
lockSentTime = Date.now();
sockjsSend(sock, createStompFrame('SEND', {
'destination': '/app/seats/lock',
'content-type': 'application/json',
}, JSON.stringify({
performanceId: PERFORMANCE_ID,
optionId: OPTION_ID,
seatIds: targets,
})));
}
function doRelease(sock) {
if (myLocked.size === 0) return;
const lockedArr = [...myLocked];
sockjsSend(sock, createStompFrame('SEND', {
'destination': '/app/seats/release',
'content-type': 'application/json',
}, JSON.stringify({
performanceId: PERFORMANCE_ID,
optionId: OPTION_ID,
seatIds: lockedArr,
})));
lockedArr.forEach((id) => myLocked.delete(id));
seatReleased.add(lockedArr.length);
maybeLog(`[VU ${__VU}] [${pattern}] release seats=${lockedArr.join(',')}`);
}
socket.on('error', () => { wsConnectFailed.add(1); });
});
check(res, { 'WebSocket 연결 성공': (r) => r && r.status === 101 });
return gotTokenExpired;
}
// ==================== 메인 ====================
export default function () {
const userId = __VU;
// 1. 대기열 진입 → 토큰 발급
const queueToken = joinQueueAndWait(userId);
if (!queueToken) {
console.log(`[VU ${__VU}] 토큰 없이 재시도 대기`);
sleep(2);
return;
}
// 2. 토큰으로 좌석 선택 (QueueToken TTL 동안 유지)
const expired = seatSelection(userId, queueToken);
// 3. 토큰 만료 시 → 다시 대기열 재진입 (새로고침 시뮬레이션)
if (expired) {
reentryCount.add(1);
console.log(`[VU ${__VU}] 토큰 만료 → 대기열 재진입`);
sleep(1 + Math.random() * 2);
const newToken = joinQueueAndWait(userId);
if (newToken) {
seatSelection(userId, newToken);
}
}
}
// ==================== 결과 요약 ====================
export function handleSummary(data) {
const lines = [];
const get = (name) => data.metrics[name]?.values || {};
const joined = get('queue_joined').count || 0;
const joinFail = get('queue_join_failed').count || 0;
const issued = get('token_issued').count || 0;
const tFailed = get('token_failed').count || 0;
const tExpired = get('token_expired').count || 0;
const reentry = get('queue_reentry').count || 0;
const q2t = get('queue_to_token_ms');
const requests = get('seat_requests').count || 0;
const secured = get('seat_secured').count || 0;
const denied = get('seat_denied').count || 0;
const released = get('seat_released').count || 0;
const sr = get('seat_secure_rate').rate;
const rt = get('seat_response_ms');
const sameSeat = get('race_same_seat').count || 0;
const lost = get('race_lost').count || 0;
const connFailed = get('ws_connect_failed').count || 0;
const sessions = get('total_sessions').count || 0;
const wsConn = data.metrics['ws_connecting']?.values || {};
const checksOk = data.metrics['checks']?.values?.passes || 0;
const checksFail = data.metrics['checks']?.values?.fails || 0;
lines.push('');
lines.push('=====================================================================');
lines.push(` QueueToken TTL 기반 부하 테스트 (TTL=${QUEUE_TOKEN_TTL_MS / 1000}s) / ${MAX_VUS}명`);
lines.push('=====================================================================');
lines.push('');
lines.push(' [ 대기열 → 토큰 ]');
lines.push(` 대기열 등록: 성공 ${joined} / 실패 ${joinFail}`);
lines.push(` 토큰 발급: 성공 ${issued} / 실패 ${tFailed}`);
lines.push(` 토큰 만료: ${tExpired}회`);
lines.push(` 대기열 재진입: ${reentry}회`);
lines.push(` 대기→발급 avg: ${q2t.avg ? (q2t.avg / 1000).toFixed(1) + 's' : 'N/A'}`);
lines.push(` 대기→발급 p95: ${q2t['p(95)'] ? (q2t['p(95)'] / 1000).toFixed(1) + 's' : 'N/A'}`);
lines.push('');
lines.push(' [ 좌석 선점 ]');
lines.push(` 선점 요청: ${requests}회`);
lines.push(` 선점 성공: ${secured}회`);
lines.push(` 선점 거절: ${denied}회`);
lines.push(` 좌석 해제: ${released}건`);
lines.push(` 좌석 확보율: ${sr !== undefined ? (sr * 100).toFixed(1) + '%' : 'N/A'}`);
lines.push('');
lines.push(' [ 경쟁 (Race Condition) ]');
lines.push(` 동일 좌석 경쟁: ${sameSeat}회`);
lines.push(` 경쟁 패배: ${lost}회`);
lines.push('');
lines.push(' [ 서버 응답 ]');
lines.push(` 좌석 응답 avg: ${rt.avg ? rt.avg.toFixed(1) + 'ms' : 'N/A'}`);
lines.push(` 좌석 응답 p95: ${rt['p(95)'] ? rt['p(95)'].toFixed(1) + 'ms' : 'N/A'}`);
lines.push(` 좌석 응답 max: ${rt.max ? rt.max.toFixed(1) + 'ms' : 'N/A'}`);
lines.push(` WS 연결시간: ${wsConn.avg ? wsConn.avg.toFixed(1) + 'ms' : 'N/A'}`);
lines.push('');
lines.push(' [ 안정성 ]');
lines.push(` 총 세션: ${sessions}개`);
lines.push(` WS 성공/실패: ${checksOk} / ${checksFail}`);
lines.push(` WS 에러: ${connFailed}회`);
if (checksFail > 0 || connFailed > 0) {
lines.push('');
lines.push(' !! 연결 실패 발생 → 서버 한계 도달 가능성');
}
if (released > 0) {
lines.push('');
lines.push(` 좌석 해제율: ${(released / (secured + denied || 1) * 100).toFixed(1)}% (실제 취소/재선택 발생)`);
}
lines.push('');
lines.push('=====================================================================');
lines.push('');
return {
'stdout': lines.join('\n'),
};
}