From 5aa69740acd5c884dc6464a6608b1fabdafd8f21 Mon Sep 17 00:00:00 2001 From: Durran Jordan Date: Thu, 22 Aug 2024 15:10:05 +0200 Subject: [PATCH] feat(NODE-6329): client bulk write happy path --- src/cmap/command_monitoring_events.ts | 16 +- src/cmap/commands.ts | 8 +- src/cmap/wire_protocol/responses.ts | 26 + src/cursor/client_bulk_write_cursor.ts | 64 ++ src/index.ts | 15 + src/mongo_client.ts | 18 + .../client_bulk_write/client_bulk_write.ts | 43 ++ .../client_bulk_write/command_builder.ts | 8 +- src/operations/client_bulk_write/common.ts | 74 +++ src/operations/client_bulk_write/executor.ts | 55 ++ .../client_bulk_write/results_merger.ts | 95 +++ test/integration/crud/crud.spec.test.ts | 6 +- test/mongodb.ts | 1 + .../unacknowledged-client-bulkWrite.json | 218 +++++++ .../unacknowledged-client-bulkWrite.yml | 109 ++++ .../logging/operation-id.json | 187 ++++++ .../server-selection/logging/operation-id.yml | 97 +++ .../unified/client-bulkWrite.json | 592 ++++++++++++++++++ .../transactions/unified/client-bulkWrite.yml | 262 ++++++++ .../transactions/unified/mongos-pin-auto.json | 294 +++++++++ .../transactions/unified/mongos-pin-auto.yml | 90 +++ .../versioned-api/crud-api-version-1.json | 82 ++- .../spec/versioned-api/crud-api-version-1.yml | 41 ++ test/tools/unified-spec-runner/match.ts | 14 +- test/tools/unified-spec-runner/operations.ts | 10 + test/unit/cmap/commands.test.ts | 10 +- .../client_bulk_write/command_builder.test.ts | 97 ++- .../client_bulk_write/results_merger.test.ts | 205 ++++++ 28 files changed, 2691 insertions(+), 46 deletions(-) create mode 100644 src/cursor/client_bulk_write_cursor.ts create mode 100644 src/operations/client_bulk_write/client_bulk_write.ts create mode 100644 src/operations/client_bulk_write/executor.ts create mode 100644 src/operations/client_bulk_write/results_merger.ts create mode 100644 test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.json create mode 100644 test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.yml create mode 100644 test/spec/transactions/unified/client-bulkWrite.json create mode 100644 test/spec/transactions/unified/client-bulkWrite.yml create mode 100644 test/unit/operations/client_bulk_write/results_merger.test.ts diff --git a/src/cmap/command_monitoring_events.ts b/src/cmap/command_monitoring_events.ts index 002ecf2c8c..da69996035 100644 --- a/src/cmap/command_monitoring_events.ts +++ b/src/cmap/command_monitoring_events.ts @@ -7,7 +7,12 @@ import { LEGACY_HELLO_COMMAND_CAMEL_CASE } from '../constants'; import { calculateDurationInMs, deepCopy } from '../utils'; -import { OpMsgRequest, type OpQueryRequest, type WriteProtocolMessageType } from './commands'; +import { + DocumentSequence, + OpMsgRequest, + type OpQueryRequest, + type WriteProtocolMessageType +} from './commands'; import type { Connection } from './connection'; /** @@ -249,7 +254,14 @@ const OP_QUERY_KEYS = [ /** Extract the actual command from the query, possibly up-converting if it's a legacy format */ function extractCommand(command: WriteProtocolMessageType): Document { if (command instanceof OpMsgRequest) { - return deepCopy(command.command); + const cmd = deepCopy(command.command); + if (cmd.ops instanceof DocumentSequence) { + cmd.ops = cmd.ops.documents; + } + if (cmd.nsInfo instanceof DocumentSequence) { + cmd.nsInfo = cmd.nsInfo.documents; + } + return cmd; } if (command.query?.$query) { diff --git a/src/cmap/commands.ts b/src/cmap/commands.ts index 73ef1f2e1f..9322fc5341 100644 --- a/src/cmap/commands.ts +++ b/src/cmap/commands.ts @@ -544,10 +544,10 @@ export class OpMsgRequest { for (const [key, value] of Object.entries(document)) { if (value instanceof DocumentSequence) { // Document sequences starts with type 1 at the first byte. - const buffer = Buffer.allocUnsafe(1 + 4 + key.length); + const buffer = Buffer.allocUnsafe(1 + 4 + key.length + 1); buffer[0] = 1; - // Third part is the field name at offset 5. - encodeUTF8Into(buffer, key, 5); + // Third part is the field name at offset 5 with trailing null byte. + encodeUTF8Into(buffer, `${key}\0`, 5); chunks.push(buffer); // Fourth part are the documents' bytes. let docsLength = 0; @@ -557,7 +557,7 @@ export class OpMsgRequest { chunks.push(docBson); } // Second part of the sequence is the length at offset 1; - buffer.writeInt32LE(key.length + docsLength, 1); + buffer.writeInt32LE(4 + key.length + 1 + docsLength, 1); // Why are we removing the field from the command? This is because it needs to be // removed in the OP_MSG request first section, and DocumentSequence is not a // BSON type and is specific to the MongoDB wire protocol so there's nothing diff --git a/src/cmap/wire_protocol/responses.ts b/src/cmap/wire_protocol/responses.ts index e69cf84cfc..6c166afd61 100644 --- a/src/cmap/wire_protocol/responses.ts +++ b/src/cmap/wire_protocol/responses.ts @@ -329,3 +329,29 @@ export class ExplainedCursorResponse extends CursorResponse { return this.toObject(options); } } + +/** + * Client bulk writes have some extra metadata at the top level that needs to be + * included in the result returned to the user. + */ +export class ClientBulkWriteCursorResponse extends CursorResponse { + get insertedCount() { + return this.get('nInserted', BSONType.int, true); + } + + get upsertedCount() { + return this.get('nUpserted', BSONType.int, true); + } + + get matchedCount() { + return this.get('nMatched', BSONType.int, true); + } + + get modifiedCount() { + return this.get('nModified', BSONType.int, true); + } + + get deletedCount() { + return this.get('nDeleted', BSONType.int, true); + } +} diff --git a/src/cursor/client_bulk_write_cursor.ts b/src/cursor/client_bulk_write_cursor.ts new file mode 100644 index 0000000000..f56f55e481 --- /dev/null +++ b/src/cursor/client_bulk_write_cursor.ts @@ -0,0 +1,64 @@ +import type { Document } from '../bson'; +import { type ClientBulkWriteCursorResponse } from '../cmap/wire_protocol/responses'; +import type { MongoClient } from '../mongo_client'; +import { ClientBulkWriteOperation } from '../operations/client_bulk_write/client_bulk_write'; +import { type ClientBulkWriteOptions } from '../operations/client_bulk_write/common'; +import { executeOperation } from '../operations/execute_operation'; +import type { ClientSession } from '../sessions'; +import { mergeOptions, MongoDBNamespace } from '../utils'; +import { + AbstractCursor, + type AbstractCursorOptions, + type InitialCursorResponse +} from './abstract_cursor'; + +/** @public */ +export interface ClientBulkWriteCursorOptions + extends AbstractCursorOptions, + ClientBulkWriteOptions {} + +/** + * @public + */ +export class ClientBulkWriteCursor extends AbstractCursor { + public readonly command: Document; + /** @internal */ + private cursorResponse?: ClientBulkWriteCursorResponse; + /** @internal */ + private clientBulkWriteOptions: ClientBulkWriteOptions; + + /** @internal */ + constructor(client: MongoClient, command: Document, options: ClientBulkWriteOptions = {}) { + super(client, new MongoDBNamespace('admin'), options); + + this.command = command; + this.clientBulkWriteOptions = options; + } + + get response(): ClientBulkWriteCursorResponse { + if (this.cursorResponse) return this.cursorResponse; + throw new Error('no cursor response'); + } + + clone(): ClientBulkWriteCursor { + const clonedOptions = mergeOptions({}, this.clientBulkWriteOptions); + delete clonedOptions.session; + return new ClientBulkWriteCursor(this.client, this.command, { + ...clonedOptions + }); + } + + /** @internal */ + async _initialize(session: ClientSession): Promise { + const clientBulkWriteOperation = new ClientBulkWriteOperation(this.command, { + ...this.clientBulkWriteOptions, + ...this.cursorOptions, + session + }); + + const response = await executeOperation(this.client, clientBulkWriteOperation); + this.cursorResponse = response; + + return { server: clientBulkWriteOperation.server, session, response }; + } +} diff --git a/src/index.ts b/src/index.ts index dda026323a..afd8f86ee0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -473,6 +473,21 @@ export type { AggregateOptions, DB_AGGREGATE_COLLECTION } from './operations/aggregate'; +export type { + AnyClientBulkWriteModel, + ClientBulkWriteOptions, + ClientBulkWriteResult, + ClientDeleteManyModel, + ClientDeleteOneModel, + ClientDeleteResult, + ClientInsertOneModel, + ClientInsertOneResult, + ClientReplaceOneModel, + ClientUpdateManyModel, + ClientUpdateOneModel, + ClientUpdateResult, + ClientWriteModel +} from './operations/client_bulk_write/common'; export type { CollationOptions, CommandOperation, diff --git a/src/mongo_client.ts b/src/mongo_client.ts index e8aae51639..eed959218f 100644 --- a/src/mongo_client.ts +++ b/src/mongo_client.ts @@ -30,6 +30,12 @@ import { SeverityLevel } from './mongo_logger'; import { TypedEventEmitter } from './mongo_types'; +import { + type AnyClientBulkWriteModel, + type ClientBulkWriteOptions, + type ClientBulkWriteResult +} from './operations/client_bulk_write/common'; +import { ClientBulkWriteExecutor } from './operations/client_bulk_write/executor'; import { executeOperation } from './operations/execute_operation'; import { RunAdminCommandOperation } from './operations/run_command'; import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern'; @@ -477,6 +483,18 @@ export class MongoClient extends TypedEventEmitter implements return this.s.bsonOptions; } + /** + * Executes a client bulk write operation, available on server 8.0+. + * @param models - The client bulk write models. + * @param options - The client bulk write options. + */ + async bulkWrite( + models: AnyClientBulkWriteModel[], + options?: ClientBulkWriteOptions + ): Promise { + return await new ClientBulkWriteExecutor(this, models, options).execute(); + } + /** * Connect to MongoDB using a url * diff --git a/src/operations/client_bulk_write/client_bulk_write.ts b/src/operations/client_bulk_write/client_bulk_write.ts new file mode 100644 index 0000000000..73f851d76f --- /dev/null +++ b/src/operations/client_bulk_write/client_bulk_write.ts @@ -0,0 +1,43 @@ +import { type Document } from 'bson'; + +import { ClientBulkWriteCursorResponse } from '../../cmap/wire_protocol/responses'; +import type { Server } from '../../sdam/server'; +import type { ClientSession } from '../../sessions'; +import { MongoDBNamespace } from '../../utils'; +import { AbstractOperation, Aspect, defineAspects } from '../operation'; +import { type ClientBulkWriteOptions } from './common'; + +export class ClientBulkWriteOperation extends AbstractOperation { + command: Document; + override options: ClientBulkWriteOptions; + + override get commandName() { + return 'bulkWrite' as const; + } + + constructor(command: Document, options: ClientBulkWriteOptions) { + super(options); + this.command = command; + this.options = options; + this.ns = new MongoDBNamespace('admin'); + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + return await server.command( + this.ns, + this.command, + { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }, + ClientBulkWriteCursorResponse + ); + } +} + +defineAspects(ClientBulkWriteOperation, [Aspect.WRITE_OPERATION]); diff --git a/src/operations/client_bulk_write/command_builder.ts b/src/operations/client_bulk_write/command_builder.ts index 4d4d323de6..0b9ff97c59 100644 --- a/src/operations/client_bulk_write/command_builder.ts +++ b/src/operations/client_bulk_write/command_builder.ts @@ -1,4 +1,4 @@ -import { type Document } from '../../bson'; +import { type Document, ObjectId } from '../../bson'; import { DocumentSequence } from '../../cmap/commands'; import type { Filter, OptionalId, UpdateFilter, WithoutId } from '../../mongo_types'; import { type CollationOptions } from '../command'; @@ -23,6 +23,7 @@ export interface ClientBulkWriteCommand { nsInfo: DocumentSequence; bypassDocumentValidation?: boolean; let?: Document; + comment?: any; } /** @internal */ @@ -88,6 +89,10 @@ export class ClientBulkWriteCommandBuilder { if (this.options.let) { command.let = this.options.let; } + + if (this.options.comment != null) { + command.comment = this.options.comment; + } return [command]; } } @@ -112,6 +117,7 @@ export const buildInsertOneOperation = ( insert: index, document: model.document }; + document.document._id = model.document._id ?? new ObjectId(); return document; }; diff --git a/src/operations/client_bulk_write/common.ts b/src/operations/client_bulk_write/common.ts index e76fb5108f..c63e0d895d 100644 --- a/src/operations/client_bulk_write/common.ts +++ b/src/operations/client_bulk_write/common.ts @@ -144,3 +144,77 @@ export type AnyClientBulkWriteModel = | ClientUpdateManyModel | ClientDeleteOneModel | ClientDeleteManyModel; + +/** @public */ +export interface ClientBulkWriteResult { + /** + * The total number of documents inserted across all insert operations. + */ + insertedCount: number; + /** + * The total number of documents upserted across all update operations. + */ + upsertedCount: number; + /** + * The total number of documents matched across all update operations. + */ + matchedCount: number; + /** + * The total number of documents modified across all update operations. + */ + modifiedCount: number; + /** + * The total number of documents deleted across all delete operations. + */ + deletedCount: number; + /** + * The results of each individual insert operation that was successfully performed. + */ + insertResults?: Map; + /** + * The results of each individual update operation that was successfully performed. + */ + updateResults?: Map; + /** + * The results of each individual delete operation that was successfully performed. + */ + deleteResults?: Map; +} + +/** @public */ +export interface ClientInsertOneResult { + /** + * The _id of the inserted document. + */ + insertedId: any; +} + +/** @public */ +export interface ClientUpdateResult { + /** + * The number of documents that matched the filter. + */ + matchedCount: number; + + /** + * The number of documents that were modified. + */ + modifiedCount: number; + + /** + * The _id field of the upserted document if an upsert occurred. + * + * It MUST be possible to discern between a BSON Null upserted ID value and this field being + * unset. If necessary, drivers MAY add a didUpsert boolean field to differentiate between + * these two cases. + */ + upsertedId?: any; +} + +/** @public */ +export interface ClientDeleteResult { + /** + * The number of documents that were deleted. + */ + deletedCount: number; +} diff --git a/src/operations/client_bulk_write/executor.ts b/src/operations/client_bulk_write/executor.ts new file mode 100644 index 0000000000..ca446cb950 --- /dev/null +++ b/src/operations/client_bulk_write/executor.ts @@ -0,0 +1,55 @@ +import { ClientBulkWriteCursor } from '../../cursor/client_bulk_write_cursor'; +import { type MongoClient } from '../../mongo_client'; +import { ClientBulkWriteCommandBuilder } from './command_builder'; +import { + type AnyClientBulkWriteModel, + type ClientBulkWriteOptions, + type ClientBulkWriteResult +} from './common'; +import { ClientBulkWriteResultsMerger } from './results_merger'; + +/** + * Responsible for executing a client bulk write. + * @internal + */ +export class ClientBulkWriteExecutor { + client: MongoClient; + options: ClientBulkWriteOptions; + operations: AnyClientBulkWriteModel[]; + + /** + * Instantiate the executor. + * @param client - The mongo client. + * @param operations - The user supplied bulk write models. + * @param options - The bulk write options. + */ + constructor( + client: MongoClient, + operations: AnyClientBulkWriteModel[], + options?: ClientBulkWriteOptions + ) { + this.client = client; + this.options = options || {}; + this.operations = operations; + } + + /** + * Execute the client bulk write. Will split commands into batches and exhaust the cursors + * for each, then merge the results into one. + * @returns The result. + */ + async execute(): Promise { + // The command builder will take the user provided models and potential split the batch + // into multiple commands due to size. + const commmandBuilder = new ClientBulkWriteCommandBuilder(this.operations, this.options); + const commands = commmandBuilder.buildCommands(); + const resultsMerger = new ClientBulkWriteResultsMerger(this.options); + // For each command will will create and exhaust a cursor for the results. + for (const command of commands) { + const cursor = new ClientBulkWriteCursor(this.client, command, this.options); + const docs = await cursor.toArray(); + resultsMerger.merge(command.ops.documents, cursor.response, docs); + } + return resultsMerger.result; + } +} diff --git a/src/operations/client_bulk_write/results_merger.ts b/src/operations/client_bulk_write/results_merger.ts new file mode 100644 index 0000000000..b66e709a71 --- /dev/null +++ b/src/operations/client_bulk_write/results_merger.ts @@ -0,0 +1,95 @@ +import { type Document } from '../../bson'; +import { type ClientBulkWriteCursorResponse } from '../../cmap/wire_protocol/responses'; +import { + type ClientBulkWriteOptions, + type ClientBulkWriteResult, + type ClientDeleteResult, + type ClientInsertOneResult, + type ClientUpdateResult +} from './common'; + +/** + * Merges client bulk write cursor responses together into a single result. + * @internal + */ +export class ClientBulkWriteResultsMerger { + result: ClientBulkWriteResult; + options: ClientBulkWriteOptions; + + /** + * Instantiate the merger. + * @param options - The options. + */ + constructor(options: ClientBulkWriteOptions) { + this.options = options; + const baseResult = { + insertedCount: 0, + upsertedCount: 0, + matchedCount: 0, + modifiedCount: 0, + deletedCount: 0 + }; + + if (options.verboseResults) { + this.result = { + ...baseResult, + insertResults: new Map(), + updateResults: new Map(), + deleteResults: new Map() + }; + } else { + this.result = baseResult; + } + } + + /** + * Merge the results in the cursor to the existing result. + * @param response - The cursor response. + * @param documents - The documents in the cursor. + * @returns The current result. + */ + merge( + operations: Document[], + response: ClientBulkWriteCursorResponse, + documents: Document[] + ): ClientBulkWriteResult { + // Update the counts from the cursor response. + this.result.insertedCount += response.insertedCount; + this.result.upsertedCount += response.upsertedCount; + this.result.matchedCount += response.matchedCount; + this.result.modifiedCount += response.modifiedCount; + this.result.deletedCount += response.deletedCount; + + if (this.options.verboseResults) { + // Iterate all the documents in the cursor and update the result. + for (const document of documents) { + // Only add to maps if ok: 1 + if (document.ok === 1) { + // Get the corresponding operation from the command. + const operation = operations[document.idx]; + // Handle insert results. + if ('insert' in operation) { + this.result.insertResults?.set(document.idx, { insertedId: operation.document._id }); + } + // Handle update results. + if ('update' in operation) { + const result: ClientUpdateResult = { + matchedCount: document.n, + modifiedCount: document.nModified || 0 + }; + if (document.upserted) { + result.upsertedId = document.upserted._id; + } + this.result.updateResults?.set(document.idx, result); + } + // Handle delete results. + if ('delete' in operation) { + this.result.deleteResults?.set(document.idx, { deletedCount: document.n }); + } + } + } + } + + return this.result; + } +} diff --git a/test/integration/crud/crud.spec.test.ts b/test/integration/crud/crud.spec.test.ts index 912fbcb1ef..a8a0d2987f 100644 --- a/test/integration/crud/crud.spec.test.ts +++ b/test/integration/crud/crud.spec.test.ts @@ -5,8 +5,6 @@ import { runUnifiedSuite } from '../../tools/unified-spec-runner/runner'; const clientBulkWriteTests = new RegExp( [ - 'client bulk write delete with collation', - 'client bulk write delete with hint', 'client bulkWrite operations support errorResponse assertions', 'an individual operation fails during an ordered bulkWrite', 'an individual operation fails during an unordered bulkWrite', @@ -15,7 +13,9 @@ const clientBulkWriteTests = new RegExp( 'a bulk write with only errors does not report a partial result', 'an empty list of write models is a client-side error', 'a write concern error occurs during a bulkWrite', - 'client bulkWrite' + 'client bulkWrite replaceOne prohibits atomic modifiers', + 'client bulkWrite updateOne requires atomic modifiers', + 'client bulkWrite updateMany requires atomic modifiers' ].join('|') ); diff --git a/test/mongodb.ts b/test/mongodb.ts index 8aeb97b592..3503412304 100644 --- a/test/mongodb.ts +++ b/test/mongodb.ts @@ -158,6 +158,7 @@ export * from '../src/operations/aggregate'; export * from '../src/operations/bulk_write'; export * from '../src/operations/client_bulk_write/command_builder'; export * from '../src/operations/client_bulk_write/common'; +export * from '../src/operations/client_bulk_write/results_merger'; export * from '../src/operations/collections'; export * from '../src/operations/command'; export * from '../src/operations/count'; diff --git a/test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.json b/test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.json new file mode 100644 index 0000000000..1099b6a1e9 --- /dev/null +++ b/test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.json @@ -0,0 +1,218 @@ +{ + "description": "unacknowledged-client-bulkWrite", + "schemaVersion": "1.7", + "runOnRequirements": [ + { + "minServerVersion": "8.0" + } + ], + "createEntities": [ + { + "client": { + "id": "client", + "useMultipleMongoses": false, + "observeEvents": [ + "commandStartedEvent", + "commandSucceededEvent", + "commandFailedEvent" + ], + "uriOptions": { + "w": 0 + } + } + }, + { + "database": { + "id": "database", + "client": "client", + "databaseName": "command-monitoring-tests" + } + }, + { + "collection": { + "id": "collection", + "database": "database", + "collectionName": "test" + } + } + ], + "initialData": [ + { + "collectionName": "test", + "databaseName": "command-monitoring-tests", + "documents": [ + { + "_id": 1, + "x": 11 + }, + { + "_id": 2, + "x": 22 + }, + { + "_id": 3, + "x": 33 + } + ] + } + ], + "_yamlAnchors": { + "namespace": "command-monitoring-tests.test" + }, + "tests": [ + { + "description": "A successful mixed client bulkWrite", + "operations": [ + { + "object": "client", + "name": "clientBulkWrite", + "arguments": { + "models": [ + { + "insertOne": { + "namespace": "command-monitoring-tests.test", + "document": { + "_id": 4, + "x": 44 + } + } + }, + { + "updateOne": { + "namespace": "command-monitoring-tests.test", + "filter": { + "_id": 3 + }, + "update": { + "$set": { + "x": 333 + } + } + } + } + ] + }, + "expectResult": { + "insertedCount": { + "$$unsetOrMatches": 0 + }, + "upsertedCount": { + "$$unsetOrMatches": 0 + }, + "matchedCount": { + "$$unsetOrMatches": 0 + }, + "modifiedCount": { + "$$unsetOrMatches": 0 + }, + "deletedCount": { + "$$unsetOrMatches": 0 + }, + "insertResults": { + "$$unsetOrMatches": {} + }, + "updateResults": { + "$$unsetOrMatches": {} + }, + "deleteResults": { + "$$unsetOrMatches": {} + } + } + }, + { + "object": "collection", + "name": "find", + "arguments": { + "filter": {} + }, + "expectResult": [ + { + "_id": 1, + "x": 11 + }, + { + "_id": 2, + "x": 22 + }, + { + "_id": 3, + "x": 333 + }, + { + "_id": 4, + "x": 44 + } + ] + } + ], + "expectEvents": [ + { + "client": "client", + "ignoreExtraEvents": true, + "events": [ + { + "commandStartedEvent": { + "commandName": "bulkWrite", + "databaseName": "admin", + "command": { + "bulkWrite": 1, + "errorsOnly": true, + "ordered": true, + "ops": [ + { + "insert": 0, + "document": { + "_id": 4, + "x": 44 + } + }, + { + "update": 0, + "filter": { + "_id": 3 + }, + "updateMods": { + "$set": { + "x": 333 + } + }, + "multi": false + } + ], + "nsInfo": [ + { + "ns": "command-monitoring-tests.test" + } + ] + } + } + }, + { + "commandSucceededEvent": { + "commandName": "bulkWrite", + "reply": { + "ok": 1, + "nInserted": { + "$$exists": false + }, + "nMatched": { + "$$exists": false + }, + "nModified": { + "$$exists": false + }, + "nUpserted": { + "$$exists": false + }, + "nDeleted": { + "$$exists": false + } + } + } + } + ] + } + ] + } + ] +} diff --git a/test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.yml b/test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.yml new file mode 100644 index 0000000000..fcc6b7b3ec --- /dev/null +++ b/test/spec/command-logging-and-monitoring/monitoring/unacknowledged-client-bulkWrite.yml @@ -0,0 +1,109 @@ +description: "unacknowledged-client-bulkWrite" + +schemaVersion: "1.7" + +runOnRequirements: + - minServerVersion: "8.0" + +createEntities: + - client: + id: &client client + useMultipleMongoses: false + observeEvents: + - commandStartedEvent + - commandSucceededEvent + - commandFailedEvent + uriOptions: + w: 0 + - database: + id: &database database + client: *client + databaseName: &databaseName command-monitoring-tests + - collection: + id: &collection collection + database: *database + collectionName: &collectionName test + +initialData: + - collectionName: *collectionName + databaseName: *databaseName + documents: + - { _id: 1, x: 11 } + - { _id: 2, x: 22 } + - { _id: 3, x: 33 } + +_yamlAnchors: + namespace: &namespace "command-monitoring-tests.test" + +tests: + - description: 'A successful mixed client bulkWrite' + operations: + - object: *client + name: clientBulkWrite + arguments: + models: + - insertOne: + namespace: *namespace + document: { _id: 4, x: 44 } + - updateOne: + namespace: *namespace + filter: { _id: 3 } + update: { $set: { x: 333 } } + expectResult: + insertedCount: + $$unsetOrMatches: 0 + upsertedCount: + $$unsetOrMatches: 0 + matchedCount: + $$unsetOrMatches: 0 + modifiedCount: + $$unsetOrMatches: 0 + deletedCount: + $$unsetOrMatches: 0 + insertResults: + $$unsetOrMatches: {} + updateResults: + $$unsetOrMatches: {} + deleteResults: + $$unsetOrMatches: {} + # Force completion of the w:0 write by executing a find on the same connection + - object: *collection + name: find + arguments: + filter: {} + expectResult: + - { _id: 1, x: 11 } + - { _id: 2, x: 22 } + - { _id: 3, x: 333 } + - { _id: 4, x: 44 } + + expectEvents: + - + client: *client + ignoreExtraEvents: true + events: + - commandStartedEvent: + commandName: bulkWrite + databaseName: admin + command: + bulkWrite: 1 + errorsOnly: true + ordered: true + ops: + - insert: 0 + document: { _id: 4, x: 44 } + - update: 0 + filter: { _id: 3 } + updateMods: { $set: { x: 333 } } + multi: false + nsInfo: + - ns: *namespace + - commandSucceededEvent: + commandName: bulkWrite + reply: + ok: 1 + nInserted: { $$exists: false } + nMatched: { $$exists: false } + nModified: { $$exists: false } + nUpserted: { $$exists: false } + nDeleted: { $$exists: false } diff --git a/test/spec/server-selection/logging/operation-id.json b/test/spec/server-selection/logging/operation-id.json index 276e4b8d6d..6cdbcb3f5a 100644 --- a/test/spec/server-selection/logging/operation-id.json +++ b/test/spec/server-selection/logging/operation-id.json @@ -47,6 +47,9 @@ } } ], + "_yamlAnchors": { + "namespace": "logging-tests.server-selection" + }, "tests": [ { "description": "Successful bulkWrite operation: log messages have operationIds", @@ -224,6 +227,190 @@ ] } ] + }, + { + "description": "Successful client bulkWrite operation: log messages have operationIds", + "runOnRequirements": [ + { + "minServerVersion": "8.0" + } + ], + "operations": [ + { + "name": "waitForEvent", + "object": "testRunner", + "arguments": { + "client": "client", + "event": { + "topologyDescriptionChangedEvent": {} + }, + "count": 2 + } + }, + { + "name": "clientBulkWrite", + "object": "client", + "arguments": { + "models": [ + { + "insertOne": { + "namespace": "logging-tests.server-selection", + "document": { + "x": 1 + } + } + } + ] + } + } + ], + "expectLogMessages": [ + { + "client": "client", + "messages": [ + { + "level": "debug", + "component": "serverSelection", + "data": { + "message": "Server selection started", + "operationId": { + "$$type": [ + "int", + "long" + ] + }, + "operation": "bulkWrite" + } + }, + { + "level": "debug", + "component": "serverSelection", + "data": { + "message": "Server selection succeeded", + "operationId": { + "$$type": [ + "int", + "long" + ] + }, + "operation": "bulkWrite" + } + } + ] + } + ] + }, + { + "description": "Failed client bulkWrite operation: log messages have operationIds", + "runOnRequirements": [ + { + "minServerVersion": "8.0" + } + ], + "operations": [ + { + "name": "failPoint", + "object": "testRunner", + "arguments": { + "client": "failPointClient", + "failPoint": { + "configureFailPoint": "failCommand", + "mode": "alwaysOn", + "data": { + "failCommands": [ + "hello", + "ismaster" + ], + "appName": "loggingClient", + "closeConnection": true + } + } + } + }, + { + "name": "waitForEvent", + "object": "testRunner", + "arguments": { + "client": "client", + "event": { + "serverDescriptionChangedEvent": { + "newDescription": { + "type": "Unknown" + } + } + }, + "count": 1 + } + }, + { + "name": "bulkWrite", + "object": "client", + "arguments": { + "models": [ + { + "insertOne": { + "namespace": "logging-tests.server-selection", + "document": { + "x": 1 + } + } + } + ] + }, + "expectError": { + "isClientError": true + } + } + ], + "expectLogMessages": [ + { + "client": "client", + "messages": [ + { + "level": "debug", + "component": "serverSelection", + "data": { + "message": "Server selection started", + "operationId": { + "$$type": [ + "int", + "long" + ] + }, + "operation": "bulkWrite" + } + }, + { + "level": "info", + "component": "serverSelection", + "data": { + "message": "Waiting for suitable server to become available", + "operationId": { + "$$type": [ + "int", + "long" + ] + }, + "operation": "bulkWrite" + } + }, + { + "level": "debug", + "component": "serverSelection", + "data": { + "message": "Server selection failed", + "operationId": { + "$$type": [ + "int", + "long" + ] + }, + "operation": "bulkWrite" + } + } + ] + } + ] } ] } diff --git a/test/spec/server-selection/logging/operation-id.yml b/test/spec/server-selection/logging/operation-id.yml index 430e81a58b..24e48f9410 100644 --- a/test/spec/server-selection/logging/operation-id.yml +++ b/test/spec/server-selection/logging/operation-id.yml @@ -30,6 +30,9 @@ createEntities: - client: id: &failPointClient failPointClient +_yamlAnchors: + namespace: &namespace "logging-tests.server-selection" + tests: - description: "Successful bulkWrite operation: log messages have operationIds" operations: @@ -122,3 +125,97 @@ tests: operationId: { $$type: [int, long] } operation: insert + - description: "Successful client bulkWrite operation: log messages have operationIds" + runOnRequirements: + - minServerVersion: "8.0" # required for bulkWrite command + operations: + # ensure we've discovered the server so it is immediately available + # and no extra "waiting for suitable server" messages are emitted. + # expected topology events reflect initial server discovery and server connect event. + - name: waitForEvent + object: testRunner + arguments: + client: *client + event: + topologyDescriptionChangedEvent: {} + count: 2 + - name: clientBulkWrite + object: *client + arguments: + models: + - insertOne: + namespace: *namespace + document: { x: 1 } + expectLogMessages: + - client: *client + messages: + - level: debug + component: serverSelection + data: + message: "Server selection started" + operationId: { $$type: [int, long] } + operation: bulkWrite + - level: debug + component: serverSelection + data: + message: "Server selection succeeded" + operationId: { $$type: [int, long] } + operation: bulkWrite + + - description: "Failed client bulkWrite operation: log messages have operationIds" + runOnRequirements: + - minServerVersion: "8.0" # required for bulkWrite command + operations: + # fail all hello/legacy hello commands for the main client. + - name: failPoint + object: testRunner + arguments: + client: *failPointClient + failPoint: + configureFailPoint: failCommand + mode: alwaysOn + data: + failCommands: ["hello", "ismaster"] + appName: *appName + closeConnection: true + # wait until we've marked the server unknown due + # to a failed heartbeat. + - name: waitForEvent + object: testRunner + arguments: + client: *client + event: + serverDescriptionChangedEvent: + newDescription: + type: Unknown + count: 1 + - name: bulkWrite + object: *client + arguments: + models: + - insertOne: + namespace: *namespace + document: { x: 1 } + expectError: + isClientError: true # server selection timeout + expectLogMessages: + - client: *client + messages: + - level: debug + component: serverSelection + data: + message: "Server selection started" + operationId: { $$type: [int, long] } + operation: bulkWrite + - level: info + component: serverSelection + data: + message: "Waiting for suitable server to become available" + operationId: { $$type: [int, long] } + operation: bulkWrite + - level: debug + component: serverSelection + data: + message: "Server selection failed" + operationId: { $$type: [int, long] } + operation: bulkWrite diff --git a/test/spec/transactions/unified/client-bulkWrite.json b/test/spec/transactions/unified/client-bulkWrite.json new file mode 100644 index 0000000000..f8f1d97169 --- /dev/null +++ b/test/spec/transactions/unified/client-bulkWrite.json @@ -0,0 +1,592 @@ +{ + "description": "client bulkWrite transactions", + "schemaVersion": "1.3", + "runOnRequirements": [ + { + "minServerVersion": "8.0", + "topologies": [ + "replicaset", + "sharded", + "load-balanced" + ] + } + ], + "createEntities": [ + { + "client": { + "id": "client0", + "observeEvents": [ + "commandStartedEvent" + ] + } + }, + { + "database": { + "id": "database0", + "client": "client0", + "databaseName": "transaction-tests" + } + }, + { + "collection": { + "id": "collection0", + "database": "database0", + "collectionName": "coll0" + } + }, + { + "session": { + "id": "session0", + "client": "client0" + } + }, + { + "client": { + "id": "client_with_wmajority", + "uriOptions": { + "w": "majority" + }, + "observeEvents": [ + "commandStartedEvent" + ] + } + }, + { + "session": { + "id": "session_with_wmajority", + "client": "client_with_wmajority" + } + } + ], + "_yamlAnchors": { + "namespace": "transaction-tests.coll0" + }, + "initialData": [ + { + "databaseName": "transaction-tests", + "collectionName": "coll0", + "documents": [ + { + "_id": 1, + "x": 11 + }, + { + "_id": 2, + "x": 22 + }, + { + "_id": 3, + "x": 33 + }, + { + "_id": 5, + "x": 55 + }, + { + "_id": 6, + "x": 66 + }, + { + "_id": 7, + "x": 77 + } + ] + } + ], + "tests": [ + { + "description": "client bulkWrite in a transaction", + "operations": [ + { + "object": "session0", + "name": "startTransaction" + }, + { + "object": "client0", + "name": "clientBulkWrite", + "arguments": { + "session": "session0", + "models": [ + { + "insertOne": { + "namespace": "transaction-tests.coll0", + "document": { + "_id": 8, + "x": 88 + } + } + }, + { + "updateOne": { + "namespace": "transaction-tests.coll0", + "filter": { + "_id": 1 + }, + "update": { + "$inc": { + "x": 1 + } + } + } + }, + { + "updateMany": { + "namespace": "transaction-tests.coll0", + "filter": { + "$and": [ + { + "_id": { + "$gt": 1 + } + }, + { + "_id": { + "$lte": 3 + } + } + ] + }, + "update": { + "$inc": { + "x": 2 + } + } + } + }, + { + "replaceOne": { + "namespace": "transaction-tests.coll0", + "filter": { + "_id": 4 + }, + "replacement": { + "x": 44 + }, + "upsert": true + } + }, + { + "deleteOne": { + "namespace": "transaction-tests.coll0", + "filter": { + "_id": 5 + } + } + }, + { + "deleteMany": { + "namespace": "transaction-tests.coll0", + "filter": { + "$and": [ + { + "_id": { + "$gt": 5 + } + }, + { + "_id": { + "$lte": 7 + } + } + ] + } + } + } + ], + "verboseResults": true + }, + "expectResult": { + "insertedCount": 1, + "upsertedCount": 1, + "matchedCount": 3, + "modifiedCount": 3, + "deletedCount": 3, + "insertResults": { + "0": { + "insertedId": 8 + } + }, + "updateResults": { + "1": { + "matchedCount": 1, + "modifiedCount": 1, + "upsertedId": { + "$$exists": false + } + }, + "2": { + "matchedCount": 2, + "modifiedCount": 2, + "upsertedId": { + "$$exists": false + } + }, + "3": { + "matchedCount": 1, + "modifiedCount": 0, + "upsertedId": 4 + } + }, + "deleteResults": { + "4": { + "deletedCount": 1 + }, + "5": { + "deletedCount": 2 + } + } + } + }, + { + "object": "session0", + "name": "commitTransaction" + } + ], + "expectEvents": [ + { + "client": "client0", + "events": [ + { + "commandStartedEvent": { + "commandName": "bulkWrite", + "databaseName": "admin", + "command": { + "lsid": { + "$$sessionLsid": "session0" + }, + "txnNumber": 1, + "startTransaction": true, + "autocommit": false, + "writeConcern": { + "$$exists": false + }, + "bulkWrite": 1, + "errorsOnly": false, + "ordered": true, + "ops": [ + { + "insert": 0, + "document": { + "_id": 8, + "x": 88 + } + }, + { + "update": 0, + "filter": { + "_id": 1 + }, + "updateMods": { + "$inc": { + "x": 1 + } + }, + "multi": false + }, + { + "update": 0, + "filter": { + "$and": [ + { + "_id": { + "$gt": 1 + } + }, + { + "_id": { + "$lte": 3 + } + } + ] + }, + "updateMods": { + "$inc": { + "x": 2 + } + }, + "multi": true + }, + { + "update": 0, + "filter": { + "_id": 4 + }, + "updateMods": { + "x": 44 + }, + "upsert": true, + "multi": false + }, + { + "delete": 0, + "filter": { + "_id": 5 + }, + "multi": false + }, + { + "delete": 0, + "filter": { + "$and": [ + { + "_id": { + "$gt": 5 + } + }, + { + "_id": { + "$lte": 7 + } + } + ] + }, + "multi": true + } + ], + "nsInfo": [ + { + "ns": "transaction-tests.coll0" + } + ] + } + } + }, + { + "commandStartedEvent": { + "commandName": "commitTransaction", + "databaseName": "admin", + "command": { + "commitTransaction": 1, + "lsid": { + "$$sessionLsid": "session0" + }, + "txnNumber": 1, + "startTransaction": { + "$$exists": false + }, + "autocommit": false, + "writeConcern": { + "$$exists": false + } + } + } + } + ] + } + ], + "outcome": [ + { + "collectionName": "coll0", + "databaseName": "transaction-tests", + "documents": [ + { + "_id": 1, + "x": 12 + }, + { + "_id": 2, + "x": 24 + }, + { + "_id": 3, + "x": 35 + }, + { + "_id": 4, + "x": 44 + }, + { + "_id": 8, + "x": 88 + } + ] + } + ] + }, + { + "description": "client writeConcern ignored for client bulkWrite in transaction", + "operations": [ + { + "object": "session_with_wmajority", + "name": "startTransaction", + "arguments": { + "writeConcern": { + "w": 1 + } + } + }, + { + "object": "client_with_wmajority", + "name": "clientBulkWrite", + "arguments": { + "session": "session_with_wmajority", + "models": [ + { + "insertOne": { + "namespace": "transaction-tests.coll0", + "document": { + "_id": 8, + "x": 88 + } + } + } + ] + }, + "expectResult": { + "insertedCount": 1, + "upsertedCount": 0, + "matchedCount": 0, + "modifiedCount": 0, + "deletedCount": 0, + "insertResults": { + "$$unsetOrMatches": {} + }, + "updateResults": { + "$$unsetOrMatches": {} + }, + "deleteResults": { + "$$unsetOrMatches": {} + } + } + }, + { + "object": "session_with_wmajority", + "name": "commitTransaction" + } + ], + "expectEvents": [ + { + "client": "client_with_wmajority", + "events": [ + { + "commandStartedEvent": { + "commandName": "bulkWrite", + "databaseName": "admin", + "command": { + "lsid": { + "$$sessionLsid": "session_with_wmajority" + }, + "txnNumber": 1, + "startTransaction": true, + "autocommit": false, + "writeConcern": { + "$$exists": false + }, + "bulkWrite": 1, + "errorsOnly": true, + "ordered": true, + "ops": [ + { + "insert": 0, + "document": { + "_id": 8, + "x": 88 + } + } + ], + "nsInfo": [ + { + "ns": "transaction-tests.coll0" + } + ] + } + } + }, + { + "commandStartedEvent": { + "command": { + "commitTransaction": 1, + "lsid": { + "$$sessionLsid": "session_with_wmajority" + }, + "txnNumber": { + "$numberLong": "1" + }, + "startTransaction": { + "$$exists": false + }, + "autocommit": false, + "writeConcern": { + "w": 1 + } + }, + "commandName": "commitTransaction", + "databaseName": "admin" + } + } + ] + } + ], + "outcome": [ + { + "collectionName": "coll0", + "databaseName": "transaction-tests", + "documents": [ + { + "_id": 1, + "x": 11 + }, + { + "_id": 2, + "x": 22 + }, + { + "_id": 3, + "x": 33 + }, + { + "_id": 5, + "x": 55 + }, + { + "_id": 6, + "x": 66 + }, + { + "_id": 7, + "x": 77 + }, + { + "_id": 8, + "x": 88 + } + ] + } + ] + }, + { + "description": "client bulkWrite with writeConcern in a transaction causes a transaction error", + "operations": [ + { + "object": "session0", + "name": "startTransaction" + }, + { + "object": "client0", + "name": "clientBulkWrite", + "arguments": { + "session": "session0", + "writeConcern": { + "w": 1 + }, + "models": [ + { + "insertOne": { + "namespace": "transaction-tests.coll0", + "document": { + "_id": 8, + "x": 88 + } + } + } + ] + }, + "expectError": { + "isClientError": true, + "errorContains": "Cannot set write concern after starting a transaction" + } + } + ] + } + ] +} diff --git a/test/spec/transactions/unified/client-bulkWrite.yml b/test/spec/transactions/unified/client-bulkWrite.yml new file mode 100644 index 0000000000..eda2babbe7 --- /dev/null +++ b/test/spec/transactions/unified/client-bulkWrite.yml @@ -0,0 +1,262 @@ +description: "client bulkWrite transactions" +schemaVersion: "1.3" +runOnRequirements: + - minServerVersion: "8.0" + topologies: + - replicaset + - sharded + - load-balanced + +createEntities: + - client: + id: &client0 client0 + observeEvents: [ commandStartedEvent ] + - database: + id: &database0 database0 + client: *client0 + databaseName: &database0Name transaction-tests + - collection: + id: &collection0 collection0 + database: *database0 + collectionName: &collection0Name coll0 + - session: + id: &session0 session0 + client: *client0 + - client: + id: &client_with_wmajority client_with_wmajority + uriOptions: + w: majority + observeEvents: + - commandStartedEvent + - session: + id: &session_with_wmajority session_with_wmajority + client: *client_with_wmajority + +_yamlAnchors: + namespace: &namespace "transaction-tests.coll0" + +initialData: + - databaseName: *database0Name + collectionName: *collection0Name + documents: + - { _id: 1, x: 11 } + - { _id: 2, x: 22 } + - { _id: 3, x: 33 } + - { _id: 5, x: 55 } + - { _id: 6, x: 66 } + - { _id: 7, x: 77 } + +tests: + - description: "client bulkWrite in a transaction" + operations: + - object: *session0 + name: startTransaction + - object: *client0 + name: clientBulkWrite + arguments: + session: *session0 + models: + - insertOne: + namespace: *namespace + document: { _id: 8, x: 88 } + - updateOne: + namespace: *namespace + filter: { _id: 1 } + update: { $inc: { x: 1 } } + - updateMany: + namespace: *namespace + filter: + $and: [ { _id: { $gt: 1 } }, { _id: { $lte: 3 } } ] + update: { $inc: { x: 2 } } + - replaceOne: + namespace: *namespace + filter: { _id: 4 } + replacement: { x: 44 } + upsert: true + - deleteOne: + namespace: *namespace + filter: { _id: 5 } + - deleteMany: + namespace: *namespace + filter: + $and: [ { _id: { $gt: 5 } }, { _id: { $lte: 7 } } ] + verboseResults: true + expectResult: + insertedCount: 1 + upsertedCount: 1 + matchedCount: 3 + modifiedCount: 3 + deletedCount: 3 + insertResults: + 0: + insertedId: 8 + updateResults: + 1: + matchedCount: 1 + modifiedCount: 1 + upsertedId: { $$exists: false } + 2: + matchedCount: 2 + modifiedCount: 2 + upsertedId: { $$exists: false } + 3: + matchedCount: 1 + modifiedCount: 0 + upsertedId: 4 + deleteResults: + 4: + deletedCount: 1 + 5: + deletedCount: 2 + - object: *session0 + name: commitTransaction + expectEvents: + - client: *client0 + events: + - commandStartedEvent: + commandName: bulkWrite + databaseName: admin + command: + lsid: { $$sessionLsid: *session0 } + txnNumber: 1 + startTransaction: true + autocommit: false + writeConcern: { $$exists: false } + bulkWrite: 1 + errorsOnly: false + ordered: true + ops: + - insert: 0 + document: { _id: 8, x: 88 } + - update: 0 + filter: { _id: 1 } + updateMods: { $inc: { x: 1 } } + multi: false + - update: 0 + filter: + $and: [ { _id: { $gt: 1 } }, { _id: { $lte: 3 } } ] + updateMods: { $inc: { x: 2 } } + multi: true + - update: 0 + filter: { _id: 4 } + updateMods: { x: 44 } + upsert: true + multi: false + - delete: 0 + filter: { _id: 5 } + multi: false + - delete: 0 + filter: + $and: [ { _id: { $gt: 5 } }, { _id: { $lte: 7 } } ] + multi: true + nsInfo: + - ns: *namespace + - commandStartedEvent: + commandName: commitTransaction + databaseName: admin + command: + commitTransaction: 1 + lsid: { $$sessionLsid: *session0 } + txnNumber: 1 + startTransaction: { $$exists: false } + autocommit: false + writeConcern: { $$exists: false } + outcome: + - collectionName: *collection0Name + databaseName: *database0Name + documents: + - { _id: 1, x: 12 } + - { _id: 2, x: 24 } + - { _id: 3, x: 35 } + - { _id: 4, x: 44 } + - { _id: 8, x: 88 } + - description: 'client writeConcern ignored for client bulkWrite in transaction' + operations: + - object: *session_with_wmajority + name: startTransaction + arguments: + writeConcern: + w: 1 + - object: *client_with_wmajority + name: clientBulkWrite + arguments: + session: *session_with_wmajority + models: + - insertOne: + namespace: *namespace + document: { _id: 8, x: 88 } + expectResult: + insertedCount: 1 + upsertedCount: 0 + matchedCount: 0 + modifiedCount: 0 + deletedCount: 0 + insertResults: + $$unsetOrMatches: {} + updateResults: + $$unsetOrMatches: {} + deleteResults: + $$unsetOrMatches: {} + - object: *session_with_wmajority + name: commitTransaction + expectEvents: + - + client: *client_with_wmajority + events: + - commandStartedEvent: + commandName: bulkWrite + databaseName: admin + command: + lsid: { $$sessionLsid: *session_with_wmajority } + txnNumber: 1 + startTransaction: true + autocommit: false + writeConcern: { $$exists: false } + bulkWrite: 1 + errorsOnly: true + ordered: true + ops: + - insert: 0 + document: { _id: 8, x: 88 } + nsInfo: + - ns: *namespace + - + commandStartedEvent: + command: + commitTransaction: 1 + lsid: { $$sessionLsid: *session_with_wmajority } + txnNumber: { $numberLong: '1' } + startTransaction: { $$exists: false } + autocommit: false + writeConcern: + w: 1 + commandName: commitTransaction + databaseName: admin + outcome: + - collectionName: *collection0Name + databaseName: *database0Name + documents: + - { _id: 1, x: 11 } + - { _id: 2, x: 22 } + - { _id: 3, x: 33 } + - { _id: 5, x: 55 } + - { _id: 6, x: 66 } + - { _id: 7, x: 77 } + - { _id: 8, x: 88 } + - description: "client bulkWrite with writeConcern in a transaction causes a transaction error" + operations: + - object: *session0 + name: startTransaction + - object: *client0 + name: clientBulkWrite + arguments: + session: *session0 + writeConcern: + w: 1 + models: + - insertOne: + namespace: *namespace + document: { _id: 8, x: 88 } + expectError: + isClientError: true + errorContains: "Cannot set write concern after starting a transaction" diff --git a/test/spec/transactions/unified/mongos-pin-auto.json b/test/spec/transactions/unified/mongos-pin-auto.json index 93eac8bb77..27db520401 100644 --- a/test/spec/transactions/unified/mongos-pin-auto.json +++ b/test/spec/transactions/unified/mongos-pin-auto.json @@ -2004,6 +2004,104 @@ } ] }, + { + "description": "remain pinned after non-transient Interrupted error on clientBulkWrite bulkWrite", + "operations": [ + { + "object": "session0", + "name": "startTransaction" + }, + { + "object": "collection0", + "name": "insertOne", + "arguments": { + "session": "session0", + "document": { + "_id": 3 + } + }, + "expectResult": { + "$$unsetOrMatches": { + "insertedId": { + "$$unsetOrMatches": 3 + } + } + } + }, + { + "name": "targetedFailPoint", + "object": "testRunner", + "arguments": { + "session": "session0", + "failPoint": { + "configureFailPoint": "failCommand", + "mode": { + "times": 1 + }, + "data": { + "failCommands": [ + "bulkWrite" + ], + "errorCode": 11601 + } + } + } + }, + { + "name": "clientBulkWrite", + "object": "client0", + "arguments": { + "session": "session0", + "models": [ + { + "insertOne": { + "namespace": "database0.collection0", + "document": { + "_id": 8, + "x": 88 + } + } + } + ] + }, + "expectError": { + "errorLabelsOmit": [ + "TransientTransactionError" + ] + } + }, + { + "object": "testRunner", + "name": "assertSessionPinned", + "arguments": { + "session": "session0" + } + }, + { + "object": "session0", + "name": "abortTransaction" + } + ], + "outcome": [ + { + "collectionName": "test", + "databaseName": "transaction-tests", + "documents": [ + { + "_id": 1 + }, + { + "_id": 2 + } + ] + } + ], + "runOnRequirements": [ + { + "minServerVersion": "8.0" + } + ] + }, { "description": "unpin after transient connection error on insertOne insert", "operations": [ @@ -5175,6 +5273,202 @@ ] } ] + }, + { + "description": "unpin after transient connection error on clientBulkWrite bulkWrite", + "operations": [ + { + "object": "session0", + "name": "startTransaction" + }, + { + "object": "collection0", + "name": "insertOne", + "arguments": { + "session": "session0", + "document": { + "_id": 3 + } + }, + "expectResult": { + "$$unsetOrMatches": { + "insertedId": { + "$$unsetOrMatches": 3 + } + } + } + }, + { + "name": "targetedFailPoint", + "object": "testRunner", + "arguments": { + "session": "session0", + "failPoint": { + "configureFailPoint": "failCommand", + "mode": { + "times": 1 + }, + "data": { + "failCommands": [ + "bulkWrite" + ], + "closeConnection": true + } + } + } + }, + { + "name": "clientBulkWrite", + "object": "client0", + "arguments": { + "session": "session0", + "models": [ + { + "insertOne": { + "namespace": "database0.collection0", + "document": { + "_id": 8, + "x": 88 + } + } + } + ] + }, + "expectError": { + "errorLabelsContain": [ + "TransientTransactionError" + ] + } + }, + { + "object": "testRunner", + "name": "assertSessionUnpinned", + "arguments": { + "session": "session0" + } + }, + { + "object": "session0", + "name": "abortTransaction" + } + ], + "outcome": [ + { + "collectionName": "test", + "databaseName": "transaction-tests", + "documents": [ + { + "_id": 1 + }, + { + "_id": 2 + } + ] + } + ], + "runOnRequirements": [ + { + "minServerVersion": "8.0" + } + ] + }, + { + "description": "unpin after transient ShutdownInProgress error on clientBulkWrite bulkWrite", + "operations": [ + { + "object": "session0", + "name": "startTransaction" + }, + { + "object": "collection0", + "name": "insertOne", + "arguments": { + "session": "session0", + "document": { + "_id": 3 + } + }, + "expectResult": { + "$$unsetOrMatches": { + "insertedId": { + "$$unsetOrMatches": 3 + } + } + } + }, + { + "name": "targetedFailPoint", + "object": "testRunner", + "arguments": { + "session": "session0", + "failPoint": { + "configureFailPoint": "failCommand", + "mode": { + "times": 1 + }, + "data": { + "failCommands": [ + "bulkWrite" + ], + "errorCode": 91 + } + } + } + }, + { + "name": "clientBulkWrite", + "object": "client0", + "arguments": { + "session": "session0", + "models": [ + { + "insertOne": { + "namespace": "database0.collection0", + "document": { + "_id": 8, + "x": 88 + } + } + } + ] + }, + "expectError": { + "errorLabelsContain": [ + "TransientTransactionError" + ] + } + }, + { + "object": "testRunner", + "name": "assertSessionUnpinned", + "arguments": { + "session": "session0" + } + }, + { + "object": "session0", + "name": "abortTransaction" + } + ], + "outcome": [ + { + "collectionName": "test", + "databaseName": "transaction-tests", + "documents": [ + { + "_id": 1 + }, + { + "_id": 2 + } + ] + } + ], + "runOnRequirements": [ + { + "minServerVersion": "8.0" + } + ] } ] } diff --git a/test/spec/transactions/unified/mongos-pin-auto.yml b/test/spec/transactions/unified/mongos-pin-auto.yml index 7a76347555..a80dd62031 100644 --- a/test/spec/transactions/unified/mongos-pin-auto.yml +++ b/test/spec/transactions/unified/mongos-pin-auto.yml @@ -676,6 +676,36 @@ tests: - *abortTransaction outcome: *outcome + - description: remain pinned after non-transient Interrupted error on clientBulkWrite bulkWrite + operations: + - *startTransaction + - *initialCommand + - name: targetedFailPoint + object: testRunner + arguments: + session: *session0 + failPoint: + configureFailPoint: failCommand + mode: {times: 1} + data: + failCommands: ["bulkWrite"] + errorCode: 11601 + - name: clientBulkWrite + object: *client0 + arguments: + session: *session0 + models: + - insertOne: + namespace: database0.collection0 + document: { _id: 8, x: 88 } + expectError: + errorLabelsOmit: ["TransientTransactionError"] + - *assertSessionPinned + - *abortTransaction + outcome: *outcome + runOnRequirements: + - minServerVersion: "8.0" # `bulkWrite` added to server 8.0" + - description: unpin after transient connection error on insertOne insert operations: - *startTransaction @@ -1614,3 +1644,63 @@ tests: - *abortTransaction outcome: *outcome + - description: unpin after transient connection error on clientBulkWrite bulkWrite + operations: + - *startTransaction + - *initialCommand + - name: targetedFailPoint + object: testRunner + arguments: + session: *session0 + failPoint: + configureFailPoint: failCommand + mode: {times: 1} + data: + failCommands: ["bulkWrite"] + closeConnection: true + - name: clientBulkWrite + object: *client0 + arguments: + session: *session0 + models: + - insertOne: + namespace: database0.collection0 + document: { _id: 8, x: 88 } + expectError: + errorLabelsContain: ["TransientTransactionError"] + - *assertSessionUnpinned + - *abortTransaction + outcome: *outcome + runOnRequirements: + - minServerVersion: "8.0" # `bulkWrite` added to server 8.0" + + - description: unpin after transient ShutdownInProgress error on clientBulkWrite bulkWrite + operations: + - *startTransaction + - *initialCommand + - name: targetedFailPoint + object: testRunner + arguments: + session: *session0 + failPoint: + configureFailPoint: failCommand + mode: {times: 1} + data: + failCommands: ["bulkWrite"] + errorCode: 91 + - name: clientBulkWrite + object: *client0 + arguments: + session: *session0 + models: + - insertOne: + namespace: database0.collection0 + document: { _id: 8, x: 88 } + expectError: + errorLabelsContain: ["TransientTransactionError"] + - *assertSessionUnpinned + - *abortTransaction + outcome: *outcome + runOnRequirements: + - minServerVersion: "8.0" # `bulkWrite` added to server 8.0" + diff --git a/test/spec/versioned-api/crud-api-version-1.json b/test/spec/versioned-api/crud-api-version-1.json index a387d0587e..fe668620f8 100644 --- a/test/spec/versioned-api/crud-api-version-1.json +++ b/test/spec/versioned-api/crud-api-version-1.json @@ -50,7 +50,8 @@ }, "apiDeprecationErrors": true } - ] + ], + "namespace": "versioned-api-tests.test" }, "initialData": [ { @@ -426,6 +427,85 @@ } ] }, + { + "description": "client bulkWrite appends declared API version", + "runOnRequirements": [ + { + "minServerVersion": "8.0" + } + ], + "operations": [ + { + "name": "clientBulkWrite", + "object": "client", + "arguments": { + "models": [ + { + "insertOne": { + "namespace": "versioned-api-tests.test", + "document": { + "_id": 6, + "x": 6 + } + } + } + ], + "verboseResults": true + }, + "expectResult": { + "insertedCount": 1, + "upsertedCount": 0, + "matchedCount": 0, + "modifiedCount": 0, + "deletedCount": 0, + "insertResults": { + "0": { + "insertedId": 6 + } + }, + "updateResults": {}, + "deleteResults": {} + } + } + ], + "expectEvents": [ + { + "client": "client", + "events": [ + { + "commandStartedEvent": { + "commandName": "bulkWrite", + "databaseName": "admin", + "command": { + "bulkWrite": 1, + "errorsOnly": false, + "ordered": true, + "ops": [ + { + "insert": 0, + "document": { + "_id": 6, + "x": 6 + } + } + ], + "nsInfo": [ + { + "ns": "versioned-api-tests.test" + } + ], + "apiVersion": "1", + "apiStrict": { + "$$unsetOrMatches": false + }, + "apiDeprecationErrors": true + } + } + } + ] + } + ] + }, { "description": "countDocuments appends declared API version", "operations": [ diff --git a/test/spec/versioned-api/crud-api-version-1.yml b/test/spec/versioned-api/crud-api-version-1.yml index 50135c1458..cb9b45e57b 100644 --- a/test/spec/versioned-api/crud-api-version-1.yml +++ b/test/spec/versioned-api/crud-api-version-1.yml @@ -34,6 +34,7 @@ _yamlAnchors: apiVersion: "1" apiStrict: { $$unsetOrMatches: false } apiDeprecationErrors: true + namespace: &namespace "versioned-api-tests.test" initialData: - collectionName: *collectionName @@ -155,6 +156,46 @@ tests: multi: { $$unsetOrMatches: false } upsert: true <<: *expectedApiVersion + + - description: "client bulkWrite appends declared API version" + runOnRequirements: + - minServerVersion: "8.0" # `bulkWrite` added to server 8.0 + operations: + - name: clientBulkWrite + object: *client + arguments: + models: + - insertOne: + namespace: *namespace + document: { _id: 6, x: 6 } + verboseResults: true + expectResult: + insertedCount: 1 + upsertedCount: 0 + matchedCount: 0 + modifiedCount: 0 + deletedCount: 0 + insertResults: + 0: + insertedId: 6 + updateResults: {} + deleteResults: {} + expectEvents: + - client: *client + events: + - commandStartedEvent: + commandName: bulkWrite + databaseName: admin + command: + bulkWrite: 1 + errorsOnly: false + ordered: true + ops: + - insert: 0 + document: { _id: 6, x: 6 } + nsInfo: + - { ns: *namespace } + <<: *expectedApiVersion - description: "countDocuments appends declared API version" operations: diff --git a/test/tools/unified-spec-runner/match.ts b/test/tools/unified-spec-runner/match.ts index 3a4d4e5e3d..90260ff5e2 100644 --- a/test/tools/unified-spec-runner/match.ts +++ b/test/tools/unified-spec-runner/match.ts @@ -213,7 +213,18 @@ export function resultCheck( } resultCheck(actual[key], value, entities, path, checkExtraKeys); } else { - resultCheck(actual[key], value, entities, path, checkExtraKeys); + // If our actual value is a map, such as in the client bulk write results, we need + // to convert the expected keys from the string numbers to actual numbers since the key + // values in the maps are actual numbers. + const isActualMap = actual instanceof Map; + const mapKey = !Number.isNaN(key) ? Number(key) : key; + resultCheck( + isActualMap ? actual.get(mapKey) : actual[key], + value, + entities, + path, + checkExtraKeys + ); } } @@ -229,6 +240,7 @@ export function resultCheck( } if (typeof actual !== 'object') { + console.log(expected, actual); expect.fail('Expected actual value to be an object'); } diff --git a/test/tools/unified-spec-runner/operations.ts b/test/tools/unified-spec-runner/operations.ts index 51d458a185..9cc67174f3 100644 --- a/test/tools/unified-spec-runner/operations.ts +++ b/test/tools/unified-spec-runner/operations.ts @@ -202,6 +202,16 @@ operations.set('bulkWrite', async ({ entities, operation }) => { return collection.bulkWrite(requests, opts); }); +operations.set('clientBulkWrite', async ({ entities, operation }) => { + const client = entities.getEntity('client', operation.object); + const { models, ...opts } = operation.arguments!; + const bulkWriteModels = models.map(model => { + const name = Object.keys(model)[0]; + return { name: name, ...model[name] }; + }); + return client.bulkWrite(bulkWriteModels, opts); +}); + // The entity exists for the name but can potentially have the wrong // type (stream/cursor) which will also throw an exception even when // telling getEntity() to ignore checking existence. diff --git a/test/unit/cmap/commands.test.ts b/test/unit/cmap/commands.test.ts index 07e3fccbb6..f4b3fdf025 100644 --- a/test/unit/cmap/commands.test.ts +++ b/test/unit/cmap/commands.test.ts @@ -41,7 +41,7 @@ describe('commands', function () { it('sets the length of the document sequence', function () { // Bytes starting at index 1 is a 4 byte length. - expect(buffers[3].readInt32LE(1)).to.equal(20); + expect(buffers[3].readInt32LE(1)).to.equal(25); }); it('sets the name of the first field to be replaced', function () { @@ -81,7 +81,7 @@ describe('commands', function () { it('sets the length of the first document sequence', function () { // Bytes starting at index 1 is a 4 byte length. - expect(buffers[3].readInt32LE(1)).to.equal(23); + expect(buffers[3].readInt32LE(1)).to.equal(28); }); it('sets the name of the first field to be replaced', function () { @@ -91,17 +91,17 @@ describe('commands', function () { it('sets the document sequence sections second type to 1', function () { // First byte is a one byte type. - expect(buffers[3][28]).to.equal(1); + expect(buffers[3][29]).to.equal(1); }); it('sets the length of the second document sequence', function () { // Bytes starting at index 1 is a 4 byte length. - expect(buffers[3].readInt32LE(29)).to.equal(23); + expect(buffers[3].readInt32LE(30)).to.equal(28); }); it('sets the name of the second field to be replaced', function () { // Bytes starting at index 33 is the field name. - expect(buffers[3].toString('utf8', 33, 41)).to.equal('fieldTwo'); + expect(buffers[3].toString('utf8', 34, 42)).to.equal('fieldTwo'); }); }); }); diff --git a/test/unit/operations/client_bulk_write/command_builder.test.ts b/test/unit/operations/client_bulk_write/command_builder.test.ts index b0e69e2b23..e62cb1c56b 100644 --- a/test/unit/operations/client_bulk_write/command_builder.test.ts +++ b/test/unit/operations/client_bulk_write/command_builder.test.ts @@ -14,21 +14,24 @@ import { type ClientReplaceOneModel, type ClientUpdateManyModel, type ClientUpdateOneModel, - DocumentSequence + DocumentSequence, + ObjectId } from '../../../mongodb'; describe('ClientBulkWriteCommandBuilder', function () { describe('#buildCommand', function () { context('when custom options are provided', function () { + const id = new ObjectId(); const model: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll', - document: { name: 1 } + document: { _id: id, name: 1 } }; const builder = new ClientBulkWriteCommandBuilder([model], { verboseResults: true, bypassDocumentValidation: true, - ordered: false + ordered: false, + comment: { bulk: 'write' } }); const commands = builder.buildCommands(); @@ -50,21 +53,29 @@ describe('ClientBulkWriteCommandBuilder', function () { it('sets the ops document sequence', function () { expect(commands[0].ops).to.be.instanceOf(DocumentSequence); - expect(commands[0].ops.documents[0]).to.deep.equal({ insert: 0, document: { name: 1 } }); + expect(commands[0].ops.documents[0]).to.deep.equal({ + insert: 0, + document: { _id: id, name: 1 } + }); }); it('sets the nsInfo document sequence', function () { expect(commands[0].nsInfo).to.be.instanceOf(DocumentSequence); expect(commands[0].nsInfo.documents[0]).to.deep.equal({ ns: 'test.coll' }); }); + + it('passes comment options into the commands', function () { + expect(commands[0].comment).to.deep.equal({ bulk: 'write' }); + }); }); context('when no options are provided', function () { context('when a single model is provided', function () { + const id = new ObjectId(); const model: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll', - document: { name: 1 } + document: { _id: id, name: 1 } }; const builder = new ClientBulkWriteCommandBuilder([model], {}); const commands = builder.buildCommands(); @@ -83,7 +94,10 @@ describe('ClientBulkWriteCommandBuilder', function () { it('sets the ops document sequence', function () { expect(commands[0].ops).to.be.instanceOf(DocumentSequence); - expect(commands[0].ops.documents[0]).to.deep.equal({ insert: 0, document: { name: 1 } }); + expect(commands[0].ops.documents[0]).to.deep.equal({ + insert: 0, + document: { _id: id, name: 1 } + }); }); it('sets the nsInfo document sequence', function () { @@ -94,15 +108,17 @@ describe('ClientBulkWriteCommandBuilder', function () { context('when multiple models are provided', function () { context('when the namespace is the same', function () { + const idOne = new ObjectId(); + const idTwo = new ObjectId(); const modelOne: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll', - document: { name: 1 } + document: { _id: idOne, name: 1 } }; const modelTwo: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll', - document: { name: 2 } + document: { _id: idTwo, name: 2 } }; const builder = new ClientBulkWriteCommandBuilder([modelOne, modelTwo], {}); const commands = builder.buildCommands(); @@ -114,8 +130,8 @@ describe('ClientBulkWriteCommandBuilder', function () { it('sets the ops document sequence', function () { expect(commands[0].ops).to.be.instanceOf(DocumentSequence); expect(commands[0].ops.documents).to.deep.equal([ - { insert: 0, document: { name: 1 } }, - { insert: 0, document: { name: 2 } } + { insert: 0, document: { _id: idOne, name: 1 } }, + { insert: 0, document: { _id: idTwo, name: 2 } } ]); }); @@ -126,15 +142,17 @@ describe('ClientBulkWriteCommandBuilder', function () { }); context('when the namespace differs', function () { + const idOne = new ObjectId(); + const idTwo = new ObjectId(); const modelOne: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll', - document: { name: 1 } + document: { _id: idOne, name: 1 } }; const modelTwo: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll2', - document: { name: 2 } + document: { _id: idTwo, name: 2 } }; const builder = new ClientBulkWriteCommandBuilder([modelOne, modelTwo], {}); const commands = builder.buildCommands(); @@ -146,8 +164,8 @@ describe('ClientBulkWriteCommandBuilder', function () { it('sets the ops document sequence', function () { expect(commands[0].ops).to.be.instanceOf(DocumentSequence); expect(commands[0].ops.documents).to.deep.equal([ - { insert: 0, document: { name: 1 } }, - { insert: 1, document: { name: 2 } } + { insert: 0, document: { _id: idOne, name: 1 } }, + { insert: 1, document: { _id: idTwo, name: 2 } } ]); }); @@ -161,20 +179,23 @@ describe('ClientBulkWriteCommandBuilder', function () { }); context('when the namespaces are intermixed', function () { + const idOne = new ObjectId(); + const idTwo = new ObjectId(); + const idThree = new ObjectId(); const modelOne: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll', - document: { name: 1 } + document: { _id: idOne, name: 1 } }; const modelTwo: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll2', - document: { name: 2 } + document: { _id: idTwo, name: 2 } }; const modelThree: ClientInsertOneModel = { name: 'insertOne', namespace: 'test.coll', - document: { name: 2 } + document: { _id: idThree, name: 2 } }; const builder = new ClientBulkWriteCommandBuilder([modelOne, modelTwo, modelThree], {}); const commands = builder.buildCommands(); @@ -186,9 +207,9 @@ describe('ClientBulkWriteCommandBuilder', function () { it('sets the ops document sequence', function () { expect(commands[0].ops).to.be.instanceOf(DocumentSequence); expect(commands[0].ops.documents).to.deep.equal([ - { insert: 0, document: { name: 1 } }, - { insert: 1, document: { name: 2 } }, - { insert: 0, document: { name: 2 } } + { insert: 0, document: { _id: idOne, name: 1 } }, + { insert: 1, document: { _id: idTwo, name: 2 } }, + { insert: 0, document: { _id: idThree, name: 2 } } ]); }); @@ -205,15 +226,33 @@ describe('ClientBulkWriteCommandBuilder', function () { }); describe('#buildInsertOneOperation', function () { - const model: ClientInsertOneModel = { - name: 'insertOne', - namespace: 'test.coll', - document: { name: 1 } - }; - const operation = buildInsertOneOperation(model, 5); - - it('generates the insert operation', function () { - expect(operation).to.deep.equal({ insert: 5, document: { name: 1 } }); + context('when no _id exists on the document', function () { + const model: ClientInsertOneModel = { + name: 'insertOne', + namespace: 'test.coll', + document: { name: 1 } + }; + const operation = buildInsertOneOperation(model, 5); + + it('generates the insert operation with an _id', function () { + expect(operation.insert).to.equal(5); + expect(operation.document.name).to.equal(1); + expect(operation.document).to.have.property('_id'); + }); + }); + + context('when an _id exists on the document', function () { + const id = new ObjectId(); + const model: ClientInsertOneModel = { + name: 'insertOne', + namespace: 'test.coll', + document: { _id: id, name: 1 } + }; + const operation = buildInsertOneOperation(model, 5); + + it('generates the insert operation with an _id', function () { + expect(operation).to.deep.equal({ insert: 5, document: { _id: id, name: 1 } }); + }); }); }); diff --git a/test/unit/operations/client_bulk_write/results_merger.test.ts b/test/unit/operations/client_bulk_write/results_merger.test.ts new file mode 100644 index 0000000000..661a15d4a1 --- /dev/null +++ b/test/unit/operations/client_bulk_write/results_merger.test.ts @@ -0,0 +1,205 @@ +import { expect } from 'chai'; + +import { + BSON, + ClientBulkWriteCursorResponse, + type ClientBulkWriteResult, + ClientBulkWriteResultsMerger, + Long +} from '../../../mongodb'; + +describe('ClientBulkWriteResultsMerger', function () { + describe('#constructor', function () { + const resultsMerger = new ClientBulkWriteResultsMerger({}); + + it('initializes the result', function () { + expect(resultsMerger.result).to.deep.equal({ + insertedCount: 0, + upsertedCount: 0, + matchedCount: 0, + modifiedCount: 0, + deletedCount: 0 + }); + }); + }); + + describe('#merge', function () { + context('when the bulk write is acknowledged', function () { + context('when requesting verbose results', function () { + // An example verbose response from the server without errors: + // { + // cursor: { + // id: Long('0'), + // firstBatch: [ { ok: 1, idx: 0, n: 1 }, { ok: 1, idx: 1, n: 1 } ], + // ns: 'admin.$cmd.bulkWrite' + // }, + // nErrors: 0, + // nInserted: 2, + // nMatched: 0, + // nModified: 0, + // nUpserted: 0, + // nDeleted: 0, + // ok: 1 + // } + context('when there are no errors', function () { + const operations = [ + { insert: 0, document: { _id: 1 } }, + { update: 0 }, + { update: 0 }, + { delete: 0 } + ]; + const documents = [ + { ok: 1, idx: 0, n: 1 }, // Insert + { ok: 1, idx: 1, n: 1, nModified: 1 }, // Update match + { ok: 1, idx: 2, n: 0, upserted: { _id: 1 } }, // Update no match with upsert + { ok: 1, idx: 3, n: 1 } // Delete + ]; + const serverResponse = { + cursor: { + id: new Long('0'), + firstBatch: documents, + ns: 'admin.$cmd.bulkWrite' + }, + nErrors: 0, + nInserted: 1, + nMatched: 1, + nModified: 1, + nUpserted: 1, + nDeleted: 1, + ok: 1 + }; + const response = new ClientBulkWriteCursorResponse(BSON.serialize(serverResponse), 0); + const merger = new ClientBulkWriteResultsMerger({ verboseResults: true }); + let result: ClientBulkWriteResult; + + before(function () { + result = merger.merge(operations, response, documents); + }); + + it('merges the inserted count', function () { + expect(result.insertedCount).to.equal(1); + }); + + it('sets insert results', function () { + expect(result.insertResults.get(0).insertedId).to.equal(1); + }); + + it('merges the upserted count', function () { + expect(result.upsertedCount).to.equal(1); + }); + + it('merges the matched count', function () { + expect(result.matchedCount).to.equal(1); + }); + + it('merges the modified count', function () { + expect(result.modifiedCount).to.equal(1); + }); + + it('sets the update results', function () { + expect(result.updateResults.get(1)).to.deep.equal({ + matchedCount: 1, + modifiedCount: 1 + }); + }); + + it('sets the upsert results', function () { + expect(result.updateResults.get(2)).to.deep.equal({ + matchedCount: 0, + modifiedCount: 0, + upsertedId: 1 + }); + }); + + it('merges the deleted count', function () { + expect(result.deletedCount).to.equal(1); + }); + + it('sets the delete results', function () { + expect(result.deleteResults.get(3).deletedCount).to.equal(1); + }); + }); + }); + + context('when not requesting verbose results', function () { + // An example verbose response from the server without errors: + // { + // cursor: { + // id: Long('0'), + // firstBatch: [], + // ns: 'admin.$cmd.bulkWrite' + // }, + // nErrors: 0, + // nInserted: 2, + // nMatched: 0, + // nModified: 0, + // nUpserted: 0, + // nDeleted: 0, + // ok: 1 + // } + context('when there are no errors', function () { + const operations = [ + { insert: 0, document: { _id: 1 } }, + { update: 0 }, + { update: 0 }, + { delete: 0 } + ]; + const documents = []; + const serverResponse = { + cursor: { + id: new Long('0'), + firstBatch: documents, + ns: 'admin.$cmd.bulkWrite' + }, + nErrors: 0, + nInserted: 1, + nMatched: 1, + nModified: 1, + nUpserted: 1, + nDeleted: 1, + ok: 1 + }; + const response = new ClientBulkWriteCursorResponse(BSON.serialize(serverResponse), 0); + const merger = new ClientBulkWriteResultsMerger({ verboseResults: false }); + let result: ClientBulkWriteResult; + + before(function () { + result = merger.merge(operations, response, documents); + }); + + it('merges the inserted count', function () { + expect(result.insertedCount).to.equal(1); + }); + + it('sets no insert results', function () { + expect(result).to.not.have.property('insertResults'); + }); + + it('merges the upserted count', function () { + expect(result.upsertedCount).to.equal(1); + }); + + it('merges the matched count', function () { + expect(result.matchedCount).to.equal(1); + }); + + it('merges the modified count', function () { + expect(result.modifiedCount).to.equal(1); + }); + + it('sets no update results', function () { + expect(result).to.not.have.property('updateResults'); + }); + + it('merges the deleted count', function () { + expect(result.deletedCount).to.equal(1); + }); + + it('sets no delete results', function () { + expect(result).to.not.have.property('deleteResults'); + }); + }); + }); + }); + }); +});