Skip to content

Commit e227c8f

Browse files
committed
docs: update docs
1 parent 27e76f2 commit e227c8f

File tree

1 file changed

+116
-8
lines changed

1 file changed

+116
-8
lines changed

packages/utils/docs/profiler.md

Lines changed: 116 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# User Timing Profiler
22

3-
43
⏱️ **High-performance profiling utility for structured timing measurements with Chrome DevTools Extensibility API payloads.** 📊
54

65
---
@@ -94,6 +93,14 @@ CP_PROFILING=false npm run build
9493

9594
The profiler provides several methods for different types of performance measurements:
9695

96+
| Method | Description |
97+
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
98+
| `measure<R>(event: string, work: () => R, options?: MeasureOptions<R>): R` | Measures synchronous operation execution time with DevTools payloads. Noop when profiling is disabled. |
99+
| `measureAsync<R>(event: string, work: () => Promise<R>, options?: MeasureOptions<R>): Promise<R>` | Measures asynchronous operation execution time with DevTools payloads. Noop when profiling is disabled. |
100+
| `marker(name: string, opt?: MarkerOptions): void` | Creates performance markers as vertical lines in DevTools timeline. Noop when profiling is disabled. |
101+
| `setEnabled(enabled: boolean): void` | Controls profiling at runtime. |
102+
| `isEnabled(): boolean` | Returns whether profiling is currently enabled. |
103+
97104
### Synchronous measurements
98105

99106
```ts
@@ -229,20 +236,121 @@ interface AppTracks {
229236
}
230237

231238
const profiler = new Profiler<AppTracks>({
239+
track: 'API',
240+
trackGroup: 'Server',
241+
color: 'primary-dark',
232242
tracks: {
233-
api: { track: 'api', trackGroup: 'network', color: 'primary' },
234-
db: { track: 'database', trackGroup: 'data', color: 'warning' },
235-
cache: { track: 'cache', trackGroup: 'data', color: 'success' },
243+
api: { color: 'primary' },
244+
db: { track: 'database', color: 'warning' },
245+
cache: { track: 'cache', color: 'success' },
236246
},
237247
});
238248

239249
// Use predefined tracks
240-
const users = await profiler.measureAsync('fetch-users', fetchUsers, {
241-
track: 'api',
242-
});
250+
const users = await profiler.measureAsync('fetch-users', fetchUsers, profiler.tracks.api);
243251

244252
const saved = profiler.measure('save-user', () => saveToDb(user), {
245-
track: 'db',
253+
...profiler.tracks.db,
254+
color: 'primary',
255+
});
256+
```
257+
258+
## NodeJSProfiler
259+
260+
This profiler extends all options and API from Profiler with automatic process exit handling for buffered performance data.
261+
262+
The NodeJSProfiler automatically subscribes to performance observation and installs exit handlers that flush buffered data on process termination (signals, fatal errors, or normal exit).
263+
264+
## Configuration
265+
266+
```ts
267+
new NodejsProfiler<DomainEvents, Tracks>(options: NodejsProfilerOptions<DomainEvents, Tracks>)
268+
```
269+
270+
**Parameters:**
271+
272+
- `options` - Configuration options for the profiler instance
273+
274+
**Options:**
275+
276+
| Property | Type | Default | Description |
277+
| ------------------------ | --------------------------------------- | ---------- | ------------------------------------------------------------------------------- |
278+
| `encodePerfEntry` | `PerformanceEntryEncoder<DomainEvents>` | _required_ | Function that encodes raw PerformanceEntry objects into domain-specific types |
279+
| `captureBufferedEntries` | `boolean` | `true` | Whether to capture performance entries that occurred before observation started |
280+
| `flushThreshold` | `number` | `20` | Threshold for triggering queue flushes based on queue length |
281+
| `maxQueueSize` | `number` | `10_000` | Maximum number of items allowed in the queue before new entries are dropped |
282+
283+
## API Methods
284+
285+
The NodeJSProfiler inherits all API methods from the base Profiler class and adds additional methods for queue management and WAL lifecycle control.
286+
287+
| Method | Description |
288+
| ------------------------------------ | ------------------------------------------------------------------------------- |
289+
| `getStats()` | Returns comprehensive queue statistics for monitoring and debugging. |
290+
| `flush()` | Forces immediate writing of all queued performance entries to the WAL. |
291+
| `setEnabled(enabled: boolean): void` | Controls profiling at runtime with automatic WAL/observer lifecycle management. |
292+
293+
### Runtime control with Write Ahead Log lifecycle management
294+
295+
```ts
296+
profiler.setEnabled(enabled: boolean): void
297+
```
298+
299+
Controls profiling at runtime and manages the WAL/observer lifecycle. Unlike the base Profiler class, this method ensures that when profiling is enabled, the WAL is opened and the performance observer is subscribed. When disabled, the WAL is closed and the observer is unsubscribed.
300+
301+
```ts
302+
// Temporarily disable profiling to reduce overhead during heavy operations
303+
profiler.setEnabled(false);
304+
await performHeavyOperation();
305+
profiler.setEnabled(true); // WAL reopens and observer resubscribes
306+
```
307+
308+
### Queue statistics
309+
310+
```ts
311+
profiler.getStats(): {
312+
enabled: boolean;
313+
observing: boolean;
314+
walOpen: boolean;
315+
isSubscribed: boolean;
316+
queued: number;
317+
dropped: number;
318+
written: number;
319+
maxQueueSize: number;
320+
flushThreshold: number;
321+
addedSinceLastFlush: number;
322+
buffered: boolean;
323+
}
324+
```
325+
326+
Returns comprehensive queue statistics for monitoring and debugging. Provides insight into the current state of the performance entry queue, useful for monitoring memory usage and processing throughput.
327+
328+
```ts
329+
const stats = profiler.getStats();
330+
console.log(`Enabled: ${stats.enabled}, WAL Open: ${stats.walOpen}, Observing: ${stats.observing}, Subscribed: ${stats.isSubscribed}, Queued: ${stats.queued}`);
331+
if (stats.enabled && stats.walOpen && stats.observing && stats.isSubscribed && stats.queued > stats.flushThreshold) {
332+
console.log('Queue nearing capacity, consider manual flush');
333+
}
334+
```
335+
336+
### Manual flushing
337+
338+
```ts
339+
profiler.flush(): void
340+
```
341+
342+
Forces immediate writing of all queued performance entries to the write ahead log, ensuring no performance data is lost. This method is useful for manual control over when buffered data is written, complementing the automatic flushing that occurs during process exit or when thresholds are reached.
343+
344+
```ts
345+
// Flush periodically in long-running applications to prevent memory buildup
346+
setInterval(() => {
347+
profiler.flush();
348+
}, 60000); // Flush every minute
349+
350+
// Ensure all measurements are saved before critical operations
351+
await profiler.measureAsync('database-migration', async () => {
352+
await runMigration();
353+
profiler.flush(); // Ensure migration timing is recorded immediately
246354
});
247355
```
248356

0 commit comments

Comments
 (0)