forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench-gateway-startup.ts
More file actions
629 lines (588 loc) · 17.2 KB
/
Copy pathbench-gateway-startup.ts
File metadata and controls
629 lines (588 loc) · 17.2 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { request } from "node:http";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { performance } from "node:perf_hooks";
type GatewayBenchCase = {
config: Record<string, unknown>;
env?: Record<string, string>;
id: string;
name: string;
pluginCount?: number;
};
type ProbeResult = {
ms: number | null;
status: number | null;
};
type GatewaySample = {
exitCode: number | null;
firstOutputMs: number | null;
healthz: ProbeResult;
outputTail: string;
readyLogMs: number | null;
readyz: ProbeResult;
signal: string | null;
startupTrace: Record<string, number>;
};
type SummaryStats = {
avg: number;
max: number;
min: number;
p50: number;
p95: number;
};
type CaseResult = {
id: string;
name: string;
samples: GatewaySample[];
summary: {
firstOutputMs: SummaryStats | null;
healthzMs: SummaryStats | null;
readyLogMs: SummaryStats | null;
readyzMs: SummaryStats | null;
startupTrace: Record<string, SummaryStats>;
};
};
type CliOptions = {
cases: GatewayBenchCase[];
entry: string;
json: boolean;
output?: string;
runs: number;
timeoutMs: number;
warmup: number;
};
const DEFAULT_RUNS = 5;
const DEFAULT_WARMUP = 1;
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_ENTRY = "dist/entry.js";
const BASE_CONFIG = {
browser: { enabled: false },
gateway: {
mode: "local",
bind: "loopback",
auth: { mode: "none" },
controlUi: { enabled: false },
tailscale: { mode: "off" },
},
plugins: {
enabled: true,
entries: {
browser: { enabled: false },
},
},
} satisfies Record<string, unknown>;
const GATEWAY_CASES: readonly GatewayBenchCase[] = [
{
id: "default",
name: "gateway default",
config: BASE_CONFIG,
},
{
id: "skipChannels",
name: "gateway, skip channels",
env: { OPENCLAW_SKIP_CHANNELS: "1" },
config: BASE_CONFIG,
},
{
id: "oneInternalHook",
name: "gateway, one configured internal hook",
env: { OPENCLAW_SKIP_CHANNELS: "1" },
config: {
...BASE_CONFIG,
hooks: {
internal: {
entries: {
"session-memory": { enabled: true },
},
},
},
},
},
{
id: "allInternalHooks",
name: "gateway, all internal hooks",
env: { OPENCLAW_SKIP_CHANNELS: "1" },
config: {
...BASE_CONFIG,
hooks: {
internal: {
enabled: true,
},
},
},
},
{
id: "fiftyPlugins",
name: "gateway, 50 manifest plugins",
env: { OPENCLAW_SKIP_CHANNELS: "1" },
pluginCount: 50,
config: BASE_CONFIG,
},
] as const;
function parseFlagValue(flag: string): string | undefined {
const index = process.argv.indexOf(flag);
if (index === -1) {
return undefined;
}
return process.argv[index + 1];
}
function hasFlag(flag: string): boolean {
return process.argv.includes(flag);
}
function parseRepeatableFlag(flag: string): string[] {
const values: string[] = [];
for (let index = 0; index < process.argv.length; index += 1) {
if (process.argv[index] === flag && process.argv[index + 1]) {
values.push(process.argv[index + 1]);
}
}
return values;
}
function parsePositiveInt(raw: string | undefined, fallback: number): number {
if (!raw) {
return fallback;
}
const parsed = Number.parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed < 0) {
return fallback;
}
return parsed;
}
function resolveCases(caseIds: string[]): GatewayBenchCase[] {
if (caseIds.length === 0) {
return [...GATEWAY_CASES];
}
const byId = new Map(GATEWAY_CASES.map((benchCase) => [benchCase.id, benchCase]));
return caseIds.map((id) => {
const benchCase = byId.get(id);
if (!benchCase) {
throw new Error(`Unknown --case "${id}"`);
}
return benchCase;
});
}
function parseOptions(): CliOptions {
return {
cases: resolveCases(parseRepeatableFlag("--case")),
entry: parseFlagValue("--entry") ?? DEFAULT_ENTRY,
json: hasFlag("--json"),
output: parseFlagValue("--output"),
runs: parsePositiveInt(parseFlagValue("--runs"), DEFAULT_RUNS),
timeoutMs: parsePositiveInt(parseFlagValue("--timeout-ms"), DEFAULT_TIMEOUT_MS),
warmup: parsePositiveInt(parseFlagValue("--warmup"), DEFAULT_WARMUP),
};
}
function median(values: number[]): number {
const sorted = [...values].toSorted((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 0) {
return (sorted[middle - 1] + sorted[middle]) / 2;
}
return sorted[middle] ?? 0;
}
function percentile(values: number[], p: number): number {
const sorted = [...values].toSorted((a, b) => a - b);
const index = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
return sorted[index] ?? 0;
}
function summarizeNumbers(values: number[]): SummaryStats | null {
if (values.length === 0) {
return null;
}
const total = values.reduce((sum, value) => sum + value, 0);
return {
avg: total / values.length,
max: Math.max(...values),
min: Math.min(...values),
p50: median(values),
p95: percentile(values, 95),
};
}
function summarizeCase(benchCase: GatewayBenchCase, samples: GatewaySample[]): CaseResult {
const startupTraceKeys = new Set<string>();
for (const sample of samples) {
for (const key of Object.keys(sample.startupTrace)) {
startupTraceKeys.add(key);
}
}
const startupTrace: Record<string, SummaryStats> = {};
for (const key of [...startupTraceKeys].toSorted()) {
const stats = summarizeNumbers(
samples
.map((sample) => sample.startupTrace[key])
.filter((value): value is number => typeof value === "number"),
);
if (stats) {
startupTrace[key] = stats;
}
}
return {
id: benchCase.id,
name: benchCase.name,
samples,
summary: {
firstOutputMs: summarizeNumbers(
samples
.map((sample) => sample.firstOutputMs)
.filter((value): value is number => typeof value === "number"),
),
healthzMs: summarizeNumbers(
samples
.map((sample) => sample.healthz.ms)
.filter((value): value is number => typeof value === "number"),
),
readyLogMs: summarizeNumbers(
samples
.map((sample) => sample.readyLogMs)
.filter((value): value is number => typeof value === "number"),
),
readyzMs: summarizeNumbers(
samples
.map((sample) => sample.readyz.ms)
.filter((value): value is number => typeof value === "number"),
),
startupTrace,
},
};
}
function formatMs(value: number | null): string {
if (value == null) {
return "n/a";
}
return `${value.toFixed(1)}ms`;
}
function formatStats(stats: SummaryStats | null): string {
if (!stats) {
return "n/a";
}
return `p50=${formatMs(stats.p50)} avg=${formatMs(stats.avg)} min=${formatMs(stats.min)} max=${formatMs(stats.max)}`;
}
async function getFreePort(): Promise<number> {
return new Promise((resolve, reject) => {
const server = createServer();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") {
server.close(() => reject(new Error("failed to allocate port")));
return;
}
const { port } = address;
server.close(() => resolve(port));
});
});
}
async function waitForProbe(params: {
deadlineAt: number;
isDone?: () => boolean;
path: string;
port: number;
startAt: number;
}): Promise<ProbeResult> {
let lastStatus: number | null = null;
while (performance.now() < params.deadlineAt) {
if (params.isDone?.()) {
break;
}
const status = await requestStatus(params.port, params.path).catch(() => null);
lastStatus = status;
if (status === 200) {
return { ms: performance.now() - params.startAt, status };
}
await delay(25);
}
return { ms: null, status: lastStatus };
}
function requestStatus(port: number, pathname: string): Promise<number> {
return new Promise((resolve, reject) => {
const req = request(
{ host: "127.0.0.1", method: "GET", path: pathname, port, timeout: 100 },
(res) => {
res.resume();
res.on("end", () => resolve(res.statusCode ?? 0));
},
);
req.on("error", reject);
req.on("timeout", () => {
req.destroy(new Error("probe timeout"));
});
req.end();
});
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function writePluginFixtures(root: string, count: number): string[] {
const files: string[] = [];
const pluginsDir = path.join(root, "plugins");
mkdirSync(pluginsDir, { recursive: true });
for (let index = 0; index < count; index += 1) {
const id = `bench-plugin-${String(index + 1).padStart(2, "0")}`;
const pluginDir = path.join(pluginsDir, id);
mkdirSync(pluginDir, { recursive: true });
const entry = path.join(pluginDir, "index.cjs");
writeFileSync(entry, `module.exports = { id: ${JSON.stringify(id)}, register() {} };\n`);
writeFileSync(
path.join(pluginDir, "openclaw.plugin.json"),
`${JSON.stringify({ id, configSchema: { type: "object", additionalProperties: false } }, null, 2)}\n`,
);
files.push(entry);
}
return files;
}
function writeConfig(root: string, benchCase: GatewayBenchCase): string {
const pluginPaths = benchCase.pluginCount ? writePluginFixtures(root, benchCase.pluginCount) : [];
const config = {
...benchCase.config,
plugins: {
...(benchCase.config.plugins as Record<string, unknown> | undefined),
...(pluginPaths.length > 0
? {
load: { paths: pluginPaths },
allow: pluginPaths.map((file) => path.basename(path.dirname(file))),
}
: {}),
},
};
const configPath = path.join(root, "openclaw.json");
writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
return configPath;
}
function sanitizedEnv(
root: string,
configPath: string,
benchCase: GatewayBenchCase,
): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {
CI: process.env.CI ?? "1",
HOME: root,
LANG: process.env.LANG ?? "en_US.UTF-8",
LOGNAME: process.env.LOGNAME ?? "openclaw-bench",
NO_COLOR: "1",
PATH: process.env.PATH,
SHELL: process.env.SHELL,
TMPDIR: process.env.TMPDIR,
USER: process.env.USER ?? "openclaw-bench",
npm_config_update_notifier: "false",
OPENCLAW_CONFIG: configPath,
OPENCLAW_CONFIG_PATH: configPath,
OPENCLAW_GATEWAY_STARTUP_TRACE: "1",
OPENCLAW_HOME: root,
OPENCLAW_LOCAL_CHECK: "0",
OPENCLAW_STATE_DIR: path.join(root, "state"),
OPENCLAW_TEST_DISABLE_UPDATE_CHECK: "1",
...benchCase.env,
};
return env;
}
async function stopChild(child: ChildProcessWithoutNullStreams): Promise<{
exitCode: number | null;
signal: string | null;
}> {
if (child.exitCode != null || child.signalCode != null) {
return { exitCode: child.exitCode, signal: child.signalCode };
}
const exited = new Promise<{ exitCode: number | null; signal: string | null }>((resolve) => {
child.once("exit", (exitCode, signal) => resolve({ exitCode, signal }));
});
killProcessTree(child, "SIGTERM");
const timeout = delay(2000).then(() => {
if (child.exitCode == null && child.signalCode == null) {
killProcessTree(child, "SIGKILL");
}
return exited;
});
return Promise.race([exited, timeout]);
}
function killProcessTree(child: ChildProcessWithoutNullStreams, signal: NodeJS.Signals): void {
if (process.platform !== "win32" && child.pid !== undefined) {
try {
process.kill(-child.pid, signal);
return;
} catch {
// Fall back to the direct child below.
}
}
child.kill(signal);
}
function collectStartupTrace(line: string, startupTrace: Record<string, number>): void {
const match = /startup trace: ([^ ]+) ([0-9.]+)ms total=([0-9.]+)ms/u.exec(line);
if (!match) {
return;
}
startupTrace[match[1]] = Number(match[2]);
startupTrace[`${match[1]}.total`] = Number(match[3]);
}
async function runGatewaySample(options: {
benchCase: GatewayBenchCase;
entry: string;
timeoutMs: number;
}): Promise<GatewaySample> {
const root = mkdtempSync(path.join(tmpdir(), "openclaw-gateway-bench-"));
const port = await getFreePort();
const configPath = writeConfig(root, options.benchCase);
const env = sanitizedEnv(root, configPath, options.benchCase);
const startAt = performance.now();
const deadlineAt = startAt + options.timeoutMs;
const startupTrace: Record<string, number> = {};
const output: string[] = [];
let firstOutputMs: number | null = null;
let readyLogMs: number | null = null;
let childExited = false;
const child = spawn(
process.execPath,
[
options.entry,
"gateway",
"run",
"--port",
String(port),
"--bind",
"loopback",
"--auth",
"none",
"--tailscale",
"off",
"--allow-unconfigured",
],
{ cwd: process.cwd(), detached: process.platform !== "win32", env },
);
const childExitPromise = new Promise<{ exitCode: number | null; signal: string | null }>(
(resolve) => {
child.once("exit", (exitCode, signal) => {
childExited = true;
resolve({ exitCode, signal });
});
},
);
const onChunk = (chunk: Buffer) => {
if (firstOutputMs == null) {
firstOutputMs = performance.now() - startAt;
}
const text = chunk.toString("utf8");
output.push(text);
if (output.length > 20) {
output.splice(0, output.length - 20);
}
for (const line of text.split(/\r?\n/u)) {
if (line.includes("ready (") && readyLogMs == null) {
readyLogMs = performance.now() - startAt;
}
collectStartupTrace(line, startupTrace);
}
};
child.stdout.on("data", onChunk);
child.stderr.on("data", onChunk);
const [healthz, readyz] = await Promise.all([
waitForProbe({
deadlineAt,
isDone: () => childExited,
path: "/healthz",
port,
startAt,
}),
waitForProbe({
deadlineAt,
isDone: () => childExited,
path: "/readyz",
port,
startAt,
}),
]);
const exit = await stopChild(child);
await childExitPromise.catch(() => null);
rmSync(root, { force: true, maxRetries: 3, recursive: true, retryDelay: 100 });
return {
exitCode: exit.exitCode,
firstOutputMs,
healthz,
outputTail: output.join("").split(/\r?\n/u).slice(-20).join("\n"),
readyLogMs,
readyz,
signal: exit.signal,
startupTrace,
};
}
async function runCase(options: {
benchCase: GatewayBenchCase;
entry: string;
runs: number;
timeoutMs: number;
warmup: number;
}): Promise<CaseResult> {
const samples: GatewaySample[] = [];
const total = options.runs + options.warmup;
for (let index = 0; index < total; index += 1) {
const sample = await runGatewaySample({
benchCase: options.benchCase,
entry: options.entry,
timeoutMs: options.timeoutMs,
});
if (index >= options.warmup) {
samples.push(sample);
console.log(
`[gateway-startup-bench] ${options.benchCase.id} run ${samples.length}/${options.runs}: healthz=${formatMs(sample.healthz.ms)} readyz=${formatMs(sample.readyz.ms)} readyLog=${formatMs(sample.readyLogMs)}`,
);
} else {
console.log(
`[gateway-startup-bench] ${options.benchCase.id} warmup ${index + 1}/${options.warmup}: healthz=${formatMs(sample.healthz.ms)} readyz=${formatMs(sample.readyz.ms)}`,
);
}
}
return summarizeCase(options.benchCase, samples);
}
function printResult(result: CaseResult): void {
console.log(`\n${result.name} (${result.id})`);
console.log(` first output: ${formatStats(result.summary.firstOutputMs)}`);
console.log(` /healthz: ${formatStats(result.summary.healthzMs)}`);
console.log(` ready log: ${formatStats(result.summary.readyLogMs)}`);
console.log(` /readyz: ${formatStats(result.summary.readyzMs)}`);
const trace = Object.entries(result.summary.startupTrace)
.filter(([name]) => !name.endsWith(".total"))
.toSorted((a, b) => (b[1].avg ?? 0) - (a[1].avg ?? 0))
.slice(0, 8);
if (trace.length > 0) {
console.log(" trace top:");
for (const [name, stats] of trace) {
console.log(` ${name}: ${formatStats(stats)}`);
}
}
}
async function main() {
const options = parseOptions();
const results: CaseResult[] = [];
for (const benchCase of options.cases) {
results.push(
await runCase({
benchCase,
entry: options.entry,
runs: options.runs,
timeoutMs: options.timeoutMs,
warmup: options.warmup,
}),
);
}
const payload = {
entry: options.entry,
generatedAt: new Date().toISOString(),
results,
};
if (options.output) {
mkdirSync(path.dirname(options.output), { recursive: true });
writeFileSync(options.output, `${JSON.stringify(payload, null, 2)}\n`);
}
if (options.json) {
console.log(JSON.stringify(payload, null, 2));
return;
}
for (const result of results) {
printResult(result);
}
}
main().catch((err) => {
console.error(err instanceof Error ? err.stack : String(err));
process.exitCode = 1;
});