bunsane 0.2.3 → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config/cache.config.ts +2 -0
- package/core/ArcheType.ts +67 -34
- package/core/BatchLoader.ts +215 -30
- package/core/Entity.ts +2 -2
- package/core/RequestContext.ts +15 -10
- package/core/RequestLoaders.ts +4 -2
- package/core/cache/CacheFactory.ts +3 -1
- package/core/cache/CacheProvider.ts +1 -0
- package/core/cache/CacheWarmer.ts +45 -23
- package/core/cache/MemoryCache.ts +10 -1
- package/core/cache/RedisCache.ts +26 -7
- package/core/validateEnv.ts +8 -0
- package/database/DatabaseHelper.ts +113 -1
- package/database/index.ts +78 -45
- package/docs/SCALABILITY_PLAN.md +175 -0
- package/package.json +13 -2
- package/query/CTENode.ts +44 -24
- package/query/ComponentInclusionNode.ts +181 -91
- package/query/Query.ts +9 -9
- package/tests/benchmark/BENCHMARK_DATABASES_PLAN.md +338 -0
- package/tests/benchmark/bunfig.toml +9 -0
- package/tests/benchmark/fixtures/EcommerceComponents.ts +283 -0
- package/tests/benchmark/fixtures/EcommerceDataGenerators.ts +301 -0
- package/tests/benchmark/fixtures/RelationTracker.ts +159 -0
- package/tests/benchmark/fixtures/index.ts +6 -0
- package/tests/benchmark/index.ts +22 -0
- package/tests/benchmark/noop-preload.ts +3 -0
- package/tests/benchmark/runners/BenchmarkLoader.ts +132 -0
- package/tests/benchmark/runners/index.ts +4 -0
- package/tests/benchmark/scenarios/query-benchmarks.test.ts +465 -0
- package/tests/benchmark/scripts/generate-db.ts +344 -0
- package/tests/benchmark/scripts/run-benchmarks.ts +97 -0
- package/tests/integration/query/Query.complexAnalysis.test.ts +557 -0
- package/tests/integration/query/Query.explainAnalyze.test.ts +233 -0
- package/tests/stress/fixtures/RealisticComponents.ts +235 -0
- package/tests/stress/scenarios/realistic-scenarios.test.ts +1081 -0
- package/tests/stress/scenarios/timeout-investigation.test.ts +522 -0
- package/tests/unit/BatchLoader.test.ts +139 -25
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Timeout Investigation Stress Tests
|
|
3
|
+
*
|
|
4
|
+
* These tests aim to reproduce and identify query timeout issues
|
|
5
|
+
* reported by users during insert and query operations.
|
|
6
|
+
*
|
|
7
|
+
* Configuration via environment variables:
|
|
8
|
+
* - STRESS_LARGE_COUNT: Number of records to seed (default: 5000)
|
|
9
|
+
* - STRESS_CONCURRENT: Number of concurrent operations (default: 10)
|
|
10
|
+
* - DB_QUERY_TIMEOUT: Query timeout in milliseconds (default: 30000)
|
|
11
|
+
*/
|
|
12
|
+
import { describe, test, beforeAll, afterAll, expect } from 'bun:test';
|
|
13
|
+
import { DataSeeder } from '../DataSeeder';
|
|
14
|
+
import { BenchmarkRunner } from '../BenchmarkRunner';
|
|
15
|
+
import { Query, FilterOp } from '../../../query/Query';
|
|
16
|
+
import { Entity } from '../../../core/Entity';
|
|
17
|
+
import { StressUser, StressProfile } from '../fixtures/StressTestComponents';
|
|
18
|
+
import { ensureComponentsRegistered } from '../../utils';
|
|
19
|
+
import db, { QUERY_TIMEOUT_MS } from '../../../database';
|
|
20
|
+
import { sql } from 'bun';
|
|
21
|
+
import { uuidv7 } from '../../../utils/uuid';
|
|
22
|
+
|
|
23
|
+
// Test configuration - scaled down for reliability, increase via env vars for stress testing
|
|
24
|
+
const LARGE_RECORD_COUNT = parseInt(process.env.STRESS_LARGE_COUNT || '5000', 10);
|
|
25
|
+
const CONCURRENT_OPERATIONS = parseInt(process.env.STRESS_CONCURRENT || '10', 10);
|
|
26
|
+
const BATCH_SIZE = Math.min(1000, Math.floor(LARGE_RECORD_COUNT / 5));
|
|
27
|
+
|
|
28
|
+
describe('Timeout Investigation - Insert Operations', () => {
|
|
29
|
+
const seeder = new DataSeeder();
|
|
30
|
+
let entityIds: string[] = [];
|
|
31
|
+
|
|
32
|
+
beforeAll(async () => {
|
|
33
|
+
await ensureComponentsRegistered(StressUser, StressProfile);
|
|
34
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
afterAll(async () => {
|
|
38
|
+
if (entityIds.length > 0) {
|
|
39
|
+
await seeder.cleanup(entityIds, BATCH_SIZE);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('bulk insert via Entity.save() - potential timeout scenario', async () => {
|
|
44
|
+
const startTime = performance.now();
|
|
45
|
+
const errors: string[] = [];
|
|
46
|
+
const batchCount = 100;
|
|
47
|
+
|
|
48
|
+
console.log(` Creating ${batchCount} entities via Entity.save()...`);
|
|
49
|
+
|
|
50
|
+
const savePromises: Promise<boolean>[] = [];
|
|
51
|
+
for (let i = 0; i < batchCount; i++) {
|
|
52
|
+
const entity = Entity.Create();
|
|
53
|
+
entity.add(StressUser, {
|
|
54
|
+
name: `Bulk User ${i}`,
|
|
55
|
+
email: `bulk${i}@test.com`,
|
|
56
|
+
age: 25 + (i % 50),
|
|
57
|
+
status: 'active',
|
|
58
|
+
score: Math.random() * 1000,
|
|
59
|
+
createdAt: new Date()
|
|
60
|
+
});
|
|
61
|
+
entityIds.push(entity.id);
|
|
62
|
+
savePromises.push(
|
|
63
|
+
entity.save().catch(err => {
|
|
64
|
+
errors.push(`Entity ${i}: ${err.message}`);
|
|
65
|
+
return false;
|
|
66
|
+
})
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const results = await Promise.all(savePromises);
|
|
71
|
+
const successCount = results.filter(r => r === true).length;
|
|
72
|
+
const elapsed = performance.now() - startTime;
|
|
73
|
+
|
|
74
|
+
console.log(` Completed: ${successCount}/${batchCount} in ${elapsed.toFixed(0)}ms`);
|
|
75
|
+
if (errors.length > 0) {
|
|
76
|
+
console.log(` Errors (first 5):`, errors.slice(0, 5));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
expect(errors.length).toBe(0);
|
|
80
|
+
expect(successCount).toBe(batchCount);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('concurrent Entity.save() - connection pool exhaustion', async () => {
|
|
84
|
+
const concurrency = CONCURRENT_OPERATIONS;
|
|
85
|
+
const startTime = performance.now();
|
|
86
|
+
const errors: string[] = [];
|
|
87
|
+
const timings: number[] = [];
|
|
88
|
+
|
|
89
|
+
console.log(` Running ${concurrency} concurrent Entity.save() operations...`);
|
|
90
|
+
|
|
91
|
+
const savePromises: Promise<void>[] = [];
|
|
92
|
+
for (let i = 0; i < concurrency; i++) {
|
|
93
|
+
const opStart = performance.now();
|
|
94
|
+
const entity = Entity.Create();
|
|
95
|
+
entity.add(StressUser, {
|
|
96
|
+
name: `Concurrent User ${i}`,
|
|
97
|
+
email: `concurrent${i}@test.com`,
|
|
98
|
+
age: 30,
|
|
99
|
+
status: 'pending',
|
|
100
|
+
score: i * 10,
|
|
101
|
+
createdAt: new Date()
|
|
102
|
+
});
|
|
103
|
+
entityIds.push(entity.id);
|
|
104
|
+
|
|
105
|
+
savePromises.push(
|
|
106
|
+
entity.save()
|
|
107
|
+
.then(() => {
|
|
108
|
+
timings.push(performance.now() - opStart);
|
|
109
|
+
})
|
|
110
|
+
.catch(err => {
|
|
111
|
+
errors.push(`Op ${i}: ${err.message}`);
|
|
112
|
+
})
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
await Promise.all(savePromises);
|
|
117
|
+
const elapsed = performance.now() - startTime;
|
|
118
|
+
|
|
119
|
+
const sortedTimings = [...timings].sort((a, b) => a - b);
|
|
120
|
+
const p50 = sortedTimings[Math.floor(timings.length / 2)] || 0;
|
|
121
|
+
const p95 = sortedTimings[Math.floor(timings.length * 0.95)] || 0;
|
|
122
|
+
const max = sortedTimings[timings.length - 1] || 0;
|
|
123
|
+
|
|
124
|
+
console.log(` Total time: ${elapsed.toFixed(0)}ms`);
|
|
125
|
+
console.log(` Latencies: p50=${p50.toFixed(0)}ms, p95=${p95.toFixed(0)}ms, max=${max.toFixed(0)}ms`);
|
|
126
|
+
console.log(` Errors: ${errors.length}`);
|
|
127
|
+
|
|
128
|
+
if (errors.length > 0) {
|
|
129
|
+
console.log(` Error samples:`, errors.slice(0, 3));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
expect(errors.length).toBe(0);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('large batch seeding - stress database connections', async () => {
|
|
136
|
+
const recordCount = Math.min(LARGE_RECORD_COUNT, 10000);
|
|
137
|
+
console.log(` Seeding ${recordCount} records via bulk insert...`);
|
|
138
|
+
|
|
139
|
+
const startTime = performance.now();
|
|
140
|
+
let hasError = false;
|
|
141
|
+
let errorMsg = '';
|
|
142
|
+
|
|
143
|
+
try {
|
|
144
|
+
const result = await seeder.seed(
|
|
145
|
+
StressUser,
|
|
146
|
+
(i) => ({
|
|
147
|
+
name: `Stress Test User ${i}`,
|
|
148
|
+
email: `stress${i}@test.com`,
|
|
149
|
+
age: 20 + (i % 60),
|
|
150
|
+
status: ['active', 'inactive', 'pending'][i % 3],
|
|
151
|
+
score: Math.random() * 1000,
|
|
152
|
+
createdAt: new Date()
|
|
153
|
+
}),
|
|
154
|
+
{
|
|
155
|
+
totalEntities: recordCount,
|
|
156
|
+
batchSize: BATCH_SIZE,
|
|
157
|
+
onProgress: (current, total, elapsed) => {
|
|
158
|
+
if (current % 5000 === 0) {
|
|
159
|
+
console.log(` Progress: ${current}/${total} (${(elapsed / 1000).toFixed(1)}s)`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
);
|
|
164
|
+
|
|
165
|
+
entityIds = [...entityIds, ...result.entityIds];
|
|
166
|
+
console.log(` Completed in ${(result.totalTime / 1000).toFixed(1)}s (${result.recordsPerSecond.toFixed(0)} records/sec)`);
|
|
167
|
+
} catch (err: any) {
|
|
168
|
+
hasError = true;
|
|
169
|
+
errorMsg = err.message;
|
|
170
|
+
console.log(` ERROR: ${errorMsg}`);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
expect(hasError).toBe(false);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe('Timeout Investigation - Query Operations', () => {
|
|
178
|
+
const seeder = new DataSeeder();
|
|
179
|
+
const benchmark = new BenchmarkRunner();
|
|
180
|
+
let entityIds: string[] = [];
|
|
181
|
+
let isSetup = false;
|
|
182
|
+
|
|
183
|
+
beforeAll(async () => {
|
|
184
|
+
await ensureComponentsRegistered(StressUser, StressProfile);
|
|
185
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
186
|
+
|
|
187
|
+
const recordCount = Math.min(LARGE_RECORD_COUNT, 20000);
|
|
188
|
+
console.log(`\n Setting up ${recordCount} records for query tests...`);
|
|
189
|
+
|
|
190
|
+
const result = await seeder.seed(
|
|
191
|
+
StressUser,
|
|
192
|
+
(i) => ({
|
|
193
|
+
name: `Query Test User ${i}`,
|
|
194
|
+
email: `query${i}@test.com`,
|
|
195
|
+
age: 18 + (i % 62),
|
|
196
|
+
status: ['active', 'inactive', 'pending', 'banned'][i % 4],
|
|
197
|
+
score: Math.random() * 10000,
|
|
198
|
+
createdAt: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000)
|
|
199
|
+
}),
|
|
200
|
+
{
|
|
201
|
+
totalEntities: recordCount,
|
|
202
|
+
batchSize: BATCH_SIZE
|
|
203
|
+
}
|
|
204
|
+
);
|
|
205
|
+
|
|
206
|
+
entityIds = result.entityIds;
|
|
207
|
+
await seeder.optimize();
|
|
208
|
+
isSetup = true;
|
|
209
|
+
console.log(` Setup complete: ${entityIds.length} records\n`);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
afterAll(async () => {
|
|
213
|
+
if (entityIds.length > 0) {
|
|
214
|
+
console.log('\n Cleaning up query test data...');
|
|
215
|
+
await seeder.cleanup(entityIds, BATCH_SIZE);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test('concurrent query operations - potential timeout', async () => {
|
|
220
|
+
if (!isSetup) return;
|
|
221
|
+
|
|
222
|
+
const concurrency = CONCURRENT_OPERATIONS;
|
|
223
|
+
const errors: string[] = [];
|
|
224
|
+
const timings: number[] = [];
|
|
225
|
+
|
|
226
|
+
console.log(` Running ${concurrency} concurrent queries...`);
|
|
227
|
+
const startTime = performance.now();
|
|
228
|
+
|
|
229
|
+
const queryPromises = Array(concurrency).fill(null).map(async (_, i) => {
|
|
230
|
+
const opStart = performance.now();
|
|
231
|
+
try {
|
|
232
|
+
await new Query()
|
|
233
|
+
.with(StressUser, {
|
|
234
|
+
filters: [{ field: 'status', operator: FilterOp.EQ, value: ['active', 'inactive', 'pending', 'banned'][i % 4] }]
|
|
235
|
+
})
|
|
236
|
+
.take(100)
|
|
237
|
+
.exec();
|
|
238
|
+
timings.push(performance.now() - opStart);
|
|
239
|
+
} catch (err: any) {
|
|
240
|
+
errors.push(`Query ${i}: ${err.message}`);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
await Promise.all(queryPromises);
|
|
245
|
+
const elapsed = performance.now() - startTime;
|
|
246
|
+
|
|
247
|
+
const sortedTimings = [...timings].sort((a, b) => a - b);
|
|
248
|
+
const p50 = sortedTimings[Math.floor(timings.length / 2)] || 0;
|
|
249
|
+
const p95 = sortedTimings[Math.floor(timings.length * 0.95)] || 0;
|
|
250
|
+
const max = sortedTimings[timings.length - 1] || 0;
|
|
251
|
+
|
|
252
|
+
console.log(` Total time: ${elapsed.toFixed(0)}ms`);
|
|
253
|
+
console.log(` Latencies: p50=${p50.toFixed(0)}ms, p95=${p95.toFixed(0)}ms, max=${max.toFixed(0)}ms`);
|
|
254
|
+
console.log(` Errors: ${errors.length}`);
|
|
255
|
+
|
|
256
|
+
if (errors.length > 0) {
|
|
257
|
+
console.log(` Error samples:`, errors.slice(0, 3));
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Check for timeout-related errors
|
|
261
|
+
const timeoutErrors = errors.filter(e => e.toLowerCase().includes('timeout'));
|
|
262
|
+
if (timeoutErrors.length > 0) {
|
|
263
|
+
console.log(` TIMEOUT ERRORS DETECTED: ${timeoutErrors.length}`);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
expect(errors.length).toBe(0);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
test('mixed read/write concurrent operations', async () => {
|
|
270
|
+
if (!isSetup) return;
|
|
271
|
+
|
|
272
|
+
const opsPerType = Math.floor(CONCURRENT_OPERATIONS / 2);
|
|
273
|
+
const errors: { type: string; message: string }[] = [];
|
|
274
|
+
const readTimings: number[] = [];
|
|
275
|
+
const writeTimings: number[] = [];
|
|
276
|
+
const newEntityIds: string[] = [];
|
|
277
|
+
|
|
278
|
+
console.log(` Running mixed operations: ${opsPerType} reads + ${opsPerType} writes...`);
|
|
279
|
+
const startTime = performance.now();
|
|
280
|
+
|
|
281
|
+
// Create read operations
|
|
282
|
+
const readOps = Array(opsPerType).fill(null).map(async (_, i) => {
|
|
283
|
+
const opStart = performance.now();
|
|
284
|
+
try {
|
|
285
|
+
await new Query()
|
|
286
|
+
.with(StressUser, {
|
|
287
|
+
filters: [{ field: 'age', operator: FilterOp.GTE, value: 20 + (i % 40) }]
|
|
288
|
+
})
|
|
289
|
+
.sortBy(StressUser, 'score', 'DESC')
|
|
290
|
+
.take(50)
|
|
291
|
+
.exec();
|
|
292
|
+
readTimings.push(performance.now() - opStart);
|
|
293
|
+
} catch (err: any) {
|
|
294
|
+
errors.push({ type: 'read', message: err.message });
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
// Create write operations
|
|
299
|
+
const writeOps = Array(opsPerType).fill(null).map(async (_, i) => {
|
|
300
|
+
const opStart = performance.now();
|
|
301
|
+
try {
|
|
302
|
+
const entity = Entity.Create();
|
|
303
|
+
entity.add(StressUser, {
|
|
304
|
+
name: `Mixed Op User ${i}`,
|
|
305
|
+
email: `mixed${i}@test.com`,
|
|
306
|
+
age: 25,
|
|
307
|
+
status: 'active',
|
|
308
|
+
score: i * 100,
|
|
309
|
+
createdAt: new Date()
|
|
310
|
+
});
|
|
311
|
+
newEntityIds.push(entity.id);
|
|
312
|
+
await entity.save();
|
|
313
|
+
writeTimings.push(performance.now() - opStart);
|
|
314
|
+
} catch (err: any) {
|
|
315
|
+
errors.push({ type: 'write', message: err.message });
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
await Promise.all([...readOps, ...writeOps]);
|
|
320
|
+
const elapsed = performance.now() - startTime;
|
|
321
|
+
|
|
322
|
+
// Add new entity IDs to cleanup list
|
|
323
|
+
entityIds = [...entityIds, ...newEntityIds];
|
|
324
|
+
|
|
325
|
+
const readP95 = [...readTimings].sort((a, b) => a - b)[Math.floor(readTimings.length * 0.95)] || 0;
|
|
326
|
+
const writeP95 = [...writeTimings].sort((a, b) => a - b)[Math.floor(writeTimings.length * 0.95)] || 0;
|
|
327
|
+
|
|
328
|
+
console.log(` Total time: ${elapsed.toFixed(0)}ms`);
|
|
329
|
+
console.log(` Read p95: ${readP95.toFixed(0)}ms, Write p95: ${writeP95.toFixed(0)}ms`);
|
|
330
|
+
console.log(` Errors: ${errors.filter(e => e.type === 'read').length} reads, ${errors.filter(e => e.type === 'write').length} writes`);
|
|
331
|
+
|
|
332
|
+
if (errors.length > 0) {
|
|
333
|
+
console.log(` Error samples:`, errors.slice(0, 3));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
expect(errors.length).toBe(0);
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
test('long-running query with complex filters', async () => {
|
|
340
|
+
if (!isSetup) return;
|
|
341
|
+
|
|
342
|
+
console.log(` Running complex query across ${entityIds.length} records...`);
|
|
343
|
+
const startTime = performance.now();
|
|
344
|
+
let hasError = false;
|
|
345
|
+
let errorMsg = '';
|
|
346
|
+
let resultCount = 0;
|
|
347
|
+
|
|
348
|
+
try {
|
|
349
|
+
const results = await new Query()
|
|
350
|
+
.with(StressUser, {
|
|
351
|
+
filters: [
|
|
352
|
+
{ field: 'age', operator: FilterOp.GTE, value: 25 },
|
|
353
|
+
{ field: 'age', operator: FilterOp.LTE, value: 45 },
|
|
354
|
+
{ field: 'status', operator: FilterOp.IN, value: ['active', 'pending'] }
|
|
355
|
+
]
|
|
356
|
+
})
|
|
357
|
+
.sortBy(StressUser, 'score', 'DESC')
|
|
358
|
+
.populate()
|
|
359
|
+
.take(500)
|
|
360
|
+
.exec();
|
|
361
|
+
|
|
362
|
+
resultCount = results.length;
|
|
363
|
+
} catch (err: any) {
|
|
364
|
+
hasError = true;
|
|
365
|
+
errorMsg = err.message;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const elapsed = performance.now() - startTime;
|
|
369
|
+
console.log(` Completed in ${elapsed.toFixed(0)}ms, returned ${resultCount} results`);
|
|
370
|
+
|
|
371
|
+
if (hasError) {
|
|
372
|
+
console.log(` ERROR: ${errorMsg}`);
|
|
373
|
+
// Check if it's a timeout error
|
|
374
|
+
if (errorMsg.toLowerCase().includes('timeout')) {
|
|
375
|
+
console.log(` TIMEOUT DETECTED - Query exceeded 30 second limit`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
expect(hasError).toBe(false);
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
test('count query on large dataset', async () => {
|
|
383
|
+
if (!isSetup) return;
|
|
384
|
+
|
|
385
|
+
console.log(` Running COUNT query on ${entityIds.length} records...`);
|
|
386
|
+
const startTime = performance.now();
|
|
387
|
+
let hasError = false;
|
|
388
|
+
let errorMsg = '';
|
|
389
|
+
let count = 0;
|
|
390
|
+
|
|
391
|
+
try {
|
|
392
|
+
count = await new Query()
|
|
393
|
+
.with(StressUser, {
|
|
394
|
+
filters: [{ field: 'status', operator: FilterOp.EQ, value: 'active' }]
|
|
395
|
+
})
|
|
396
|
+
.count();
|
|
397
|
+
} catch (err: any) {
|
|
398
|
+
hasError = true;
|
|
399
|
+
errorMsg = err.message;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const elapsed = performance.now() - startTime;
|
|
403
|
+
console.log(` Completed in ${elapsed.toFixed(0)}ms, count=${count}`);
|
|
404
|
+
|
|
405
|
+
if (hasError) {
|
|
406
|
+
console.log(` ERROR: ${errorMsg}`);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
expect(hasError).toBe(false);
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
test('sustained concurrent load - connection pool stress', async () => {
|
|
413
|
+
if (!isSetup) return;
|
|
414
|
+
|
|
415
|
+
const durationMs = 5000;
|
|
416
|
+
const concurrency = 10;
|
|
417
|
+
const errors: string[] = [];
|
|
418
|
+
const timings: number[] = [];
|
|
419
|
+
let queryCount = 0;
|
|
420
|
+
|
|
421
|
+
console.log(` Running sustained load for ${durationMs}ms with ${concurrency} concurrent workers...`);
|
|
422
|
+
const startTime = performance.now();
|
|
423
|
+
|
|
424
|
+
const worker = async () => {
|
|
425
|
+
while (performance.now() - startTime < durationMs) {
|
|
426
|
+
const opStart = performance.now();
|
|
427
|
+
try {
|
|
428
|
+
await new Query()
|
|
429
|
+
.with(StressUser)
|
|
430
|
+
.take(10)
|
|
431
|
+
.exec();
|
|
432
|
+
timings.push(performance.now() - opStart);
|
|
433
|
+
queryCount++;
|
|
434
|
+
} catch (err: any) {
|
|
435
|
+
errors.push(err.message);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
await Promise.all(Array(concurrency).fill(null).map(() => worker()));
|
|
441
|
+
const elapsed = performance.now() - startTime;
|
|
442
|
+
|
|
443
|
+
const sortedTimings = [...timings].sort((a, b) => a - b);
|
|
444
|
+
const p50 = sortedTimings[Math.floor(timings.length / 2)] || 0;
|
|
445
|
+
const p95 = sortedTimings[Math.floor(timings.length * 0.95)] || 0;
|
|
446
|
+
const p99 = sortedTimings[Math.floor(timings.length * 0.99)] || 0;
|
|
447
|
+
const max = sortedTimings[timings.length - 1] || 0;
|
|
448
|
+
|
|
449
|
+
const qps = (queryCount / elapsed) * 1000;
|
|
450
|
+
|
|
451
|
+
console.log(` Completed ${queryCount} queries in ${elapsed.toFixed(0)}ms (${qps.toFixed(0)} QPS)`);
|
|
452
|
+
console.log(` Latencies: p50=${p50.toFixed(0)}ms, p95=${p95.toFixed(0)}ms, p99=${p99.toFixed(0)}ms, max=${max.toFixed(0)}ms`);
|
|
453
|
+
console.log(` Errors: ${errors.length}`);
|
|
454
|
+
|
|
455
|
+
const timeoutErrors = errors.filter(e => e.toLowerCase().includes('timeout'));
|
|
456
|
+
if (timeoutErrors.length > 0) {
|
|
457
|
+
console.log(` TIMEOUT ERRORS: ${timeoutErrors.length}`);
|
|
458
|
+
console.log(` Samples:`, timeoutErrors.slice(0, 3));
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Fail if more than 5% error rate
|
|
462
|
+
const errorRate = errors.length / queryCount;
|
|
463
|
+
expect(errorRate).toBeLessThan(0.05);
|
|
464
|
+
});
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
describe('Timeout Investigation - Database Diagnostics', () => {
|
|
468
|
+
test('connection pool status', async () => {
|
|
469
|
+
console.log(' Checking database connection pool...');
|
|
470
|
+
console.log(` Configured query timeout: ${QUERY_TIMEOUT_MS}ms`);
|
|
471
|
+
|
|
472
|
+
try {
|
|
473
|
+
// Run multiple quick queries to check pool behavior
|
|
474
|
+
const startTime = performance.now();
|
|
475
|
+
const queries = Array(5).fill(null).map(() =>
|
|
476
|
+
db`SELECT 1 as test`
|
|
477
|
+
);
|
|
478
|
+
await Promise.all(queries);
|
|
479
|
+
const elapsed = performance.now() - startTime;
|
|
480
|
+
|
|
481
|
+
console.log(` 5 parallel queries completed in ${elapsed.toFixed(0)}ms`);
|
|
482
|
+
expect(elapsed).toBeLessThan(5000);
|
|
483
|
+
} catch (err: any) {
|
|
484
|
+
console.log(` Connection pool error: ${err.message}`);
|
|
485
|
+
throw err;
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
test('statement timeout configuration', async () => {
|
|
490
|
+
console.log(' Checking statement timeout setting...');
|
|
491
|
+
|
|
492
|
+
try {
|
|
493
|
+
const result = await db`SHOW statement_timeout`;
|
|
494
|
+
console.log(` statement_timeout = ${result[0]?.statement_timeout || 'not set'}`);
|
|
495
|
+
} catch (err: any) {
|
|
496
|
+
console.log(` Could not check statement_timeout: ${err.message}`);
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
test('active connections count', async () => {
|
|
501
|
+
console.log(' Checking active connections...');
|
|
502
|
+
|
|
503
|
+
try {
|
|
504
|
+
const result = await db.unsafe(`
|
|
505
|
+
SELECT count(*) as active_connections
|
|
506
|
+
FROM pg_stat_activity
|
|
507
|
+
WHERE state = 'active'
|
|
508
|
+
`);
|
|
509
|
+
console.log(` Active connections: ${result[0]?.active_connections || 0}`);
|
|
510
|
+
} catch (err: any) {
|
|
511
|
+
console.log(` Could not check connections: ${err.message}`);
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
test('framework timeout configuration', async () => {
|
|
516
|
+
console.log(' Framework Timeout Settings:');
|
|
517
|
+
console.log(` DB_QUERY_TIMEOUT: ${QUERY_TIMEOUT_MS}ms (${QUERY_TIMEOUT_MS / 1000}s)`);
|
|
518
|
+
console.log(` Applies to: Query.exec(), Query.count(), Entity.save(), etc.`);
|
|
519
|
+
console.log(` Configure via: DB_QUERY_TIMEOUT environment variable`);
|
|
520
|
+
expect(QUERY_TIMEOUT_MS).toBeGreaterThan(0);
|
|
521
|
+
});
|
|
522
|
+
});
|