feat: add copilot metrics (#8455)

fix CLOUD-73
This commit is contained in:
darkskygit
2024-10-18 03:30:02 +00:00
parent 4122cec096
commit fa554b1054
14 changed files with 198 additions and 112 deletions
@@ -19,7 +19,7 @@ export type { GraphqlContext } from './graphql';
export * from './guard';
export { CryptoHelper, URLHelper } from './helpers';
export { MailService } from './mailer';
export { CallCounter, CallTimer, metrics } from './metrics';
export { CallMetric, metrics } from './metrics';
export { type ILocker, Lock, Locker, Mutex, RequestMutex } from './mutex';
export {
GatewayErrorWrapper,
@@ -36,7 +36,8 @@ export type KnownMetricScopes =
| 'controllers'
| 'doc'
| 'sse'
| 'mail';
| 'mail'
| 'ai';
const metricCreators: MetricCreators = {
counter(meter: Meter, name: string, opts?: MetricOptions) {
@@ -1,10 +1,18 @@
import { Attributes } from '@opentelemetry/api';
import type { Attributes } from '@opentelemetry/api';
import { KnownMetricScopes, metrics } from './metrics';
import { type KnownMetricScopes, metrics } from './metrics';
export const CallTimer = (
/**
* Decorator for measuring the call time, record call count and if is throw of a function call
* @param scope metric scope
* @param name metric event name
* @param attrs attributes
* @returns
*/
export const CallMetric = (
scope: KnownMetricScopes,
name: string,
record?: { timer?: boolean; count?: boolean; error?: boolean },
attrs?: Attributes
): MethodDecorator => {
// @ts-expect-error allow
@@ -23,54 +31,35 @@ export const CallTimer = (
description: `function call time costs of ${name}`,
unit: 'ms',
});
metrics[scope]
.counter(`${name}_calls`, {
description: `function call counts of ${name}`,
})
.add(1, attrs);
const count = metrics[scope].counter(`${name}_calls`, {
description: `function call counter of ${name}`,
});
const errorCount = metrics[scope].counter(`${name}_errors`, {
description: `function call error counter of ${name}`,
});
const start = Date.now();
const end = () => {
timer.record(Date.now() - start, attrs);
timer?.record(Date.now() - start, attrs);
};
try {
if (!record || !!record.count) {
count.add(1, attrs);
}
return await originalMethod.apply(this, args);
} catch (err) {
if (!record || !!record.error) {
errorCount.add(1, attrs);
}
throw err;
} finally {
end();
if (!record || !!record.timer) {
end();
}
}
};
return desc;
};
};
export const CallCounter = (
scope: KnownMetricScopes,
name: string,
attrs?: Attributes
): MethodDecorator => {
// @ts-expect-error allow
return (
_target,
_key,
desc: TypedPropertyDescriptor<(...args: any[]) => any>
) => {
const originalMethod = desc.value;
if (!originalMethod) {
return desc;
}
desc.value = function (...args: any[]) {
const count = metrics[scope].counter(name, {
description: `function call counter of ${name}`,
});
count.add(1, attrs);
return originalMethod.apply(this, args);
};
return desc;
};
};