-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepro.ts
More file actions
283 lines (253 loc) · 8.91 KB
/
repro.ts
File metadata and controls
283 lines (253 loc) · 8.91 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
import { SQL } from "bun";
type Mode = "single" | "split";
type Scenario = {
mode: Mode;
transactionalWrite: boolean;
rows: number;
batchSize: number;
};
function env(name: string, required = true): string | undefined {
const value = process.env[name]?.trim();
if (required && !value) {
throw new Error(`Missing required env var: ${name}`);
}
return value;
}
function boolEnv(name: string, fallback: boolean): boolean {
const value = process.env[name];
if (value == null) return fallback;
return value === "1" || value.toLowerCase() === "true";
}
function intEnv(name: string, fallback: number): number {
const value = process.env[name];
if (value == null) return fallback;
const n = Number(value);
return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
}
function nowLabel(): string {
return new Date().toISOString();
}
function log(step: string, payload?: unknown): void {
const prefix = `[${nowLabel()}] ${step}`;
if (payload === undefined) {
console.log(prefix);
return;
}
console.log(prefix, payload);
}
function buildRows(count: number, startMs: number, endMs: number): Array<{
id: number;
created_at: string;
variant_id: number;
quantity_change: number;
}> {
const span = Math.max(1, endMs - startMs);
const rows: Array<{
id: number;
created_at: string;
variant_id: number;
quantity_change: number;
}> = [];
for (let i = 0; i < count; i += 1) {
const created = new Date(startMs + Math.floor((i / count) * span)).toISOString();
rows.push({
id: i + 1,
created_at: created,
variant_id: (i % 3000) + 1,
quantity_change: -((i % 8) + 1),
});
}
return rows;
}
function connOptions() {
const hostname = env("MYSQL_HOST") as string;
const username = env("MYSQL_USER") as string;
const password = env("MYSQL_PASSWORD") as string;
const database = env("MYSQL_DATABASE") as string;
const portRaw = env("MYSQL_PORT", false);
const port = portRaw ? Number(portRaw) : undefined;
const tls = boolEnv("MYSQL_TLS", false);
return {
adapter: "mysql" as const,
hostname,
...(Number.isFinite(port) ? { port } : {}),
username,
password,
database,
tls,
};
}
async function ensureSchema(sql: InstanceType<typeof SQL>): Promise<void> {
await sql`
CREATE TABLE IF NOT EXISTS bun_repro_cached_ranges (
query_type VARCHAR(255) NOT NULL,
params_hash VARCHAR(255) NOT NULL,
range_start BIGINT NOT NULL,
range_end BIGINT NOT NULL,
cached_at BIGINT NOT NULL,
PRIMARY KEY (query_type, params_hash, range_start),
INDEX idx_ranges_type_params (query_type, params_hash)
)
`;
await sql`
CREATE TABLE IF NOT EXISTS bun_repro_cached_inventory_movements (
id BIGINT NOT NULL,
query_type VARCHAR(255) NOT NULL,
params_hash VARCHAR(255) NOT NULL DEFAULT '',
created_at_api BIGINT NOT NULL,
cached_at BIGINT NOT NULL,
created_at VARCHAR(64) NULL,
variant_id BIGINT NULL,
quantity_change DOUBLE NULL,
PRIMARY KEY (query_type, params_hash, id),
INDEX idx_movements_type_created (query_type, params_hash, created_at_api)
)
`;
}
async function clearScenarioData(sql: InstanceType<typeof SQL>, paramsHash: string): Promise<void> {
await sql.unsafe(
`DELETE FROM bun_repro_cached_inventory_movements WHERE query_type = ? AND params_hash = ?`,
["inventoryMovements", paramsHash],
);
await sql.unsafe(
`DELETE FROM bun_repro_cached_ranges WHERE query_type = ? AND params_hash = ?`,
["inventoryMovements", paramsHash],
);
}
async function runScenario(s: Scenario): Promise<void> {
log("scenario:start", s);
const options = connOptions();
const writeSql = new SQL(options);
const readSql = s.mode === "split" ? new SQL(options) : writeSql;
const queryType = "inventoryMovements";
const paramsHash = `bun-repro-${s.mode}-${s.transactionalWrite ? "tx" : "autocommit"}`;
const end = Date.now();
const start = end - 90 * 24 * 60 * 60 * 1000;
const rows = buildRows(s.rows, start, end);
try {
log("step:ensureSchema");
await ensureSchema(writeSql);
log("step:ensureSchema:ok");
log("step:clear");
await clearScenarioData(writeSql, paramsHash);
log("step:clear:ok");
log("step:readRanges:before");
const rangesBefore = await readSql.unsafe(
`SELECT range_start, range_end FROM bun_repro_cached_ranges WHERE query_type = ? AND params_hash = ? ORDER BY range_start`,
[queryType, paramsHash],
);
log("step:readRanges:ok", { count: rangesBefore.length });
const now = Date.now();
if (s.transactionalWrite) {
log("step:write:beginTransaction", { rows: rows.length, batchSize: s.batchSize });
await writeSql.begin(async (tx) => {
for (let i = 0; i < rows.length; i += s.batchSize) {
const batch = rows.slice(i, i + s.batchSize);
const placeholders = batch.map(() => "(?, ?, ?, ?, ?, ?, ?, ?)").join(", ");
const values: unknown[] = [];
for (const row of batch) {
values.push(
row.id,
queryType,
paramsHash,
new Date(row.created_at).getTime(),
now,
row.created_at,
row.variant_id,
row.quantity_change,
);
}
await tx.unsafe(
`INSERT INTO bun_repro_cached_inventory_movements (id, query_type, params_hash, created_at_api, cached_at, created_at, variant_id, quantity_change) VALUES ${placeholders}
ON DUPLICATE KEY UPDATE created_at_api = VALUES(created_at_api), cached_at = VALUES(cached_at), created_at = VALUES(created_at), variant_id = VALUES(variant_id), quantity_change = VALUES(quantity_change)`,
values,
);
}
await tx.unsafe(
`INSERT INTO bun_repro_cached_ranges (query_type, params_hash, range_start, range_end, cached_at)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
range_end = GREATEST(range_end, VALUES(range_end)),
cached_at = VALUES(cached_at)`,
[queryType, paramsHash, start, end, now],
);
});
log("step:write:commit:ok");
} else {
log("step:write:autocommit", { rows: rows.length, batchSize: s.batchSize });
for (let i = 0; i < rows.length; i += s.batchSize) {
const batch = rows.slice(i, i + s.batchSize);
const placeholders = batch.map(() => "(?, ?, ?, ?, ?, ?, ?, ?)").join(", ");
const values: unknown[] = [];
for (const row of batch) {
values.push(
row.id,
queryType,
paramsHash,
new Date(row.created_at).getTime(),
now,
row.created_at,
row.variant_id,
row.quantity_change,
);
}
await writeSql.unsafe(
`INSERT INTO bun_repro_cached_inventory_movements (id, query_type, params_hash, created_at_api, cached_at, created_at, variant_id, quantity_change) VALUES ${placeholders}
ON DUPLICATE KEY UPDATE created_at_api = VALUES(created_at_api), cached_at = VALUES(cached_at), created_at = VALUES(created_at), variant_id = VALUES(variant_id), quantity_change = VALUES(quantity_change)`,
values,
);
}
await writeSql.unsafe(
`INSERT INTO bun_repro_cached_ranges (query_type, params_hash, range_start, range_end, cached_at)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
range_end = GREATEST(range_end, VALUES(range_end)),
cached_at = VALUES(cached_at)`,
[queryType, paramsHash, start, end, now],
);
log("step:write:autocommit:ok");
}
log("step:readRows:before");
const rowsRead = await readSql.unsafe(
`SELECT id, created_at_api, cached_at, created_at, variant_id, quantity_change
FROM bun_repro_cached_inventory_movements
WHERE query_type = ? AND params_hash = ?
ORDER BY created_at_api`,
[queryType, paramsHash],
);
log("step:readRows:ok", { count: rowsRead.length });
log("scenario:done");
} finally {
if (readSql !== writeSql) {
await Promise.allSettled([readSql.close(), writeSql.close()]);
} else {
await writeSql.close();
}
}
}
async function main() {
const rows = intEnv("REPRO_ROWS", 30000);
const batchSize = intEnv("REPRO_BATCH", 500);
const modeRaw = (process.env.REPRO_MODE ?? "single").toLowerCase();
const mode: Mode = modeRaw === "split" ? "split" : "single";
const transactionalWrite = boolEnv("REPRO_TX", true);
log("repro:start", {
bun: Bun.version,
platform: process.platform,
arch: process.arch,
mode,
transactionalWrite,
rows,
batchSize,
});
await runScenario({
mode,
transactionalWrite,
rows,
batchSize,
});
}
main().catch((error) => {
console.error("repro:error", error);
process.exit(1);
});