-
Notifications
You must be signed in to change notification settings - Fork 15
feat(utils): add NodeJS profiler #1219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BioPhoton
wants to merge
6
commits into
main
Choose a base branch
from
feat/utils/profiler-perf-buffer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b71f3c7
feat: add NodeJSProfiler
BioPhoton d8d5a93
docs: clarify that sink defines output format in NodejsProfiler JSDoc
BioPhoton 673b5c4
test: convert all MockSink and MockTraceEventFileSink methods to spies
BioPhoton 7c14a0b
refactor: add tests
BioPhoton b6babbe
Merge branch 'main' into feat/utils/profiler-perf-buffer
BioPhoton d328c9f
refactor: fix lint
BioPhoton File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,255 @@ | ||
| # @code-pushup/utils - Profiler | ||
|
|
||
| [](https://www.npmjs.com/package/@code-pushup/utils) | ||
| [](https://npmtrends.com/@code-pushup/utils) | ||
| [](https://www.npmjs.com/package/@code-pushup/utils?activeTab=dependencies) | ||
|
|
||
| ⏱️ **High-performance profiling utility for structured timing measurements with Chrome DevTools Extensibility API payloads.** 📊 | ||
|
|
||
| --- | ||
|
|
||
| The `Profiler` class provides a clean, type-safe API for performance monitoring that integrates seamlessly with Chrome DevTools. It supports both synchronous and asynchronous operations with smart defaults for custom track visualization, enabling developers to track performance bottlenecks and optimize application speed. | ||
|
|
||
| ## Getting started | ||
|
|
||
| 1. If you haven't already, install [@code-pushup/utils](../../README.md). | ||
|
|
||
| 2. Install as a dependency with your package manager: | ||
|
|
||
| ```sh | ||
| npm install @code-pushup/utils | ||
| ``` | ||
|
|
||
| ```sh | ||
| yarn add @code-pushup/utils | ||
| ``` | ||
|
|
||
| ```sh | ||
| pnpm add @code-pushup/utils | ||
| ``` | ||
|
|
||
| 3. Import and create a profiler instance: | ||
|
|
||
| ```ts | ||
| import { Profiler } from '@code-pushup/utils'; | ||
|
|
||
| const profiler = new Profiler({ | ||
| prefix: 'cp', | ||
| track: 'CLI', | ||
| trackGroup: 'Code Pushup', | ||
| color: 'primary-dark', | ||
| tracks: { | ||
| utils: { track: 'Utils', color: 'primary' }, | ||
| core: { track: 'Core', color: 'primary-light' }, | ||
| }, | ||
| enabled: true, | ||
| }); | ||
| ``` | ||
|
|
||
| 4. Start measuring performance: | ||
|
|
||
| ```ts | ||
| // Measure synchronous operations | ||
| const result = profiler.measure('data-processing', () => { | ||
| return processData(data); | ||
| }); | ||
|
|
||
| // Measure asynchronous operations | ||
| const asyncResult = await profiler.measureAsync('api-call', async () => { | ||
| return await fetch('/api/data').then(r => r.json()); | ||
| }); | ||
| ``` | ||
|
|
||
| ## Configuration | ||
|
|
||
| ```ts | ||
| new Profiler<T>(options: ProfilerOptions<T>) | ||
| ``` | ||
|
|
||
| **Parameters:** | ||
|
|
||
| - `options` - Configuration options for the profiler instance | ||
|
|
||
| **Options:** | ||
|
|
||
| | Property | Type | Default | Description | | ||
| | ------------ | --------- | ----------- | --------------------------------------------------------------- | | ||
| | `tracks` | `object` | `undefined` | Custom track configurations merged with defaults | | ||
| | `prefix` | `string` | `undefined` | Prefix for all measurement names | | ||
| | `track` | `string` | `undefined` | Default track name for measurements | | ||
| | `trackGroup` | `string` | `undefined` | Default track group for organization | | ||
| | `color` | `string` | `undefined` | Default color for track entries | | ||
| | `enabled` | `boolean` | `env var` | Whether profiling is enabled (defaults to CP_PROFILING env var) | | ||
|
|
||
| ### Environment Variables | ||
|
|
||
| - `CP_PROFILING` - Enables or disables profiling globally (boolean) | ||
|
|
||
| ```bash | ||
| # Enable profiling in development | ||
| CP_PROFILING=true npm run dev | ||
|
|
||
| # Disable profiling in production | ||
| CP_PROFILING=false npm run build | ||
| ``` | ||
|
|
||
| ## API Methods | ||
|
|
||
| The profiler provides several methods for different types of performance measurements: | ||
|
|
||
| ### Synchronous measurements | ||
|
|
||
| ```ts | ||
| profiler.measure<R>(event: string, work: () => R, options?: MeasureOptions<R>): R | ||
| ``` | ||
|
|
||
| Measures the execution time of a synchronous operation. Creates performance start/end marks and a final measure with Chrome DevTools Extensibility API payloads. | ||
|
|
||
| ```ts | ||
| const result = profiler.measure( | ||
| 'file-processing', | ||
| () => { | ||
| return fs.readFileSync('large-file.txt', 'utf8'); | ||
| }, | ||
| { | ||
| track: 'io-operations', | ||
| color: 'warning', | ||
| }, | ||
| ); | ||
| ``` | ||
|
|
||
| ### Asynchronous measurements | ||
|
|
||
| ```ts | ||
| profiler.measureAsync<R>(event: string, work: () => Promise<R>, options?: MeasureOptions<R>): Promise<R> | ||
| ``` | ||
|
|
||
| Measures the execution time of an asynchronous operation. | ||
|
|
||
| ```ts | ||
| const data = await profiler.measureAsync( | ||
| 'api-request', | ||
| async () => { | ||
| const response = await fetch('/api/data'); | ||
| return response.json(); | ||
| }, | ||
| { | ||
| track: 'network', | ||
| trackGroup: 'external', | ||
| }, | ||
| ); | ||
| ``` | ||
|
|
||
| ### Performance markers | ||
|
|
||
| ```ts | ||
| profiler.marker(name: string, options?: EntryMeta & { color?: DevToolsColor }): void | ||
| ``` | ||
|
|
||
| Creates a performance mark with Chrome DevTools marker visualization. Markers appear as vertical lines spanning all tracks and can include custom metadata. | ||
|
|
||
| ```ts | ||
| profiler.marker('user-action', { | ||
| color: 'secondary', | ||
| tooltipText: 'User clicked save button', | ||
| properties: [ | ||
| ['action', 'save'], | ||
| ['elementId', 'save-btn'], | ||
| ], | ||
| }); | ||
| ``` | ||
|
|
||
| ### Runtime control | ||
|
|
||
| ```ts | ||
| profiler.setEnabled(enabled: boolean): void | ||
| profiler.isEnabled(): boolean | ||
| ``` | ||
|
|
||
| Control profiling at runtime and check current status. | ||
|
|
||
| ```ts | ||
| // Disable profiling temporarily | ||
| profiler.setEnabled(false); | ||
|
|
||
| // Check if profiling is active | ||
| if (profiler.isEnabled()) { | ||
| console.log('Performance monitoring is active'); | ||
| } | ||
| ``` | ||
|
|
||
| ## Examples | ||
|
|
||
| ### Basic usage | ||
|
|
||
| ```ts | ||
| import { Profiler } from '@code-pushup/utils'; | ||
|
|
||
| const profiler = new Profiler({ | ||
| prefix: 'cp', | ||
| track: 'CLI', | ||
| trackGroup: 'Code Pushup', | ||
| color: 'primary-dark', | ||
| tracks: { | ||
| utils: { track: 'Utils', color: 'primary' }, | ||
| core: { track: 'Core', color: 'primary-light' }, | ||
| }, | ||
| enabled: true, | ||
| }); | ||
|
|
||
| // Simple measurement | ||
| const result = profiler.measure('data-transform', () => { | ||
| return transformData(input); | ||
| }); | ||
|
|
||
| // Async measurement with custom options | ||
| const data = await profiler.measureAsync( | ||
| 'fetch-user', | ||
| async () => { | ||
| return await api.getUser(userId); | ||
| }, | ||
| { | ||
| track: 'api', | ||
| color: 'info', | ||
| }, | ||
| ); | ||
|
|
||
| // Add a marker for important events | ||
| profiler.marker('user-login', { | ||
| tooltipText: 'User authentication completed', | ||
| }); | ||
| ``` | ||
|
|
||
| ### Custom tracks | ||
|
|
||
| Define custom track configurations for better organization: | ||
|
|
||
| ```ts | ||
| interface AppTracks { | ||
| api: ActionTrackEntryPayload; | ||
| db: ActionTrackEntryPayload; | ||
| cache: ActionTrackEntryPayload; | ||
| } | ||
|
|
||
| const profiler = new Profiler<AppTracks>({ | ||
| tracks: { | ||
| api: { track: 'api', trackGroup: 'network', color: 'primary' }, | ||
| db: { track: 'database', trackGroup: 'data', color: 'warning' }, | ||
| cache: { track: 'cache', trackGroup: 'data', color: 'success' }, | ||
| }, | ||
| }); | ||
|
|
||
| // Use predefined tracks | ||
| const users = await profiler.measureAsync('fetch-users', fetchUsers, { | ||
| track: 'api', | ||
| }); | ||
|
|
||
| const saved = profiler.measure('save-user', () => saveToDb(user), { | ||
| track: 'db', | ||
| }); | ||
| ``` | ||
|
|
||
| ## Resources | ||
|
|
||
| - **[Chrome DevTools Extensibility API](?)** - Official documentation for performance profiling | ||
| - **[User Timing API](https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API)** - Web Performance API reference | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,30 +1,55 @@ | ||
| import type { Sink } from '../src/lib/sink-source.type'; | ||
| import { vi } from 'vitest'; | ||
| import type { | ||
| RecoverResult, | ||
| Recoverable, | ||
| Sink, | ||
| } from '../src/lib/sink-source.type'; | ||
|
|
||
| export class MockSink implements Sink<string, string> { | ||
| private writtenItems: string[] = []; | ||
| private closed = false; | ||
| private closed = true; | ||
|
|
||
| open(): void { | ||
| open = vi.fn((): void => { | ||
| this.closed = false; | ||
| } | ||
| }); | ||
|
|
||
| write(input: string): void { | ||
| write = vi.fn((input: string): void => { | ||
| this.writtenItems.push(input); | ||
| } | ||
| }); | ||
|
|
||
| close(): void { | ||
| close = vi.fn((): void => { | ||
| this.closed = true; | ||
| } | ||
| }); | ||
|
|
||
| isClosed(): boolean { | ||
| isClosed = vi.fn((): boolean => { | ||
| return this.closed; | ||
| } | ||
| }); | ||
|
|
||
| encode(input: string): string { | ||
| encode = vi.fn((input: string): string => { | ||
| return `${input}-${this.constructor.name}-encoded`; | ||
| } | ||
| }); | ||
|
|
||
| getWrittenItems(): string[] { | ||
| getWrittenItems = vi.fn((): string[] => { | ||
| return [...this.writtenItems]; | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| export class MockTraceEventFileSink extends MockSink implements Recoverable { | ||
| recover = vi.fn( | ||
| (): { | ||
| records: unknown[]; | ||
| errors: { lineNo: number; line: string; error: Error }[]; | ||
| partialTail: string | null; | ||
| } => { | ||
| return { | ||
| records: this.getWrittenItems(), | ||
| errors: [], | ||
| partialTail: null, | ||
| } satisfies RecoverResult<string>; | ||
| }, | ||
| ); | ||
|
|
||
| repack = vi.fn((): void => {}); | ||
|
|
||
| finalize = vi.fn((): void => {}); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is the URL intentionally omitted?