mirror of
https://github.com/nodejs/node.git
synced 2026-11-25 23:01:06 -05:00
build,win: add PGO workload scripts
Signed-off-by: StefanStojanovic <stefan.stojanovic@janeasystems.com> PR-URL: https://github.com/nodejs/node/pull/63696 Refs: https://github.com/nodejs/node/issues/61964 Reviewed-By: Richard Lau <richard.lau@ibm.com>
This commit is contained in:
1 parent
ea4b37fe59
commit
58d58a47e3
14 files changed
+5643
No files matched your search
@@ -0,0 +1,162 @@
|
||||
# PGO (Profile-Guided Optimization) training script for Node.js (Clang / LLVM)
|
||||
#
|
||||
# Runs PGO training workloads against an instrumented Node.js binary
|
||||
# (Release\node.exe) and merges the resulting .profraw files into
|
||||
# node.profdata for use with -fprofile-use.
|
||||
#
|
||||
# Usage (from a VS Developer Command Prompt):
|
||||
# .\pgo.ps1 # Run workloads (15s each) and merge
|
||||
# .\pgo.ps1 -Duration 30 # Run workloads (30s each) and merge
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Release\node.exe must be an instrumented build (built with pgo-generate)
|
||||
# - llvm-profdata must be available (shipped with VS LLVM toolset)
|
||||
#
|
||||
# Output:
|
||||
# - node.profdata in the repo root (ready for vcbuild.bat pgo-use)
|
||||
|
||||
param(
|
||||
[int]$Duration = 15
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Locate llvm-profdata shipped with Visual Studio's LLVM toolset
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function Find-LlvmProfdata {
|
||||
# vcbuild.bat uses %VCINSTALLDIR%\Tools\Llvm\x64\bin for clang.exe - same spot for profdata
|
||||
$vcInstallDir = $env:VCINSTALLDIR
|
||||
|
||||
if ($vcInstallDir) {
|
||||
$candidate = Join-Path $vcInstallDir "Tools\Llvm\x64\bin\llvm-profdata.exe"
|
||||
if (Test-Path $candidate) {
|
||||
return $candidate
|
||||
}
|
||||
}
|
||||
|
||||
# Fallback: try VS 2022 / 2026 default install locations
|
||||
$vsPaths = @(
|
||||
"${env:ProgramFiles}\Microsoft Visual Studio\2026\Enterprise\VC\Tools\Llvm\x64\bin",
|
||||
"${env:ProgramFiles}\Microsoft Visual Studio\2026\Community\VC\Tools\Llvm\x64\bin",
|
||||
"${env:ProgramFiles}\Microsoft Visual Studio\2022\Enterprise\VC\Tools\Llvm\x64\bin",
|
||||
"${env:ProgramFiles}\Microsoft Visual Studio\2022\Community\VC\Tools\Llvm\x64\bin"
|
||||
)
|
||||
foreach ($dir in $vsPaths) {
|
||||
$candidate = Join-Path $dir "llvm-profdata.exe"
|
||||
if (Test-Path $candidate) {
|
||||
return $candidate
|
||||
}
|
||||
}
|
||||
|
||||
# Last resort: PATH
|
||||
$fromPath = Get-Command llvm-profdata -ErrorAction SilentlyContinue
|
||||
if ($fromPath) {
|
||||
return $fromPath.Source
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Validate prerequisites
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
$instrumentedNode = Join-Path $PSScriptRoot "Release\node.exe"
|
||||
if (-not (Test-Path $instrumentedNode)) {
|
||||
Write-Error "Instrumented binary not found: $instrumentedNode`nBuild with: vcbuild.bat pgo-generate"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$pgoRunAll = Join-Path $PSScriptRoot "tools\pgo\pgo-run-all.js"
|
||||
if (-not (Test-Path $pgoRunAll)) {
|
||||
Write-Error "PGO training script not found: $pgoRunAll"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$llvmProfdata = Find-LlvmProfdata
|
||||
if (-not $llvmProfdata) {
|
||||
Write-Error "llvm-profdata not found. Install the LLVM toolset via Visual Studio Installer."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# STEP 1 – Run workloads with the instrumented binary to collect profiles
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Write-Host "`n=== STEP 1: Collect PGO profiles ===" -ForegroundColor Cyan
|
||||
|
||||
# Directory that will receive .profraw files from the instrumented binary.
|
||||
# %p (PID) and %m (module hash) keep concurrent/fork'd processes from colliding.
|
||||
$profileDir = Join-Path $PSScriptRoot "pgo-profiles"
|
||||
|
||||
if (Test-Path $profileDir) {
|
||||
Remove-Item -Recurse -Force $profileDir
|
||||
}
|
||||
New-Item -ItemType Directory -Path $profileDir | Out-Null
|
||||
|
||||
$env:LLVM_PROFILE_FILE = Join-Path $profileDir "node-%p-%m.profraw"
|
||||
|
||||
Write-Host "Instrumented node : $instrumentedNode"
|
||||
Write-Host "Profile output : $($env:LLVM_PROFILE_FILE)"
|
||||
Write-Host "Duration per script: ${Duration}s"
|
||||
Write-Host ""
|
||||
|
||||
$sw = [System.Diagnostics.Stopwatch]::StartNew()
|
||||
$proc = Start-Process `
|
||||
-FilePath $instrumentedNode `
|
||||
-ArgumentList "`"$pgoRunAll`" --verbose --duration=$Duration" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
$sw.Stop()
|
||||
Write-Host ("PGO training completed in {0}m {1}s (exit code: {2})" -f `
|
||||
$sw.Elapsed.Minutes, $sw.Elapsed.Seconds, $proc.ExitCode)
|
||||
if ($proc.ExitCode -ne 0) {
|
||||
Write-Warning "PGO training exited with code $($proc.ExitCode) - continuing with merge"
|
||||
}
|
||||
|
||||
# Remove the env var so subsequent builds are not affected
|
||||
Remove-Item Env:\LLVM_PROFILE_FILE -ErrorAction SilentlyContinue
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# STEP 2 – Merge .profraw files -> node.profdata
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Write-Host "`n=== STEP 2: Merge profile data ===" -ForegroundColor Cyan
|
||||
|
||||
Write-Host "Using llvm-profdata: $llvmProfdata"
|
||||
|
||||
$profrawFiles = Get-ChildItem -Path $profileDir -Filter "*.profraw" -ErrorAction SilentlyContinue
|
||||
if ($profrawFiles.Count -eq 0) {
|
||||
Write-Error "No .profraw files found in '$profileDir'. The instrumented binary may not have generated profile data."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$totalSize = ($profrawFiles | Measure-Object -Property Length -Sum).Sum
|
||||
$totalSizeMB = [math]::Round($totalSize / 1MB, 1)
|
||||
Write-Host "Found $($profrawFiles.Count) .profraw file(s), ${totalSizeMB} MB total"
|
||||
|
||||
$profdata = Join-Path $PSScriptRoot "node.profdata"
|
||||
$mergeArgs = @("merge", "--output=$profdata") + ($profrawFiles | Select-Object -ExpandProperty FullName)
|
||||
|
||||
$mergeStopwatch = [System.Diagnostics.Stopwatch]::StartNew()
|
||||
& $llvmProfdata @mergeArgs
|
||||
$mergeExitCode = $LASTEXITCODE
|
||||
$mergeStopwatch.Stop()
|
||||
|
||||
if ($mergeExitCode -ne 0) {
|
||||
Write-Error "llvm-profdata merge failed (exit code $mergeExitCode)"
|
||||
exit $mergeExitCode
|
||||
}
|
||||
|
||||
$profdataSize = [math]::Round((Get-Item $profdata).Length / 1MB, 1)
|
||||
Write-Host "Merge completed in $([math]::Round($mergeStopwatch.Elapsed.TotalSeconds, 1))s"
|
||||
|
||||
# Clean up .profraw files now that they've been merged
|
||||
Remove-Item -Recurse -Force $profileDir
|
||||
Write-Host "Removed $($profrawFiles.Count) .profraw file(s) (${totalSizeMB} MB reclaimed)"
|
||||
|
||||
Write-Host "`n=== PGO training complete ===" -ForegroundColor Green
|
||||
Write-Host " Profile data: $profdata (${profdataSize} MB)"
|
||||
Write-Host " Next step: vcbuild.bat pgo-use"
|
||||
@@ -0,0 +1,98 @@
|
||||
# Node.js PGO Training Scripts
|
||||
|
||||
Training workloads for Profile-Guided Optimization (PGO) builds using
|
||||
Clang/LLVM (including Clang-CL on Windows).
|
||||
|
||||
## What is PGO?
|
||||
|
||||
PGO uses runtime profile data to guide compiler optimizations (inlining,
|
||||
branch prediction, code layout), typically improving throughput by 5-20%.
|
||||
|
||||
The process has three phases:
|
||||
|
||||
1. **Instrument** — Build with `-fprofile-generate` (produces `.profraw` files)
|
||||
2. **Train** — Run representative workloads to collect profile data
|
||||
3. **Optimize** — Merge `.profraw` → `node.profdata` via `llvm-profdata`,
|
||||
then rebuild with `-fprofile-use`
|
||||
|
||||
## Quick Start
|
||||
|
||||
From a VS Developer Command Prompt:
|
||||
|
||||
```powershell
|
||||
# Step 1: Build the instrumented binary
|
||||
vcbuild.bat pgo-generate
|
||||
|
||||
# Step 2: Run workloads and merge profile data
|
||||
.\pgo.ps1
|
||||
|
||||
# Step 3: Build the optimized binary
|
||||
vcbuild.bat pgo-use
|
||||
```
|
||||
|
||||
`pgo.ps1` expects the instrumented binary at `Release\node.exe` (produced by
|
||||
step 1) and writes `node.profdata` to the repo root (consumed by step 3).
|
||||
|
||||
```powershell
|
||||
# Optionally set a longer training duration (default: 15s per script)
|
||||
.\pgo.ps1 -Duration 30
|
||||
```
|
||||
|
||||
## Training Scripts
|
||||
|
||||
All scripts use only Node.js built-in modules (no npm dependencies).
|
||||
Each script is run as a separate process via `fork()`, producing its own
|
||||
`.profraw` file.
|
||||
|
||||
| Script | What it exercises |
|
||||
| ------------------------ | ------------------------------------------------------------- |
|
||||
| `pgo-http-server.js` | llhttp parser, TCP stack, header serialization, JSON, routing |
|
||||
| `pgo-json.js` | V8 JSON parser/serializer, string allocation, GC pressure |
|
||||
| `pgo-crypto.js` | OpenSSL (hashing, HMAC, AES, RSA, ECDSA, random, KDF) |
|
||||
| `pgo-streams-buffers.js` | Buffer C++ impl, stream state machine, back-pressure |
|
||||
| `pgo-fs.js` | libuv fs operations, thread pool, path module |
|
||||
| `pgo-async-patterns.js` | V8 Promises, microtask queue, EventEmitter, timers |
|
||||
| `pgo-url-string.js` | Ada URL parser, V8 string internals, regex JIT |
|
||||
| `pgo-compression.js` | zlib, brotli C libraries, streaming compression |
|
||||
| `pgo-net.js` | libuv TCP/pipe handles, c-ares DNS resolver |
|
||||
| `pgo-module-loading.js` | Module resolver, V8 script compilation, vm module |
|
||||
| `pgo-child-workers.js` | Worker thread messaging, SharedArrayBuffer, inline eval |
|
||||
|
||||
### Running the Orchestrator Directly
|
||||
|
||||
The orchestrator can also be invoked directly (e.g. for testing individual
|
||||
workloads). When used with `pgo.ps1`, this is handled automatically.
|
||||
|
||||
```bash
|
||||
# Run all scripts
|
||||
node tools/pgo/pgo-run-all.js --duration=15 --verbose
|
||||
|
||||
# Run specific scripts
|
||||
node tools/pgo/pgo-run-all.js --scripts=http-server,json,crypto --duration=30
|
||||
|
||||
# Show help
|
||||
node tools/pgo/pgo-run-all.js --help
|
||||
```
|
||||
|
||||
Each script reads the `PGO_TRAINING_DURATION` environment variable (in
|
||||
milliseconds) to determine how long to run. The orchestrator sets this
|
||||
automatically from the `--duration` flag (in seconds).
|
||||
|
||||
## Files
|
||||
|
||||
```
|
||||
tools/pgo/
|
||||
├── pgo-run-all.js # Training orchestrator
|
||||
├── pgo-http-server.js # HTTP server + client workload
|
||||
├── pgo-json.js # JSON parse/stringify workload
|
||||
├── pgo-crypto.js # Crypto operations workload
|
||||
├── pgo-streams-buffers.js # Streams and Buffer workload
|
||||
├── pgo-fs.js # File system operations workload
|
||||
├── pgo-async-patterns.js # Promise/async, EventEmitter, timers workload
|
||||
├── pgo-url-string.js # URL parsing, string ops, regex workload
|
||||
├── pgo-compression.js # Gzip/brotli/deflate compression workload
|
||||
├── pgo-net.js # TCP networking and DNS workload
|
||||
├── pgo-module-loading.js # Module require/import, VM compilation workload
|
||||
├── pgo-child-workers.js # Worker threads workload
|
||||
└── README.md # This file
|
||||
```
|
||||
@@ -0,0 +1,467 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable no-void */
|
||||
|
||||
// PGO Training Script: Async Patterns, Timers, and Events
|
||||
//
|
||||
// Modern Node.js code is dominated by async/await and Promises.
|
||||
// This script exercises:
|
||||
// - Promise creation, chaining, and resolution (every async operation)
|
||||
// - async/await control flow (the primary coding pattern)
|
||||
// - Promise.all/allSettled/race/any (concurrent operation patterns)
|
||||
// - EventEmitter (backbone of all Node.js I/O)
|
||||
// - Timers: setTimeout, setInterval, setImmediate (scheduling)
|
||||
// - AbortController/AbortSignal (cancellation - growing usage)
|
||||
// - queueMicrotask / process.nextTick (microtask scheduling)
|
||||
// - AsyncLocalStorage (request context propagation - growing fast)
|
||||
//
|
||||
// This exercises: V8 Promise machinery, microtask queue, libuv timer heap,
|
||||
// EventEmitter C++/JS boundary, AbortSignal C++ implementation.
|
||||
|
||||
const { EventEmitter } = require('events');
|
||||
const { AsyncLocalStorage } = require('async_hooks');
|
||||
const {
|
||||
setTimeout: setTimeoutPromise,
|
||||
setImmediate: setImmediatePromise,
|
||||
} = require('timers/promises');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
|
||||
// Workload 1: Promise chains (REST API middleware pattern)
|
||||
async function workloadPromiseChains(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Simple promise chain (Express middleware-like)
|
||||
await Promise.resolve({ method: 'GET', url: '/api/users' })
|
||||
.then((req) => ({ ...req, authenticated: true }))
|
||||
.then((req) => ({ ...req, parsed: true, body: {} }))
|
||||
.then((req) => ({ ...req, validated: true }))
|
||||
.then(() => ({
|
||||
status: 200,
|
||||
body: JSON.stringify({ users: [], total: 0 }),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
ops++;
|
||||
|
||||
// Promise with error handling (try/catch in async flow)
|
||||
try {
|
||||
await Promise.resolve(i)
|
||||
.then((v) => {
|
||||
if (v % 7 === 0) throw new Error('validation');
|
||||
return v;
|
||||
})
|
||||
.then((v) => v * 2)
|
||||
.catch((err) => ({ error: err.message }));
|
||||
ops++;
|
||||
} catch {
|
||||
ops++;
|
||||
}
|
||||
|
||||
// Nested promise resolution (database query pattern)
|
||||
const result = await new Promise((resolve) => {
|
||||
// Simulate async work
|
||||
resolve({
|
||||
rows: Array.from({ length: 10 }, (_, j) => ({ id: j, value: i + j })),
|
||||
});
|
||||
});
|
||||
await new Promise((resolve) => {
|
||||
resolve(result.rows.map((r) => ({ ...r, processed: true })));
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: Promise.all / allSettled / race / any (concurrent patterns)
|
||||
async function workloadPromiseConcurrency(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Promise.all (parallel database queries, batch API calls)
|
||||
await Promise.all(
|
||||
Array.from({ length: 20 }, (_, j) =>
|
||||
Promise.resolve({ id: j, data: `result_${j}` }),
|
||||
),
|
||||
);
|
||||
ops++;
|
||||
|
||||
// Promise.allSettled (fault-tolerant batch operations)
|
||||
await Promise.allSettled(
|
||||
Array.from({ length: 15 }, (_, j) =>
|
||||
(j % 5 === 0 ?
|
||||
Promise.reject(new Error(`fail_${j}`)) :
|
||||
Promise.resolve({ id: j, ok: true })),
|
||||
),
|
||||
);
|
||||
ops++;
|
||||
|
||||
// Promise.race (timeout pattern)
|
||||
await Promise.race([
|
||||
Promise.resolve('fast'),
|
||||
new Promise((resolve) => setTimeout(resolve, 10000, 'slow')),
|
||||
]);
|
||||
ops++;
|
||||
|
||||
// Promise.any (failover pattern)
|
||||
await Promise.any([
|
||||
Promise.reject(new Error('server1')),
|
||||
Promise.resolve('server2'),
|
||||
Promise.resolve('server3'),
|
||||
]);
|
||||
ops++;
|
||||
|
||||
// Batched parallel with limit (connection pool pattern)
|
||||
const batchSize = 5;
|
||||
const items = Array.from({ length: 20 }, (_, j) => j);
|
||||
for (let start = 0; start < items.length; start += batchSize) {
|
||||
const batch = items.slice(start, start + batchSize);
|
||||
await Promise.all(batch.map((item) => Promise.resolve(item * 2)));
|
||||
}
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: EventEmitter (core Node.js pattern)
|
||||
function workloadEventEmitter(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const emitter = new EventEmitter();
|
||||
|
||||
// Add multiple listeners (typical server setup)
|
||||
const listeners = [];
|
||||
for (let j = 0; j < 10; j++) {
|
||||
const listener = (data) => {
|
||||
data.processed = true;
|
||||
};
|
||||
listeners.push(listener);
|
||||
emitter.on('data', listener);
|
||||
}
|
||||
ops++;
|
||||
|
||||
// Once listener (connection setup pattern)
|
||||
emitter.once('connect', () => {});
|
||||
emitter.once('ready', () => {});
|
||||
ops++;
|
||||
|
||||
// Emit events (hot path in I/O)
|
||||
for (let j = 0; j < 100; j++) {
|
||||
emitter.emit('data', { id: j, value: j * 2 });
|
||||
}
|
||||
ops += 100;
|
||||
|
||||
// Emit with multiple arguments
|
||||
for (let j = 0; j < 20; j++) {
|
||||
emitter.emit('data', { id: j }, 'extra', j);
|
||||
}
|
||||
ops += 20;
|
||||
|
||||
// Error event handling
|
||||
emitter.on('error', () => {});
|
||||
emitter.emit('error', new Error('test'));
|
||||
ops++;
|
||||
|
||||
// listenerCount / listeners (monitoring)
|
||||
emitter.listenerCount('data');
|
||||
emitter.listeners('data');
|
||||
emitter.rawListeners('data');
|
||||
emitter.eventNames();
|
||||
ops += 4;
|
||||
|
||||
// Remove listeners (cleanup)
|
||||
for (const listener of listeners) {
|
||||
emitter.removeListener('data', listener);
|
||||
}
|
||||
emitter.removeAllListeners();
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 4: EventTarget (Web API compatibility — growing usage)
|
||||
function workloadEventTarget(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const target = new EventTarget();
|
||||
|
||||
// Add listeners
|
||||
const handlers = [];
|
||||
for (let j = 0; j < 5; j++) {
|
||||
const handler = (e) => {
|
||||
void e.detail;
|
||||
};
|
||||
handlers.push(handler);
|
||||
target.addEventListener('message', handler);
|
||||
}
|
||||
ops++;
|
||||
|
||||
// Dispatch events
|
||||
for (let j = 0; j < 50; j++) {
|
||||
target.dispatchEvent(new Event('message'));
|
||||
}
|
||||
ops += 50;
|
||||
|
||||
// Remove listeners
|
||||
for (const handler of handlers) {
|
||||
target.removeEventListener('message', handler);
|
||||
}
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: Timers (setTimeout, setInterval, setImmediate)
|
||||
async function workloadTimers(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// setTimeout with 0 (defer to next event loop - very common)
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
ops++;
|
||||
|
||||
// setImmediate (process next I/O callbacks first)
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
ops++;
|
||||
|
||||
// setTimeout promise API
|
||||
await setTimeoutPromise(0);
|
||||
ops++;
|
||||
|
||||
// setImmediate promise API
|
||||
await setImmediatePromise();
|
||||
ops++;
|
||||
|
||||
// Timer creation and cancellation (debounce/throttle patterns)
|
||||
for (let j = 0; j < 10; j++) {
|
||||
const timer = setTimeout(() => {}, 10000);
|
||||
clearTimeout(timer);
|
||||
}
|
||||
ops += 10;
|
||||
|
||||
// setInterval + clearInterval (polling pattern)
|
||||
const interval = setInterval(() => {}, 1000);
|
||||
clearInterval(interval);
|
||||
ops++;
|
||||
|
||||
// process.nextTick (microtask — higher priority than timers)
|
||||
await new Promise((resolve) => process.nextTick(resolve));
|
||||
ops++;
|
||||
|
||||
// queueMicrotask
|
||||
await new Promise((resolve) => queueMicrotask(resolve));
|
||||
ops++;
|
||||
|
||||
// Nested nextTick/microtask (realistic: multiple middleware layers)
|
||||
await new Promise((outerResolve) => {
|
||||
process.nextTick(() => {
|
||||
queueMicrotask(() => {
|
||||
process.nextTick(() => {
|
||||
outerResolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 6: AbortController (cancellation — widely used since Node.js 16+)
|
||||
async function workloadAbortController(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Create and signal (timeout pattern)
|
||||
const ac1 = new AbortController();
|
||||
const { signal: sig1 } = ac1;
|
||||
sig1.addEventListener('abort', () => {});
|
||||
ac1.abort();
|
||||
ops++;
|
||||
|
||||
// AbortSignal.timeout (modern API)
|
||||
const sig2 = AbortSignal.timeout(5000);
|
||||
void sig2.aborted; // check status
|
||||
ops++;
|
||||
|
||||
// AbortSignal.any (composite signals)
|
||||
const ac3 = new AbortController();
|
||||
const sig3 = AbortSignal.any([ac3.signal, AbortSignal.timeout(10000)]);
|
||||
sig3.addEventListener('abort', () => {});
|
||||
ac3.abort('cancelled');
|
||||
ops++;
|
||||
|
||||
// Using with setTimeout (common pattern)
|
||||
try {
|
||||
const ac = new AbortController();
|
||||
const timer = setTimeout(() => ac.abort(), 0);
|
||||
await setTimeoutPromise(0, undefined, { signal: ac.signal });
|
||||
clearTimeout(timer);
|
||||
ops++;
|
||||
} catch {
|
||||
ops++; // AbortError is expected sometimes
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 7: AsyncLocalStorage (request context — Express, Fastify, Nest.js)
|
||||
async function workloadAsyncLocalStorage(iterations) {
|
||||
let ops = 0;
|
||||
const als = new AsyncLocalStorage();
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Run with context (HTTP request lifecycle)
|
||||
await als.run(
|
||||
{ requestId: `req-${i}`, userId: `user-${i % 100}` },
|
||||
async () => {
|
||||
const store = als.getStore();
|
||||
|
||||
// "Middleware" that reads context
|
||||
void store.requestId;
|
||||
|
||||
// "Service" layer — context propagates through async calls
|
||||
await Promise.resolve().then(() => {
|
||||
const ctx = als.getStore();
|
||||
return { ...ctx, processed: true };
|
||||
});
|
||||
|
||||
// Nested async operation with context
|
||||
await new Promise((resolve) => {
|
||||
setImmediate(() => {
|
||||
const ctx = als.getStore();
|
||||
resolve(ctx);
|
||||
});
|
||||
});
|
||||
|
||||
ops++;
|
||||
},
|
||||
);
|
||||
|
||||
// enterWith pattern (alternative API)
|
||||
als.enterWith({ contextId: i });
|
||||
als.getStore();
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 8: Error creation and stack traces (very frequent in real apps)
|
||||
function workloadErrors(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Error creation with stack trace
|
||||
const err1 = new Error(`Something went wrong: ${i}`);
|
||||
void err1.stack; // Access stack (forces stack trace computation)
|
||||
void err1.message;
|
||||
ops++;
|
||||
|
||||
// TypeError (most common runtime error)
|
||||
const err2 = new TypeError(`Cannot read property of undefined`);
|
||||
void err2.stack;
|
||||
ops++;
|
||||
|
||||
// RangeError
|
||||
const err3 = new RangeError(`Value out of range: ${i}`);
|
||||
err3.code = 'ERR_OUT_OF_RANGE';
|
||||
void err3.stack;
|
||||
ops++;
|
||||
|
||||
// try/catch (V8's exception handling path)
|
||||
for (let j = 0; j < 10; j++) {
|
||||
try {
|
||||
if (j % 3 === 0) throw new Error(`Caught error ${j}`);
|
||||
if (j % 7 === 0) throw new TypeError(`Type error ${j}`);
|
||||
} catch (e) {
|
||||
void e.message; // Access message
|
||||
}
|
||||
}
|
||||
ops += 10;
|
||||
|
||||
// Error.captureStackTrace (custom errors pattern)
|
||||
class AppError extends Error {
|
||||
constructor(message, code) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
Error.captureStackTrace(this, AppError);
|
||||
}
|
||||
}
|
||||
const err4 = new AppError('Not found', 404);
|
||||
void err4.stack;
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-async-patterns] Starting async patterns workload...');
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// Promise chains (extremely high frequency)
|
||||
if (round === 1)
|
||||
console.log('[pgo-async-patterns] Running promise chains...');
|
||||
totalOps += await workloadPromiseChains(iterScale(500));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Promise concurrency
|
||||
if (round === 1)
|
||||
console.log('[pgo-async-patterns] Running promise concurrency...');
|
||||
totalOps += await workloadPromiseConcurrency(iterScale(200));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// EventEmitter (core pattern)
|
||||
if (round === 1)
|
||||
console.log('[pgo-async-patterns] Running EventEmitter...');
|
||||
totalOps += workloadEventEmitter(iterScale(200));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// EventTarget
|
||||
if (round === 1) console.log('[pgo-async-patterns] Running EventTarget...');
|
||||
totalOps += workloadEventTarget(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Timers
|
||||
if (round === 1) console.log('[pgo-async-patterns] Running timers...');
|
||||
totalOps += await workloadTimers(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// AbortController
|
||||
if (round === 1)
|
||||
console.log('[pgo-async-patterns] Running AbortController...');
|
||||
totalOps += await workloadAbortController(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// AsyncLocalStorage
|
||||
if (round === 1)
|
||||
console.log('[pgo-async-patterns] Running AsyncLocalStorage...');
|
||||
totalOps += await workloadAsyncLocalStorage(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Errors
|
||||
if (round === 1)
|
||||
console.log('[pgo-async-patterns] Running error patterns...');
|
||||
totalOps += workloadErrors(iterScale(300));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-async-patterns] Completed ${totalOps} ops in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-async-patterns] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,284 @@
|
||||
'use strict';
|
||||
|
||||
// PGO Training Script: Worker Threads
|
||||
//
|
||||
// Node.js Worker threads are used for:
|
||||
// - CPU-intensive parallel work (image processing, parsing, compilation)
|
||||
// - Thread pool patterns for offloading blocking work
|
||||
// - SharedArrayBuffer-based parallel computation
|
||||
// - Inline eval workers (used by some frameworks)
|
||||
//
|
||||
// This exercises: Worker thread messaging, structured clone serialization,
|
||||
// SharedArrayBuffer, Atomics, V8 isolate creation, module loading in workers.
|
||||
//
|
||||
// Note: child_process.spawn/fork are excluded from PGO training because each
|
||||
// spawned process generates its own .profraw file, creating hundreds of
|
||||
// startup-heavy profiles that dilute the steady-state profile data.
|
||||
|
||||
const { Worker, isMainThread } = require('worker_threads');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const fs = require('fs');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
const TEMP_DIR = path.join(
|
||||
os.tmpdir(),
|
||||
`node-pgo-workers-${process.pid}-${Date.now()}`,
|
||||
);
|
||||
|
||||
function setup() {
|
||||
fs.mkdirSync(TEMP_DIR, { recursive: true });
|
||||
|
||||
// Write worker script files
|
||||
fs.writeFileSync(
|
||||
path.join(TEMP_DIR, 'worker-cpu.js'),
|
||||
`
|
||||
'use strict';
|
||||
const { parentPort, workerData } = require('worker_threads');
|
||||
|
||||
// CPU-intensive work: hash computation, JSON processing, regex
|
||||
function doWork(data) {
|
||||
const crypto = require('crypto');
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < data.iterations; i++) {
|
||||
// Hash computation
|
||||
const hash = crypto.createHash('sha256')
|
||||
.update(JSON.stringify({ index: i, data: data.payload }))
|
||||
.digest('hex');
|
||||
|
||||
// JSON round-trip
|
||||
const obj = JSON.parse(JSON.stringify({
|
||||
id: i,
|
||||
hash,
|
||||
timestamp: Date.now(),
|
||||
nested: { a: { b: { c: i } } },
|
||||
}));
|
||||
|
||||
// Regex processing
|
||||
const text = 'The quick brown fox jumps over the lazy dog '.repeat(10);
|
||||
const matches = text.match(/\\b\\w{4,}\\b/g) || [];
|
||||
|
||||
results.push({ hash: hash.slice(0, 8), matches: matches.length });
|
||||
}
|
||||
|
||||
return { count: results.length, sample: results[0] };
|
||||
}
|
||||
|
||||
parentPort.on('message', (msg) => {
|
||||
if (msg.type === 'work') {
|
||||
const result = doWork(msg.data);
|
||||
parentPort.postMessage({ type: 'result', data: result });
|
||||
}
|
||||
if (msg.type === 'exit') {
|
||||
process.exit(0);
|
||||
}
|
||||
});
|
||||
|
||||
// Also handle direct workerData
|
||||
if (workerData && workerData.autoStart) {
|
||||
const result = doWork(workerData);
|
||||
parentPort.postMessage({ type: 'result', data: result });
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(TEMP_DIR, 'worker-shared.js'),
|
||||
`
|
||||
'use strict';
|
||||
const { parentPort, workerData } = require('worker_threads');
|
||||
|
||||
// Shared memory worker: operates on SharedArrayBuffer
|
||||
const { buffer, offset, length } = workerData;
|
||||
const view = new Int32Array(buffer);
|
||||
|
||||
// Process assigned segment
|
||||
for (let i = offset; i < offset + length; i++) {
|
||||
// Atomic operations
|
||||
Atomics.add(view, i, 1);
|
||||
Atomics.load(view, i);
|
||||
}
|
||||
|
||||
parentPort.postMessage({ done: true, processed: length });
|
||||
`,
|
||||
);
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
try {
|
||||
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
}
|
||||
|
||||
// Workload 1: Worker threads — message passing (the dominant pattern)
|
||||
async function workloadWorkerMessages(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const worker = new Worker(path.join(TEMP_DIR, 'worker-cpu.js'));
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
worker.on('message', (msg) => {
|
||||
if (msg.type === 'result') {
|
||||
ops++;
|
||||
worker.postMessage({ type: 'exit' });
|
||||
}
|
||||
});
|
||||
worker.on('exit', resolve);
|
||||
worker.on('error', reject);
|
||||
|
||||
// Send work
|
||||
worker.postMessage({
|
||||
type: 'work',
|
||||
data: { iterations: 50, payload: `batch_${i}` },
|
||||
});
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: Worker threads — workerData initialization
|
||||
async function workloadWorkerData(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const worker = new Worker(path.join(TEMP_DIR, 'worker-cpu.js'), {
|
||||
workerData: { autoStart: true, iterations: 30, payload: `init_${i}` },
|
||||
});
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
worker.on('message', (msg) => {
|
||||
if (msg.type === 'result') {
|
||||
ops++;
|
||||
worker.terminate();
|
||||
}
|
||||
});
|
||||
worker.on('exit', resolve);
|
||||
worker.on('error', reject);
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: Worker threads — SharedArrayBuffer (parallel computation)
|
||||
async function workloadSharedMemory(iterations) {
|
||||
let ops = 0;
|
||||
const ARRAY_SIZE = 1024;
|
||||
const NUM_WORKERS = Math.min(4, os.cpus().length);
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const sharedBuffer = new SharedArrayBuffer(ARRAY_SIZE * 4); // Int32Array
|
||||
const segmentSize = Math.floor(ARRAY_SIZE / NUM_WORKERS);
|
||||
|
||||
const workers = [];
|
||||
const promises = [];
|
||||
|
||||
for (let w = 0; w < NUM_WORKERS; w++) {
|
||||
const worker = new Worker(path.join(TEMP_DIR, 'worker-shared.js'), {
|
||||
workerData: {
|
||||
buffer: sharedBuffer,
|
||||
offset: w * segmentSize,
|
||||
length: segmentSize,
|
||||
},
|
||||
});
|
||||
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
worker.on('message', (msg) => {
|
||||
ops++;
|
||||
resolve(msg);
|
||||
});
|
||||
worker.on('error', reject);
|
||||
worker.on('exit', () => resolve());
|
||||
});
|
||||
|
||||
workers.push(worker);
|
||||
promises.push(promise);
|
||||
}
|
||||
|
||||
await Promise.all(promises);
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 4: Worker from inline code (eval pattern — used by some frameworks)
|
||||
async function workloadInlineWorker(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const code = `
|
||||
const { parentPort } = require('worker_threads');
|
||||
const crypto = require('crypto');
|
||||
const result = crypto.createHash('sha256').update('data-${i}').digest('hex');
|
||||
parentPort.postMessage({ hash: result });
|
||||
`;
|
||||
|
||||
const worker = new Worker(code, { eval: true });
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
worker.on('message', (msg) => {
|
||||
ops++;
|
||||
resolve(msg);
|
||||
});
|
||||
worker.on('error', reject);
|
||||
worker.on('exit', () => resolve());
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (!isMainThread) return; // Guard against being loaded as worker
|
||||
|
||||
console.log('[pgo-child-workers] Starting worker thread workload...');
|
||||
|
||||
setup();
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
try {
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// Worker threads (most impactful for PGO)
|
||||
if (round === 1)
|
||||
console.log('[pgo-child-workers] Running worker messages...');
|
||||
totalOps += await workloadWorkerMessages(iterScale(10));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-child-workers] Running workerData init...');
|
||||
totalOps += await workloadWorkerData(iterScale(10));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-child-workers] Running shared memory workers...');
|
||||
totalOps += await workloadSharedMemory(iterScale(5));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-child-workers] Running inline workers...');
|
||||
totalOps += await workloadInlineWorker(iterScale(10));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-child-workers] Completed ${totalOps} ops in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-child-workers] Error:', err);
|
||||
cleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,417 @@
|
||||
'use strict';
|
||||
|
||||
// PGO Training Script: Compression (zlib/brotli)
|
||||
//
|
||||
// HTTP response compression is used on virtually every production Node.js server.
|
||||
// This script exercises:
|
||||
// - gzip compression/decompression (the most common HTTP content-encoding)
|
||||
// - deflate compression/decompression
|
||||
// - brotli compression/decompression (modern, better ratio)
|
||||
// - Streaming compression (piped through HTTP responses)
|
||||
// - One-shot compression (in-memory buffers)
|
||||
// - Various compression levels and data types
|
||||
// - CRC-32 computation
|
||||
//
|
||||
// This exercises: zlib C library, brotli C library, libuv thread pool
|
||||
// (async compression), stream infrastructure, Buffer allocation.
|
||||
|
||||
const zlib = require('zlib');
|
||||
const crypto = require('crypto');
|
||||
const { pipeline } = require('stream/promises');
|
||||
const { Readable, Writable } = require('stream');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
|
||||
// Test data of different types and sizes (compression ratio varies)
|
||||
const JSON_DATA = Buffer.from(
|
||||
JSON.stringify({
|
||||
users: Array.from({ length: 200 }, (_, i) => ({
|
||||
id: i,
|
||||
name: `User ${i}`,
|
||||
email: `user${i}@example.com`,
|
||||
role: ['admin', 'editor', 'viewer'][i % 3],
|
||||
active: i % 4 !== 0,
|
||||
profile: {
|
||||
bio: `This is the biography for user ${i}. It contains some repetitive text to demonstrate compression.`,
|
||||
location: ['New York', 'London', 'Tokyo', 'Berlin', 'Sydney'][i % 5],
|
||||
joinDate: `2024-${String((i % 12) + 1).padStart(2, '0')}-${String((i % 28) + 1).padStart(2, '0')}`,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
);
|
||||
|
||||
const HTML_DATA = Buffer.from(`<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="UTF-8"><title>Test Page</title></head>
|
||||
<body>
|
||||
${Array.from(
|
||||
{ length: 100 },
|
||||
(_, i) => `
|
||||
<div class="card" id="card-${i}">
|
||||
<h2 class="card-title">Card Title ${i}</h2>
|
||||
<p class="card-body">This is the body text for card number ${i}. It contains enough text to be meaningful for compression benchmarks.</p>
|
||||
<div class="card-footer">
|
||||
<button class="btn btn-primary">Action ${i}</button>
|
||||
<span class="badge">${i % 5}</span>
|
||||
</div>
|
||||
</div>`,
|
||||
).join('\n')}
|
||||
</body></html>`);
|
||||
|
||||
const CSS_DATA = Buffer.from(
|
||||
Array.from(
|
||||
{ length: 200 },
|
||||
(_, i) => `
|
||||
.component-${i} { display: flex; align-items: center; padding: ${i}px; margin: ${i % 20}px; }
|
||||
.component-${i}:hover { background-color: #${String(i * 111)
|
||||
.padStart(6, '0')
|
||||
.slice(0, 6)}; transition: all 0.3s ease; }
|
||||
.component-${i} .title { font-size: ${12 + (i % 8)}px; font-weight: ${i % 2 === 0 ? 'bold' : 'normal'}; }
|
||||
.component-${i} .description { color: #666; line-height: 1.5; max-width: ${200 + i * 5}px; }
|
||||
`,
|
||||
).join('\n'),
|
||||
);
|
||||
|
||||
const JS_DATA = Buffer.from(
|
||||
Array.from(
|
||||
{ length: 100 },
|
||||
(_, i) => `
|
||||
function handler${i}(req, res) {
|
||||
const data = req.body;
|
||||
if (!data || !data.id) {
|
||||
return res.status(400).json({ error: 'Missing id' });
|
||||
}
|
||||
const result = processData${i}(data);
|
||||
return res.json({ success: true, data: result, timestamp: Date.now() });
|
||||
}
|
||||
function processData${i}(data) {
|
||||
return { ...data, processed: true, handler: 'handler${i}' };
|
||||
}
|
||||
module.exports = { handler${i}, processData${i} };
|
||||
`,
|
||||
).join('\n'),
|
||||
);
|
||||
|
||||
// Binary data (images, wasm — less compressible)
|
||||
const BINARY_DATA = crypto.randomBytes(32768);
|
||||
|
||||
const TEST_DATA = [
|
||||
{ name: 'JSON', data: JSON_DATA, weight: 5 },
|
||||
{ name: 'HTML', data: HTML_DATA, weight: 3 },
|
||||
{ name: 'CSS', data: CSS_DATA, weight: 2 },
|
||||
{ name: 'JS', data: JS_DATA, weight: 2 },
|
||||
{ name: 'Binary', data: BINARY_DATA, weight: 1 },
|
||||
];
|
||||
|
||||
const weightedData = [];
|
||||
for (const item of TEST_DATA) {
|
||||
for (let i = 0; i < item.weight; i++) {
|
||||
weightedData.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
// Workload 1: Gzip compress/decompress (one-shot, most common pattern)
|
||||
async function workloadGzip(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const item = weightedData[i % weightedData.length];
|
||||
|
||||
// Compress (HTTP response compression)
|
||||
const compressed = await new Promise((resolve, reject) => {
|
||||
zlib.gzip(item.data, (err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
|
||||
// Decompress (HTTP response decompression on client)
|
||||
await new Promise((resolve, reject) => {
|
||||
zlib.gunzip(compressed, (err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
|
||||
// Sync variant (used in some build tools)
|
||||
if (i % 5 === 0) {
|
||||
const compSync = zlib.gzipSync(item.data);
|
||||
zlib.gunzipSync(compSync);
|
||||
ops += 2;
|
||||
}
|
||||
|
||||
// Different compression levels
|
||||
if (i % 3 === 0) {
|
||||
await new Promise((resolve, reject) => {
|
||||
zlib.gzip(item.data, { level: 1 }, (err, result) => {
|
||||
// Fast
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
if (i % 7 === 0) {
|
||||
await new Promise((resolve, reject) => {
|
||||
zlib.gzip(item.data, { level: 9 }, (err, result) => {
|
||||
// Best
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: Deflate compress/decompress
|
||||
async function workloadDeflate(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const item = weightedData[i % weightedData.length];
|
||||
|
||||
// deflate (used in some HTTP implementations)
|
||||
const compressed = await new Promise((resolve, reject) => {
|
||||
zlib.deflate(item.data, (err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
zlib.inflate(compressed, (err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
|
||||
// deflateRaw (no header — used in some protocols)
|
||||
if (i % 3 === 0) {
|
||||
const raw = zlib.deflateRawSync(item.data);
|
||||
zlib.inflateRawSync(raw);
|
||||
ops += 2;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: Brotli compress/decompress (modern HTTP content-encoding)
|
||||
async function workloadBrotli(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const item = weightedData[i % weightedData.length];
|
||||
|
||||
// Brotli compress (response compression for supported clients)
|
||||
const compressed = await new Promise((resolve, reject) => {
|
||||
zlib.brotliCompress(item.data, (err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
|
||||
// Brotli decompress
|
||||
await new Promise((resolve, reject) => {
|
||||
zlib.brotliDecompress(compressed, (err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
|
||||
// Different quality levels
|
||||
if (i % 3 === 0) {
|
||||
await new Promise((resolve, reject) => {
|
||||
zlib.brotliCompress(
|
||||
item.data,
|
||||
{
|
||||
params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 1 }, // Fast
|
||||
},
|
||||
(err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
},
|
||||
);
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 4: Streaming compression (piped HTTP responses)
|
||||
async function workloadStreamCompress(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const item = weightedData[i % weightedData.length];
|
||||
|
||||
// Gzip stream (Express compression middleware pattern)
|
||||
await pipeline(
|
||||
Readable.from([item.data]),
|
||||
zlib.createGzip(),
|
||||
new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
}),
|
||||
);
|
||||
ops++;
|
||||
|
||||
// Brotli stream
|
||||
if (i % 2 === 0) {
|
||||
await pipeline(
|
||||
Readable.from([item.data]),
|
||||
zlib.createBrotliCompress(),
|
||||
new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
}),
|
||||
);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// Chunked stream compression (large response simulation)
|
||||
if (i % 3 === 0) {
|
||||
const chunkSize = 4096;
|
||||
const chunks = [];
|
||||
for (let offset = 0; offset < item.data.length; offset += chunkSize) {
|
||||
chunks.push(
|
||||
item.data.subarray(
|
||||
offset,
|
||||
Math.min(offset + chunkSize, item.data.length),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await pipeline(
|
||||
Readable.from(chunks),
|
||||
zlib.createGzip({ flush: zlib.constants.Z_SYNC_FLUSH }),
|
||||
new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
}),
|
||||
);
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: CRC-32 (used in gzip, PNG, etc.)
|
||||
function workloadCRC32(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const item = weightedData[i % weightedData.length];
|
||||
zlib.crc32(item.data);
|
||||
ops++;
|
||||
|
||||
// Incremental CRC (streaming pattern)
|
||||
if (i % 3 === 0) {
|
||||
const chunkSize = 1024;
|
||||
let crc = 0;
|
||||
for (let offset = 0; offset < item.data.length; offset += chunkSize) {
|
||||
const chunk = item.data.subarray(
|
||||
offset,
|
||||
Math.min(offset + chunkSize, item.data.length),
|
||||
);
|
||||
crc = zlib.crc32(chunk, crc);
|
||||
}
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 6: Compression object creation (middleware initialization)
|
||||
function workloadCompressionCreation(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Express compression middleware creates these per-request
|
||||
zlib.createGzip();
|
||||
zlib.createGunzip();
|
||||
zlib.createDeflate();
|
||||
zlib.createInflate();
|
||||
zlib.createBrotliCompress();
|
||||
zlib.createBrotliDecompress();
|
||||
ops += 6;
|
||||
|
||||
// With options (common in production)
|
||||
zlib.createGzip({ level: 6, memLevel: 8, windowBits: 15 });
|
||||
zlib.createBrotliCompress({
|
||||
params: {
|
||||
[zlib.constants.BROTLI_PARAM_QUALITY]: 4,
|
||||
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
|
||||
},
|
||||
});
|
||||
ops += 2;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-compression] Starting compression workload...');
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// Gzip (most common — Accept-Encoding: gzip is universal)
|
||||
if (round === 1) console.log('[pgo-compression] Running gzip...');
|
||||
totalOps += await workloadGzip(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Deflate
|
||||
if (round === 1) console.log('[pgo-compression] Running deflate...');
|
||||
totalOps += await workloadDeflate(iterScale(50));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Brotli (growing rapidly)
|
||||
if (round === 1) console.log('[pgo-compression] Running brotli...');
|
||||
totalOps += await workloadBrotli(iterScale(50));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Streaming compression
|
||||
if (round === 1)
|
||||
console.log('[pgo-compression] Running stream compression...');
|
||||
totalOps += await workloadStreamCompress(iterScale(30));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// CRC-32
|
||||
if (round === 1) console.log('[pgo-compression] Running CRC-32...');
|
||||
totalOps += workloadCRC32(iterScale(1000));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Object creation
|
||||
if (round === 1)
|
||||
console.log('[pgo-compression] Running compression object creation...');
|
||||
totalOps += workloadCompressionCreation(iterScale(500));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-compression] Completed ${totalOps} ops in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-compression] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,401 @@
|
||||
'use strict';
|
||||
|
||||
// PGO Training Script: Crypto Operations
|
||||
//
|
||||
// Exercises the most common crypto operations in Node.js applications:
|
||||
// - TLS/HTTPS is used in virtually every production deployment
|
||||
// - Password hashing (bcrypt-like patterns via pbkdf2/scrypt)
|
||||
// - HMAC for API authentication (AWS Signature, JWT)
|
||||
// - SHA-256/SHA-512 hashing for checksums, ETags, content-addressing
|
||||
// - AES-GCM encryption for data-at-rest
|
||||
// - Random byte generation (session tokens, UUIDs, nonces)
|
||||
// - Certificate/key handling patterns
|
||||
//
|
||||
// This exercises: OpenSSL (via Node.js crypto binding), Buffer allocation,
|
||||
// C++ ↔ JS boundary crossing, async crypto operations, KeyObject handling.
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { subtle } = globalThis.crypto;
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
|
||||
// Test data of varying sizes
|
||||
const DATA_TINY = Buffer.from('Hello, World!');
|
||||
const DATA_SMALL = crypto.randomBytes(256);
|
||||
const DATA_MEDIUM = crypto.randomBytes(4096);
|
||||
const DATA_LARGE = crypto.randomBytes(65536);
|
||||
const DATA_XLARGE = crypto.randomBytes(262144); // 256 KB
|
||||
const DATA_SIZES = [
|
||||
DATA_TINY,
|
||||
DATA_SMALL,
|
||||
DATA_MEDIUM,
|
||||
DATA_LARGE,
|
||||
DATA_XLARGE,
|
||||
];
|
||||
|
||||
// Pre-generated keys for symmetric encryption
|
||||
const AES_KEY = crypto.randomBytes(32); // AES-256
|
||||
const HMAC_KEY = crypto.randomBytes(64);
|
||||
|
||||
// RSA key pair (pre-generated for speed)
|
||||
const { publicKey: RSA_PUBLIC, privateKey: RSA_PRIVATE } =
|
||||
crypto.generateKeyPairSync('rsa', {
|
||||
modulusLength: 2048,
|
||||
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
||||
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
||||
});
|
||||
|
||||
// EC key pair
|
||||
const { publicKey: EC_PUBLIC, privateKey: EC_PRIVATE } =
|
||||
crypto.generateKeyPairSync('ec', {
|
||||
namedCurve: 'P-256',
|
||||
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
||||
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
||||
});
|
||||
|
||||
// Ed25519 for modern signing
|
||||
const { publicKey: ED_PUBLIC, privateKey: ED_PRIVATE } =
|
||||
crypto.generateKeyPairSync('ed25519', {
|
||||
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
||||
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
||||
});
|
||||
|
||||
// Workload 1: Hashing (most common crypto operation)
|
||||
function workloadHashing(iterations) {
|
||||
const algorithms = ['sha256', 'sha384', 'sha512', 'sha1', 'md5'];
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const algo of algorithms) {
|
||||
const data = DATA_SIZES[i % DATA_SIZES.length];
|
||||
|
||||
// One-shot hash (most common pattern: ETags, checksums)
|
||||
crypto.createHash(algo).update(data).digest('hex');
|
||||
ops++;
|
||||
|
||||
// Streaming hash (file hashing pattern)
|
||||
if (i % 5 === 0) {
|
||||
const hash = crypto.createHash(algo);
|
||||
const chunkSize = 1024;
|
||||
for (let offset = 0; offset < data.length; offset += chunkSize) {
|
||||
hash.update(
|
||||
data.subarray(offset, Math.min(offset + chunkSize, data.length)),
|
||||
);
|
||||
}
|
||||
hash.digest('base64');
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: HMAC (API auth, JWT signatures, webhook verification)
|
||||
function workloadHMAC(iterations) {
|
||||
let ops = 0;
|
||||
const algorithms = ['sha256', 'sha384', 'sha512'];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const algo = algorithms[i % algorithms.length];
|
||||
const data = DATA_SIZES[i % DATA_SIZES.length];
|
||||
|
||||
// HMAC compute (AWS Signature v4, JWT pattern)
|
||||
const sig = crypto.createHmac(algo, HMAC_KEY).update(data).digest();
|
||||
ops++;
|
||||
|
||||
// HMAC verify (webhook verification pattern)
|
||||
const sig2 = crypto.createHmac(algo, HMAC_KEY).update(data).digest();
|
||||
crypto.timingSafeEqual(sig, sig2);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: AES-GCM encryption/decryption (data protection)
|
||||
function workloadAESGCM(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const data = DATA_SIZES[i % DATA_SIZES.length];
|
||||
const iv = crypto.randomBytes(12);
|
||||
|
||||
// Encrypt
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', AES_KEY, iv);
|
||||
const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
ops++;
|
||||
|
||||
// Decrypt
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', AES_KEY, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 4: RSA sign/verify (JWT RS256, code signing)
|
||||
function workloadRSASignVerify(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const data = DATA_SIZES[Math.min(i % 3, DATA_SIZES.length - 1)]; // RSA limits payload size
|
||||
|
||||
// Sign
|
||||
const sign = crypto.createSign('RSA-SHA256');
|
||||
sign.update(data);
|
||||
const signature = sign.sign(RSA_PRIVATE);
|
||||
ops++;
|
||||
|
||||
// Verify
|
||||
const verify = crypto.createVerify('RSA-SHA256');
|
||||
verify.update(data);
|
||||
verify.verify(RSA_PUBLIC, signature);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: ECDSA sign/verify (modern TLS, smaller keys)
|
||||
function workloadECDSA(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const data = DATA_SIZES[i % DATA_SIZES.length];
|
||||
|
||||
const signature = crypto.sign('SHA256', data, EC_PRIVATE);
|
||||
ops++;
|
||||
|
||||
crypto.verify('SHA256', data, EC_PUBLIC, signature);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 6: Ed25519 sign/verify (modern fast signing)
|
||||
function workloadEd25519(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const data = DATA_SIZES[i % DATA_SIZES.length];
|
||||
|
||||
const signature = crypto.sign(null, data, ED_PRIVATE);
|
||||
ops++;
|
||||
|
||||
crypto.verify(null, data, ED_PUBLIC, signature);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 7: Random byte generation (tokens, session IDs, UUIDs)
|
||||
function workloadRandom(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Session tokens
|
||||
crypto.randomBytes(32);
|
||||
ops++;
|
||||
|
||||
// UUID generation
|
||||
crypto.randomUUID();
|
||||
ops++;
|
||||
|
||||
// Random integers (for OTP codes, etc.)
|
||||
crypto.randomInt(100000, 999999);
|
||||
ops++;
|
||||
|
||||
// Fill existing buffer (pool pattern)
|
||||
const buf = Buffer.allocUnsafe(64);
|
||||
crypto.randomFillSync(buf);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 8: PBKDF2 / Scrypt (password hashing - async)
|
||||
async function workloadPasswordHashing(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const password = `password_${i}_with_some_length`;
|
||||
const salt = crypto.randomBytes(16);
|
||||
|
||||
// PBKDF2 (most common password hashing in Node.js)
|
||||
await new Promise((resolve, reject) => {
|
||||
crypto.pbkdf2(password, salt, 1000, 64, 'sha512', (err, key) => {
|
||||
if (err) reject(err);
|
||||
else resolve(key);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
|
||||
// Scrypt (recommended for new apps)
|
||||
if (i % 3 === 0) {
|
||||
await new Promise((resolve, reject) => {
|
||||
crypto.scrypt(
|
||||
password,
|
||||
salt,
|
||||
64,
|
||||
{ N: 1024, r: 8, p: 1 },
|
||||
(err, key) => {
|
||||
if (err) reject(err);
|
||||
else resolve(key);
|
||||
},
|
||||
);
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 9: HKDF (key derivation for encryption key rotation)
|
||||
async function workloadHKDF(iterations) {
|
||||
let ops = 0;
|
||||
const ikm = crypto.randomBytes(32);
|
||||
const salt = crypto.randomBytes(32);
|
||||
const info = Buffer.from('encryption-key-v1');
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
await new Promise((resolve, reject) => {
|
||||
crypto.hkdf('sha256', ikm, salt, info, 32, (err, key) => {
|
||||
if (err) reject(err);
|
||||
else resolve(key);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 10: WebCrypto API (increasingly used in modern Node.js)
|
||||
async function workloadWebCrypto(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
// Generate WebCrypto key
|
||||
const key = await subtle.generateKey(
|
||||
{ name: 'AES-GCM', length: 256 },
|
||||
false,
|
||||
['encrypt', 'decrypt'],
|
||||
);
|
||||
|
||||
const hmacKey = await subtle.generateKey(
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign', 'verify'],
|
||||
);
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const data = DATA_SIZES[i % 3]; // Keep data smaller for WebCrypto
|
||||
const iv = crypto.randomBytes(12);
|
||||
|
||||
// AES-GCM encrypt/decrypt via WebCrypto
|
||||
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, key, data);
|
||||
await subtle.decrypt({ name: 'AES-GCM', iv }, key, encrypted);
|
||||
ops += 2;
|
||||
|
||||
// HMAC sign/verify via WebCrypto
|
||||
const sig = await subtle.sign('HMAC', hmacKey, data);
|
||||
await subtle.verify('HMAC', hmacKey, sig, data);
|
||||
ops += 2;
|
||||
|
||||
// SHA-256 digest via WebCrypto
|
||||
await subtle.digest('SHA-256', data);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 11: DH key exchange (TLS handshake simulation)
|
||||
function workloadDH(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// ECDH key exchange (used in every TLS connection)
|
||||
const alice = crypto.createECDH('prime256v1');
|
||||
const bob = crypto.createECDH('prime256v1');
|
||||
|
||||
alice.generateKeys();
|
||||
bob.generateKeys();
|
||||
|
||||
const aliceSecret = alice.computeSecret(bob.getPublicKey());
|
||||
bob.computeSecret(alice.getPublicKey());
|
||||
|
||||
// Derive encryption key from shared secret
|
||||
crypto.createHash('sha256').update(aliceSecret).digest();
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-crypto] Starting crypto workload...');
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// Sync workloads (weighted by real-world frequency)
|
||||
if (round === 1) console.log('[pgo-crypto] Running hash workloads...');
|
||||
totalOps += workloadHashing(iterScale(500));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running HMAC workloads...');
|
||||
totalOps += workloadHMAC(iterScale(300));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running AES-GCM workloads...');
|
||||
totalOps += workloadAESGCM(iterScale(200));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running random generation...');
|
||||
totalOps += workloadRandom(iterScale(500));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running RSA sign/verify...');
|
||||
totalOps += workloadRSASignVerify(iterScale(30));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running ECDSA sign/verify...');
|
||||
totalOps += workloadECDSA(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running Ed25519 sign/verify...');
|
||||
totalOps += workloadEd25519(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running DH key exchange...');
|
||||
totalOps += workloadDH(iterScale(30));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Async workloads
|
||||
if (round === 1)
|
||||
console.log('[pgo-crypto] Running password hashing (async)...');
|
||||
totalOps += await workloadPasswordHashing(iterScale(20));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running HKDF (async)...');
|
||||
totalOps += await workloadHKDF(iterScale(50));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-crypto] Running WebCrypto workloads...');
|
||||
totalOps += await workloadWebCrypto(iterScale(50));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-crypto] Completed ${totalOps} crypto operations in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-crypto] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,447 @@
|
||||
'use strict';
|
||||
|
||||
// PGO Training Script: File System Operations
|
||||
//
|
||||
// Exercises the most common fs operations in Node.js applications:
|
||||
// - readFile/writeFile (config loading, template rendering, static file serving)
|
||||
// - stat/access (file existence checks, middleware, caching)
|
||||
// - readdir (directory listings, file discovery, build tools)
|
||||
// - read/write streams (log file appending, file upload/download)
|
||||
// - mkdir/rmdir (temp directories, build artifacts)
|
||||
// - path operations (resolve, join, parse — used constantly)
|
||||
// - watch (file watchers in dev tools, though we only test creation here)
|
||||
//
|
||||
// This exercises: libuv filesystem operations, thread pool (async fs),
|
||||
// Buffer allocation for file data, string encoding, path module.
|
||||
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs/promises');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
|
||||
// Create a unique temp directory for our operations
|
||||
const TEMP_DIR = path.join(
|
||||
os.tmpdir(),
|
||||
`node-pgo-fs-${process.pid}-${Date.now()}`,
|
||||
);
|
||||
|
||||
// Test data
|
||||
const MEDIUM_CONTENT = Array.from(
|
||||
{ length: 100 },
|
||||
(_, i) => `Line ${i}: ${crypto.randomBytes(40).toString('hex')}`,
|
||||
).join('\n');
|
||||
const LARGE_CONTENT = crypto.randomBytes(256 * 1024).toString('base64');
|
||||
const JSON_CONFIG = JSON.stringify(
|
||||
{
|
||||
database: {
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
name: 'myapp',
|
||||
pool: { min: 2, max: 10 },
|
||||
},
|
||||
redis: { host: 'localhost', port: 6379, db: 0 },
|
||||
server: { port: 3000, host: '0.0.0.0', cors: { origin: '*' } },
|
||||
logging: { level: 'info', format: 'json', outputs: ['stdout', 'file'] },
|
||||
features: { darkMode: true, betaFeatures: false, maxUploadSize: 10485760 },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
function setup() {
|
||||
fs.mkdirSync(TEMP_DIR, { recursive: true });
|
||||
fs.mkdirSync(path.join(TEMP_DIR, 'subdir', 'nested'), { recursive: true });
|
||||
fs.mkdirSync(path.join(TEMP_DIR, 'logs'), { recursive: true });
|
||||
fs.mkdirSync(path.join(TEMP_DIR, 'uploads'), { recursive: true });
|
||||
fs.mkdirSync(path.join(TEMP_DIR, 'cache'), { recursive: true });
|
||||
|
||||
// Pre-create files for reading
|
||||
for (let i = 0; i < 50; i++) {
|
||||
fs.writeFileSync(
|
||||
path.join(TEMP_DIR, `file-${i}.txt`),
|
||||
`Content of file ${i}\n`.repeat(10),
|
||||
);
|
||||
}
|
||||
for (let i = 0; i < 10; i++) {
|
||||
fs.writeFileSync(
|
||||
path.join(TEMP_DIR, 'subdir', `sub-${i}.json`),
|
||||
JSON.stringify({ id: i, data: `value-${i}` }),
|
||||
);
|
||||
}
|
||||
fs.writeFileSync(path.join(TEMP_DIR, 'config.json'), JSON_CONFIG);
|
||||
fs.writeFileSync(path.join(TEMP_DIR, 'large.dat'), LARGE_CONTENT);
|
||||
fs.writeFileSync(path.join(TEMP_DIR, 'medium.txt'), MEDIUM_CONTENT);
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
try {
|
||||
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Best effort cleanup
|
||||
}
|
||||
}
|
||||
|
||||
// Workload 1: readFile + writeFile (async, the dominant pattern)
|
||||
async function workloadReadWriteAsync(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Read config file (very common — Express/Fastify load configs at startup)
|
||||
await fsp.readFile(path.join(TEMP_DIR, 'config.json'), 'utf8');
|
||||
ops++;
|
||||
|
||||
// Read and parse JSON config
|
||||
const configStr = await fsp.readFile(
|
||||
path.join(TEMP_DIR, 'config.json'),
|
||||
'utf8',
|
||||
);
|
||||
JSON.parse(configStr);
|
||||
ops++;
|
||||
|
||||
// Read binary file (static file serving)
|
||||
await fsp.readFile(path.join(TEMP_DIR, `file-${i % 50}.txt`));
|
||||
ops++;
|
||||
|
||||
// Write new file (log rotation, temp files, uploads)
|
||||
const tempFile = path.join(TEMP_DIR, 'uploads', `upload-${i}.tmp`);
|
||||
await fsp.writeFile(
|
||||
tempFile,
|
||||
`Upload content ${i}: ${crypto.randomBytes(100).toString('hex')}`,
|
||||
);
|
||||
ops++;
|
||||
|
||||
// Read back
|
||||
await fsp.readFile(tempFile, 'utf8');
|
||||
ops++;
|
||||
|
||||
// Overwrite (atomic-ish update pattern)
|
||||
await fsp.writeFile(tempFile, `Updated content ${i}`);
|
||||
ops++;
|
||||
|
||||
// Read large file (less frequently)
|
||||
if (i % 10 === 0) {
|
||||
await fsp.readFile(path.join(TEMP_DIR, 'large.dat'));
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: readFileSync + writeFileSync (startup, require.resolve)
|
||||
function workloadReadWriteSync(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Sync read (very common in require() for package.json, .json configs)
|
||||
fs.readFileSync(path.join(TEMP_DIR, 'config.json'), 'utf8');
|
||||
ops++;
|
||||
|
||||
// Sync read various files
|
||||
fs.readFileSync(path.join(TEMP_DIR, `file-${i % 50}.txt`), 'utf8');
|
||||
ops++;
|
||||
|
||||
// Sync JSON file read/parse (package.json pattern)
|
||||
for (let j = 0; j < 10; j++) {
|
||||
const content = fs.readFileSync(
|
||||
path.join(TEMP_DIR, 'subdir', `sub-${j}.json`),
|
||||
'utf8',
|
||||
);
|
||||
JSON.parse(content);
|
||||
}
|
||||
ops += 10;
|
||||
|
||||
// Sync write (cache files, lock files)
|
||||
const cacheFile = path.join(TEMP_DIR, 'cache', `cache-${i % 20}.json`);
|
||||
fs.writeFileSync(
|
||||
cacheFile,
|
||||
JSON.stringify({ key: `key-${i}`, value: i * 42, ts: Date.now() }),
|
||||
);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: stat / access / exists (file existence checks)
|
||||
async function workloadStatAccess(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// stat (used by express.static, require.resolve, etc.)
|
||||
await fsp.stat(path.join(TEMP_DIR, `file-${i % 50}.txt`));
|
||||
ops++;
|
||||
|
||||
// stat directory
|
||||
await fsp.stat(path.join(TEMP_DIR, 'subdir'));
|
||||
ops++;
|
||||
|
||||
// Access check (permission verification)
|
||||
try {
|
||||
await fsp.access(
|
||||
path.join(TEMP_DIR, `file-${i % 50}.txt`),
|
||||
fs.constants.R_OK,
|
||||
);
|
||||
} catch {
|
||||
/* expected for some */
|
||||
}
|
||||
ops++;
|
||||
|
||||
// lstat (symlink-aware, used by tools)
|
||||
await fsp.lstat(path.join(TEMP_DIR, `file-${i % 50}.txt`));
|
||||
ops++;
|
||||
|
||||
// Stat non-existent (cache miss pattern)
|
||||
try {
|
||||
await fsp.stat(path.join(TEMP_DIR, `nonexistent-${i}.txt`));
|
||||
} catch {
|
||||
/* expected */
|
||||
}
|
||||
ops++;
|
||||
|
||||
// Sync variants (require.resolve uses these)
|
||||
fs.statSync(path.join(TEMP_DIR, `file-${i % 50}.txt`));
|
||||
ops++;
|
||||
|
||||
fs.existsSync(path.join(TEMP_DIR, `file-${i % 50}.txt`));
|
||||
ops++;
|
||||
|
||||
fs.existsSync(path.join(TEMP_DIR, `nonexistent-${i}.txt`));
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 4: readdir (directory listing, build tools, file watchers)
|
||||
async function workloadReaddir(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Simple readdir
|
||||
await fsp.readdir(TEMP_DIR);
|
||||
ops++;
|
||||
|
||||
// Readdir with file types (common for file tree traversal)
|
||||
await fsp.readdir(TEMP_DIR, { withFileTypes: true });
|
||||
ops++;
|
||||
|
||||
// Readdir subdirectory
|
||||
await fsp.readdir(path.join(TEMP_DIR, 'subdir'), { withFileTypes: true });
|
||||
ops++;
|
||||
|
||||
// Sync variant (build tools)
|
||||
fs.readdirSync(TEMP_DIR);
|
||||
ops++;
|
||||
|
||||
// Recursive readdir (newer API, gaining adoption)
|
||||
if (i % 5 === 0) {
|
||||
await fsp.readdir(TEMP_DIR, { recursive: true });
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: mkdir / rmdir / rename / copy (build tool patterns)
|
||||
async function workloadDirectoryOps(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const dir = path.join(TEMP_DIR, `build-${i}`);
|
||||
|
||||
// mkdir (build output directories)
|
||||
await fsp.mkdir(dir, { recursive: true });
|
||||
ops++;
|
||||
|
||||
// Create file in new dir
|
||||
const file = path.join(dir, 'output.txt');
|
||||
await fsp.writeFile(file, `Build output ${i}`);
|
||||
ops++;
|
||||
|
||||
// Rename (atomic file update pattern)
|
||||
const newFile = path.join(dir, 'output.final.txt');
|
||||
await fsp.rename(file, newFile);
|
||||
ops++;
|
||||
|
||||
// Copy file
|
||||
const copyDest = path.join(dir, 'output.backup.txt');
|
||||
await fsp.copyFile(newFile, copyDest);
|
||||
ops++;
|
||||
|
||||
// rmdir (cleanup)
|
||||
await fsp.rm(dir, { recursive: true, force: true });
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 6: Stream read/write (large file processing, log files)
|
||||
async function workloadStreams(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Read stream (file download, static serving of large files)
|
||||
await new Promise((resolve, reject) => {
|
||||
const rs = fs.createReadStream(path.join(TEMP_DIR, 'large.dat'), {
|
||||
highWaterMark: 16 * 1024,
|
||||
});
|
||||
rs.on('data', () => {});
|
||||
rs.on('end', () => {
|
||||
ops++;
|
||||
resolve();
|
||||
});
|
||||
rs.on('error', reject);
|
||||
});
|
||||
|
||||
// Write stream (log file appending)
|
||||
await new Promise((resolve, reject) => {
|
||||
const ws = fs.createWriteStream(
|
||||
path.join(TEMP_DIR, 'logs', `app-${i % 5}.log`),
|
||||
{ flags: 'a' },
|
||||
);
|
||||
for (let j = 0; j < 50; j++) {
|
||||
ws.write(
|
||||
`[${new Date().toISOString()}] INFO: Request processed in ${Math.random() * 100}ms\n`,
|
||||
);
|
||||
}
|
||||
ws.end(() => {
|
||||
ops++;
|
||||
resolve();
|
||||
});
|
||||
ws.on('error', reject);
|
||||
});
|
||||
|
||||
// Pipe pattern (file copy via streams)
|
||||
if (i % 3 === 0) {
|
||||
await new Promise((resolve, reject) => {
|
||||
const rs = fs.createReadStream(path.join(TEMP_DIR, 'medium.txt'));
|
||||
const ws = fs.createWriteStream(
|
||||
path.join(TEMP_DIR, `pipe-copy-${i}.txt`),
|
||||
);
|
||||
rs.pipe(ws);
|
||||
ws.on('finish', () => {
|
||||
ops++;
|
||||
resolve();
|
||||
});
|
||||
ws.on('error', reject);
|
||||
});
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 7: Path operations (used in every file operation)
|
||||
function workloadPathOps(iterations) {
|
||||
let ops = 0;
|
||||
const testPaths = [
|
||||
'/usr/local/lib/node_modules/express/lib/router/index.js',
|
||||
'C:\\Users\\user\\project\\node_modules\\lodash\\lodash.js',
|
||||
'../relative/path/to/file.js',
|
||||
'./src/components/Button/index.tsx',
|
||||
'https://example.com/path/to/resource?query=value#hash',
|
||||
'/path/with spaces/and (parens)/file name.txt',
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const p of testPaths) {
|
||||
path.resolve(p);
|
||||
path.dirname(p);
|
||||
path.basename(p);
|
||||
path.extname(p);
|
||||
path.parse(p);
|
||||
path.normalize(p);
|
||||
path.isAbsolute(p);
|
||||
ops += 7;
|
||||
}
|
||||
|
||||
// path.join (the most common path operation)
|
||||
path.join('src', 'components', 'Button', 'index.tsx');
|
||||
path.join(TEMP_DIR, 'subdir', 'nested', 'file.txt');
|
||||
path.join('..', '..', 'node_modules', '.cache');
|
||||
ops += 3;
|
||||
|
||||
// path.relative (monorepo/build tool pattern)
|
||||
path.relative(
|
||||
'/project/packages/core/src',
|
||||
'/project/packages/utils/src/helpers.js',
|
||||
);
|
||||
path.relative(TEMP_DIR, path.join(TEMP_DIR, 'subdir', 'file.txt'));
|
||||
ops += 2;
|
||||
|
||||
// path.format (inverse of parse)
|
||||
path.format({
|
||||
root: '/',
|
||||
dir: '/home/user',
|
||||
base: 'file.txt',
|
||||
ext: '.txt',
|
||||
name: 'file',
|
||||
});
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-fs] Starting file system workload...');
|
||||
|
||||
setup();
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
try {
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// Path ops first — pure CPU, exercises V8 string handling
|
||||
if (round === 1) console.log('[pgo-fs] Running path operations...');
|
||||
totalOps += workloadPathOps(iterScale(2000));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Sync reads (startup/require pattern)
|
||||
if (round === 1) console.log('[pgo-fs] Running sync read/write...');
|
||||
totalOps += workloadReadWriteSync(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Async reads/writes (most common runtime pattern)
|
||||
if (round === 1) console.log('[pgo-fs] Running async read/write...');
|
||||
totalOps += await workloadReadWriteAsync(iterScale(50));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// stat/access (middleware, require.resolve)
|
||||
if (round === 1) console.log('[pgo-fs] Running stat/access...');
|
||||
totalOps += await workloadStatAccess(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Directory operations
|
||||
if (round === 1) console.log('[pgo-fs] Running readdir...');
|
||||
totalOps += await workloadReaddir(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-fs] Running directory ops...');
|
||||
totalOps += await workloadDirectoryOps(iterScale(30));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Stream operations
|
||||
if (round === 1) console.log('[pgo-fs] Running stream read/write...');
|
||||
totalOps += await workloadStreams(iterScale(20));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-fs] Completed ${totalOps} fs operations in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-fs] Error:', err);
|
||||
cleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,380 @@
|
||||
'use strict';
|
||||
|
||||
// PGO Training Script: HTTP Server Workload
|
||||
//
|
||||
// Simulates the most common Node.js use case — an HTTP server handling:
|
||||
// - JSON REST API requests (GET/POST with JSON bodies)
|
||||
// - Static content serving (HTML, CSS, JS responses)
|
||||
// - Chunked transfer encoding
|
||||
// - Various header patterns (few/many headers, Set-Cookie, CORS)
|
||||
// - Keep-alive connections with request pipelining
|
||||
// - URL routing with path parameters and query strings
|
||||
//
|
||||
// This exercises: llhttp parser, TCP stack (libuv), header serialization,
|
||||
// Buffer encoding, URL parsing, JSON parse/stringify, EventEmitter, streams.
|
||||
|
||||
const http = require('http');
|
||||
const { URL } = require('url');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
const CONCURRENT_CLIENTS = 20;
|
||||
const PORT = 0; // OS-assigned
|
||||
|
||||
// Realistic JSON payloads of varying sizes
|
||||
const SMALL_JSON = JSON.stringify({ id: 1, name: 'test', active: true });
|
||||
const MEDIUM_JSON = JSON.stringify({
|
||||
users: Array.from({ length: 50 }, (_, i) => ({
|
||||
id: i,
|
||||
name: `user_${i}`,
|
||||
email: `user${i}@example.com`,
|
||||
age: 20 + (i % 40),
|
||||
active: i % 3 !== 0,
|
||||
tags: ['tag1', 'tag2', 'tag3'],
|
||||
address: {
|
||||
street: `${i * 100} Main St`,
|
||||
city: 'Anytown',
|
||||
state: 'CA',
|
||||
zip: `${90000 + i}`,
|
||||
},
|
||||
})),
|
||||
total: 50,
|
||||
page: 1,
|
||||
perPage: 50,
|
||||
});
|
||||
const LARGE_JSON = JSON.stringify({
|
||||
data: Array.from({ length: 500 }, (_, i) => ({
|
||||
id: crypto.randomUUID(),
|
||||
timestamp: new Date().toISOString(),
|
||||
type: ['click', 'view', 'purchase', 'signup'][i % 4],
|
||||
properties: {
|
||||
source: ['web', 'mobile', 'api'][i % 3],
|
||||
browser: ['chrome', 'firefox', 'safari', 'edge'][i % 4],
|
||||
os: ['windows', 'macos', 'linux', 'ios', 'android'][i % 5],
|
||||
duration: Math.random() * 10000,
|
||||
amount: i % 4 === 2 ? (Math.random() * 500).toFixed(2) : undefined,
|
||||
items:
|
||||
i % 4 === 2 ?
|
||||
Array.from({ length: 3 }, (_, j) => ({
|
||||
sku: `SKU-${j}-${i}`,
|
||||
qty: j + 1,
|
||||
price: (Math.random() * 100).toFixed(2),
|
||||
})) :
|
||||
undefined,
|
||||
},
|
||||
metadata: {
|
||||
ip: `192.168.${i % 256}.${(i * 7) % 256}`,
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
sessionId: crypto.randomUUID(),
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
// Simulated HTML page
|
||||
const HTML_PAGE = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>App</title>
|
||||
<link rel="stylesheet" href="/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
// Simulated CSS
|
||||
const CSS_CONTENT = `body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
|
||||
.container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }
|
||||
.header { background: #1a1a2e; color: white; padding: 1rem 0; }
|
||||
.nav { display: flex; gap: 1rem; }
|
||||
.card { border: 1px solid #ddd; border-radius: 8px; padding: 1rem; margin: 1rem 0; }
|
||||
.btn { display: inline-block; padding: 0.5rem 1rem; border-radius: 4px; cursor: pointer; }
|
||||
.btn-primary { background: #0066cc; color: white; }
|
||||
@media (max-width: 768px) { .container { padding: 0 10px; } }`;
|
||||
|
||||
// Simulated JS bundle (minified-ish)
|
||||
const JS_BUNDLE =
|
||||
`!function(){"use strict";` +
|
||||
'const e=document.getElementById("root");' +
|
||||
'function t(e,t){return Object.assign(document.createElement(e),t)}' +
|
||||
Array.from(
|
||||
{ length: 100 },
|
||||
(_, i) =>
|
||||
`function c${i}(d){return t("div",{className:"c${i}",textContent:JSON.stringify(d)})}`,
|
||||
).join(';') +
|
||||
'}();';
|
||||
|
||||
function handleRequest(req, res) {
|
||||
const url = new URL(req.url, `http://localhost`);
|
||||
const path = url.pathname;
|
||||
const method = req.method;
|
||||
|
||||
// CORS headers (very common in REST APIs)
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader(
|
||||
'Access-Control-Allow-Methods',
|
||||
'GET, POST, PUT, DELETE, OPTIONS',
|
||||
);
|
||||
res.setHeader('X-Request-Id', crypto.randomUUID());
|
||||
|
||||
if (method === 'OPTIONS') {
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// REST API routes
|
||||
if (path === '/api/users' && method === 'GET') {
|
||||
const page = url.searchParams.get('page') || '1';
|
||||
const limit = url.searchParams.get('limit') || '50';
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Page': page,
|
||||
'X-Limit': limit,
|
||||
'X-Total': '500',
|
||||
'Cache-Control': 'no-cache',
|
||||
});
|
||||
res.end(MEDIUM_JSON);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path === '/api/events' && method === 'POST') {
|
||||
let body = '';
|
||||
req.on('data', (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on('end', () => {
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
const response = JSON.stringify({
|
||||
status: 'accepted',
|
||||
count: Array.isArray(parsed) ? parsed.length : 1,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
res.writeHead(202, {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(response),
|
||||
});
|
||||
res.end(response);
|
||||
} catch {
|
||||
res.writeHead(400, { 'Content-Type': 'application/json' });
|
||||
res.end('{"error":"Invalid JSON"}');
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (path === '/api/analytics' && method === 'GET') {
|
||||
// Chunked response (common for large datasets)
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'Transfer-Encoding': 'chunked',
|
||||
});
|
||||
res.write(LARGE_JSON.slice(0, 4096));
|
||||
res.write(LARGE_JSON.slice(4096, 8192));
|
||||
res.write(LARGE_JSON.slice(8192));
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (path.startsWith('/api/users/') && method === 'GET') {
|
||||
const userId = path.split('/')[3];
|
||||
const user = JSON.stringify({
|
||||
id: userId,
|
||||
name: `User ${userId}`,
|
||||
email: `user${userId}@example.com`,
|
||||
createdAt: new Date().toISOString(),
|
||||
profile: { bio: 'A sample user', avatar: '/img/default.png' },
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'ETag': `"${crypto.createHash('md5').update(user).digest('hex')}"`,
|
||||
'Cache-Control': 'max-age=60',
|
||||
});
|
||||
res.end(user);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path === '/health') {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(SMALL_JSON);
|
||||
return;
|
||||
}
|
||||
|
||||
// Static content routes
|
||||
if (path === '/' || path === '/index.html') {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Content-Length': Buffer.byteLength(HTML_PAGE),
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
});
|
||||
res.end(HTML_PAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path === '/styles.css') {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/css',
|
||||
'Content-Length': Buffer.byteLength(CSS_CONTENT),
|
||||
'Cache-Control': 'public, max-age=86400',
|
||||
});
|
||||
res.end(CSS_CONTENT);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path === '/app.js') {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
'Content-Length': Buffer.byteLength(JS_BUNDLE),
|
||||
'Cache-Control': 'public, max-age=86400',
|
||||
});
|
||||
res.end(JS_BUNDLE);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set-Cookie responses (common for auth)
|
||||
if (path === '/api/login' && method === 'POST') {
|
||||
req.on('data', () => {});
|
||||
req.on('end', () => {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'Set-Cookie': [
|
||||
`token=${token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=3600`,
|
||||
`session=${crypto.randomUUID()}; HttpOnly; Path=/`,
|
||||
],
|
||||
});
|
||||
res.end(JSON.stringify({ token, expiresIn: 3600 }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 404
|
||||
res.writeHead(404, { 'Content-Type': 'application/json' });
|
||||
res.end('{"error":"Not Found"}');
|
||||
}
|
||||
|
||||
// Request patterns that clients will cycle through
|
||||
const REQUEST_PATTERNS = [
|
||||
// Weight distribution reflects real API usage
|
||||
{ method: 'GET', path: '/api/users?page=1&limit=50', weight: 20 },
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/users?page=2&limit=25&sort=name&order=asc',
|
||||
weight: 10,
|
||||
},
|
||||
{ method: 'GET', path: '/api/users/123', weight: 15 },
|
||||
{ method: 'GET', path: '/api/users/456', weight: 10 },
|
||||
{ method: 'GET', path: '/api/analytics', weight: 5 },
|
||||
{ method: 'GET', path: '/health', weight: 15 },
|
||||
{ method: 'GET', path: '/', weight: 8 },
|
||||
{ method: 'GET', path: '/styles.css', weight: 4 },
|
||||
{ method: 'GET', path: '/app.js', weight: 4 },
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/events',
|
||||
body: JSON.stringify([
|
||||
{ type: 'click', target: 'button', timestamp: Date.now() },
|
||||
{ type: 'view', page: '/dashboard', timestamp: Date.now() },
|
||||
]),
|
||||
weight: 5,
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/login',
|
||||
body: '{"email":"test@example.com","password":"pass123"}',
|
||||
weight: 3,
|
||||
},
|
||||
{ method: 'OPTIONS', path: '/api/users', weight: 1 },
|
||||
];
|
||||
|
||||
// Build weighted selection array
|
||||
const weightedPatterns = [];
|
||||
for (const pattern of REQUEST_PATTERNS) {
|
||||
for (let i = 0; i < pattern.weight; i++) {
|
||||
weightedPatterns.push(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
function makeRequest(port, pattern) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const options = {
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
path: pattern.path,
|
||||
method: pattern.method,
|
||||
headers: {
|
||||
'Host': 'localhost',
|
||||
'User-Agent': 'PGO-Training/1.0',
|
||||
'Accept': 'application/json, text/html',
|
||||
'Accept-Encoding': 'identity',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
};
|
||||
|
||||
if (pattern.body) {
|
||||
options.headers['Content-Type'] = 'application/json';
|
||||
options.headers['Content-Length'] = Buffer.byteLength(pattern.body);
|
||||
}
|
||||
|
||||
const req = http.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on('end', () =>
|
||||
resolve({ status: res.statusCode, size: data.length }),
|
||||
);
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (pattern.body) req.write(pattern.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function runClient(port, endTime) {
|
||||
let requests = 0;
|
||||
const agent = new http.Agent({ keepAlive: true, maxSockets: 2 });
|
||||
|
||||
while (Date.now() < endTime) {
|
||||
const pattern =
|
||||
weightedPatterns[Math.floor(Math.random() * weightedPatterns.length)];
|
||||
try {
|
||||
await makeRequest(port, pattern);
|
||||
requests++;
|
||||
} catch {
|
||||
// Instrumented builds are slow; brief pause on error
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
}
|
||||
agent.destroy();
|
||||
return requests;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const server = http.createServer(handleRequest);
|
||||
|
||||
await new Promise((resolve) => server.listen(PORT, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
console.log(`[pgo-http-server] Server listening on port ${port}`);
|
||||
|
||||
const endTime = Date.now() + DURATION_MS;
|
||||
const clients = Array.from({ length: CONCURRENT_CLIENTS }, () =>
|
||||
runClient(port, endTime),
|
||||
);
|
||||
const results = await Promise.all(clients);
|
||||
const totalRequests = results.reduce((a, b) => a + b, 0);
|
||||
|
||||
server.close();
|
||||
console.log(
|
||||
`[pgo-http-server] Completed ${totalRequests} requests in ${DURATION_MS / 1000}s (${(totalRequests / (DURATION_MS / 1000)).toFixed(0)} req/s)`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-http-server] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,341 @@
|
||||
'use strict';
|
||||
|
||||
// PGO Training Script: JSON Processing Workload
|
||||
//
|
||||
// JSON.parse() and JSON.stringify() are among the most frequently called
|
||||
// functions in Node.js applications (every REST API request/response cycle).
|
||||
// This script exercises the JSON parser and serializer with:
|
||||
// - Small objects (API responses, config)
|
||||
// - Medium objects (paginated lists, user profiles)
|
||||
// - Large objects (analytics payloads, data exports)
|
||||
// - Nested structures (deep objects, arrays of objects)
|
||||
// - Various value types (strings, numbers, booleans, null, arrays, objects)
|
||||
// - Edge cases (unicode, escaped characters, large numbers, empty objects)
|
||||
// - Realistic patterns: parse → transform → stringify pipeline
|
||||
//
|
||||
// This exercises: V8 JSON parser, V8 JSON serializer, string allocation,
|
||||
// property access patterns, array iteration, GC pressure from allocations.
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
const ITERATIONS_PER_BATCH = 500;
|
||||
|
||||
// Realistic JSON payloads matching common API shapes
|
||||
|
||||
// 1. Small config/health check (~100 bytes)
|
||||
const SMALL_PAYLOADS = [
|
||||
'{"status":"ok","uptime":12345,"version":"1.0.0"}',
|
||||
'{"id":42,"name":"test","active":true,"score":98.5}',
|
||||
'{"error":null,"data":{"key":"value"},"meta":{}}',
|
||||
'{"token":"abc123def456","expires":1700000000}',
|
||||
'{"success":true,"count":0,"items":[]}',
|
||||
];
|
||||
|
||||
// 2. Medium user/product objects (~1-5 KB)
|
||||
function generateUserPayload(count) {
|
||||
const users = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
users.push({
|
||||
id: `usr_${i.toString(36).padStart(8, '0')}`,
|
||||
email: `user${i}@company.example.com`,
|
||||
name: { first: `First${i}`, last: `Last${i}` },
|
||||
role: ['admin', 'editor', 'viewer', 'member'][i % 4],
|
||||
permissions: ['read', 'write', 'delete', 'admin'].slice(0, (i % 4) + 1),
|
||||
settings: {
|
||||
theme: i % 2 === 0 ? 'dark' : 'light',
|
||||
language: ['en', 'es', 'fr', 'de', 'ja'][i % 5],
|
||||
notifications: { email: true, push: i % 3 !== 0, sms: false },
|
||||
timezone: 'America/New_York',
|
||||
},
|
||||
metadata: {
|
||||
createdAt: '2024-01-15T08:30:00.000Z',
|
||||
updatedAt: '2024-12-01T14:22:33.456Z',
|
||||
lastLogin: '2024-12-15T09:45:00.000Z',
|
||||
loginCount: 100 + i * 7,
|
||||
},
|
||||
});
|
||||
}
|
||||
return JSON.stringify({ data: users, total: count, page: 1, perPage: count });
|
||||
}
|
||||
|
||||
// 3. Large analytics/event payloads (~50-200 KB)
|
||||
function generateEventPayload(count) {
|
||||
const events = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
events.push({
|
||||
id: `evt_${Date.now()}_${i}`,
|
||||
type: [
|
||||
'page_view',
|
||||
'click',
|
||||
'form_submit',
|
||||
'api_call',
|
||||
'error',
|
||||
'purchase',
|
||||
][i % 6],
|
||||
timestamp: new Date(Date.now() - i * 60000).toISOString(),
|
||||
session: `sess_${Math.floor(i / 10)}`,
|
||||
user: i % 5 === 0 ? null : `usr_${i % 100}`,
|
||||
properties: {
|
||||
url: `https://example.com/page/${i % 20}?ref=dashboard&utm_source=email`,
|
||||
title: `Page Title ${i % 20} — Application Dashboard`,
|
||||
referrer: i % 3 === 0 ? 'https://google.com/search?q=test' : '',
|
||||
duration: Math.round(Math.random() * 30000),
|
||||
viewport: { width: 1920, height: 1080 },
|
||||
device: {
|
||||
type: ['desktop', 'mobile', 'tablet'][i % 3],
|
||||
os: ['Windows 11', 'macOS 14', 'iOS 17', 'Android 14'][i % 4],
|
||||
browser: ['Chrome 120', 'Firefox 121', 'Safari 17'][i % 3],
|
||||
},
|
||||
},
|
||||
context: {
|
||||
ip: `10.${i % 256}.${(i * 3) % 256}.${(i * 7) % 256}`,
|
||||
locale: ['en-US', 'en-GB', 'es-ES', 'fr-FR', 'de-DE'][i % 5],
|
||||
campaign:
|
||||
i % 10 === 0 ?
|
||||
{ name: 'holiday_sale', medium: 'email', source: 'mailchimp' } :
|
||||
null,
|
||||
},
|
||||
});
|
||||
}
|
||||
return JSON.stringify({
|
||||
events,
|
||||
batch_id: `batch_${Date.now()}`,
|
||||
sent_at: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Deeply nested structure (config files, GraphQL responses)
|
||||
function generateNestedPayload(depth, breadth) {
|
||||
function nest(d) {
|
||||
if (d === 0) return { value: 'leaf', count: 42, tags: ['a', 'b'] };
|
||||
const obj = {};
|
||||
for (let i = 0; i < breadth; i++) {
|
||||
obj[`level_${d}_key_${i}`] = nest(d - 1);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
return JSON.stringify({ root: nest(depth), _meta: { depth, breadth } });
|
||||
}
|
||||
|
||||
// 5. Array-heavy payload (table data, CSV-like)
|
||||
function generateTablePayload(rows, cols) {
|
||||
const headers = Array.from({ length: cols }, (_, i) => `column_${i}`);
|
||||
const data = [];
|
||||
for (let r = 0; r < rows; r++) {
|
||||
const row = {};
|
||||
for (let c = 0; c < cols; c++) {
|
||||
row[headers[c]] =
|
||||
c % 3 === 0 ? r * c : c % 3 === 1 ? `val_${r}_${c}` : r % 2 === 0;
|
||||
}
|
||||
data.push(row);
|
||||
}
|
||||
return JSON.stringify({ headers, data, rowCount: rows });
|
||||
}
|
||||
|
||||
// 6. Unicode-heavy payload (i18n content)
|
||||
const UNICODE_PAYLOAD = JSON.stringify({
|
||||
messages: {
|
||||
en: { greeting: 'Hello, World!', farewell: 'Goodbye!' },
|
||||
ja: { greeting: 'こんにちは世界!', farewell: 'さようなら!' },
|
||||
ko: { greeting: '안녕하세요 세계!', farewell: '안녕히 가세요!' },
|
||||
zh: { greeting: '你好世界!', farewell: '再见!' },
|
||||
ar: { greeting: 'مرحبا بالعالم!', farewell: 'مع السلامة!' },
|
||||
ru: { greeting: 'Привет мир!', farewell: 'До свидания!' },
|
||||
de: { greeting: 'Hallo Welt!', farewell: 'Auf Wiedersehen!' },
|
||||
emoji: { greeting: '👋🌍✨', farewell: '👋😢💫' },
|
||||
},
|
||||
descriptions: Array.from(
|
||||
{ length: 50 },
|
||||
(_, i) =>
|
||||
`Item ${i}: Ünîcödé tëst with spëcîal chars — «quotes» "double" 'single' & ampersand \\ backslash / slash`,
|
||||
),
|
||||
});
|
||||
|
||||
// Pre-generate payloads as strings
|
||||
const mediumPayload10 = generateUserPayload(10);
|
||||
const mediumPayload50 = generateUserPayload(50);
|
||||
const largePayload100 = generateEventPayload(100);
|
||||
const largePayload500 = generateEventPayload(500);
|
||||
const nestedPayload = generateNestedPayload(5, 3);
|
||||
const tablePayload = generateTablePayload(200, 15);
|
||||
|
||||
// All payloads weighted by real-world frequency
|
||||
const PAYLOADS = [
|
||||
// Small payloads (health checks, simple responses) - most frequent
|
||||
...SMALL_PAYLOADS.map((p) => ({ json: p, weight: 5 })),
|
||||
// Medium payloads (typical API responses)
|
||||
{ json: mediumPayload10, weight: 8 },
|
||||
{ json: mediumPayload50, weight: 6 },
|
||||
// Large payloads (analytics, batch operations)
|
||||
{ json: largePayload100, weight: 3 },
|
||||
{ json: largePayload500, weight: 1 },
|
||||
// Nested payloads (config, GraphQL)
|
||||
{ json: nestedPayload, weight: 2 },
|
||||
// Table payloads (data grids, reports)
|
||||
{ json: tablePayload, weight: 2 },
|
||||
// Unicode payloads (i18n)
|
||||
{ json: UNICODE_PAYLOAD, weight: 2 },
|
||||
];
|
||||
|
||||
const weightedPayloads = [];
|
||||
for (const p of PAYLOADS) {
|
||||
for (let i = 0; i < p.weight; i++) {
|
||||
weightedPayloads.push(p.json);
|
||||
}
|
||||
}
|
||||
|
||||
// Workload 1: Parse → access properties → stringify (REST API middleware pattern)
|
||||
function workloadParseTransformStringify(jsonStr) {
|
||||
const obj = JSON.parse(jsonStr);
|
||||
|
||||
// Typical middleware transforms
|
||||
if (obj.data && Array.isArray(obj.data)) {
|
||||
// Add computed field (common API pattern)
|
||||
for (const item of obj.data) {
|
||||
item._computed =
|
||||
typeof item.id === 'string' ? item.id.toUpperCase() : String(item.id);
|
||||
}
|
||||
}
|
||||
if (obj.events && Array.isArray(obj.events)) {
|
||||
// Filter/transform (analytics pipeline)
|
||||
obj.events = obj.events.filter((e) => e.type !== 'error');
|
||||
obj.filteredCount = obj.events.length;
|
||||
}
|
||||
|
||||
return JSON.stringify(obj);
|
||||
}
|
||||
|
||||
// Workload 2: Parse → extract subset → stringify (GraphQL resolver pattern)
|
||||
function workloadSelectiveSerialize(jsonStr) {
|
||||
const obj = JSON.parse(jsonStr);
|
||||
const subset = {};
|
||||
|
||||
// Pick only requested fields (like GraphQL field selection)
|
||||
for (const key of Object.keys(obj)) {
|
||||
if (typeof obj[key] !== 'object' || obj[key] === null) {
|
||||
subset[key] = obj[key];
|
||||
} else if (Array.isArray(obj[key]) && obj[key].length > 0) {
|
||||
subset[key] = obj[key].slice(0, 5).map((item) => {
|
||||
if (typeof item === 'object' && item !== null) {
|
||||
const { id, name, type, email } = item;
|
||||
return { id, name, type, email };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(subset);
|
||||
}
|
||||
|
||||
// Workload 3: Repeated parse/stringify of same shape (template response caching pattern)
|
||||
function workloadRepeatedShapes() {
|
||||
const results = [];
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const obj = {
|
||||
id: i,
|
||||
name: `Item ${i}`,
|
||||
description: `Description for item ${i} with some additional text`,
|
||||
price: (i * 1.5).toFixed(2),
|
||||
inStock: i % 3 !== 0,
|
||||
categories: ['cat1', 'cat2'],
|
||||
ratings: { average: 4.5, count: i * 10 },
|
||||
};
|
||||
results.push(JSON.stringify(obj));
|
||||
}
|
||||
// Parse them all back
|
||||
return results.map((s) => JSON.parse(s));
|
||||
}
|
||||
|
||||
// Workload 4: JSON.parse with reviver / JSON.stringify with replacer
|
||||
function workloadReviverReplacer(jsonStr) {
|
||||
// Parse with date reviver (common pattern)
|
||||
const dateReviver = (key, value) => {
|
||||
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
|
||||
return new Date(value);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
const obj = JSON.parse(jsonStr, dateReviver);
|
||||
|
||||
// Stringify with replacer to exclude nulls (sanitization)
|
||||
const nullRemover = (key, value) => (value === null ? undefined : value);
|
||||
return JSON.stringify(obj, nullRemover);
|
||||
}
|
||||
|
||||
// Workload 5: Build large JSON incrementally (logging, audit trail)
|
||||
function workloadIncrementalBuild() {
|
||||
const entries = [];
|
||||
for (let i = 0; i < 200; i++) {
|
||||
entries.push({
|
||||
level: ['info', 'warn', 'error', 'debug'][i % 4],
|
||||
message: `Log entry ${i}: Operation completed successfully with result code ${i * 3}`,
|
||||
timestamp: Date.now() - i * 1000,
|
||||
context: { requestId: `req_${i}`, userId: `user_${i % 20}` },
|
||||
});
|
||||
}
|
||||
const logBatch = JSON.stringify({ entries, count: entries.length });
|
||||
// Verify round-trip
|
||||
const parsed = JSON.parse(logBatch);
|
||||
return parsed.count;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-json] Starting JSON processing workload...');
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let batchNum = 0;
|
||||
|
||||
while (Date.now() - startTime < DURATION_MS) {
|
||||
batchNum++;
|
||||
|
||||
// Workload 1: Parse-transform-stringify (highest weight — most common)
|
||||
for (let i = 0; i < ITERATIONS_PER_BATCH; i++) {
|
||||
const payload = weightedPayloads[i % weightedPayloads.length];
|
||||
workloadParseTransformStringify(payload);
|
||||
totalOps++;
|
||||
}
|
||||
|
||||
// Workload 2: Selective serialization
|
||||
for (let i = 0; i < Math.floor(ITERATIONS_PER_BATCH / 2); i++) {
|
||||
const payload = weightedPayloads[i % weightedPayloads.length];
|
||||
workloadSelectiveSerialize(payload);
|
||||
totalOps++;
|
||||
}
|
||||
|
||||
// Workload 3: Repeated shapes (every 3rd batch)
|
||||
if (batchNum % 3 === 0) {
|
||||
workloadRepeatedShapes();
|
||||
totalOps += 200; // 100 stringify + 100 parse
|
||||
}
|
||||
|
||||
// Workload 4: Reviver/replacer (every 2nd batch)
|
||||
if (batchNum % 2 === 0) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const payload = weightedPayloads[i % weightedPayloads.length];
|
||||
workloadReviverReplacer(payload);
|
||||
totalOps++;
|
||||
}
|
||||
}
|
||||
|
||||
// Workload 5: Incremental build (every 5th batch)
|
||||
if (batchNum % 5 === 0) {
|
||||
workloadIncrementalBuild();
|
||||
totalOps += 201; // 200 items + 1 round-trip
|
||||
}
|
||||
|
||||
// Yield to event loop periodically (realistic for servers)
|
||||
if (batchNum % 10 === 0) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-json] Completed ${totalOps} JSON operations in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s)`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-json] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,719 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable no-void */
|
||||
|
||||
// PGO Training Script: Module Loading and Startup
|
||||
//
|
||||
// Module loading (require/import) is one of Node.js's most performance-critical
|
||||
// paths, especially for:
|
||||
// - Application startup time (serverless cold starts, CLI tools)
|
||||
// - require() resolution algorithm (stat cascade, package.json parsing)
|
||||
// - ESM vs CJS loading (import() dynamic imports)
|
||||
// - Circular dependency resolution
|
||||
// - Built-in module loading
|
||||
// - JSON module loading (package.json, config files)
|
||||
//
|
||||
// This exercises: module resolver (fs.stat/readFile cascade), V8 script
|
||||
// compilation, source code parsing, JSON parsing, path resolution,
|
||||
// module wrapper function, exports/require machinery.
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const vm = require('vm');
|
||||
const Module = require('module');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
const TEMP_DIR = path.join(
|
||||
os.tmpdir(),
|
||||
`node-pgo-module-${process.pid}-${Date.now()}`,
|
||||
);
|
||||
|
||||
function setup() {
|
||||
fs.mkdirSync(TEMP_DIR, { recursive: true });
|
||||
|
||||
// Create a realistic module tree
|
||||
// node_modules/
|
||||
// express/
|
||||
// package.json
|
||||
// index.js
|
||||
// lib/router.js, lib/request.js, lib/response.js
|
||||
// lodash/
|
||||
// package.json
|
||||
// lodash.js
|
||||
// config/
|
||||
// package.json
|
||||
// index.js
|
||||
// src/
|
||||
// index.js, utils.js, helpers.js, constants.js
|
||||
// models/user.js, models/product.js
|
||||
// middleware/auth.js, middleware/logger.js
|
||||
|
||||
const dirs = [
|
||||
'node_modules/express/lib',
|
||||
'node_modules/lodash',
|
||||
'node_modules/config',
|
||||
'node_modules/debug',
|
||||
'node_modules/body-parser',
|
||||
'src/models',
|
||||
'src/middleware',
|
||||
'src/routes',
|
||||
'src/utils',
|
||||
'lib',
|
||||
];
|
||||
|
||||
for (const dir of dirs) {
|
||||
fs.mkdirSync(path.join(TEMP_DIR, dir), { recursive: true });
|
||||
}
|
||||
|
||||
// Express-like module
|
||||
writeFile(
|
||||
'node_modules/express/package.json',
|
||||
JSON.stringify({
|
||||
name: 'express',
|
||||
version: '4.18.2',
|
||||
main: 'index.js',
|
||||
}),
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/express/index.js',
|
||||
`
|
||||
'use strict';
|
||||
const router = require('./lib/router');
|
||||
const request = require('./lib/request');
|
||||
const response = require('./lib/response');
|
||||
function createApp() {
|
||||
const app = { routes: [], use(fn) { this.routes.push(fn); return this; } };
|
||||
Object.assign(app, router, request, response);
|
||||
return app;
|
||||
}
|
||||
module.exports = createApp;
|
||||
module.exports.Router = router.Router;
|
||||
module.exports.static = function(root) { return function(req, res, next) { next(); }; };
|
||||
`,
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/express/lib/router.js',
|
||||
`
|
||||
'use strict';
|
||||
class Router { constructor() { this.stack = []; } route(path) { return this; } }
|
||||
exports.Router = function() { return new Router(); };
|
||||
exports.handle = function(req, res) {};
|
||||
exports.param = function(name, fn) {};
|
||||
`,
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/express/lib/request.js',
|
||||
`
|
||||
'use strict';
|
||||
exports.get = function(field) { return ''; };
|
||||
exports.accepts = function() { return true; };
|
||||
exports.is = function(type) { return type; };
|
||||
`,
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/express/lib/response.js',
|
||||
`
|
||||
'use strict';
|
||||
exports.send = function(body) { return this; };
|
||||
exports.json = function(obj) { return this; };
|
||||
exports.status = function(code) { return this; };
|
||||
`,
|
||||
);
|
||||
|
||||
// Lodash-like module
|
||||
writeFile(
|
||||
'node_modules/lodash/package.json',
|
||||
JSON.stringify({
|
||||
name: 'lodash',
|
||||
version: '4.17.21',
|
||||
main: 'lodash.js',
|
||||
}),
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/lodash/lodash.js',
|
||||
`
|
||||
'use strict';
|
||||
const _ = {};
|
||||
_.map = (arr, fn) => arr.map(fn);
|
||||
_.filter = (arr, fn) => arr.filter(fn);
|
||||
_.reduce = (arr, fn, init) => arr.reduce(fn, init);
|
||||
_.get = (obj, path, def) => { const keys = path.split('.'); let val = obj; for (const k of keys) { val = val?.[k]; } return val ?? def; };
|
||||
_.set = (obj, path, val) => { const keys = path.split('.'); let cur = obj; for (let i = 0; i < keys.length - 1; i++) { cur = cur[keys[i]] ??= {}; } cur[keys[keys.length-1]] = val; return obj; };
|
||||
_.cloneDeep = (obj) => JSON.parse(JSON.stringify(obj));
|
||||
_.debounce = (fn, wait) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), wait); }; };
|
||||
_.chunk = (arr, size) => { const res = []; for (let i = 0; i < arr.length; i += size) res.push(arr.slice(i, i + size)); return res; };
|
||||
_.flatten = (arr) => arr.flat();
|
||||
_.uniq = (arr) => [...new Set(arr)];
|
||||
module.exports = _;
|
||||
`,
|
||||
);
|
||||
|
||||
// Config module
|
||||
writeFile(
|
||||
'node_modules/config/package.json',
|
||||
JSON.stringify({
|
||||
name: 'config',
|
||||
version: '3.3.9',
|
||||
main: 'index.js',
|
||||
}),
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/config/index.js',
|
||||
`
|
||||
'use strict';
|
||||
const config = { db: { host: 'localhost', port: 5432 }, app: { port: 3000 } };
|
||||
module.exports = { get(key) { return key.split('.').reduce((o, k) => o?.[k], config); }, has(key) { return this.get(key) !== undefined; } };
|
||||
`,
|
||||
);
|
||||
|
||||
// Debug module
|
||||
writeFile(
|
||||
'node_modules/debug/package.json',
|
||||
JSON.stringify({
|
||||
name: 'debug',
|
||||
version: '4.3.4',
|
||||
main: 'index.js',
|
||||
}),
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/debug/index.js',
|
||||
`
|
||||
'use strict';
|
||||
module.exports = function(namespace) {
|
||||
return function(...args) { /* noop in production */ };
|
||||
};
|
||||
`,
|
||||
);
|
||||
|
||||
// Body-parser module
|
||||
writeFile(
|
||||
'node_modules/body-parser/package.json',
|
||||
JSON.stringify({
|
||||
name: 'body-parser',
|
||||
version: '1.20.2',
|
||||
main: 'index.js',
|
||||
}),
|
||||
);
|
||||
writeFile(
|
||||
'node_modules/body-parser/index.js',
|
||||
`
|
||||
'use strict';
|
||||
exports.json = function(options) { return function(req, res, next) { next(); }; };
|
||||
exports.urlencoded = function(options) { return function(req, res, next) { next(); }; };
|
||||
exports.raw = function(options) { return function(req, res, next) { next(); }; };
|
||||
`,
|
||||
);
|
||||
|
||||
// Application source files
|
||||
writeFile(
|
||||
'src/index.js',
|
||||
`
|
||||
'use strict';
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const debug = require('debug');
|
||||
const config = require('config');
|
||||
const { authenticate } = require('./middleware/auth');
|
||||
const { logger } = require('./middleware/logger');
|
||||
const userRoutes = require('./routes/users');
|
||||
const { formatDate, generateId } = require('./utils/helpers');
|
||||
const { ROLES, STATUS } = require('./utils/constants');
|
||||
module.exports = { express, bodyParser, debug, config, authenticate, logger, userRoutes, formatDate, generateId, ROLES, STATUS };
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
'src/utils/helpers.js',
|
||||
`
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
exports.formatDate = (d) => new Date(d).toISOString();
|
||||
exports.generateId = () => crypto.randomUUID();
|
||||
exports.sanitize = (str) => str.replace(/[<>&"']/g, '');
|
||||
exports.paginate = (arr, page, size) => arr.slice((page - 1) * size, page * size);
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
'src/utils/constants.js',
|
||||
`
|
||||
'use strict';
|
||||
exports.ROLES = Object.freeze({ ADMIN: 'admin', USER: 'user', GUEST: 'guest' });
|
||||
exports.STATUS = Object.freeze({ ACTIVE: 'active', INACTIVE: 'inactive', PENDING: 'pending' });
|
||||
exports.LIMITS = Object.freeze({ MAX_PAGE_SIZE: 100, MAX_UPLOAD: 10 * 1024 * 1024 });
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
'src/models/user.js',
|
||||
`
|
||||
'use strict';
|
||||
const { generateId } = require('../utils/helpers');
|
||||
const { ROLES, STATUS } = require('../utils/constants');
|
||||
class User { constructor(data) { this.id = generateId(); this.role = ROLES.USER; this.status = STATUS.PENDING; Object.assign(this, data); } toJSON() { return { id: this.id, name: this.name, role: this.role }; } }
|
||||
module.exports = User;
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
'src/models/product.js',
|
||||
`
|
||||
'use strict';
|
||||
const { generateId } = require('../utils/helpers');
|
||||
class Product { constructor(data) { this.id = generateId(); Object.assign(this, data); } toJSON() { return { id: this.id, name: this.name, price: this.price }; } }
|
||||
module.exports = Product;
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
'src/middleware/auth.js',
|
||||
`
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
exports.authenticate = function(req, res, next) { const token = req?.headers?.authorization; return !!token; };
|
||||
exports.authorize = function(...roles) { return function(req, res, next) { return roles.length > 0; }; };
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
'src/middleware/logger.js',
|
||||
`
|
||||
'use strict';
|
||||
exports.logger = function(req, res, next) {
|
||||
const start = Date.now();
|
||||
return { duration: Date.now() - start, method: req?.method, url: req?.url };
|
||||
};
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
'src/routes/users.js',
|
||||
`
|
||||
'use strict';
|
||||
const User = require('../models/user');
|
||||
const { paginate } = require('../utils/helpers');
|
||||
const { authenticate } = require('../middleware/auth');
|
||||
exports.getUsers = function(page, size) { return paginate([], page, size); };
|
||||
exports.createUser = function(data) { return new User(data); };
|
||||
exports.getUser = function(id) { return null; };
|
||||
`,
|
||||
);
|
||||
|
||||
// ESM modules
|
||||
writeFile(
|
||||
'src/esm-entry.mjs',
|
||||
`
|
||||
import { createRequire } from 'module';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname, join } from 'path';
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const require = createRequire(import.meta.url);
|
||||
export const config = { loaded: true, dir: __dirname };
|
||||
export function greet(name) { return \`Hello, \${name}!\`; }
|
||||
export default { config, greet };
|
||||
`,
|
||||
);
|
||||
|
||||
// JSON file (loaded as module)
|
||||
writeFile(
|
||||
'config/default.json',
|
||||
JSON.stringify(
|
||||
{
|
||||
server: { port: 3000, host: '0.0.0.0' },
|
||||
database: {
|
||||
url: 'postgres://localhost:5432/myapp',
|
||||
pool: { min: 2, max: 10 },
|
||||
},
|
||||
redis: { url: 'redis://localhost:6379' },
|
||||
jwt: { secret: 'test-secret', expiresIn: '1h' },
|
||||
logging: { level: 'info' },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
// package.json at root
|
||||
writeFile(
|
||||
'package.json',
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'pgo-test-app',
|
||||
version: '1.0.0',
|
||||
main: 'src/index.js',
|
||||
dependencies: {
|
||||
'express': '^4.18.0',
|
||||
'lodash': '^4.17.0',
|
||||
'config': '^3.3.0',
|
||||
'debug': '^4.3.0',
|
||||
'body-parser': '^1.20.0',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function writeFile(relPath, content) {
|
||||
const fullPath = path.join(TEMP_DIR, relPath);
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
fs.writeFileSync(fullPath, content);
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
try {
|
||||
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
}
|
||||
|
||||
// Workload 1: require() with full resolution (CJS — the dominant pattern)
|
||||
function workloadCJSRequire(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Clear module cache to force re-resolution
|
||||
const keys = Object.keys(require.cache).filter((k) =>
|
||||
k.startsWith(TEMP_DIR),
|
||||
);
|
||||
for (const key of keys) {
|
||||
delete require.cache[key];
|
||||
}
|
||||
|
||||
// Require the full app (cascading dependencies)
|
||||
require(path.join(TEMP_DIR, 'src', 'index.js'));
|
||||
ops++;
|
||||
|
||||
// Require individual modules
|
||||
require(path.join(TEMP_DIR, 'node_modules', 'lodash', 'lodash.js'));
|
||||
require(path.join(TEMP_DIR, 'src', 'models', 'user.js'));
|
||||
require(path.join(TEMP_DIR, 'src', 'models', 'product.js'));
|
||||
ops += 3;
|
||||
|
||||
// JSON require (package.json resolution)
|
||||
delete require.cache[path.join(TEMP_DIR, 'package.json')];
|
||||
require(path.join(TEMP_DIR, 'package.json'));
|
||||
delete require.cache[path.join(TEMP_DIR, 'config', 'default.json')];
|
||||
require(path.join(TEMP_DIR, 'config', 'default.json'));
|
||||
ops += 2;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: Built-in module loading (no resolution needed, but exercises native binding)
|
||||
function workloadBuiltinRequire(iterations) {
|
||||
let ops = 0;
|
||||
const builtins = [
|
||||
'fs',
|
||||
'path',
|
||||
'http',
|
||||
'https',
|
||||
'crypto',
|
||||
'os',
|
||||
'url',
|
||||
'util',
|
||||
'events',
|
||||
'stream',
|
||||
'buffer',
|
||||
'net',
|
||||
'dns',
|
||||
'zlib',
|
||||
'child_process',
|
||||
'querystring',
|
||||
'string_decoder',
|
||||
'timers',
|
||||
'assert',
|
||||
'tls',
|
||||
'fs/promises',
|
||||
'stream/promises',
|
||||
'timers/promises',
|
||||
'node:fs',
|
||||
'node:path',
|
||||
'node:http',
|
||||
'node:crypto',
|
||||
'node:os',
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const mod of builtins) {
|
||||
require(mod);
|
||||
}
|
||||
ops += builtins.length;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: Module.createRequire and resolution
|
||||
function workloadModuleResolution(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// createRequire (used in ESM ↔ CJS interop)
|
||||
const customRequire = Module.createRequire(
|
||||
path.join(TEMP_DIR, 'src', 'index.js'),
|
||||
);
|
||||
|
||||
// Resolve module paths (this is the hot path in require())
|
||||
try {
|
||||
customRequire.resolve('express');
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
customRequire.resolve('lodash');
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
customRequire.resolve('./models/user');
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
customRequire.resolve('../package.json');
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
ops += 4;
|
||||
|
||||
// Module._resolveFilename (internal but exercises the same path)
|
||||
try {
|
||||
Module._resolveFilename('fs');
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
Module._resolveFilename('path');
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
ops += 2;
|
||||
|
||||
// Module.builtinModules
|
||||
void Module.builtinModules;
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 4: vm.Script compilation (V8 script compilation path)
|
||||
function workloadVMCompilation(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
const scripts = [
|
||||
// Simple expression
|
||||
'const x = 1 + 2; x;',
|
||||
// Function definition
|
||||
'function add(a, b) { return a + b; } add(1, 2);',
|
||||
// Object manipulation
|
||||
'const obj = { a: 1, b: { c: [1, 2, 3] } }; JSON.stringify(obj);',
|
||||
// Loop
|
||||
'let sum = 0; for (let i = 0; i < 1000; i++) sum += i; sum;',
|
||||
// Async-like pattern
|
||||
'const p = Promise.resolve(42); p.then(v => v * 2);',
|
||||
// Class definition (modern JS)
|
||||
`class Foo { constructor(x) { this.x = x; } get value() { return this.x; } }
|
||||
const f = new Foo(42); f.value;`,
|
||||
// Destructuring + spread
|
||||
'const { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 }; [a, b, ...Object.values(rest)];',
|
||||
// Map/Set
|
||||
'const m = new Map([[1,"a"],[2,"b"]]); const s = new Set([1,2,3]); m.size + s.size;',
|
||||
// Regex
|
||||
'const re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/; re.test("test@example.com");',
|
||||
// Template literals
|
||||
// eslint-disable-next-line no-template-curly-in-string
|
||||
'const name = "World"; const greeting = `Hello, ${name}! Today is ${new Date().toISOString()}`; greeting;',
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const code of scripts) {
|
||||
const script = new vm.Script(code, {
|
||||
filename: `script-${i}.js`,
|
||||
produceCachedData: i % 5 === 0, // Some with code caching
|
||||
});
|
||||
|
||||
const context = vm.createContext({
|
||||
JSON,
|
||||
Date,
|
||||
Promise,
|
||||
Map,
|
||||
Set,
|
||||
console,
|
||||
});
|
||||
script.runInContext(context, { timeout: 1000 });
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: Dynamic import() (ESM loading — growing usage)
|
||||
async function workloadDynamicImport(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Dynamic import of built-in modules (common in ESM code)
|
||||
await import('node:fs');
|
||||
await import('node:path');
|
||||
await import('node:crypto');
|
||||
await import('node:os');
|
||||
await import('node:util');
|
||||
await import('node:url');
|
||||
await import('node:events');
|
||||
await import('node:stream');
|
||||
ops += 8;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 6: Module._compile simulation (exercises V8 compilation)
|
||||
function workloadCompilePatterns(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
// Source code patterns that exercise different V8 compilation paths
|
||||
const sourcePatterns = [
|
||||
// Arrow functions (very common in modern JS)
|
||||
'module.exports = {\n' +
|
||||
Array.from(
|
||||
{ length: 20 },
|
||||
(_, i) => ` fn${i}: (x) => x * ${i + 1},`,
|
||||
).join('\n') +
|
||||
'\n};',
|
||||
|
||||
// async/await (extremely common in server code)
|
||||
`module.exports = async function(data) {
|
||||
const result = await Promise.resolve(data);
|
||||
const items = await Promise.all(
|
||||
Array.from({length: 10}, (_, i) => Promise.resolve(i * 2))
|
||||
);
|
||||
return { result, items, total: items.reduce((a,b) => a+b, 0) };
|
||||
};`,
|
||||
|
||||
// try/catch with specific error types
|
||||
`module.exports = function(input) {
|
||||
try {
|
||||
const data = JSON.parse(input);
|
||||
if (!data.id) throw new TypeError('Missing id');
|
||||
if (data.age < 0) throw new RangeError('Invalid age');
|
||||
return data;
|
||||
} catch (err) {
|
||||
if (err instanceof SyntaxError) return { error: 'Invalid JSON' };
|
||||
if (err instanceof TypeError) return { error: err.message };
|
||||
throw err;
|
||||
}
|
||||
};`,
|
||||
|
||||
// Generator function (used in Koa, some ORMs)
|
||||
`module.exports = function* paginate(items, pageSize) {
|
||||
for (let i = 0; i < items.length; i += pageSize) {
|
||||
yield items.slice(i, i + pageSize);
|
||||
}
|
||||
};`,
|
||||
|
||||
// Proxy/Reflect (used in Vue.js reactivity, ORMs)
|
||||
`module.exports = function createReactive(target) {
|
||||
return new Proxy(target, {
|
||||
get(obj, prop) { return Reflect.get(obj, prop); },
|
||||
set(obj, prop, value) { return Reflect.set(obj, prop, value); },
|
||||
has(obj, prop) { return Reflect.has(obj, prop); },
|
||||
});
|
||||
};`,
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const source of sourcePatterns) {
|
||||
const script = new vm.Script(
|
||||
`(function(exports, require, module, __filename, __dirname) { ${source} })`,
|
||||
{ filename: `compile-${i}.js` },
|
||||
);
|
||||
const context = vm.createContext({
|
||||
JSON,
|
||||
Promise,
|
||||
Array,
|
||||
Object,
|
||||
Map,
|
||||
Set,
|
||||
Proxy,
|
||||
Reflect,
|
||||
TypeError,
|
||||
RangeError,
|
||||
SyntaxError,
|
||||
Error,
|
||||
});
|
||||
script.runInContext(context);
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-module-loading] Starting module loading workload...');
|
||||
|
||||
setup();
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
try {
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// CJS require (the most common module operation)
|
||||
if (round === 1)
|
||||
console.log('[pgo-module-loading] Running CJS require...');
|
||||
totalOps += workloadCJSRequire(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Built-in module loading
|
||||
if (round === 1)
|
||||
console.log('[pgo-module-loading] Running built-in require...');
|
||||
totalOps += workloadBuiltinRequire(iterScale(200));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Module resolution
|
||||
if (round === 1)
|
||||
console.log('[pgo-module-loading] Running module resolution...');
|
||||
totalOps += workloadModuleResolution(iterScale(200));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// VM compilation
|
||||
if (round === 1)
|
||||
console.log('[pgo-module-loading] Running VM compilation...');
|
||||
totalOps += workloadVMCompilation(iterScale(50));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Compilation patterns
|
||||
if (round === 1)
|
||||
console.log('[pgo-module-loading] Running compile patterns...');
|
||||
totalOps += workloadCompilePatterns(iterScale(100));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Dynamic import
|
||||
if (round === 1)
|
||||
console.log('[pgo-module-loading] Running dynamic import...');
|
||||
totalOps += await workloadDynamicImport(iterScale(50));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-module-loading] Completed ${totalOps} ops in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-module-loading] Error:', err);
|
||||
cleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,443 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable no-void */
|
||||
|
||||
// PGO Training Script: Network (TCP) and DNS
|
||||
//
|
||||
// Exercises the core networking primitives used by every HTTP server/client:
|
||||
// - TCP server/client (the foundation of HTTP)
|
||||
// - DNS resolution (every outbound connection)
|
||||
// - Connection pooling patterns (keep-alive, max sockets)
|
||||
// - Various data transfer patterns (small messages, large payloads, streaming)
|
||||
// - Unix domain sockets / named pipes on Windows (IPC)
|
||||
//
|
||||
// This exercises: libuv TCP/pipe handles, DNS resolver (c-ares),
|
||||
// socket state machine, Buffer transfers, EventEmitter for net events.
|
||||
|
||||
const net = require('net');
|
||||
const dns = require('dns');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
const PORT_TCP = 0; // OS-assigned
|
||||
|
||||
// Test payloads simulating real protocols
|
||||
const SMALL_MSG = Buffer.from('{"type":"ping","ts":1234567890}\n');
|
||||
const MEDIUM_MSG = Buffer.from(
|
||||
JSON.stringify({
|
||||
type: 'data',
|
||||
payload: Array.from({ length: 100 }, (_, i) => ({
|
||||
key: `item_${i}`,
|
||||
value: crypto.randomBytes(16).toString('hex'),
|
||||
})),
|
||||
}) + '\n',
|
||||
);
|
||||
const LARGE_MSG = crypto.randomBytes(64 * 1024);
|
||||
|
||||
// Workload 1: TCP echo server with concurrent clients
|
||||
async function workloadTCPEcho(duration) {
|
||||
let totalOps = 0;
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
socket.on('data', (data) => {
|
||||
// Echo back with a small transformation (realistic: add header/length prefix)
|
||||
const response = Buffer.concat([Buffer.from(`${data.length}:`), data]);
|
||||
socket.write(response);
|
||||
});
|
||||
socket.on('error', () => {});
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(PORT_TCP, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
|
||||
const endTime = Date.now() + duration;
|
||||
|
||||
async function runClient() {
|
||||
let ops = 0;
|
||||
while (Date.now() < endTime) {
|
||||
await new Promise((resolve) => {
|
||||
const client = net.createConnection({ port, host: '127.0.0.1' }, () => {
|
||||
let msgsSent = 0;
|
||||
const maxMsgs = 50;
|
||||
|
||||
function sendNext() {
|
||||
if (msgsSent >= maxMsgs || Date.now() >= endTime) {
|
||||
client.end();
|
||||
return;
|
||||
}
|
||||
// Vary message sizes (realistic: mostly small, some medium, rare large)
|
||||
const r = Math.random();
|
||||
const msg = r < 0.7 ? SMALL_MSG : r < 0.95 ? MEDIUM_MSG : LARGE_MSG;
|
||||
client.write(msg);
|
||||
msgsSent++;
|
||||
ops++;
|
||||
}
|
||||
|
||||
client.on('data', () => {
|
||||
sendNext();
|
||||
});
|
||||
sendNext();
|
||||
});
|
||||
|
||||
client.on('end', resolve);
|
||||
client.on('error', () => resolve());
|
||||
client.setTimeout(2000, () => {
|
||||
client.destroy();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
const clients = Array.from({ length: 10 }, () => runClient());
|
||||
const results = await Promise.all(clients);
|
||||
totalOps = results.reduce((a, b) => a + b, 0);
|
||||
|
||||
server.close();
|
||||
return totalOps;
|
||||
}
|
||||
|
||||
// Workload 2: TCP request/response (HTTP-like pattern without HTTP overhead)
|
||||
async function workloadTCPRequestResponse(duration) {
|
||||
let totalOps = 0;
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
let buffer = '';
|
||||
socket.on('data', (data) => {
|
||||
buffer += data.toString();
|
||||
// Simple line-delimited protocol (like Redis, memcached)
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
try {
|
||||
const req = JSON.parse(line);
|
||||
let response;
|
||||
|
||||
switch (req.cmd) {
|
||||
case 'GET':
|
||||
response = {
|
||||
status: 'ok',
|
||||
key: req.key,
|
||||
value: 'cached_value_' + req.key,
|
||||
};
|
||||
break;
|
||||
case 'SET':
|
||||
response = { status: 'ok', key: req.key };
|
||||
break;
|
||||
case 'DEL':
|
||||
response = { status: 'ok', deleted: 1 };
|
||||
break;
|
||||
case 'MGET':
|
||||
response = {
|
||||
status: 'ok',
|
||||
values: req.keys.map((k) => 'val_' + k),
|
||||
};
|
||||
break;
|
||||
default:
|
||||
response = { status: 'error', message: 'Unknown command' };
|
||||
}
|
||||
socket.write(JSON.stringify(response) + '\n');
|
||||
} catch {
|
||||
socket.write('{"status":"error","message":"Parse error"}\n');
|
||||
}
|
||||
}
|
||||
});
|
||||
socket.on('error', () => {});
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
|
||||
const endTime = Date.now() + duration;
|
||||
|
||||
async function runClient() {
|
||||
let ops = 0;
|
||||
while (Date.now() < endTime) {
|
||||
await new Promise((resolve) => {
|
||||
const client = net.createConnection({ port, host: '127.0.0.1' }, () => {
|
||||
let pending = 0;
|
||||
const maxOps = 100;
|
||||
|
||||
function sendNext() {
|
||||
if (pending >= maxOps || Date.now() >= endTime) {
|
||||
client.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const commands = [
|
||||
{ cmd: 'GET', key: `user:${pending}` },
|
||||
{
|
||||
cmd: 'SET',
|
||||
key: `session:${pending}`,
|
||||
value: crypto.randomUUID(),
|
||||
},
|
||||
{ cmd: 'MGET', keys: ['key1', 'key2', 'key3'] },
|
||||
{ cmd: 'DEL', key: `temp:${pending}` },
|
||||
];
|
||||
const cmd = commands[pending % commands.length];
|
||||
client.write(JSON.stringify(cmd) + '\n');
|
||||
pending++;
|
||||
ops++;
|
||||
}
|
||||
|
||||
client.on('data', () => {
|
||||
sendNext();
|
||||
});
|
||||
sendNext();
|
||||
});
|
||||
|
||||
client.on('end', resolve);
|
||||
client.on('error', () => resolve());
|
||||
client.setTimeout(2000, () => {
|
||||
client.destroy();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
const clients = Array.from({ length: 8 }, () => runClient());
|
||||
const results = await Promise.all(clients);
|
||||
totalOps = results.reduce((a, b) => a + b, 0);
|
||||
|
||||
server.close();
|
||||
return totalOps;
|
||||
}
|
||||
|
||||
// Workload 3: Named pipe / IPC (very common on Windows - VS Code, build tools)
|
||||
async function workloadIPC(duration) {
|
||||
let totalOps = 0;
|
||||
const pipePath =
|
||||
process.platform === 'win32' ?
|
||||
`\\\\.\\pipe\\node-pgo-${process.pid}-${Date.now()}` :
|
||||
path.join(os.tmpdir(), `node-pgo-ipc-${process.pid}.sock`);
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
socket.on('data', (data) => {
|
||||
// IPC protocol: length-prefixed messages
|
||||
const msg = JSON.parse(data.toString());
|
||||
const response = {
|
||||
id: msg.id,
|
||||
result: msg.method === 'eval' ? 'ok' : 'unknown',
|
||||
data: { processed: true, timestamp: Date.now() },
|
||||
};
|
||||
const buf = Buffer.from(JSON.stringify(response));
|
||||
socket.write(buf);
|
||||
});
|
||||
socket.on('error', () => {});
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(pipePath, resolve));
|
||||
|
||||
const endTime = Date.now() + duration;
|
||||
|
||||
async function runClient() {
|
||||
let ops = 0;
|
||||
while (Date.now() < endTime) {
|
||||
await new Promise((resolve) => {
|
||||
const client = net.createConnection(pipePath, () => {
|
||||
let count = 0;
|
||||
const maxMsgs = 50;
|
||||
|
||||
function sendNext() {
|
||||
if (count >= maxMsgs || Date.now() >= endTime) {
|
||||
client.end();
|
||||
return;
|
||||
}
|
||||
const msg = {
|
||||
id: count,
|
||||
method: ['eval', 'complete', 'lint', 'format'][count % 4],
|
||||
params: { file: `src/file${count}.ts`, line: count * 2 },
|
||||
};
|
||||
client.write(JSON.stringify(msg));
|
||||
count++;
|
||||
ops++;
|
||||
}
|
||||
|
||||
client.on('data', () => sendNext());
|
||||
sendNext();
|
||||
});
|
||||
|
||||
client.on('end', resolve);
|
||||
client.on('error', () => resolve());
|
||||
client.setTimeout(2000, () => {
|
||||
client.destroy();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
const clients = Array.from({ length: 4 }, () => runClient());
|
||||
const results = await Promise.all(clients);
|
||||
totalOps = results.reduce((a, b) => a + b, 0);
|
||||
|
||||
server.close();
|
||||
// Cleanup socket file on Unix
|
||||
if (process.platform !== 'win32') {
|
||||
try {
|
||||
require('fs').unlinkSync(pipePath);
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
}
|
||||
return totalOps;
|
||||
}
|
||||
|
||||
// Workload 4: DNS resolution (every HTTP client connection does this)
|
||||
async function workloadDNS(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
// Use localhost and standard DNS patterns
|
||||
const hosts = ['localhost', '127.0.0.1', '::1'];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// dns.lookup (uses OS resolver — libuv thread pool)
|
||||
for (const host of hosts) {
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
dns.lookup(host, (err, address) => {
|
||||
if (err) reject(err);
|
||||
else resolve(address);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
} catch {
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
|
||||
// dns.lookup with options (IPv4/IPv6 preference)
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
dns.lookup('localhost', { family: 4 }, (err, address) => {
|
||||
if (err) reject(err);
|
||||
else resolve(address);
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
} catch {
|
||||
ops++;
|
||||
}
|
||||
|
||||
// dns.lookupService (reverse lookup)
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
dns.lookupService('127.0.0.1', 80, (err, hostname, service) => {
|
||||
if (err) reject(err);
|
||||
else resolve({ hostname, service });
|
||||
});
|
||||
});
|
||||
ops++;
|
||||
} catch {
|
||||
ops++;
|
||||
}
|
||||
|
||||
// net.isIP / net.isIPv4 / net.isIPv6 (validation in every request)
|
||||
net.isIP('192.168.1.1');
|
||||
net.isIP('::1');
|
||||
net.isIP('not-an-ip');
|
||||
net.isIPv4('192.168.1.1');
|
||||
net.isIPv6('::1');
|
||||
net.isIPv6('fe80::1%eth0');
|
||||
ops += 6;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: Socket options and state transitions
|
||||
async function workloadSocketOps(duration) {
|
||||
let totalOps = 0;
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
// Exercise socket properties (common in logging, monitoring)
|
||||
void socket.remoteAddress;
|
||||
void socket.remotePort;
|
||||
void socket.localAddress;
|
||||
void socket.localPort;
|
||||
void socket.bytesRead;
|
||||
void socket.bytesWritten;
|
||||
void socket.readyState;
|
||||
|
||||
socket.setNoDelay(true);
|
||||
socket.setKeepAlive(true, 1000);
|
||||
|
||||
socket.on('data', (data) => {
|
||||
socket.write(data);
|
||||
});
|
||||
socket.on('error', () => {});
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
|
||||
const endTime = Date.now() + duration;
|
||||
|
||||
// Rapid connect/disconnect (connection churn — load balancer pattern)
|
||||
while (Date.now() < endTime) {
|
||||
await new Promise((resolve) => {
|
||||
const client = net.createConnection({ port, host: '127.0.0.1' }, () => {
|
||||
client.setNoDelay(true);
|
||||
client.write('ping');
|
||||
});
|
||||
client.on('data', () => {
|
||||
totalOps++;
|
||||
client.end();
|
||||
});
|
||||
client.on('end', resolve);
|
||||
client.on('error', () => resolve());
|
||||
client.setTimeout(1000, () => {
|
||||
client.destroy();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
server.close();
|
||||
return totalOps;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-net] Starting network workload...');
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
|
||||
const timeBudget = (fraction) => Math.floor(DURATION_MS * fraction);
|
||||
|
||||
// TCP echo (data transfer throughput)
|
||||
console.log('[pgo-net] Running TCP echo...');
|
||||
totalOps += await workloadTCPEcho(timeBudget(0.25));
|
||||
|
||||
// TCP request/response (protocol handling)
|
||||
console.log('[pgo-net] Running TCP request/response...');
|
||||
totalOps += await workloadTCPRequestResponse(timeBudget(0.25));
|
||||
|
||||
// IPC / Named pipes
|
||||
console.log('[pgo-net] Running IPC...');
|
||||
totalOps += await workloadIPC(timeBudget(0.15));
|
||||
|
||||
// DNS resolution
|
||||
console.log('[pgo-net] Running DNS...');
|
||||
totalOps += await workloadDNS(100);
|
||||
|
||||
// Socket operations
|
||||
console.log('[pgo-net] Running socket ops...');
|
||||
totalOps += await workloadSocketOps(timeBudget(0.15));
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-net] Completed ${totalOps} net operations in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s)`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-net] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
'use strict';
|
||||
|
||||
// PGO Training Orchestrator: Runs All PGO Training Workloads
|
||||
//
|
||||
// This script orchestrates the execution of all PGO training workloads
|
||||
// sequentially. It is designed to be run against a PGO-instrumented
|
||||
|
||||
// Node.js build to generate profile data (.profraw files on Clang/Clang-CL,
|
||||
// .gcda files on GCC).
|
||||
//
|
||||
// Usage:
|
||||
// node tools/pgo/pgo-run-all.js [--duration=<seconds>] [--scripts=<comma-separated>]
|
||||
//
|
||||
// Options:
|
||||
// --duration=<seconds> Duration per script in seconds (default: 15)
|
||||
// --scripts=<list> Comma-separated list of scripts to run (default: all)
|
||||
// e.g. --scripts=http-server,json,crypto
|
||||
// --sequential Run scripts one at a time (default, safest for PGO)
|
||||
// --verbose Show detailed output from each script
|
||||
//
|
||||
// The scripts are ordered by their importance to real-world Node.js usage:
|
||||
// 1. HTTP Server (~60% of Node.js usage is web servers)
|
||||
// 2. JSON Processing (every REST API request/response)
|
||||
// 3. Crypto/TLS (every HTTPS connection)
|
||||
// 4. Streams/Buffers (all I/O goes through these)
|
||||
// 5. File System (config loading, static serving, build tools)
|
||||
// 6. Async Patterns (Promise/async-await is the concurrency model)
|
||||
// 7. URL/String (URL parsing in every request, string ops everywhere)
|
||||
// 8. Compression (HTTP response compression)
|
||||
// 9. Net/DNS (underlying TCP/DNS for all networking)
|
||||
// 10. Module Loading (startup, require() resolution)
|
||||
// 11. Child/Workers (build tools, process managers)
|
||||
|
||||
const { fork } = require('child_process');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const SCRIPT_DIR = __dirname;
|
||||
|
||||
// Training scripts in order of real-world importance
|
||||
const ALL_SCRIPTS = [
|
||||
{
|
||||
name: 'http-server',
|
||||
file: 'pgo-http-server.js',
|
||||
desc: 'HTTP server with JSON APIs, static content, routing',
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
file: 'pgo-json.js',
|
||||
desc: 'JSON parse/stringify with realistic payloads',
|
||||
},
|
||||
{
|
||||
name: 'crypto',
|
||||
file: 'pgo-crypto.js',
|
||||
desc: 'Hashing, HMAC, AES-GCM, RSA/ECDSA, random, PBKDF2',
|
||||
},
|
||||
{
|
||||
name: 'streams-buffers',
|
||||
file: 'pgo-streams-buffers.js',
|
||||
desc: 'Buffer creation/encoding, stream pipes, transforms',
|
||||
},
|
||||
{
|
||||
name: 'fs',
|
||||
file: 'pgo-fs.js',
|
||||
desc: 'File read/write, stat, readdir, streams, path ops',
|
||||
},
|
||||
{
|
||||
name: 'async-patterns',
|
||||
file: 'pgo-async-patterns.js',
|
||||
desc: 'Promises, EventEmitter, timers, AbortController, ALS',
|
||||
},
|
||||
{
|
||||
name: 'url-string',
|
||||
file: 'pgo-url-string.js',
|
||||
desc: 'URL parsing, regex, string ops, TextEncoder, util',
|
||||
},
|
||||
{
|
||||
name: 'compression',
|
||||
file: 'pgo-compression.js',
|
||||
desc: 'Gzip, deflate, brotli compress/decompress',
|
||||
},
|
||||
{
|
||||
name: 'net',
|
||||
file: 'pgo-net.js',
|
||||
desc: 'TCP server/client, IPC, DNS resolution',
|
||||
},
|
||||
{
|
||||
name: 'module-loading',
|
||||
file: 'pgo-module-loading.js',
|
||||
desc: 'CJS require, ESM import, VM compilation',
|
||||
},
|
||||
{
|
||||
name: 'child-workers',
|
||||
file: 'pgo-child-workers.js',
|
||||
desc: 'Worker thread messaging, SharedArrayBuffer, inline eval',
|
||||
},
|
||||
];
|
||||
|
||||
function parseArgs() {
|
||||
const args = {
|
||||
duration: 15,
|
||||
scripts: null,
|
||||
verbose: false,
|
||||
};
|
||||
|
||||
for (const arg of process.argv.slice(2)) {
|
||||
if (arg.startsWith('--duration=')) {
|
||||
args.duration = parseInt(arg.split('=')[1], 10);
|
||||
} else if (arg.startsWith('--scripts=')) {
|
||||
args.scripts = arg
|
||||
.split('=')[1]
|
||||
.split(',')
|
||||
.map((s) => s.trim());
|
||||
} else if (arg === '--verbose') {
|
||||
args.verbose = true;
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
console.log(`
|
||||
PGO Training Orchestrator for Node.js
|
||||
|
||||
Usage: node tools/pgo/pgo-run-all.js [options]
|
||||
|
||||
Options:
|
||||
--duration=<seconds> Duration per script (default: 15)
|
||||
--scripts=<list> Comma-separated script names (default: all)
|
||||
--verbose Show script output
|
||||
--help Show this help
|
||||
|
||||
Available scripts:
|
||||
${ALL_SCRIPTS.map((s) => ` ${s.name.padEnd(20)} ${s.desc}`).join('\n')}
|
||||
|
||||
Example:
|
||||
node tools/pgo/pgo-run-all.js --duration=20 --verbose
|
||||
node tools/pgo/pgo-run-all.js --scripts=http-server,json,crypto --duration=30
|
||||
`);
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
function runScript(scriptPath, duration, verbose) {
|
||||
return new Promise((resolve) => {
|
||||
const env = {
|
||||
...process.env,
|
||||
PGO_TRAINING_DURATION: String(duration * 1000),
|
||||
};
|
||||
const child = fork(scriptPath, [], {
|
||||
stdio: verbose ? 'inherit' : ['ignore', 'pipe', 'pipe', 'ipc'],
|
||||
env,
|
||||
});
|
||||
|
||||
let output = '';
|
||||
if (!verbose && child.stdout) {
|
||||
child.stdout.on('data', (data) => {
|
||||
output += data.toString();
|
||||
});
|
||||
}
|
||||
if (!verbose && child.stderr) {
|
||||
child.stderr.on('data', (data) => {
|
||||
output += data.toString();
|
||||
});
|
||||
}
|
||||
|
||||
// Safety timeout: kill if script runs too long
|
||||
const timeout = setTimeout(
|
||||
() => {
|
||||
console.log(' [TIMEOUT] Killing script...');
|
||||
child.kill('SIGTERM');
|
||||
setTimeout(() => child.kill('SIGKILL'), 5000);
|
||||
},
|
||||
(duration + 30) * 1000,
|
||||
);
|
||||
|
||||
child.on('exit', (code) => {
|
||||
clearTimeout(timeout);
|
||||
if (code !== 0 && code !== null) {
|
||||
// Extract last line of output for summary
|
||||
const lastLine = output.trim().split('\n').pop() || '';
|
||||
console.log(` [WARNING] Exited with code ${code}: ${lastLine}`);
|
||||
}
|
||||
resolve({ code, output });
|
||||
});
|
||||
|
||||
child.on('error', (err) => {
|
||||
clearTimeout(timeout);
|
||||
console.log(` [ERROR] ${err.message}`);
|
||||
resolve({ code: -1, output: err.message });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs();
|
||||
|
||||
// Select scripts
|
||||
let scripts = ALL_SCRIPTS;
|
||||
if (args.scripts) {
|
||||
scripts = args.scripts.map((name) => {
|
||||
const found = ALL_SCRIPTS.find((s) => s.name === name);
|
||||
if (!found) {
|
||||
console.error(`Unknown script: ${name}`);
|
||||
console.error(
|
||||
`Available: ${ALL_SCRIPTS.map((s) => s.name).join(', ')}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
return found;
|
||||
});
|
||||
}
|
||||
|
||||
const totalTime = scripts.length * args.duration;
|
||||
|
||||
console.log(
|
||||
'╔══════════════════════════════════════════════════════════════╗',
|
||||
);
|
||||
console.log('║ Node.js PGO Training Workload Runner ║');
|
||||
console.log(
|
||||
'╠══════════════════════════════════════════════════════════════╣',
|
||||
);
|
||||
console.log(`║ Scripts: ${String(scripts.length).padEnd(48)}║`);
|
||||
console.log(
|
||||
`║ Duration: ${String(args.duration + 's per script').padEnd(48)}║`,
|
||||
);
|
||||
console.log(`║ Total: ~${String(totalTime + 's estimated').padEnd(47)}║`);
|
||||
console.log(`║ Node: ${process.version.padEnd(48)}║`);
|
||||
console.log(
|
||||
`║ Arch: ${(process.arch + ' / ' + process.platform).padEnd(48)}║`,
|
||||
);
|
||||
console.log(
|
||||
'╚══════════════════════════════════════════════════════════════╝',
|
||||
);
|
||||
console.log('');
|
||||
|
||||
const startTime = Date.now();
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < scripts.length; i++) {
|
||||
const script = scripts[i];
|
||||
const scriptPath = path.join(SCRIPT_DIR, script.file);
|
||||
const num = `[${i + 1}/${scripts.length}]`;
|
||||
|
||||
console.log(`${num} Running: ${script.name}`);
|
||||
console.log(` ${script.desc}`);
|
||||
|
||||
const scriptStart = Date.now();
|
||||
const result = await runScript(scriptPath, args.duration, args.verbose);
|
||||
const elapsed = ((Date.now() - scriptStart) / 1000).toFixed(1);
|
||||
|
||||
const status = result.code === 0 ? 'OK' : `FAIL(${result.code})`;
|
||||
console.log(` Completed in ${elapsed}s [${status}]`);
|
||||
|
||||
// Extract ops/s from output if available
|
||||
if (!args.verbose && result.output) {
|
||||
const match = result.output.match(/(\d+) ops\/s|(\d+) req\/s/);
|
||||
if (match) {
|
||||
console.log(` Throughput: ${match[0]}`);
|
||||
}
|
||||
}
|
||||
console.log('');
|
||||
|
||||
results.push({
|
||||
name: script.name,
|
||||
elapsed: parseFloat(elapsed),
|
||||
code: result.code,
|
||||
});
|
||||
}
|
||||
|
||||
const totalElapsed = ((Date.now() - startTime) / 1000).toFixed(1);
|
||||
const passed = results.filter((r) => r.code === 0).length;
|
||||
const failed = results.filter((r) => r.code !== 0).length;
|
||||
|
||||
console.log(
|
||||
'════════════════════════════════════════════════════════════════',
|
||||
);
|
||||
console.log(`PGO Training Complete: ${totalElapsed}s total`);
|
||||
console.log(
|
||||
` ${passed} passed, ${failed} failed out of ${results.length} scripts`,
|
||||
);
|
||||
|
||||
if (failed > 0) {
|
||||
console.log(
|
||||
` Failed: ${results
|
||||
.filter((r) => r.code !== 0)
|
||||
.map((r) => r.name)
|
||||
.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Scan for .profraw files to verify profile data was collected
|
||||
const profrawDir = process.env.LLVM_PROFILE_FILE ?
|
||||
path.dirname(process.env.LLVM_PROFILE_FILE.replace(/%[mp]/g, '_')) :
|
||||
process.cwd();
|
||||
let profrawFiles = [];
|
||||
try {
|
||||
profrawFiles = fs
|
||||
.readdirSync(profrawDir)
|
||||
.filter((f) => f.endsWith('.profraw'));
|
||||
} catch {
|
||||
// Directory may not exist if LLVM_PROFILE_FILE points elsewhere
|
||||
}
|
||||
|
||||
console.log('');
|
||||
if (profrawFiles.length > 0) {
|
||||
let totalSize = 0;
|
||||
for (const f of profrawFiles) {
|
||||
try {
|
||||
totalSize += fs.statSync(path.join(profrawDir, f)).size;
|
||||
} catch {
|
||||
// Ignore stat errors
|
||||
}
|
||||
}
|
||||
const sizeMB = (totalSize / (1024 * 1024)).toFixed(1);
|
||||
console.log(
|
||||
`Profile data: ${profrawFiles.length} .profraw file(s), ${sizeMB} MB total`,
|
||||
);
|
||||
console.log(` Location: ${profrawDir}`);
|
||||
} else {
|
||||
console.log('WARNING: No .profraw files found in ' + profrawDir);
|
||||
console.log(
|
||||
' Ensure LLVM_PROFILE_FILE is set and the binary was built with -fprofile-generate',
|
||||
);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log(
|
||||
'Profile data should now be available for PGO-optimized rebuild.',
|
||||
);
|
||||
console.log(
|
||||
'════════════════════════════════════════════════════════════════',
|
||||
);
|
||||
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('PGO Orchestrator error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,579 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable no-void */
|
||||
|
||||
// PGO Training Script: Streams and Buffers
|
||||
//
|
||||
// Buffers and Streams are the backbone of all I/O in Node.js.
|
||||
// This script exercises:
|
||||
// - Buffer creation (from, alloc, allocUnsafe — most frequent allocations)
|
||||
// - Buffer encoding conversion (utf8, base64, hex, latin1 — every HTTP body)
|
||||
// - Buffer copy, slice, concat, compare, indexOf (data processing)
|
||||
// - Readable streams (HTTP request bodies, file reads)
|
||||
// - Writable streams (HTTP responses, file writes)
|
||||
// - Transform streams (compression, encryption, data pipelines)
|
||||
// - Pipe chains (the core streaming pattern)
|
||||
// - Object mode streams (ORMs, data processing libraries)
|
||||
// - Async iteration over streams (modern pattern)
|
||||
//
|
||||
// This exercises: Buffer C++ implementation, stream state machine,
|
||||
// back-pressure handling, highWaterMark management, GC pressure.
|
||||
|
||||
const { Readable, Writable, Transform, PassThrough } = require('stream');
|
||||
const { pipeline: pipelinePromise } = require('stream/promises');
|
||||
const { Buffer } = require('buffer');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
|
||||
// ============== BUFFER WORKLOADS ==============
|
||||
|
||||
// Workload 1: Buffer creation (the most frequent allocation in Node.js)
|
||||
function workloadBufferCreation(iterations) {
|
||||
let ops = 0;
|
||||
const str =
|
||||
'Hello, World! This is a test string for buffer creation benchmarks.';
|
||||
const arr = Array.from({ length: 64 }, (_, i) => i);
|
||||
const uint8 = new Uint8Array(64);
|
||||
const ab = new ArrayBuffer(64);
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Buffer.from string (most common — every HTTP body, every JSON parse input)
|
||||
Buffer.from(str);
|
||||
Buffer.from(str, 'utf8');
|
||||
Buffer.from(str, 'ascii');
|
||||
Buffer.from(str, 'latin1');
|
||||
ops += 4;
|
||||
|
||||
// Buffer.from with various source types
|
||||
Buffer.from(arr);
|
||||
Buffer.from(uint8);
|
||||
Buffer.from(ab);
|
||||
Buffer.from(Buffer.alloc(64));
|
||||
ops += 4;
|
||||
|
||||
// Buffer.alloc (zeroed — safe allocation)
|
||||
Buffer.alloc(16);
|
||||
Buffer.alloc(256);
|
||||
Buffer.alloc(4096);
|
||||
Buffer.alloc(64, 0xff);
|
||||
ops += 4;
|
||||
|
||||
// Buffer.allocUnsafe (fast allocation — used in hot paths)
|
||||
Buffer.allocUnsafe(16);
|
||||
Buffer.allocUnsafe(256);
|
||||
Buffer.allocUnsafe(4096);
|
||||
Buffer.allocUnsafe(65536);
|
||||
ops += 4;
|
||||
|
||||
// Buffer.concat (building response bodies)
|
||||
const chunks = [
|
||||
Buffer.from('chunk1'),
|
||||
Buffer.from('chunk2'),
|
||||
Buffer.from('chunk3'),
|
||||
];
|
||||
Buffer.concat(chunks);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: Buffer encoding/decoding (every HTTP interaction)
|
||||
function workloadBufferEncoding(iterations) {
|
||||
let ops = 0;
|
||||
const testData = crypto.randomBytes(1024);
|
||||
const testString =
|
||||
'The quick brown fox jumps over the lazy dog. 日本語テスト 🎉';
|
||||
const base64Data = testData.toString('base64');
|
||||
const hexData = testData.toString('hex');
|
||||
const base64urlData = testData.toString('base64url');
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// UTF-8 encode/decode (dominant encoding for web)
|
||||
const utf8Buf = Buffer.from(testString, 'utf8');
|
||||
utf8Buf.toString('utf8');
|
||||
ops += 2;
|
||||
|
||||
// Base64 encode/decode (binary data in JSON, data URIs, email attachments)
|
||||
testData.toString('base64');
|
||||
Buffer.from(base64Data, 'base64');
|
||||
ops += 2;
|
||||
|
||||
// Base64url (JWT tokens)
|
||||
testData.toString('base64url');
|
||||
Buffer.from(base64urlData, 'base64url');
|
||||
ops += 2;
|
||||
|
||||
// Hex encode/decode (crypto hashes, color codes, debugging)
|
||||
testData.toString('hex');
|
||||
Buffer.from(hexData, 'hex');
|
||||
ops += 2;
|
||||
|
||||
// ASCII/Latin1 (HTTP headers, protocol parsing)
|
||||
Buffer.from(
|
||||
'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n',
|
||||
'ascii',
|
||||
);
|
||||
Buffer.from('Set-Cookie: session=abc123; Path=/; HttpOnly', 'latin1');
|
||||
ops += 2;
|
||||
|
||||
// Buffer.byteLength (Content-Length header computation)
|
||||
Buffer.byteLength(testString, 'utf8');
|
||||
Buffer.byteLength(base64Data, 'base64');
|
||||
Buffer.byteLength('simple ascii text');
|
||||
ops += 3;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: Buffer operations (data processing patterns)
|
||||
function workloadBufferOps(iterations) {
|
||||
let ops = 0;
|
||||
const buf1 = crypto.randomBytes(1024);
|
||||
const buf2 = crypto.randomBytes(1024);
|
||||
const needle = Buffer.from('test');
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Buffer.compare (sorting, binary search)
|
||||
Buffer.compare(buf1, buf2);
|
||||
buf1.compare(buf2, 0, 100, 0, 100);
|
||||
ops += 2;
|
||||
|
||||
// Buffer.equals
|
||||
buf1.equals(buf2);
|
||||
buf1.equals(buf1);
|
||||
ops += 2;
|
||||
|
||||
// slice/subarray (zero-copy views — extremely common)
|
||||
buf1.subarray(0, 256);
|
||||
buf1.subarray(256, 512);
|
||||
buf1.subarray(512);
|
||||
ops += 3;
|
||||
|
||||
// copy (building protocol messages)
|
||||
const dest = Buffer.allocUnsafe(2048);
|
||||
buf1.copy(dest, 0);
|
||||
buf2.copy(dest, 1024);
|
||||
ops += 2;
|
||||
|
||||
// indexOf / includes (searching in binary data, parsers)
|
||||
buf1.indexOf(needle);
|
||||
buf1.includes(65); // ASCII 'A'
|
||||
buf1.lastIndexOf(0);
|
||||
ops += 3;
|
||||
|
||||
// fill (clearing sensitive data, initializing)
|
||||
const fillBuf = Buffer.allocUnsafe(256);
|
||||
fillBuf.fill(0);
|
||||
fillBuf.fill('abc');
|
||||
ops += 2;
|
||||
|
||||
// Read/write numeric values (protocol parsing, binary formats)
|
||||
buf1.readUInt32BE(0);
|
||||
buf1.readUInt32LE(0);
|
||||
buf1.readInt16BE(4);
|
||||
buf1.readFloatLE(8);
|
||||
buf1.readDoubleBE(16);
|
||||
dest.writeUInt32BE(i, 0);
|
||||
dest.writeInt16LE(i % 32768, 4);
|
||||
dest.writeFloatLE(i * 1.5, 8);
|
||||
ops += 8;
|
||||
|
||||
// swap (endianness conversion)
|
||||
const swapBuf = Buffer.from(buf1.subarray(0, 64));
|
||||
swapBuf.swap16();
|
||||
swapBuf.swap32();
|
||||
ops += 2;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// ============== STREAM WORKLOADS ==============
|
||||
|
||||
// Workload 4: Readable → Writable pipe (canonical throughput pattern)
|
||||
async function workloadPipeChain(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const chunkCount = 1000;
|
||||
const chunkSize = 1024;
|
||||
|
||||
await new Promise((resolve) => {
|
||||
let pushed = 0;
|
||||
const source = new Readable({
|
||||
read() {
|
||||
if (pushed >= chunkCount) {
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
this.push(crypto.randomBytes(chunkSize));
|
||||
pushed++;
|
||||
},
|
||||
});
|
||||
|
||||
const sink = new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
});
|
||||
|
||||
sink.on('finish', () => {
|
||||
ops += chunkCount;
|
||||
resolve();
|
||||
});
|
||||
source.pipe(sink);
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: Transform streams (compression/encryption pattern)
|
||||
async function workloadTransform(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
await new Promise((resolve) => {
|
||||
let pushed = 0;
|
||||
const chunkCount = 500;
|
||||
const source = new Readable({
|
||||
read() {
|
||||
if (pushed >= chunkCount) {
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
this.push(
|
||||
Buffer.from(
|
||||
`{"id":${pushed},"data":"${crypto.randomBytes(32).toString('hex')}"}\n`,
|
||||
),
|
||||
);
|
||||
pushed++;
|
||||
},
|
||||
});
|
||||
|
||||
// Transform: parse JSON line by line (NDJSON processing pattern)
|
||||
const transformer = new Transform({
|
||||
transform(chunk, encoding, callback) {
|
||||
const lines = chunk.toString().split('\n').filter(Boolean);
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const obj = JSON.parse(line);
|
||||
obj.processed = true;
|
||||
obj.timestamp = Date.now();
|
||||
this.push(JSON.stringify(obj) + '\n');
|
||||
} catch {
|
||||
/* skip invalid */
|
||||
}
|
||||
}
|
||||
callback();
|
||||
},
|
||||
});
|
||||
|
||||
const sink = new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
});
|
||||
|
||||
sink.on('finish', () => {
|
||||
ops += chunkCount;
|
||||
resolve();
|
||||
});
|
||||
source.pipe(transformer).pipe(sink);
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 6: Object mode streams (database query result processing)
|
||||
async function workloadObjectMode(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
await new Promise((resolve) => {
|
||||
let pushed = 0;
|
||||
const objCount = 200;
|
||||
|
||||
const source = new Readable({
|
||||
objectMode: true,
|
||||
read() {
|
||||
if (pushed >= objCount) {
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
this.push({
|
||||
id: pushed,
|
||||
name: `Record ${pushed}`,
|
||||
value: Math.random() * 1000,
|
||||
tags: ['tag1', 'tag2'],
|
||||
metadata: { created: Date.now(), source: 'db' },
|
||||
});
|
||||
pushed++;
|
||||
},
|
||||
});
|
||||
|
||||
// Transform: filter + map (like a database cursor)
|
||||
const filter = new Transform({
|
||||
objectMode: true,
|
||||
transform(obj, encoding, callback) {
|
||||
if (obj.value > 100) {
|
||||
callback(null, {
|
||||
...obj,
|
||||
value: Math.round(obj.value * 100) / 100,
|
||||
qualified: true,
|
||||
});
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const results = [];
|
||||
const collect = new Writable({
|
||||
objectMode: true,
|
||||
write(obj, encoding, callback) {
|
||||
results.push(obj);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
|
||||
collect.on('finish', () => {
|
||||
ops += objCount;
|
||||
resolve();
|
||||
});
|
||||
source.pipe(filter).pipe(collect);
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 7: Async iteration over streams (modern Node.js pattern)
|
||||
async function workloadAsyncIteration(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
let pushed = 0;
|
||||
const chunkCount = 500;
|
||||
|
||||
const source = new Readable({
|
||||
read() {
|
||||
if (pushed >= chunkCount) {
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
this.push(
|
||||
Buffer.from(
|
||||
`Line ${pushed}: ${crypto.randomBytes(20).toString('hex')}\n`,
|
||||
),
|
||||
);
|
||||
pushed++;
|
||||
},
|
||||
});
|
||||
|
||||
let lines = 0;
|
||||
for await (const chunk of source) {
|
||||
lines += chunk.toString().split('\n').filter(Boolean).length;
|
||||
}
|
||||
ops += lines;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 8: pipeline() with error handling (production pattern)
|
||||
async function workloadPipeline(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
let pushed = 0;
|
||||
const chunkCount = 300;
|
||||
|
||||
const source = new Readable({
|
||||
read() {
|
||||
if (pushed >= chunkCount) {
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
this.push(crypto.randomBytes(512));
|
||||
pushed++;
|
||||
},
|
||||
});
|
||||
|
||||
const uppercase = new Transform({
|
||||
transform(chunk, encoding, callback) {
|
||||
callback(null, chunk.toString('hex').toUpperCase());
|
||||
},
|
||||
});
|
||||
|
||||
let bytes = 0;
|
||||
const sink = new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
bytes += chunk.length;
|
||||
callback();
|
||||
},
|
||||
});
|
||||
|
||||
await pipelinePromise(source, uppercase, sink);
|
||||
ops += chunkCount;
|
||||
void bytes;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 9: PassThrough / Duplex (proxy patterns, tee)
|
||||
async function workloadPassThrough(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
let pushed = 0;
|
||||
const chunkCount = 200;
|
||||
|
||||
const source = new Readable({
|
||||
read() {
|
||||
if (pushed >= chunkCount) {
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
this.push(crypto.randomBytes(256));
|
||||
pushed++;
|
||||
},
|
||||
});
|
||||
|
||||
// Tee pattern: split stream to two destinations
|
||||
const pt1 = new PassThrough();
|
||||
const pt2 = new PassThrough();
|
||||
|
||||
let bytes1 = 0;
|
||||
let bytes2 = 0;
|
||||
const sink1 = new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
bytes1 += chunk.length;
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const sink2 = new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
bytes2 += chunk.length;
|
||||
callback();
|
||||
},
|
||||
});
|
||||
|
||||
source.pipe(pt1).pipe(sink1);
|
||||
source.pipe(pt2).pipe(sink2);
|
||||
|
||||
await Promise.all([
|
||||
new Promise((r) => sink1.on('finish', r)),
|
||||
new Promise((r) => sink2.on('finish', r)),
|
||||
]);
|
||||
ops += chunkCount * 2;
|
||||
void bytes1;
|
||||
void bytes2;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 10: Readable.from() with generators (modern data source pattern)
|
||||
async function workloadReadableFrom(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// From array
|
||||
const arr = Array.from({ length: 100 }, (_, j) => `item-${j}\n`);
|
||||
const stream1 = Readable.from(arr);
|
||||
let data1 = '';
|
||||
for await (const chunk of stream1) {
|
||||
data1 += chunk;
|
||||
}
|
||||
ops += 100;
|
||||
void data1;
|
||||
|
||||
// From async generator (database cursor simulation)
|
||||
async function* generateRows() {
|
||||
for (let j = 0; j < 100; j++) {
|
||||
yield JSON.stringify({ row: j, value: Math.random() }) + '\n';
|
||||
}
|
||||
}
|
||||
|
||||
const stream2 = Readable.from(generateRows());
|
||||
let data2 = '';
|
||||
for await (const chunk of stream2) {
|
||||
data2 += chunk;
|
||||
}
|
||||
ops += 100;
|
||||
void data2;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-streams-buffers] Starting streams & buffers workload...');
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// Buffer workloads (sync, fast — exercise C++ bindings extensively)
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running buffer creation...');
|
||||
totalOps += workloadBufferCreation(iterScale(2000));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running buffer encoding...');
|
||||
totalOps += workloadBufferEncoding(iterScale(1000));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running buffer operations...');
|
||||
totalOps += workloadBufferOps(iterScale(1000));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Stream workloads (async, exercise event loop + back-pressure)
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running pipe chains...');
|
||||
totalOps += await workloadPipeChain(iterScale(5));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running transform streams...');
|
||||
totalOps += await workloadTransform(iterScale(5));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running object mode streams...');
|
||||
totalOps += await workloadObjectMode(iterScale(10));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running async iteration...');
|
||||
totalOps += await workloadAsyncIteration(iterScale(5));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1) console.log('[pgo-streams-buffers] Running pipeline()...');
|
||||
totalOps += await workloadPipeline(iterScale(5));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running PassThrough...');
|
||||
totalOps += await workloadPassThrough(iterScale(5));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
if (round === 1)
|
||||
console.log('[pgo-streams-buffers] Running Readable.from()...');
|
||||
totalOps += await workloadReadableFrom(iterScale(10));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-streams-buffers] Completed ${totalOps} ops in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-streams-buffers] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,566 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable no-void */
|
||||
|
||||
// PGO Training Script: URL Parsing and String Operations
|
||||
//
|
||||
// URL parsing and string manipulation are pervasive in Node.js web apps:
|
||||
// - WHATWG URL parsing (every HTTP request in modern code)
|
||||
// - Legacy url.parse (still heavily used in existing codebases)
|
||||
// - URLSearchParams (query string handling in every API)
|
||||
// - Regex matching (routing, validation, sanitization)
|
||||
// - String operations (template rendering, concatenation, encoding)
|
||||
// - TextEncoder/TextDecoder (Web API string encoding)
|
||||
// - querystring module (legacy but still widely used)
|
||||
// - util.format, util.inspect (logging, debugging)
|
||||
//
|
||||
// This exercises: V8 string internals (one-byte/two-byte, cons, sliced),
|
||||
// Ada URL parser (C++), regex JIT, TextEncoder/Decoder C++ implementation.
|
||||
|
||||
const url = require('url');
|
||||
const { URL, URLSearchParams } = url;
|
||||
const querystring = require('querystring');
|
||||
const util = require('util');
|
||||
const { TextEncoder, TextDecoder } = util;
|
||||
|
||||
const DURATION_MS = parseInt(process.env.PGO_TRAINING_DURATION, 10) || 15_000;
|
||||
|
||||
// Realistic URLs from web applications
|
||||
const TEST_URLS = [
|
||||
'https://api.example.com/v2/users?page=1&limit=50&sort=name&order=asc',
|
||||
'https://www.example.com/products/category/electronics?brand=apple&min_price=100&max_price=2000&in_stock=true',
|
||||
'http://localhost:3000/api/auth/login',
|
||||
'https://cdn.example.com/assets/images/hero-banner-2024.webp?w=1920&h=1080&q=85',
|
||||
'https://user:pass@db.example.com:5432/myapp?ssl=true&pool=10',
|
||||
'wss://realtime.example.com/ws/v1?token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0',
|
||||
'https://example.com/path/to/resource#section-2',
|
||||
'https://search.example.com/q?query=node.js+performance+optimization&lang=en&safe=on',
|
||||
'https://api.example.com/v3/organizations/org-123/projects/proj-456/deployments/deploy-789/logs?since=2024-01-01T00:00:00Z&until=2024-12-31T23:59:59Z&level=error',
|
||||
'https://example.com/path%20with%20spaces/file%23name.html?key=value%26more',
|
||||
'https://xn--nxasmq6b.example.com/internationalized', // IDN
|
||||
'file:///C:/Users/user/Documents/project/index.html',
|
||||
'https://api.github.com/repos/nodejs/node/commits?sha=main&per_page=30',
|
||||
'https://registry.npmjs.org/@types/node/-/node-20.10.0.tgz',
|
||||
'http://[::1]:8080/ipv6-local',
|
||||
'data:text/html;base64,PGh0bWw+PC9odG1sPg==',
|
||||
];
|
||||
|
||||
// Workload 1: WHATWG URL parsing (modern standard — every HTTP request)
|
||||
function workloadWHATWGURL(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const urlStr of TEST_URLS) {
|
||||
try {
|
||||
const parsed = new URL(urlStr);
|
||||
|
||||
// Access all properties (common in routing/logging)
|
||||
void parsed.href;
|
||||
void parsed.origin;
|
||||
void parsed.protocol;
|
||||
void parsed.hostname;
|
||||
void parsed.port;
|
||||
void parsed.pathname;
|
||||
void parsed.search;
|
||||
void parsed.hash;
|
||||
void parsed.username;
|
||||
void parsed.password;
|
||||
ops++;
|
||||
|
||||
// Modify URL (redirect, base URL construction)
|
||||
const modified = new URL(urlStr);
|
||||
modified.pathname = '/new-path';
|
||||
modified.searchParams.set('modified', 'true');
|
||||
modified.toString();
|
||||
ops++;
|
||||
|
||||
// URL.canParse (validation)
|
||||
URL.canParse(urlStr);
|
||||
URL.canParse('not-a-url');
|
||||
ops++;
|
||||
} catch {
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 2: URLSearchParams (query string handling)
|
||||
function workloadURLSearchParams(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Create from string
|
||||
const params1 = new URLSearchParams(
|
||||
'page=1&limit=50&sort=name&order=asc&fields=id,name,email',
|
||||
);
|
||||
params1.get('page');
|
||||
params1.get('limit');
|
||||
params1.getAll('fields');
|
||||
params1.has('sort');
|
||||
ops++;
|
||||
|
||||
// Create from object (common API pattern)
|
||||
const params2 = new URLSearchParams({
|
||||
q: 'node.js performance',
|
||||
lang: 'en',
|
||||
page: '1',
|
||||
format: 'json',
|
||||
});
|
||||
params2.toString();
|
||||
ops++;
|
||||
|
||||
// Create from entries (Map-like)
|
||||
const params3 = new URLSearchParams([
|
||||
['key1', 'value1'],
|
||||
['key2', 'value2'],
|
||||
['key1', 'value3'],
|
||||
]);
|
||||
params3.getAll('key1');
|
||||
ops++;
|
||||
|
||||
// Iterate (common for logging, forwarding)
|
||||
for (const entry of params1) {
|
||||
void entry;
|
||||
}
|
||||
ops++;
|
||||
|
||||
// Modify (adding/removing filters in API clients)
|
||||
params1.set('page', '2');
|
||||
params1.append('filter', 'active');
|
||||
params1.append('filter', 'verified');
|
||||
params1.delete('order');
|
||||
params1.sort();
|
||||
params1.toString();
|
||||
ops++;
|
||||
|
||||
// Complex real-world query strings
|
||||
const complexQuery = new URLSearchParams(
|
||||
'filters[status]=active&filters[role][]=admin&filters[role][]=editor&' +
|
||||
'sort=-createdAt&fields=id,name,email,role&page[number]=1&page[size]=25&' +
|
||||
'include=profile,permissions&meta=true',
|
||||
);
|
||||
for (const entry of complexQuery) {
|
||||
void entry;
|
||||
}
|
||||
complexQuery.toString();
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 3: Legacy url.parse (still very common in existing code)
|
||||
function workloadLegacyURL(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const urlStr of TEST_URLS) {
|
||||
try {
|
||||
// url.parse (Express's req.url handling)
|
||||
const parsed = url.parse(urlStr, true); // true = parse query string
|
||||
void parsed.pathname;
|
||||
void parsed.query;
|
||||
void parsed.hostname;
|
||||
void parsed.protocol;
|
||||
ops++;
|
||||
|
||||
// url.format (building URLs)
|
||||
url.format({
|
||||
protocol: 'https',
|
||||
hostname: 'api.example.com',
|
||||
pathname: `/v2/users/${i}`,
|
||||
query: { fields: 'id,name', format: 'json' },
|
||||
});
|
||||
ops++;
|
||||
|
||||
// url.resolve (relative URL resolution)
|
||||
url.resolve('https://example.com/base/', './relative/path');
|
||||
url.resolve('https://example.com/base/path', '../other/path');
|
||||
ops++;
|
||||
} catch {
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 4: querystring module (legacy but still heavily used)
|
||||
function workloadQuerystring(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
const testQueries = [
|
||||
'name=John+Doe&age=30&city=New+York',
|
||||
'key1=val1&key2=val2&key3=val3&key4=val4&key5=val5',
|
||||
'q=search+term&page=1&per_page=20&sort=relevance',
|
||||
'data=%7B%22key%22%3A%22value%22%7D',
|
||||
'tags=node&tags=javascript&tags=performance',
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const qs of testQueries) {
|
||||
// Parse
|
||||
const parsed = querystring.parse(qs);
|
||||
ops++;
|
||||
|
||||
// Stringify
|
||||
querystring.stringify(parsed);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// Encode/decode
|
||||
querystring.escape('Hello World! <>&"');
|
||||
querystring.unescape('Hello%20World%21%20%3C%3E%26%22');
|
||||
ops += 2;
|
||||
|
||||
// Stringify with custom separator (some APIs use ; instead of &)
|
||||
querystring.stringify({ a: 1, b: 2, c: 3 }, ';', ':');
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 5: String operations (templating, manipulation)
|
||||
function workloadStringOps(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
const template = 'Hello, {{name}}! You have {{count}} new {{type}} messages.';
|
||||
const strings = [
|
||||
'the quick brown fox jumps over the lazy dog',
|
||||
'UPPERCASE STRING TO CONVERT',
|
||||
' whitespace string with extra spaces ',
|
||||
'CamelCaseString_with_mixed_SEPARATORS-and-dashes',
|
||||
'path/to/some/file.extension.backup.2024',
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Template replacement (Mustache/Handlebars-like pattern)
|
||||
template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
|
||||
const values = { name: 'User', count: '5', type: 'unread' };
|
||||
return values[key] || match;
|
||||
});
|
||||
ops++;
|
||||
|
||||
for (const str of strings) {
|
||||
// Case conversion (header normalization, camelCase conversion)
|
||||
str.toLowerCase();
|
||||
str.toUpperCase();
|
||||
ops += 2;
|
||||
|
||||
// Trim (input sanitization)
|
||||
str.trim();
|
||||
str.trimStart();
|
||||
str.trimEnd();
|
||||
ops += 3;
|
||||
|
||||
// Split/join (CSV processing, path parsing)
|
||||
str.split(/[\s_-]+/).join(' ');
|
||||
str.split('.').join('/');
|
||||
ops += 2;
|
||||
|
||||
// Include/startsWith/endsWith (routing, MIME detection)
|
||||
str.includes('fox');
|
||||
str.startsWith('the');
|
||||
str.endsWith('dog');
|
||||
str.indexOf('the');
|
||||
str.lastIndexOf('the');
|
||||
ops += 5;
|
||||
|
||||
// Slice/substring (truncation, preview generation)
|
||||
str.slice(0, 20);
|
||||
str.substring(5, 15);
|
||||
ops += 2;
|
||||
|
||||
// Replace (sanitization, normalization)
|
||||
str.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
str.replaceAll(' ', '-');
|
||||
ops += 2;
|
||||
|
||||
// padStart/padEnd (formatting)
|
||||
String(i).padStart(6, '0');
|
||||
str.slice(0, 10).padEnd(20, '.');
|
||||
ops += 2;
|
||||
|
||||
// Repeat (indentation generation)
|
||||
' '.repeat(Math.min(i % 10, 5));
|
||||
ops++;
|
||||
}
|
||||
|
||||
// String concatenation patterns
|
||||
let result = '';
|
||||
for (let j = 0; j < 100; j++) {
|
||||
result += `item_${j},`;
|
||||
}
|
||||
ops++;
|
||||
void result;
|
||||
|
||||
// Template literal (most common string building pattern)
|
||||
const items = Array.from(
|
||||
{ length: 20 },
|
||||
(_, j) => ` "${j}": "value_${j}"`,
|
||||
);
|
||||
const json = `{\n${items.join(',\n')}\n}`;
|
||||
ops++;
|
||||
void json;
|
||||
|
||||
// String.fromCharCode / codePointAt (encoding)
|
||||
for (let j = 32; j < 127; j++) {
|
||||
String.fromCharCode(j);
|
||||
}
|
||||
'Hello! 日本語'.codePointAt(0);
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 6: Regular expressions (routing, validation, parsing)
|
||||
function workloadRegex(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
// Pre-compiled regexes (real-world patterns)
|
||||
const emailRe = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
|
||||
const uuidRe =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const ipv4Re = /^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
const routeRe =
|
||||
/^\/api\/v(\d+)\/(users|products|orders)(?:\/([a-zA-Z0-9_-]+))?$/;
|
||||
const htmlTagRe = /<([a-z]+)([^>]*)>(.*?)<\/\1>/gi;
|
||||
const semverRe =
|
||||
/^v?(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.]+))?(?:\+([a-zA-Z0-9.]+))?$/;
|
||||
const dateRe = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z?)?$/;
|
||||
const csvRe = /(?:^|,)("(?:[^"]*(?:""[^"]*)*)"|[^,]*)/g;
|
||||
|
||||
const testStrings = {
|
||||
emails: ['test@example.com', 'invalid@', 'user+tag@domain.co.uk', 'nope'],
|
||||
uuids: [
|
||||
'550e8400-e29b-41d4-a716-446655440000',
|
||||
'not-a-uuid',
|
||||
'550E8400-E29B-41D4-A716-446655440000',
|
||||
],
|
||||
ips: ['192.168.1.1', '10.0.0.0', '999.999.999.999', 'not.an.ip'],
|
||||
routes: [
|
||||
'/api/v2/users',
|
||||
'/api/v1/products/abc-123',
|
||||
'/api/v3/orders/',
|
||||
'/other/path',
|
||||
],
|
||||
html: [
|
||||
'<div class="container">Hello</div>',
|
||||
'<p>Text</p>',
|
||||
'<span id="x">Content</span>',
|
||||
],
|
||||
semver: ['v1.2.3', '2.0.0-beta.1', '1.0.0+build.123', '1.2', 'not-semver'],
|
||||
dates: [
|
||||
'2024-01-15',
|
||||
'2024-01-15T10:30:00Z',
|
||||
'2024-01-15T10:30:00.123Z',
|
||||
'not-a-date',
|
||||
],
|
||||
csv: [
|
||||
'"John","Doe",30',
|
||||
'"Jane ""J"" Doe","Smith",25',
|
||||
'simple,values,here',
|
||||
],
|
||||
};
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// Email validation (form submission, user registration)
|
||||
for (const email of testStrings.emails) {
|
||||
emailRe.test(email);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// UUID validation (API parameters)
|
||||
for (const uuid of testStrings.uuids) {
|
||||
uuidRe.test(uuid);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// IP validation (rate limiting, geo-blocking)
|
||||
for (const ip of testStrings.ips) {
|
||||
ipv4Re.test(ip);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// Route matching (URL routing in Express/Fastify)
|
||||
for (const route of testStrings.routes) {
|
||||
const match = routeRe.exec(route);
|
||||
if (match) {
|
||||
void match[1];
|
||||
void match[2];
|
||||
void match[3];
|
||||
}
|
||||
ops++;
|
||||
}
|
||||
|
||||
// HTML tag parsing (template engines, sanitization)
|
||||
for (const html of testStrings.html) {
|
||||
html.replace(htmlTagRe, (match, tag, attrs, content) => content);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// Semver parsing (package resolution)
|
||||
for (const ver of testStrings.semver) {
|
||||
semverRe.test(ver);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// Date validation (API input)
|
||||
for (const date of testStrings.dates) {
|
||||
dateRe.test(date);
|
||||
ops++;
|
||||
}
|
||||
|
||||
// CSV parsing (data import)
|
||||
for (const csv of testStrings.csv) {
|
||||
void [...csv.matchAll(csvRe)];
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 7: TextEncoder/TextDecoder (Web API compatibility)
|
||||
function workloadTextEncoding(iterations) {
|
||||
let ops = 0;
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder('utf-8');
|
||||
const testStrings = [
|
||||
'Hello, World!',
|
||||
'The quick brown fox jumps over the lazy dog',
|
||||
'日本語テスト Unicode text with émojis 🎉',
|
||||
'A'.repeat(1000),
|
||||
Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'),
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
for (const str of testStrings) {
|
||||
// Encode (string → Uint8Array)
|
||||
const encoded = encoder.encode(str);
|
||||
ops++;
|
||||
|
||||
// Decode (Uint8Array → string)
|
||||
decoder.decode(encoded);
|
||||
ops++;
|
||||
|
||||
// encodeInto (reuse buffer — more efficient)
|
||||
const dest = new Uint8Array(str.length * 3);
|
||||
encoder.encodeInto(str, dest);
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
// Workload 8: util.format and util.inspect (logging — extremely common)
|
||||
function workloadUtilFormat(iterations) {
|
||||
let ops = 0;
|
||||
|
||||
const testObjects = [
|
||||
{ simple: 'object', count: 42 },
|
||||
{ nested: { deep: { value: [1, 2, 3] } }, fn: () => {} },
|
||||
new Map([['key', 'value']]),
|
||||
new Set([1, 2, 3]),
|
||||
new Error('test error'),
|
||||
Buffer.from('test'),
|
||||
/regex/gi,
|
||||
new Date(),
|
||||
];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
// util.format (console.log uses this internally)
|
||||
util.format('Request %s %s completed in %dms', 'GET', '/api/users', 42.5);
|
||||
util.format('User %j logged in', { id: 1, name: 'test' });
|
||||
util.format('Values: %o %O', { a: 1 }, { b: 2 });
|
||||
ops += 3;
|
||||
|
||||
// util.inspect (debug output, REPL)
|
||||
for (const obj of testObjects) {
|
||||
util.inspect(obj, { depth: 3, colors: false, maxArrayLength: 10 });
|
||||
ops++;
|
||||
}
|
||||
|
||||
// util.types (type checking)
|
||||
util.types.isDate(new Date());
|
||||
util.types.isRegExp(/test/);
|
||||
util.types.isSet(new Set());
|
||||
util.types.isMap(new Map());
|
||||
util.types.isPromise(Promise.resolve());
|
||||
ops += 5;
|
||||
|
||||
// util.deprecate (module system pattern)
|
||||
util.deprecate(() => {}, 'Use newAPI instead');
|
||||
ops++;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[pgo-url-string] Starting URL & string workload...');
|
||||
const startTime = Date.now();
|
||||
let totalOps = 0;
|
||||
let round = 0;
|
||||
|
||||
const remaining = () => DURATION_MS - (Date.now() - startTime);
|
||||
|
||||
while (remaining() > 0) {
|
||||
round++;
|
||||
const scale = Math.max(0.1, remaining() / DURATION_MS);
|
||||
const iterScale = (base) => Math.max(1, Math.floor(base * scale));
|
||||
|
||||
// WHATWG URL (highest priority — modern web standard)
|
||||
if (round === 1)
|
||||
console.log('[pgo-url-string] Running WHATWG URL parsing...');
|
||||
totalOps += workloadWHATWGURL(iterScale(300));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// URLSearchParams
|
||||
if (round === 1) console.log('[pgo-url-string] Running URLSearchParams...');
|
||||
totalOps += workloadURLSearchParams(iterScale(500));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Legacy URL
|
||||
if (round === 1)
|
||||
console.log('[pgo-url-string] Running legacy url.parse...');
|
||||
totalOps += workloadLegacyURL(iterScale(200));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Querystring
|
||||
if (round === 1) console.log('[pgo-url-string] Running querystring...');
|
||||
totalOps += workloadQuerystring(iterScale(500));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// String operations
|
||||
if (round === 1)
|
||||
console.log('[pgo-url-string] Running string operations...');
|
||||
totalOps += workloadStringOps(iterScale(300));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// Regex
|
||||
if (round === 1) console.log('[pgo-url-string] Running regex patterns...');
|
||||
totalOps += workloadRegex(iterScale(500));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// TextEncoder/Decoder
|
||||
if (round === 1)
|
||||
console.log('[pgo-url-string] Running TextEncoder/Decoder...');
|
||||
totalOps += workloadTextEncoding(iterScale(500));
|
||||
if (remaining() <= 0) break;
|
||||
|
||||
// util.format/inspect
|
||||
if (round === 1)
|
||||
console.log('[pgo-url-string] Running util.format/inspect...');
|
||||
totalOps += workloadUtilFormat(iterScale(200));
|
||||
}
|
||||
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
console.log(
|
||||
`[pgo-url-string] Completed ${totalOps} ops in ${elapsed.toFixed(1)}s (${(totalOps / elapsed).toFixed(0)} ops/s) [${round} rounds]`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[pgo-url-string] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user