-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulate-application.ts
More file actions
173 lines (146 loc) · 4.63 KB
/
simulate-application.ts
File metadata and controls
173 lines (146 loc) · 4.63 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
import { Worker } from 'node:worker_threads';
import { spawn } from 'node:child_process';
import { mkdtemp, readFile, rm, unlink, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { randomBytes } from 'node:crypto';
import { getMode, randomInRange, type Mode } from './modes.ts';
interface SimulationResultSuccess {
fileIoAmount: number;
processCount: number;
threadCount: number;
mode: Mode;
success: true;
}
interface SimulationResultFailure {
error: unknown;
mode: Mode;
success: false;
}
type SimulationResult = SimulationResultSuccess | SimulationResultFailure;
/**
* Simulates a resource-intensive application that performs various operations:
* - File system I/O (configurable via mode)
* - Spawns child processes (configurable via mode)
* - Creates worker threads for CPU-intensive work
* - Database-like operations with serialization
*/
export async function simulateApplication(modeName: string = 'default'): Promise<SimulationResult> {
console.log('starting simulation with mode:', modeName);
// Get mode configuration
const mode = getMode(modeName);
// Use a unique directory per request to avoid race conditions
const tmpDir = await mkdtemp(join(tmpdir(), `node-test-runner-parallelization-analysis-`));
try {
// File I/O work based on mode range (in MB)
const fileIoMB = randomInRange(mode.fileIoRange[0], mode.fileIoRange[1]);
const fileIoAmount = Math.floor(fileIoMB) * 1024 * 1024;
await performFileOperations(tmpDir, fileIoAmount);
// Spawn child processes based on mode range
const processCount = Math.floor(randomInRange(mode.processRange[0], mode.processRange[1]));
await spawnChildProcesses(processCount);
// CPU-intensive work via worker threads (simulating database operations)
const threadCount = Math.floor(randomInRange(mode.threadRange[0], mode.threadRange[1]));
await spawnThreads(threadCount, mode.cpuWorkMultiplier);
return {
fileIoAmount,
processCount,
threadCount,
mode,
success: true
};
} catch (error) {
return {
error,
mode,
success: false
};
} finally {
await cleanup(tmpDir);
}
}
async function performFileOperations(tmpDir: string, totalBytes: number) {
if (totalBytes === 0) return;
const chunkSize = 1024 * 1024; // 1MB chunks
const chunks = Math.ceil(totalBytes / chunkSize);
// Write files
const writePromises = [];
for (let i = 0; i < chunks; i++) {
const filePath = join(tmpDir, `data-${i}.bin`);
const data = randomBytes(Math.min(chunkSize, totalBytes - (i * chunkSize)));
writePromises.push(writeFile(filePath, data));
}
await Promise.all(writePromises);
// Read files back
const readPromises = [];
for (let i = 0; i < chunks; i++) {
const filePath = join(tmpDir, `data-${i}.bin`);
readPromises.push(readFile(filePath));
}
await Promise.all(readPromises);
// Delete files
const deletePromises = [];
for (let i = 0; i < chunks; i++) {
const filePath = join(tmpDir, `data-${i}.bin`);
deletePromises.push(unlink(filePath));
}
await Promise.all(deletePromises);
}
async function spawnChildProcesses(count: number) {
if (count === 0) return;
const processes = [];
for (let i = 0; i < count; i++) {
const workDuration = 50 + Math.random() * 150;
// Spawn a simple process that does some work
const proc = spawn('node', ['-e', `
// Simulate some CPU work
const start = Date.now();
let sum = 0;
while (Date.now() - start < ${workDuration}) {
sum += Math.random();
}
console.log('Done');
`]);
processes.push(new Promise((resolve) => {
proc.on('exit', resolve);
}));
}
await Promise.all(processes);
}
function spawnThreads(count: number, cpuMultiplier: number) {
if (count === 0) return Promise.resolve();
return Promise.all(
Array.from({ length: count }, () => performCpuWork(cpuMultiplier))
);
}
function performCpuWork(multiplier = 1.0) {
return new Promise((resolve, reject) => {
const iterations = Math.floor(10_000_000 * multiplier);
const worker = new Worker(`
import { parentPort, workerData } from 'node:worker_threads';
// Simulate CPU-intensive work
let result = 0;
for (let i = 0; i < ${iterations}; i++) {
result += Math.sqrt(i) * Math.random();
}
parentPort.postMessage({ result });
`, { eval: true });
worker.on('message', (msg) => {
worker.terminate();
resolve(msg.result);
});
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
});
}
async function cleanup(tmpDir: string) {
try {
await rm(tmpDir, { recursive: true, force: true });
} catch (error) {
// Ignore cleanup errors
}
}