-
Notifications
You must be signed in to change notification settings - Fork 7
feat: Metrics extended labels #414
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
c8f3177
metricParams is protected
CarlosGamero dbf179b
Adding PrometheusMessageCounter
CarlosGamero 29af2c7
Error counter migrated and status fixes
CarlosGamero 0534fbd
Adding tests
CarlosGamero aea99b8
Adding PrometheusMessageByStatusCounter
CarlosGamero 8389f9b
Update to have backward compatible change
CarlosGamero 619bc19
Allowing adding labels on PrometheusMessageTimeMetric
CarlosGamero d47d3c4
Readme improvement
CarlosGamero 9fe0b01
Lint fixes
CarlosGamero 26cd040
Typo fix
CarlosGamero feb4a47
AI comment for consistency
CarlosGamero d9ef3e6
AI suggestion to simplify code
CarlosGamero bd5efb9
Symplifying type
CarlosGamero 47f1b24
readme updated
CarlosGamero ac0a0c0
lint fix
CarlosGamero 3bc6389
Test fix
CarlosGamero 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 |
|---|---|---|
| @@ -1,27 +1,225 @@ | ||
| # Metrics | ||
|
|
||
| This packages contains utilities for collecting metrics in `@message-queue-toolkit` | ||
| This package contains utilities for collecting metrics in `@message-queue-toolkit`. | ||
|
|
||
| ## Installation | ||
|
|
||
| ```sh | ||
| npm install @message-queue-toolkit/metrics | ||
| ``` | ||
|
|
||
| ## Overview | ||
|
|
||
| All metrics implement the `MessageMetricsManager` interface from `@message-queue-toolkit/core`, which means they can be passed directly to any `AbstractQueueService` via the `messageMetricsManager` option. | ||
|
|
||
| ```ts | ||
| import { PrometheusMessageProcessingTimeMetric } from '@message-queue-toolkit/metrics' | ||
|
|
||
| const metric = new PrometheusMessageProcessingTimeMetric({ | ||
| name: 'message_processing_duration_ms', | ||
| helpDescription: 'Time spent processing a message', | ||
| buckets: [10, 50, 100, 500, 1000], | ||
| }) | ||
|
|
||
| // Pass to your queue service | ||
| const service = new MyQueueService({ messageMetricsManager: metric }) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Prometheus metrics | ||
|
|
||
| Metrics that use [Prometheus](https://prometheus.io/) toolkit and [prom-client](https://github.com/siimon/prom-client) library | ||
| All Prometheus metrics use [prom-client](https://github.com/siimon/prom-client) under the hood. | ||
|
|
||
| ### Base parameters | ||
|
|
||
| All metrics accept `PrometheusMetricParams`: | ||
|
|
||
| | Field | Type | Required | Description | | ||
| |---|---|---|---| | ||
| | `name` | `string` | yes | Prometheus metric name | | ||
| | `helpDescription` | `string` | yes | Prometheus metric description | | ||
| | `buckets` | `number[]` | histograms only | Histogram bucket boundaries | | ||
| | `messageVersion` | `string \| (metadata) => string \| undefined` | no | Static version string or function to extract version from message metadata | | ||
| | `labelNames` | `Labels[]` | when `Labels` is specified | Names of the custom labels to register. Must not overlap with `DefaultLabels` (`queue`, `messageType`, `version`, `result`) — TypeScript enforces this at compile time | | ||
|
|
||
| An optional second argument accepts a custom `prom-client` instance (useful for testing or multi-registry setups). | ||
|
|
||
| --- | ||
|
|
||
| ### Histogram metrics (time-based) | ||
|
|
||
| Use `Histogram` to measure message timing. Base labels registered on every observation: | ||
|
|
||
| | Label | Value | | ||
| |---|---| | ||
| | `messageType` | Message type identifier | | ||
| | `version` | Resolved message version | | ||
| | `queue` | Queue or topic name | | ||
| | `result` | Processing result status (`consumed`, `published`, `retryLater`, `error`) | | ||
|
|
||
| #### Built-in implementations | ||
|
|
||
| **`PrometheusMessageProcessingTimeMetric`** | ||
| Measures elapsed time from when processing started to when it ended. | ||
| ``` | ||
| value = messageProcessingEndTimestamp - messageProcessingStartTimestamp | ||
| ``` | ||
|
|
||
| **`PrometheusMessageLifetimeMetric`** | ||
| Measures elapsed time from when the message was originally sent to when it was fully processed. Includes any time the message spent waiting in the queue. | ||
| ``` | ||
| value = messageProcessingEndTimestamp - messageTimestamp | ||
| ``` | ||
| Skips observation if `messageTimestamp` is not available. | ||
|
|
||
| **`PrometheusMessageQueueTimeMetric`** | ||
| Measures elapsed time from when the message was originally sent to when processing started (i.e., queue wait time only). | ||
| ``` | ||
| value = messageProcessingStartTimestamp - messageTimestamp | ||
| ``` | ||
| Skips observation if `messageTimestamp` is not available. | ||
|
|
||
| #### Custom histogram with extra labels | ||
|
|
||
| Extend `PrometheusMessageTimeMetric` to add custom labels. Pass `labelNames` in the params and override `getLabelValuesForProcessedMessage`. Custom label names must not conflict with `DefaultLabels` — using a reserved name (e.g. `'result'`) will produce a TypeScript compile error: | ||
|
|
||
| ```ts | ||
| import { PrometheusMessageTimeMetric } from '@message-queue-toolkit/metrics' | ||
| import type { ProcessedMessageMetadata } from '@message-queue-toolkit/core' | ||
| import type { LabelValues } from 'prom-client' | ||
|
|
||
| class MyProcessingTimeMetric extends PrometheusMessageTimeMetric<MyMessage, 'env'> { | ||
| protected calculateObservedValue(metadata: ProcessedMessageMetadata<MyMessage>): number | null { | ||
| return metadata.messageProcessingEndTimestamp - metadata.messageProcessingStartTimestamp | ||
| } | ||
|
|
||
| protected getLabelValuesForProcessedMessage(): LabelValues<'env'> { | ||
| return { env: process.env.NODE_ENV ?? 'unknown' } | ||
| } | ||
| } | ||
|
|
||
| const metric = new MyProcessingTimeMetric({ | ||
| name: 'message_processing_duration_ms', | ||
| helpDescription: 'Processing time by environment', | ||
| buckets: [10, 50, 100, 500], | ||
| labelNames: ['env'], | ||
| }) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ### Counter metrics (event-based) | ||
|
|
||
| Use `Counter` to count message events. Base labels registered on every increment: | ||
|
|
||
| | Label | Value | | ||
| |---|---| | ||
| | `messageType` | Message type identifier | | ||
| | `version` | Resolved message version | | ||
| | `queue` | Queue or topic name | | ||
| | `result` | Processing result status (`consumed`, `published`, `retryLater`, `error`) | | ||
|
|
||
| #### Built-in implementations | ||
|
|
||
| **`PrometheusMessageResultCounter`** | ||
| Counts all processed messages using only the built-in base labels. No extra configuration needed. | ||
|
|
||
| ```ts | ||
| import { PrometheusMessageResultCounter } from '@message-queue-toolkit/metrics' | ||
|
|
||
| const metric = new PrometheusMessageResultCounter({ | ||
| name: 'messages_total', | ||
| helpDescription: 'Number of messages processed', | ||
| }) | ||
| ``` | ||
|
|
||
| **`PrometheusMessageErrorCounter`** | ||
| Counts only messages that result in an error. Adds an `errorReason` label. Skips all non-error messages. | ||
|
|
||
| ```ts | ||
| import { PrometheusMessageErrorCounter } from '@message-queue-toolkit/metrics' | ||
|
|
||
| const metric = new PrometheusMessageErrorCounter({ | ||
| name: 'message_errors_total', | ||
| helpDescription: 'Number of messages that failed processing', | ||
| labelNames: ['errorReason'], | ||
| }) | ||
| ``` | ||
|
|
||
| #### Custom counter with extra labels | ||
|
|
||
| Extend `PrometheusMessageCounter` and implement `calculateCount`. Override `getLabelValuesForProcessedMessage` when adding custom labels. Same as histograms, custom label names must not conflict with `DefaultLabels`: | ||
|
|
||
| ```ts | ||
| import { PrometheusMessageCounter } from '@message-queue-toolkit/metrics' | ||
| import type { ProcessedMessageMetadata } from '@message-queue-toolkit/core' | ||
| import type { LabelValues } from 'prom-client' | ||
|
|
||
| class MyRegionCounter extends PrometheusMessageCounter<MyMessage, 'region'> { | ||
| protected calculateCount(): number | null { | ||
| return 1 | ||
| } | ||
|
|
||
| protected override getLabelValuesForProcessedMessage( | ||
| metadata: ProcessedMessageMetadata<MyMessage>, | ||
| ): LabelValues<'region'> { | ||
| return { region: metadata.message.region } | ||
| } | ||
| } | ||
|
|
||
| const metric = new MyRegionCounter({ | ||
| name: 'messages_by_region_total', | ||
| helpDescription: 'Number of messages processed, by region', | ||
| labelNames: ['region'], | ||
| }) | ||
| ``` | ||
|
|
||
| When no custom labels are needed, omit `labelNames` and skip overriding `getLabelValuesForProcessedMessage`: | ||
|
|
||
| ```ts | ||
| class MyConsumedCounter extends PrometheusMessageCounter<MyMessage> { | ||
| protected calculateCount(metadata: ProcessedMessageMetadata<MyMessage>): number | null { | ||
| return metadata.processingResult.status === 'consumed' ? 1 : null | ||
| } | ||
| } | ||
|
|
||
| const metric = new MyConsumedCounter({ | ||
| name: 'messages_consumed_total', | ||
| helpDescription: 'Number of successfully consumed messages', | ||
| }) | ||
| ``` | ||
|
|
||
| ### MessageProcessingPrometheusMetric | ||
| Abstract class implementing `MessageMetricsManager` interface, that can be injected into `AbstractQueueService` from `@message-queue-toolkit/core`. | ||
| --- | ||
|
|
||
| It uses [Histogram](https://prometheus.io/docs/concepts/metric_types/#histogram) metric to collect message processing times with labels: | ||
| - `messageType` - message type | ||
| - `version` - message version | ||
| - `queue` - name of the queue or topic | ||
| - `result` - processing result | ||
| ### Using multiple metrics together | ||
|
|
||
| See [MessageProcessingPrometheusMetric.ts](lib/prometheus/MessageProcessingPrometheusMetric.ts) for available parameters. | ||
| `MessageMultiMetricManager` aggregates multiple `MessageMetricsManager` instances and fans out each `registerProcessedMessage` call to all of them. | ||
|
|
||
| There are following non-abstract implementations available: | ||
| - `MessageProcessingTimeMetric` - registers elapsed time from start to the end of message processing | ||
| - `MessageLifetimeMetric` - registers elapsed time from the point where message was initially sent, to the point when it was processed. | ||
| Note: if message is waiting in the queue due to high load or barrier, the waiting time is included in the measurement | ||
| ```ts | ||
| import { | ||
| MessageMultiMetricManager, | ||
| PrometheusMessageProcessingTimeMetric, | ||
| PrometheusMessageResultCounter, | ||
| PrometheusMessageErrorCounter, | ||
| } from '@message-queue-toolkit/metrics' | ||
|
|
||
| ### MessageProcessingMultiMetrics | ||
| Implementation of `MessageMetricsManager` that allows to use multiple `MessageProcessingPrometheusMetric` instances. | ||
| const metricsManager = new MessageMultiMetricManager([ | ||
| new PrometheusMessageProcessingTimeMetric({ | ||
| name: 'message_processing_duration_ms', | ||
| helpDescription: 'Message processing time', | ||
| buckets: [10, 50, 100, 500, 1000], | ||
| }), | ||
| new PrometheusMessageResultCounter({ | ||
| name: 'messages_total', | ||
| helpDescription: 'Messages processed', | ||
| }), | ||
| new PrometheusMessageErrorCounter({ | ||
| name: 'message_errors_total', | ||
| helpDescription: 'Messages that failed processing', | ||
| labelNames: ['errorReason'], | ||
| }), | ||
| ]) | ||
|
|
||
| const service = new MyQueueService({ messageMetricsManager: metricsManager }) | ||
| ``` | ||
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.
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.
Uh oh!
There was an error while loading. Please reload this page.