forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
332 lines (287 loc) · 11.4 KB
/
server.mjs
File metadata and controls
332 lines (287 loc) · 11.4 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
// @ts-check
import http from 'node:http';
import path from 'node:path';
import fs from 'node:fs';
import { generateTestCase } from '../cli.mjs';
import { emitSwift } from '../emit/swift-emitter.mjs';
import { emitJS } from '../emit/js-emitter.mjs';
import { setupWorkerProject, writeTestCase } from '../emit/project.mjs';
import { buildAndBundle } from '../runner/build.mjs';
import { executeHarness } from '../runner/execute.mjs';
import { FailureTracker } from '../runner/failures.mjs';
import { WorkerPool } from '../runner/worker-pool.mjs';
import { dashboardHTML } from './dashboard.mjs';
/**
* @typedef {import('../types.mjs').FailurePhase} FailurePhase
*/
/**
* @typedef {{
* port: number,
* fuzzTestingDir: string,
* jskitPath: string,
* numWorkers: number,
* iterations: number,
* startSeed: number,
* maxDepth: number,
* maxParams: number,
* maxOps: number,
* timeout: number,
* verbose: boolean,
* onFailure?: string,
* }} ServerOptions
*/
/**
* Shared fuzzer state visible to API handlers and SSE clients.
*/
class FuzzerState {
/** @type {number} */ totalIterations = 0;
/** @type {number} */ totalFailures = 0;
/** @type {number} */ startTime = Date.now();
/** @type {boolean} */ running = false;
/** @type {boolean} */ paused = false;
/** @type {Map<string, number>} */ typeCoverage = new Map();
/** @type {Array<{ seed: number, ok: boolean, phase?: string, time: number }>} */ recentResults = [];
/** @type {number} */ currentSeed = 0;
/** @type {Set<http.ServerResponse>} */
sseClients = new Set();
/**
* Broadcast a Server-Sent Event to all connected clients.
* @param {string} event
* @param {*} data
*/
broadcast(event, data) {
const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of this.sseClients) {
try { res.write(msg); } catch { this.sseClients.delete(res); }
}
}
statusJSON() {
const elapsed = (Date.now() - this.startTime) / 1000;
return {
running: this.running,
paused: this.paused,
totalIterations: this.totalIterations,
totalFailures: this.totalFailures,
elapsed: elapsed.toFixed(1),
throughput: elapsed > 0 ? (this.totalIterations / elapsed).toFixed(2) : '0',
currentSeed: this.currentSeed,
};
}
}
/**
* Start the fuzzer with an HTTP dashboard.
* @param {ServerOptions} options
*/
export async function startServer(options) {
const {
port, fuzzTestingDir, jskitPath, numWorkers, iterations, startSeed,
maxDepth, maxParams, maxOps, timeout, verbose, onFailure,
} = options;
const failCasesDir = path.join(fuzzTestingDir, 'FailCases');
const tracker = new FailureTracker(failCasesDir, { onFailureHook: onFailure });
const state = new FuzzerState();
const genOpts = { maxDepth, maxParams, maxOps };
// ---- HTTP Server ----
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? '/', `http://localhost:${port}`);
const pathname = url.pathname;
// CORS for dev convenience
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
// ---- Routes ----
if (pathname === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(dashboardHTML());
return;
}
if (pathname === '/api/status' && req.method === 'GET') {
json(res, state.statusJSON());
return;
}
if (pathname === '/api/failures' && req.method === 'GET') {
json(res, tracker.list());
return;
}
if (pathname.startsWith('/api/failures/') && req.method === 'GET') {
const id = pathname.slice('/api/failures/'.length);
const failDir = path.join(failCasesDir, id);
if (!fs.existsSync(failDir)) { notFound(res); return; }
const meta = safeReadJSON(path.join(failDir, 'metadata.json'));
const swift = safeRead(path.join(failDir, 'main.swift'));
const harness = safeRead(path.join(failDir, 'harness.mjs'));
const error = safeRead(path.join(failDir, 'error.txt'));
json(res, { ...meta, files: { 'main.swift': swift, 'harness.mjs': harness, 'error.txt': error } });
return;
}
if (pathname === '/api/coverage' && req.method === 'GET') {
json(res, Object.fromEntries(state.typeCoverage));
return;
}
if (pathname === '/api/recent' && req.method === 'GET') {
json(res, state.recentResults.slice(-100));
return;
}
if (pathname === '/api/events' && req.method === 'GET') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
res.write(`data: ${JSON.stringify(state.statusJSON())}\n\n`);
state.sseClients.add(res);
req.on('close', () => state.sseClients.delete(res));
return;
}
if (pathname === '/api/control/pause' && req.method === 'POST') {
state.paused = true;
state.broadcast('status', state.statusJSON());
json(res, { ok: true, paused: true });
return;
}
if (pathname === '/api/control/resume' && req.method === 'POST') {
state.paused = false;
state.broadcast('status', state.statusJSON());
json(res, { ok: true, paused: false });
return;
}
notFound(res);
});
server.listen(port, () => {
console.log(`Dashboard: http://localhost:${port}/`);
console.log(`API: http://localhost:${port}/api/status`);
console.log(`SSE: http://localhost:${port}/api/events`);
console.log('');
});
// ---- Collect types for coverage tracking ----
/**
* @param {import('../types.mjs').TestCase} testCase
*/
function trackCoverage(testCase) {
/** @param {import('../types.mjs').BridgeType} t */
function walk(t) {
state.typeCoverage.set(t.kind, (state.typeCoverage.get(t.kind) ?? 0) + 1);
if (t.kind === 'nullable') walk(t.wrapped);
else if (t.kind === 'array') walk(t.element);
else if (t.kind === 'dictionary') walk(t.value);
}
for (const tf of testCase.testFuncs) {
walk(tf.returnType);
for (const p of tf.params) walk(p.type);
}
}
/**
* @param {import('../types.mjs').TestCase} testCase
* @returns {string[]}
*/
function collectTypes(testCase) {
/** @type {Set<string>} */
const kinds = new Set();
/** @param {import('../types.mjs').BridgeType} t */
function walk(t) { kinds.add(t.kind); if (t.kind === 'nullable') walk(t.wrapped); else if (t.kind === 'array') walk(t.element); else if (t.kind === 'dictionary') walk(t.value); }
for (const func of testCase.env.importedFuncs) { walk(func.returnType); for (const p of func.params) walk(p.type); }
for (const cls of testCase.env.importedClasses) { for (const p of cls.constructorParams) walk(p.type); }
for (const tf of testCase.testFuncs) { walk(tf.returnType); for (const p of tf.params) walk(p.type); }
return [...kinds].sort();
}
// ---- Run the fuzzer ----
state.running = true;
state.currentSeed = startSeed;
if (numWorkers > 1) {
const pool = new WorkerPool({ fuzzTestingDir, jskitPath, numWorkers, timeout, verbose });
console.log(`Initializing ${numWorkers} workers...`);
await pool.initialize();
await pool.run({
startSeed,
iterations,
generateJob(seed) {
// Respect pause
state.currentSeed = seed;
const testCase = generateTestCase(seed, genOpts);
trackCoverage(testCase);
return { seed, swiftSource: emitSwift(testCase), jsSource: emitJS(testCase) };
},
async onResult(result) {
state.totalIterations++;
const entry = { seed: result.seed, ok: result.success, phase: result.phase, time: Date.now() };
state.recentResults.push(entry);
if (state.recentResults.length > 500) state.recentResults.shift();
if (!result.success) {
state.totalFailures++;
const testCase = generateTestCase(result.seed, genOpts);
const phase = /** @type {FailurePhase} */ (result.phase ?? 'runtime-error');
await tracker.record(
result.seed, phase, result.error ?? 'Unknown error',
{ 'main.swift': emitSwift(testCase), 'harness.mjs': emitJS(testCase) },
{ typesInvolved: collectTypes(testCase) },
);
}
state.broadcast('result', entry);
state.broadcast('status', state.statusJSON());
},
});
await pool.shutdown();
} else {
// Sequential mode
const workerDir = path.join(fuzzTestingDir, 'WorkerProject');
setupWorkerProject(workerDir, jskitPath);
let seed = startSeed;
while (true) {
if (iterations > 0 && state.totalIterations >= iterations) break;
if (state.paused) { await delay(200); continue; }
state.currentSeed = seed;
const testCase = generateTestCase(seed, genOpts);
trackCoverage(testCase);
const swiftSource = emitSwift(testCase);
const jsSource = emitJS(testCase);
writeTestCase(workerDir, swiftSource);
const buildResult = await buildAndBundle(workerDir, { timeout, verbose });
/** @type {{ seed: number, ok: boolean, phase?: string, time: number }} */
let entry;
if (!buildResult.success) {
state.totalFailures++;
await tracker.record(seed, 'compile-error', buildResult.error ?? '', { 'main.swift': swiftSource, 'harness.mjs': jsSource }, { typesInvolved: collectTypes(testCase) });
entry = { seed, ok: false, phase: 'compile-error', time: Date.now() };
} else {
const outputDir = /** @type {string} */ (buildResult.outputDir);
const harnessPath = path.join(outputDir, 'harness.mjs');
fs.writeFileSync(harnessPath, jsSource, 'utf-8');
const execResult = await executeHarness(harnessPath, { timeout, verbose });
if (!execResult.success) {
state.totalFailures++;
const phase = /** @type {FailurePhase} */ (execResult.phase ?? 'runtime-error');
await tracker.record(seed, phase, execResult.error ?? '', { 'main.swift': swiftSource, 'harness.mjs': jsSource }, { typesInvolved: collectTypes(testCase) });
entry = { seed, ok: false, phase, time: Date.now() };
} else {
entry = { seed, ok: true, time: Date.now() };
}
}
state.totalIterations++;
state.recentResults.push(entry);
if (state.recentResults.length > 500) state.recentResults.shift();
state.broadcast('result', entry);
state.broadcast('status', state.statusJSON());
seed++;
}
}
state.running = false;
state.broadcast('status', state.statusJSON());
console.log('\nFuzzing complete. Dashboard remains running. Press Ctrl-C to exit.');
}
// ---- Helpers ----
/** @param {http.ServerResponse} res @param {*} data */
function json(res, data) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
/** @param {http.ServerResponse} res */
function notFound(res) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'not found' }));
}
/** @param {string} p @returns {string} */
function safeRead(p) { try { return fs.readFileSync(p, 'utf-8'); } catch { return ''; } }
/** @param {string} p @returns {*} */
function safeReadJSON(p) { try { return JSON.parse(fs.readFileSync(p, 'utf-8')); } catch { return {}; } }
/** @param {number} ms @returns {Promise<void>} */
function delay(ms) { return new Promise(r => setTimeout(r, ms)); }