Skip to content

Commit

Permalink
feat(createTimedSpan): Add an optional afterCompletion hook to pass…
Browse files Browse the repository at this point in the history
… back `latency` (#209)

* feat(createTimedSpan): Add an optional `afterCompletion` hook to pass back `latency`

* Add `success` to callback
  • Loading branch information
AkiraJ48 authored Jul 14, 2023
1 parent a8b58b2 commit e4c5402
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
21 changes: 21 additions & 0 deletions src/createTimedSpan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,27 @@ describe('timedSpan', () => {
}
});

it('should call afterCompletion', async () => {
jest.spyOn(metricsClient, 'increment');
jest.spyOn(metricsClient, 'timing');

let duration = 0;

const result = await timedSpan(
'test',
// This is false but we still successfully resolved
() => Promise.resolve(false),
(timedDuration) => {
duration = timedDuration;
},
);

expect(result).toBe(false);

// Hopefully this doesn't become flaky and end up as 0
expect(duration).toBeGreaterThan(0);
});

it('should handle failure', async () => {
const mockIncrement = jest.spyOn(metricsClient, 'increment');
const mockTiming = jest.spyOn(metricsClient, 'timing');
Expand Down
11 changes: 9 additions & 2 deletions src/createTimedSpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,22 @@ type TimingMetricsClient = Pick<MetricsClient, 'increment' | 'timing'>;
*/
export const createTimedSpan =
(metricsClient: TimingMetricsClient) =>
async <T>(name: string, block: () => PromiseLike<T>): Promise<T> => {
async <T>(
name: string,
block: () => PromiseLike<T>,
afterCompletion?: (duration: number, success: boolean) => void,
): Promise<T> => {
const startTime = process.hrtime.bigint();

const handleCompletion = (success: boolean) => {
const durationNanos = process.hrtime.bigint() - startTime;
const successTag = success ? 'success' : 'failure';
const durationMilliseconds = Number(durationNanos) / 1e6;

metricsClient.timing(`${name}.latency`, Number(durationNanos) / 1e6);
metricsClient.timing(`${name}.latency`, durationMilliseconds);
metricsClient.increment(`${name}.count`, [successTag]);

afterCompletion?.(durationMilliseconds, success);
};

try {
Expand Down

0 comments on commit e4c5402

Please sign in to comment.