Skip to content

Commit 8560dba

Browse files
legraphistaStefan-Gabriel Muscalu
authored andcommitted
fix(mongo): when cursor is returned, track lifecycle until close
this commit check the return value of collection operation, and if determined to be a cursor, it closes span on cursor 'close' event
1 parent 9c66c39 commit 8560dba

File tree

1 file changed

+21
-2
lines changed
  • packages/tracing/src/integrations/node

1 file changed

+21
-2
lines changed

packages/tracing/src/integrations/node/mongo.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,19 @@ interface MongoOptions {
8888
useMongoose?: boolean;
8989
}
9090

91+
interface MongoCursor {
92+
once(event: 'close', listener: () => void): void;
93+
}
94+
95+
function isCursor(value: unknown): value is MongoCursor {
96+
return (
97+
typeof value === 'function' &&
98+
value?.constructor?.name.indexOf('Cursor') !== -1 &&
99+
'once' in value &&
100+
typeof (value as MongoCursor).once === 'function'
101+
);
102+
}
103+
91104
/** Tracing integration for mongo package */
92105
export class Mongo implements Integration {
93106
/**
@@ -153,15 +166,21 @@ export class Mongo implements Integration {
153166
// its (non-callback) arguments can also be functions.)
154167
if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {
155168
const span = parentSpan?.startChild(getSpanContext(this, operation, args));
156-
const maybePromise = orig.call(this, ...args) as Promise<unknown>;
169+
const maybePromise = orig.call(this, ...args) as Promise<unknown> | MongoCursor;
157170

158171
if (isThenable(maybePromise)) {
159172
return maybePromise.then((res: unknown) => {
160173
span?.finish();
161174
return res;
162175
});
163176
} else {
164-
span?.finish();
177+
if (isCursor(maybePromise)) {
178+
maybePromise.once('close', () => {
179+
span?.finish();
180+
});
181+
} else {
182+
span?.finish();
183+
}
165184
return maybePromise;
166185
}
167186
}

0 commit comments

Comments
 (0)