Skip to content

fix(mongo): when cursor is returned, track lifecycle until close #5968

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

Closed
Closed
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
24 changes: 22 additions & 2 deletions packages/tracing/src/integrations/node/mongo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,20 @@ interface MongoOptions {
useMongoose?: boolean;
}

interface MongoCursor {
once(event: 'close', listener: () => void): void;
}

function isCursor(value: unknown): value is MongoCursor {
return (
typeof value === 'object' &&
!!value &&
value.constructor.name.indexOf('Cursor') !== -1 &&
'once' in value &&
typeof (value as MongoCursor).once === 'function'
);
}

/** Tracing integration for mongo package */
export class Mongo implements Integration {
/**
Expand Down Expand Up @@ -153,15 +167,21 @@ export class Mongo implements Integration {
// its (non-callback) arguments can also be functions.)
if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {
const span = parentSpan?.startChild(getSpanContext(this, operation, args));
const maybePromise = orig.call(this, ...args) as Promise<unknown>;
const maybePromise = orig.call(this, ...args) as Promise<unknown> | MongoCursor;

if (isThenable(maybePromise)) {
return maybePromise.then((res: unknown) => {
span?.finish();
return res;
});
} else {
span?.finish();
if (isCursor(maybePromise)) {
maybePromise.once('close', () => {
span?.finish();
});
} else {
span?.finish();
}
return maybePromise;
}
}
Expand Down