-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertMockData.js
More file actions
192 lines (167 loc) · 5.98 KB
/
Copy pathinsertMockData.js
File metadata and controls
192 lines (167 loc) · 5.98 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
const { createClient } = require('@clickhouse/client');
const { CLICKHOUSE_URL, USERNAME, PASSWORD, DATABASE } = require('./config');
const clickhouse = createClient({
host: CLICKHOUSE_URL,
username: USERNAME,
password: PASSWORD,
database: DATABASE,
});
const CONVERSION_RATE = 0.7;
const DAYS = 5;
const USER_COUNT = 50;
const SESSIONS_PER_USER = 3;
const SDK_KEY = '7ea40a3f-e0eb-475b-a787-2fbbd7f9aa98';
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomDateWithinNHours() {
const now = Date.now();
const offset = Math.floor(Math.random() * DAYS * 24 * 60 * 60 * 1000);
return new Date(now - offset);
}
function formatLocalDateTime(date = new Date()) {
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, '0');
const dd = String(date.getDate()).padStart(2, '0');
const hh = String(date.getHours()).padStart(2, '0');
const mi = String(date.getMinutes()).padStart(2, '0');
const ss = String(date.getSeconds()).padStart(2, '0');
return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;
}
function shuffleArray(arr) {
return arr.map(v => [v, Math.random()]).sort((a, b) => a[1] - b[1]).map(([v]) => v);
}
function getShuffledPageFlow() {
const core = [
'/home', '/products', '/products/shoes', '/products/shoes/123',
'/products/shirts', '/products/shirts/456', '/cart', '/checkout', '/checkout/success'
];
const extras = shuffleArray([
'/login', '/signup', '/about', '/faq', '/help',
'/profile', '/profile/orders', '/profile/settings', '/events/summer-sale'
]);
return [...core, ...extras.slice(0, getRandomInt(2, 5))];
}
const buttonLabels = [
'구매하기', '장바구니 담기', '찜하기', '로그인', '회원가입',
'쿠폰 받기', '리뷰 작성', '더보기', '지금 주문', '문의하기',
'결제하기', '신청하기', '공유', '좋아요', '삭제', '수정'
];
function generateSession(userId, sessionId) {
const fullPageFlow = getShuffledPageFlow();
const device = ['desktop', 'mobile'][getRandomInt(0, 1)];
const browser = ['Chrome', 'Safari', 'Edge'][getRandomInt(0, 2)];
const source = ['google', 'naver', 'kakao', 'direct'][getRandomInt(0, 3)];
const gender = ['female', 'male'][userId % 2];
const age = getRandomInt(18, 60);
const baseTime = getRandomDateWithinNHours();
const maxSteps = Math.min(10, fullPageFlow.length);
const dropoffIndex = Math.random() < CONVERSION_RATE
? fullPageFlow.length
: getRandomInt(3, maxSteps);
const pageFlow = fullPageFlow.slice(0, dropoffIndex);
const events = [];
pageFlow.forEach((page, i) => {
const timestamp = new Date(baseTime.getTime() + i * 30000); // 30초 간격
let event_name = 'auto_click';
if (i === 0) event_name = 'page_view';
else if (i === pageFlow.length - 1) event_name = 'page_exit';
const time_on_page_seconds = (event_name === 'page_exit') ? getRandomInt(5, 30) : 0;
const event = {
event_name,
timestamp: formatLocalDateTime(timestamp),
client_id: `client_${userId}`,
user_id: 1000 + userId,
session_id: `sess_${sessionId}`,
device_type: device,
device_os: device === 'desktop' ? 'Windows' : 'iOS',
traffic_medium: i % 2 === 0 ? 'cpc' : 'organic',
traffic_source: source,
traffic_campaign: 'summer_sale',
page_path: page,
page_title: page.replace('/', '') || 'home',
referrer: i === 0 ? '' : pageFlow[i - 1],
click_x: null,
click_y: null,
target_text: '',
target_tag: '',
target_class: '',
target_id: '',
target_href: '',
target_type: '',
is_button: 0,
is_link: 0,
is_input: 0,
is_textarea: 0,
is_select: 0,
element_tag: '',
element_id: '',
element_class: '',
element_text: '',
element_path: '',
country: 'KR',
city: 'Seoul',
timezone: 'Asia/Seoul',
browser: browser,
language: 'ko-KR',
user_agent: 'Mozilla/5.0',
screen_resolution: '1920x1080',
viewport_size: '1920x947',
utm_params: '',
form_action: '',
form_method: '',
form_id: '',
form_class: '',
form_fields: '',
form_field_count: 0,
user_gender: gender,
user_age: age,
time_on_page_seconds,
created_at: formatLocalDateTime(timestamp),
sdk_key: SDK_KEY
};
// auto_click일 경우에만 클릭 관련 필드 채우기
if (event_name === 'auto_click') {
const idx = getRandomInt(0, buttonLabels.length - 1);
const label = buttonLabels[idx];
event.click_x = getRandomInt(100, 500);
event.click_y = getRandomInt(100, 500);
event.target_text = label;
event.target_tag = 'button';
event.target_class = 'btn';
event.target_id = `target_${idx}`;
event.target_href = `/action/${idx}`;
event.target_type = 'action';
event.is_button = 1;
event.element_tag = 'button';
event.element_id = `el_${idx}`;
event.element_class = 'btn';
event.element_text = label;
event.element_path = `body > div > button:nth-child(${idx + 1})`;
}
events.push(event);
});
return events;
}
async function insertMockData(userCount = USER_COUNT, sessionsPerUser = SESSIONS_PER_USER) {
const allEvents = [];
let sessionIdCounter = 0;
for (let userId = 0; userId < userCount; userId++) {
for (let j = 0; j < sessionsPerUser; j++) {
allEvents.push(...generateSession(userId, sessionIdCounter++));
}
}
await clickhouse.insert({
table: 'events',
values: allEvents,
format: 'JSONEachRow',
contentType: 'application/json'
});
console.log(`[insertMockData] 총 ${allEvents.length}건 삽입 완료`);
}
// CLI 인자 처리
const userArg = parseInt(process.argv[2], 10);
const sessionArg = parseInt(process.argv[3], 10);
const userCount = isNaN(userArg) ? USER_COUNT : userArg;
const sessionsPerUser = isNaN(sessionArg) ? SESSIONS_PER_USER : sessionArg;
insertMockData(userCount, sessionsPerUser).catch(console.error);