Skip to content

Commit 833eaa4

Browse files
fix(NODE-6362): cache cursor deserialization options across deserialize calls (#4221)
1 parent d6c147d commit 833eaa4

File tree

10 files changed

+129
-241
lines changed

10 files changed

+129
-241
lines changed

src/bson.ts

+11
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,14 @@ export function resolveBSONOptions(
132132
options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true
133133
};
134134
}
135+
136+
/** @internal */
137+
export function parseUtf8ValidationOption(options?: { enableUtf8Validation?: boolean }): {
138+
utf8: { writeErrors: false } | false;
139+
} {
140+
const enableUtf8Validation = options?.enableUtf8Validation;
141+
if (enableUtf8Validation === false) {
142+
return { utf8: false };
143+
}
144+
return { utf8: { writeErrors: false } };
145+
}

src/cmap/connection.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { type DeserializeOptions } from 'bson';
12
import { type Readable, Transform, type TransformCallback } from 'stream';
23
import { clearTimeout, setTimeout } from 'timers';
34

@@ -487,7 +488,7 @@ export class Connection extends TypedEventEmitter<ConnectionEvents> {
487488

488489
// If `documentsReturnedIn` not set or raw is not enabled, use input bson options
489490
// Otherwise, support raw flag. Raw only works for cursors that hardcode firstBatch/nextBatch fields
490-
const bsonOptions =
491+
const bsonOptions: DeserializeOptions =
491492
options.documentsReturnedIn == null || !options.raw
492493
? options
493494
: {

src/cmap/wire_protocol/on_demand/document.ts

+14-18
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1+
import { type DeserializeOptions } from 'bson';
2+
13
import {
24
Binary,
35
type BSONElement,
46
BSONError,
5-
type BSONSerializeOptions,
67
BSONType,
78
deserialize,
89
getBigInt64LE,
910
getFloat64LE,
1011
getInt32LE,
1112
ObjectId,
1213
parseToElementsToArray,
13-
pluckBSONSerializeOptions,
1414
Timestamp,
1515
toUTF8
1616
} from '../../../bson';
@@ -44,6 +44,14 @@ export type JSTypeOf = {
4444
/** @internal */
4545
type CachedBSONElement = { element: BSONElement; value: any | undefined };
4646

47+
/**
48+
* @internal
49+
*
50+
* Options for `OnDemandDocument.toObject()`. Validation is required to ensure
51+
* that callers provide utf8 validation options. */
52+
export type OnDemandDocumentDeserializeOptions = Omit<DeserializeOptions, 'validation'> &
53+
Required<Pick<DeserializeOptions, 'validation'>>;
54+
4755
/** @internal */
4856
export class OnDemandDocument {
4957
/**
@@ -330,24 +338,12 @@ export class OnDemandDocument {
330338
* Deserialize this object, DOES NOT cache result so avoid multiple invocations
331339
* @param options - BSON deserialization options
332340
*/
333-
public toObject(options?: BSONSerializeOptions): Record<string, any> {
334-
const exactBSONOptions = {
335-
...pluckBSONSerializeOptions(options ?? {}),
336-
validation: this.parseBsonSerializationOptions(options),
341+
public toObject(options?: OnDemandDocumentDeserializeOptions): Record<string, any> {
342+
return deserialize(this.bson, {
343+
...options,
337344
index: this.offset,
338345
allowObjectSmallerThanBufferSize: true
339-
};
340-
return deserialize(this.bson, exactBSONOptions);
341-
}
342-
343-
private parseBsonSerializationOptions(options?: { enableUtf8Validation?: boolean }): {
344-
utf8: { writeErrors: false } | false;
345-
} {
346-
const enableUtf8Validation = options?.enableUtf8Validation;
347-
if (enableUtf8Validation === false) {
348-
return { utf8: false };
349-
}
350-
return { utf8: { writeErrors: false } };
346+
});
351347
}
352348

353349
/** Returns this document's bytes only */

src/cmap/wire_protocol/responses.ts

+23-5
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
1+
import { type DeserializeOptions } from 'bson';
2+
13
import {
24
type BSONElement,
35
type BSONSerializeOptions,
46
BSONType,
57
type Document,
68
Long,
79
parseToElementsToArray,
10+
parseUtf8ValidationOption,
11+
pluckBSONSerializeOptions,
812
type Timestamp
913
} from '../../bson';
1014
import { MongoUnexpectedServerResponseError } from '../../error';
1115
import { type ClusterTime } from '../../sdam/common';
1216
import { decorateDecryptionResult, ns } from '../../utils';
13-
import { type JSTypeOf, OnDemandDocument } from './on_demand/document';
17+
import {
18+
type JSTypeOf,
19+
OnDemandDocument,
20+
type OnDemandDocumentDeserializeOptions
21+
} from './on_demand/document';
1422

1523
// eslint-disable-next-line no-restricted-syntax
1624
const enum BSONElementOffset {
@@ -112,7 +120,8 @@ export class MongoDBResponse extends OnDemandDocument {
112120
this.get('recoveryToken', BSONType.object)?.toObject({
113121
promoteValues: false,
114122
promoteLongs: false,
115-
promoteBuffers: false
123+
promoteBuffers: false,
124+
validation: { utf8: true }
116125
}) ?? null
117126
);
118127
}
@@ -165,6 +174,14 @@ export class MongoDBResponse extends OnDemandDocument {
165174
}
166175
return this.clusterTime ?? null;
167176
}
177+
178+
public override toObject(options?: BSONSerializeOptions): Record<string, any> {
179+
const exactBSONOptions = {
180+
...pluckBSONSerializeOptions(options ?? {}),
181+
validation: parseUtf8ValidationOption(options)
182+
};
183+
return super.toObject(exactBSONOptions);
184+
}
168185
}
169186

170187
/** @internal */
@@ -248,12 +265,13 @@ export class CursorResponse extends MongoDBResponse {
248265
this.cursor.get('postBatchResumeToken', BSONType.object)?.toObject({
249266
promoteValues: false,
250267
promoteLongs: false,
251-
promoteBuffers: false
268+
promoteBuffers: false,
269+
validation: { utf8: true }
252270
}) ?? null
253271
);
254272
}
255273

256-
public shift(options?: BSONSerializeOptions): any {
274+
public shift(options: OnDemandDocumentDeserializeOptions): any {
257275
if (this.iterated >= this.batchSize) {
258276
return null;
259277
}
@@ -305,7 +323,7 @@ export class ExplainedCursorResponse extends CursorResponse {
305323
return this._length;
306324
}
307325

308-
override shift(options?: BSONSerializeOptions | undefined) {
326+
override shift(options?: DeserializeOptions) {
309327
if (this._length === 0) return null;
310328
this._length -= 1;
311329
return this.toObject(options);

src/cursor/abstract_cursor.ts

+15-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Readable, Transform } from 'stream';
22

33
import { type BSONSerializeOptions, type Document, Long, pluckBSONSerializeOptions } from '../bson';
4+
import { type OnDemandDocumentDeserializeOptions } from '../cmap/wire_protocol/on_demand/document';
45
import { type CursorResponse } from '../cmap/wire_protocol/responses';
56
import {
67
MongoAPIError,
@@ -157,6 +158,9 @@ export abstract class AbstractCursor<
157158
/** @event */
158159
static readonly CLOSE = 'close' as const;
159160

161+
/** @internal */
162+
protected deserializationOptions: OnDemandDocumentDeserializeOptions;
163+
160164
/** @internal */
161165
protected constructor(
162166
client: MongoClient,
@@ -211,6 +215,13 @@ export abstract class AbstractCursor<
211215
} else {
212216
this.cursorSession = this.cursorClient.startSession({ owner: this, explicit: false });
213217
}
218+
219+
this.deserializationOptions = {
220+
...this.cursorOptions,
221+
validation: {
222+
utf8: options?.enableUtf8Validation === false ? false : true
223+
}
224+
};
214225
}
215226

216227
/**
@@ -304,7 +315,7 @@ export abstract class AbstractCursor<
304315
);
305316

306317
for (let count = 0; count < documentsToRead; count++) {
307-
const document = this.documents?.shift(this.cursorOptions);
318+
const document = this.documents?.shift(this.deserializationOptions);
308319
if (document != null) {
309320
bufferedDocs.push(document);
310321
}
@@ -406,7 +417,7 @@ export abstract class AbstractCursor<
406417
}
407418

408419
do {
409-
const doc = this.documents?.shift(this.cursorOptions);
420+
const doc = this.documents?.shift(this.deserializationOptions);
410421
if (doc != null) {
411422
if (this.transform != null) return await this.transformDocument(doc);
412423
return doc;
@@ -425,15 +436,15 @@ export abstract class AbstractCursor<
425436
throw new MongoCursorExhaustedError();
426437
}
427438

428-
let doc = this.documents?.shift(this.cursorOptions);
439+
let doc = this.documents?.shift(this.deserializationOptions);
429440
if (doc != null) {
430441
if (this.transform != null) return await this.transformDocument(doc);
431442
return doc;
432443
}
433444

434445
await this.fetchBatch();
435446

436-
doc = this.documents?.shift(this.cursorOptions);
447+
doc = this.documents?.shift(this.deserializationOptions);
437448
if (doc != null) {
438449
if (this.transform != null) return await this.transformDocument(doc);
439450
return doc;

src/cursor/aggregation_cursor.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export class AggregationCursor<TSchema = any> extends AbstractCursor<TSchema> {
7676
explain: verbosity ?? true
7777
})
7878
)
79-
).shift(this.aggregateOptions);
79+
).shift(this.deserializationOptions);
8080
}
8181

8282
/** Add a stage to the aggregation pipeline

src/cursor/find_cursor.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ export class FindCursor<TSchema = any> extends AbstractCursor<TSchema> {
143143
explain: verbosity ?? true
144144
})
145145
)
146-
).shift(this.findOptions);
146+
).shift(this.deserializationOptions);
147147
}
148148

149149
/** Set the cursor query */

src/index.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,11 @@ export type { ClientMetadata, ClientMetadataOptions } from './cmap/handshake/cli
302302
export type { ConnectionPoolMetrics } from './cmap/metrics';
303303
export type { StreamDescription, StreamDescriptionOptions } from './cmap/stream_description';
304304
export type { CompressorName } from './cmap/wire_protocol/compression';
305-
export type { JSTypeOf, OnDemandDocument } from './cmap/wire_protocol/on_demand/document';
305+
export type {
306+
JSTypeOf,
307+
OnDemandDocument,
308+
OnDemandDocumentDeserializeOptions
309+
} from './cmap/wire_protocol/on_demand/document';
306310
export type {
307311
CursorResponse,
308312
MongoDBResponse,

0 commit comments

Comments
 (0)