Skip to content

feat(core): Allow metrics aggregator per client #10949

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 3 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
/**
* @inheritdoc
*/
public sendEnvelope(envelope: Envelope): PromiseLike<TransportMakeRequestResponse> | void {
public sendEnvelope(envelope: Envelope): PromiseLike<TransportMakeRequestResponse> {
this.emit('beforeEnvelope', envelope);

if (this._isEnabled() && this._transport) {
Expand All @@ -545,6 +545,8 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
}

DEBUG_BUILD && logger.error('Transport disabled');

return resolvedSyncPromise({});
}

/* eslint-enable @typescript-eslint/unified-signatures */
Expand Down
10 changes: 2 additions & 8 deletions packages/core/src/metrics/aggregator.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import type {
ClientOptions,
MeasurementUnit,
MetricsAggregator as MetricsAggregatorBase,
Primitive,
} from '@sentry/types';
import type { Client, MeasurementUnit, MetricsAggregator as MetricsAggregatorBase, Primitive } from '@sentry/types';
import { timestampInSeconds } from '@sentry/utils';
import type { BaseClient } from '../baseclient';
import { DEFAULT_FLUSH_INTERVAL, MAX_WEIGHT, NAME_AND_TAG_KEY_NORMALIZATION_REGEX, SET_METRIC_TYPE } from './constants';
import { captureAggregateMetrics } from './envelope';
import { METRIC_MAP } from './instance';
Expand Down Expand Up @@ -40,7 +34,7 @@ export class MetricsAggregator implements MetricsAggregatorBase {
// Force flush is used on either shutdown, flush() or when we exceed the max weight.
private _forceFlush: boolean;

public constructor(private readonly _client: BaseClient<ClientOptions>) {
public constructor(private readonly _client: Client) {
this._buckets = new Map();
this._bucketsTotalWeight = 0;
this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL);
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/metrics/browser-aggregator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { ClientOptions, MeasurementUnit, MetricsAggregator, Primitive } from '@sentry/types';
import type { Client, MeasurementUnit, MetricsAggregator, Primitive } from '@sentry/types';
import { timestampInSeconds } from '@sentry/utils';
import type { BaseClient } from '../baseclient';
import { DEFAULT_BROWSER_FLUSH_INTERVAL, NAME_AND_TAG_KEY_NORMALIZATION_REGEX, SET_METRIC_TYPE } from './constants';
import { captureAggregateMetrics } from './envelope';
import { METRIC_MAP } from './instance';
Expand All @@ -21,7 +20,7 @@ export class BrowserMetricsAggregator implements MetricsAggregator {
private _buckets: MetricBucket;
private readonly _interval: ReturnType<typeof setInterval>;

public constructor(private readonly _client: BaseClient<ClientOptions>) {
public constructor(private readonly _client: Client) {
this._buckets = new Map();
this._interval = setInterval(() => this.flush(), DEFAULT_BROWSER_FLUSH_INTERVAL);
}
Expand Down
15 changes: 2 additions & 13 deletions packages/core/src/metrics/envelope.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
import type {
ClientOptions,
DsnComponents,
MetricBucketItem,
SdkMetadata,
StatsdEnvelope,
StatsdItem,
} from '@sentry/types';
import type { Client, DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';
import { createEnvelope, dsnToString, logger } from '@sentry/utils';
import type { BaseClient } from '../baseclient';
import { serializeMetricBuckets } from './utils';

/**
* Captures aggregated metrics to the supplied client.
*/
export function captureAggregateMetrics(
client: BaseClient<ClientOptions>,
metricBucketItems: Array<MetricBucketItem>,
): void {
export function captureAggregateMetrics(client: Client, metricBucketItems: Array<MetricBucketItem>): void {
logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);
const dsn = client.getDsn();
const metadata = client.getSdkMetadata();
Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/metrics/exports-default.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Client, MetricsAggregator as MetricsAggregatorInterface } from '@sentry/types';
import { MetricsAggregator } from './aggregator';
import type { MetricData } from './exports';
import { metrics as metricsCore } from './exports';
Expand Down Expand Up @@ -38,9 +39,20 @@ function gauge(name: string, value: number, data?: MetricData): void {
metricsCore.gauge(MetricsAggregator, name, value, data);
}

/**
* Returns the metrics aggregator for a given client.
*/
function getMetricsAggregatorForClient(client: Client): MetricsAggregatorInterface {
return metricsCore.getMetricsAggregatorForClient(client, MetricsAggregator);
}

export const metricsDefault = {
increment,
distribution,
set,
gauge,
/**
* @ignore This is for internal use only.
*/
getMetricsAggregatorForClient,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually should we export this as a separate method to help with treeshaking?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The getMetricsAggregatorForClient function is in the call chain for all the other Sentry.metrics.* functions so there will be no impact to tree shaking.

};
88 changes: 55 additions & 33 deletions packages/core/src/metrics/exports.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import type {
ClientOptions,
Client,
MeasurementUnit,
MetricsAggregator as MetricsAggregatorInterface,
Primitive,
} from '@sentry/types';
import { logger } from '@sentry/utils';
import type { BaseClient } from '../baseclient';
import { getCurrentScope } from '../currentScopes';
import { getClient } from '../currentScopes';
import { DEBUG_BUILD } from '../debug-build';
Expand All @@ -17,18 +16,43 @@ export interface MetricData {
unit?: MeasurementUnit;
tags?: Record<string, Primitive>;
timestamp?: number;
client?: Client;
}

type MetricsAggregatorConstructor = {
new (client: BaseClient<ClientOptions>): MetricsAggregatorInterface;
new (client: Client): MetricsAggregatorInterface;
};

/**
* Global metrics aggregator instance.
*
* This is initialized on the first call to any `Sentry.metric.*` method.
* A metrics aggregator instance per Client.
*/
let globalMetricsAggregator: MetricsAggregatorInterface | undefined;
let globalMetricsAggregators: WeakMap<Client, MetricsAggregatorInterface> | undefined;

/**
* Gets the metrics aggregator for a given client.
* @param client The client for which to get the metrics aggregator.
* @param Aggregator Optional metrics aggregator class to use to create an aggregator if one does not exist.
*/
function getMetricsAggregatorForClient(
client: Client,
Aggregator: MetricsAggregatorConstructor,
): MetricsAggregatorInterface {
if (!globalMetricsAggregators) {
globalMetricsAggregators = new WeakMap();
}

const aggregator = globalMetricsAggregators.get(client);
if (aggregator) {
return aggregator;
}

const newAggregator = new Aggregator(client);
client.on('flush', () => newAggregator.flush());
client.on('close', () => newAggregator.close());
globalMetricsAggregators.set(client, newAggregator);

return newAggregator;
}

function addToMetricsAggregator(
Aggregator: MetricsAggregatorConstructor,
Expand All @@ -37,38 +61,32 @@ function addToMetricsAggregator(
value: number | string,
data: MetricData | undefined = {},
): void {
const client = getClient<BaseClient<ClientOptions>>();
const client = data.client || getClient<Client>();

if (!client) {
return;
}

if (!globalMetricsAggregator) {
const aggregator = (globalMetricsAggregator = new Aggregator(client));

client.on('flush', () => aggregator.flush());
client.on('close', () => aggregator.close());
const scope = getCurrentScope();
const { unit, tags, timestamp } = data;
const { release, environment } = client.getOptions();
// eslint-disable-next-line deprecation/deprecation
const transaction = scope.getTransaction();
const metricTags: Record<string, string> = {};
if (release) {
metricTags.release = release;
}

if (client) {
const scope = getCurrentScope();
const { unit, tags, timestamp } = data;
const { release, environment } = client.getOptions();
// eslint-disable-next-line deprecation/deprecation
const transaction = scope.getTransaction();
const metricTags: Record<string, string> = {};
if (release) {
metricTags.release = release;
}
if (environment) {
metricTags.environment = environment;
}
if (transaction) {
metricTags.transaction = spanToJSON(transaction).description || '';
}

DEBUG_BUILD && logger.log(`Adding value of ${value} to ${metricType} metric ${name}`);
globalMetricsAggregator.add(metricType, name, value, unit, { ...metricTags, ...tags }, timestamp);
if (environment) {
metricTags.environment = environment;
}
if (transaction) {
metricTags.transaction = spanToJSON(transaction).description || '';
}

DEBUG_BUILD && logger.log(`Adding value of ${value} to ${metricType} metric ${name}`);

const aggregator = getMetricsAggregatorForClient(client, Aggregator);
aggregator.add(metricType, name, value, unit, { ...metricTags, ...tags }, timestamp);
}

/**
Expand Down Expand Up @@ -112,4 +130,8 @@ export const metrics = {
distribution,
set,
gauge,
/**
* @ignore This is for internal use only.
*/
getMetricsAggregatorForClient,
};
3 changes: 3 additions & 0 deletions packages/types/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,9 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/** Submits the session to Sentry */
sendSession(session: Session | SessionAggregates): void;

/** Sends an envelope to Sentry */
sendEnvelope(envelope: Envelope): PromiseLike<TransportMakeRequestResponse>;

/**
* Record on the client that an event got dropped (ie, an event that will not be sent to sentry).
*
Expand Down