1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
|
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package driver
import (
"context"
"errors"
"strconv"
"time"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/mongo/description"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver/wiremessage"
)
var (
firstBatchIdentifier = "firstBatch"
nextBatchIdentifier = "nextBatch"
listCollectionsNamespace = "system.namespaces"
listIndexesNamespace = "system.indexes"
// ErrFilterType is returned when the filter for a legacy list collections operation is of the wrong type.
ErrFilterType = errors.New("filter for list collections operation must be a string")
)
func (op Operation) getFullCollectionName(coll string) string {
return op.Database + "." + coll
}
func (op Operation) legacyFind(ctx context.Context, dst []byte, srvr Server, conn Connection, desc description.SelectedServer) error {
wm, startedInfo, collName, err := op.createLegacyFindWireMessage(dst, desc)
if err != nil {
return err
}
startedInfo.connID = conn.ID()
op.publishStartedEvent(ctx, startedInfo)
finishedInfo := finishedInformation{
cmdName: startedInfo.cmdName,
requestID: startedInfo.requestID,
startTime: time.Now(),
connID: startedInfo.connID,
}
finishedInfo.response, finishedInfo.cmdErr = op.roundTripLegacyCursor(ctx, wm, srvr, conn, collName, firstBatchIdentifier)
op.publishFinishedEvent(ctx, finishedInfo)
if finishedInfo.cmdErr != nil {
return finishedInfo.cmdErr
}
if op.ProcessResponseFn != nil {
// CurrentIndex is always 0 in this mode.
info := ResponseInfo{
ServerResponse: finishedInfo.response,
Server: srvr,
Connection: conn,
ConnectionDescription: desc.Server,
}
return op.ProcessResponseFn(info)
}
return nil
}
// returns wire message, collection name, error
func (op Operation) createLegacyFindWireMessage(dst []byte, desc description.SelectedServer) ([]byte, startedInformation, string, error) {
info := startedInformation{
requestID: wiremessage.NextRequestID(),
cmdName: "find",
}
// call CommandFn on an empty slice rather than dst because the options will need to be converted to legacy
var cmdDoc bsoncore.Document
var cmdIndex int32
var err error
cmdIndex, cmdDoc = bsoncore.AppendDocumentStart(cmdDoc)
cmdDoc, err = op.CommandFn(cmdDoc, desc)
if err != nil {
return dst, info, "", err
}
cmdDoc, _ = bsoncore.AppendDocumentEnd(cmdDoc, cmdIndex)
// for monitoring legacy events, the upconverted document should be captured rather than the legacy one
info.cmd = cmdDoc
cmdElems, err := cmdDoc.Elements()
if err != nil {
return dst, info, "", err
}
// take each option from the non-legacy command and convert it
// build options as a byte slice of elements rather than a bsoncore.Document because they will be appended
// to another document with $query
var optsElems []byte
flags := op.secondaryOK(desc)
var numToSkip, numToReturn, batchSize, limit int32 // numToReturn calculated from batchSize and limit
var filter, returnFieldsSelector bsoncore.Document
var collName string
var singleBatch bool
for _, elem := range cmdElems {
switch elem.Key() {
case "find":
collName = elem.Value().StringValue()
case "filter":
filter = elem.Value().Data
case "sort":
optsElems = bsoncore.AppendValueElement(optsElems, "$orderby", elem.Value())
case "hint":
optsElems = bsoncore.AppendValueElement(optsElems, "$hint", elem.Value())
case "comment":
optsElems = bsoncore.AppendValueElement(optsElems, "$comment", elem.Value())
case "max":
optsElems = bsoncore.AppendValueElement(optsElems, "$max", elem.Value())
case "min":
optsElems = bsoncore.AppendValueElement(optsElems, "$min", elem.Value())
case "returnKey":
optsElems = bsoncore.AppendValueElement(optsElems, "$returnKey", elem.Value())
case "showRecordId":
optsElems = bsoncore.AppendValueElement(optsElems, "$showDiskLoc", elem.Value())
case "maxTimeMS":
optsElems = bsoncore.AppendValueElement(optsElems, "$maxTimeMS", elem.Value())
case "snapshot":
optsElems = bsoncore.AppendValueElement(optsElems, "$snapshot", elem.Value())
case "projection":
returnFieldsSelector = elem.Value().Data
case "skip":
// CRUD spec declares skip as int64 but numToSkip is int32 in OP_QUERY
numToSkip = int32(elem.Value().Int64())
case "batchSize":
batchSize = elem.Value().Int32()
// Not possible to use batchSize = 1 because cursor will be closed on first batch
if batchSize == 1 {
batchSize = 2
}
case "limit":
// CRUD spec declares limit as int64 but numToReturn is int32 in OP_QUERY
limit = int32(elem.Value().Int64())
case "singleBatch":
singleBatch = elem.Value().Boolean()
case "tailable":
flags |= wiremessage.TailableCursor
case "awaitData":
flags |= wiremessage.AwaitData
case "oplogReplay":
flags |= wiremessage.OplogReplay
case "noCursorTimeout":
flags |= wiremessage.NoCursorTimeout
case "allowPartialResults":
flags |= wiremessage.Partial
}
}
// for non-legacy servers, a negative limit is implemented as a positive limit + singleBatch = true
if singleBatch {
limit = limit * -1
}
numToReturn = op.calculateNumberToReturn(limit, batchSize)
// add read preference if needed
rp, err := op.createReadPref(desc, true)
if err != nil {
return dst, info, "", err
}
if len(rp) > 0 {
optsElems = bsoncore.AppendDocumentElement(optsElems, "$readPreference", rp)
}
if len(filter) == 0 {
var fidx int32
fidx, filter = bsoncore.AppendDocumentStart(filter)
filter, _ = bsoncore.AppendDocumentEnd(filter, fidx)
}
var wmIdx int32
wmIdx, dst = wiremessage.AppendHeaderStart(dst, info.requestID, 0, wiremessage.OpQuery)
dst = wiremessage.AppendQueryFlags(dst, flags)
dst = wiremessage.AppendQueryFullCollectionName(dst, op.getFullCollectionName(collName))
dst = wiremessage.AppendQueryNumberToSkip(dst, numToSkip)
dst = wiremessage.AppendQueryNumberToReturn(dst, numToReturn)
dst = op.appendLegacyQueryDocument(dst, filter, optsElems)
if len(returnFieldsSelector) != 0 {
// returnFieldsSelector is optional
dst = append(dst, returnFieldsSelector...)
}
return bsoncore.UpdateLength(dst, wmIdx, int32(len(dst[wmIdx:]))), info, collName, nil
}
func (op Operation) calculateNumberToReturn(limit, batchSize int32) int32 {
var numToReturn int32
if limit < 0 {
numToReturn = limit
} else if limit == 0 {
numToReturn = batchSize
} else if batchSize == 0 {
numToReturn = limit
} else if limit < batchSize {
numToReturn = limit
} else {
numToReturn = batchSize
}
return numToReturn
}
func (op Operation) legacyGetMore(ctx context.Context, dst []byte, srvr Server, conn Connection, desc description.SelectedServer) error {
wm, startedInfo, collName, err := op.createLegacyGetMoreWiremessage(dst, desc)
if err != nil {
return err
}
startedInfo.connID = conn.ID()
op.publishStartedEvent(ctx, startedInfo)
finishedInfo := finishedInformation{
cmdName: startedInfo.cmdName,
requestID: startedInfo.requestID,
startTime: time.Now(),
connID: startedInfo.connID,
}
finishedInfo.response, finishedInfo.cmdErr = op.roundTripLegacyCursor(ctx, wm, srvr, conn, collName, nextBatchIdentifier)
op.publishFinishedEvent(ctx, finishedInfo)
if finishedInfo.cmdErr != nil {
return finishedInfo.cmdErr
}
if op.ProcessResponseFn != nil {
// CurrentIndex is always 0 in this mode.
info := ResponseInfo{
ServerResponse: finishedInfo.response,
Server: srvr,
Connection: conn,
ConnectionDescription: desc.Server,
}
return op.ProcessResponseFn(info)
}
return nil
}
func (op Operation) createLegacyGetMoreWiremessage(dst []byte, desc description.SelectedServer) ([]byte, startedInformation, string, error) {
info := startedInformation{
requestID: wiremessage.NextRequestID(),
cmdName: "getMore",
}
var cmdDoc bsoncore.Document
var cmdIdx int32
var err error
cmdIdx, cmdDoc = bsoncore.AppendDocumentStart(cmdDoc)
cmdDoc, err = op.CommandFn(cmdDoc, desc)
if err != nil {
return dst, info, "", err
}
cmdDoc, _ = bsoncore.AppendDocumentEnd(cmdDoc, cmdIdx)
info.cmd = cmdDoc
cmdElems, err := cmdDoc.Elements()
if err != nil {
return dst, info, "", err
}
var cursorID int64
var numToReturn int32
var collName string
for _, elem := range cmdElems {
switch elem.Key() {
case "getMore":
cursorID = elem.Value().Int64()
case "collection":
collName = elem.Value().StringValue()
case "batchSize":
numToReturn = elem.Value().Int32()
}
}
var wmIdx int32
wmIdx, dst = wiremessage.AppendHeaderStart(dst, info.requestID, 0, wiremessage.OpGetMore)
dst = wiremessage.AppendGetMoreZero(dst)
dst = wiremessage.AppendGetMoreFullCollectionName(dst, op.getFullCollectionName(collName))
dst = wiremessage.AppendGetMoreNumberToReturn(dst, numToReturn)
dst = wiremessage.AppendGetMoreCursorID(dst, cursorID)
return bsoncore.UpdateLength(dst, wmIdx, int32(len(dst[wmIdx:]))), info, collName, nil
}
func (op Operation) legacyKillCursors(ctx context.Context, dst []byte, srvr Server, conn Connection, desc description.SelectedServer) error {
wm, startedInfo, _, err := op.createLegacyKillCursorsWiremessage(dst, desc)
if err != nil {
return err
}
startedInfo.connID = conn.ID()
op.publishStartedEvent(ctx, startedInfo)
// skip startTime because OP_KILL_CURSORS does not return a response
finishedInfo := finishedInformation{
cmdName: "killCursors",
requestID: startedInfo.requestID,
connID: startedInfo.connID,
}
err = conn.WriteWireMessage(ctx, wm)
if err != nil {
err = Error{Message: err.Error(), Labels: []string{TransientTransactionError, NetworkError}}
if ep, ok := srvr.(ErrorProcessor); ok {
_ = ep.ProcessError(err, conn)
}
finishedInfo.cmdErr = err
op.publishFinishedEvent(ctx, finishedInfo)
return err
}
ridx, response := bsoncore.AppendDocumentStart(nil)
response = bsoncore.AppendInt32Element(response, "ok", 1)
response = bsoncore.AppendArrayElement(response, "cursorsUnknown", startedInfo.cmd.Lookup("cursors").Array())
response, _ = bsoncore.AppendDocumentEnd(response, ridx)
finishedInfo.response = response
op.publishFinishedEvent(ctx, finishedInfo)
return nil
}
func (op Operation) createLegacyKillCursorsWiremessage(dst []byte, desc description.SelectedServer) ([]byte, startedInformation, string, error) {
info := startedInformation{
cmdName: "killCursors",
requestID: wiremessage.NextRequestID(),
}
var cmdDoc bsoncore.Document
var cmdIdx int32
var err error
cmdIdx, cmdDoc = bsoncore.AppendDocumentStart(cmdDoc)
cmdDoc, err = op.CommandFn(cmdDoc, desc)
if err != nil {
return nil, info, "", err
}
cmdDoc, _ = bsoncore.AppendDocumentEnd(cmdDoc, cmdIdx)
info.cmd = cmdDoc
cmdElems, err := cmdDoc.Elements()
if err != nil {
return nil, info, "", err
}
var collName string
var cursors bsoncore.Array
for _, elem := range cmdElems {
switch elem.Key() {
case "killCursors":
collName = elem.Value().StringValue()
case "cursors":
cursors = elem.Value().Array()
}
}
var cursorIDs []int64
if cursors != nil {
cursorValues, err := cursors.Values()
if err != nil {
return nil, info, "", err
}
for _, cursorVal := range cursorValues {
cursorIDs = append(cursorIDs, cursorVal.Int64())
}
}
var wmIdx int32
wmIdx, dst = wiremessage.AppendHeaderStart(dst, info.requestID, 0, wiremessage.OpKillCursors)
dst = wiremessage.AppendKillCursorsZero(dst)
dst = wiremessage.AppendKillCursorsNumberIDs(dst, int32(len(cursorIDs)))
dst = wiremessage.AppendKillCursorsCursorIDs(dst, cursorIDs)
return bsoncore.UpdateLength(dst, wmIdx, int32(len(dst[wmIdx:]))), info, collName, nil
}
func (op Operation) legacyListCollections(ctx context.Context, dst []byte, srvr Server, conn Connection, desc description.SelectedServer) error {
wm, startedInfo, collName, err := op.createLegacyListCollectionsWiremessage(dst, desc)
if err != nil {
return err
}
startedInfo.connID = conn.ID()
op.publishStartedEvent(ctx, startedInfo)
finishedInfo := finishedInformation{
cmdName: startedInfo.cmdName,
requestID: startedInfo.requestID,
startTime: time.Now(),
connID: startedInfo.connID,
}
finishedInfo.response, finishedInfo.cmdErr = op.roundTripLegacyCursor(ctx, wm, srvr, conn, collName, firstBatchIdentifier)
op.publishFinishedEvent(ctx, finishedInfo)
if finishedInfo.cmdErr != nil {
return finishedInfo.cmdErr
}
if op.ProcessResponseFn != nil {
// CurrentIndex is always 0 in this mode.
info := ResponseInfo{
ServerResponse: finishedInfo.response,
Server: srvr,
Connection: conn,
ConnectionDescription: desc.Server,
}
return op.ProcessResponseFn(info)
}
return nil
}
func (op Operation) createLegacyListCollectionsWiremessage(dst []byte, desc description.SelectedServer) ([]byte, startedInformation, string, error) {
info := startedInformation{
cmdName: "find",
requestID: wiremessage.NextRequestID(),
}
var cmdDoc bsoncore.Document
var cmdIdx int32
var err error
cmdIdx, cmdDoc = bsoncore.AppendDocumentStart(cmdDoc)
if cmdDoc, err = op.CommandFn(cmdDoc, desc); err != nil {
return dst, info, "", err
}
cmdDoc, _ = bsoncore.AppendDocumentEnd(cmdDoc, cmdIdx)
info.cmd, err = op.convertCommandToFind(cmdDoc, listCollectionsNamespace)
if err != nil {
return nil, info, "", err
}
// lookup filter directly instead of calling cmdDoc.Elements() because the only listCollections option is nameOnly,
// which doesn't apply to legacy servers
var originalFilter bsoncore.Document
if filterVal, err := cmdDoc.LookupErr("filter"); err == nil {
originalFilter = filterVal.Document()
}
var optsElems []byte
filter, err := op.transformListCollectionsFilter(originalFilter)
if err != nil {
return dst, info, "", err
}
rp, err := op.createReadPref(desc, true)
if err != nil {
return dst, info, "", err
}
if len(rp) > 0 {
optsElems = bsoncore.AppendDocumentElement(optsElems, "$readPreference", rp)
}
var batchSize int32
if val, ok := cmdDoc.Lookup("cursor", "batchSize").AsInt32OK(); ok {
batchSize = val
}
var wmIdx int32
wmIdx, dst = wiremessage.AppendHeaderStart(dst, info.requestID, 0, wiremessage.OpQuery)
dst = wiremessage.AppendQueryFlags(dst, op.secondaryOK(desc))
dst = wiremessage.AppendQueryFullCollectionName(dst, op.getFullCollectionName(listCollectionsNamespace))
dst = wiremessage.AppendQueryNumberToSkip(dst, 0)
dst = wiremessage.AppendQueryNumberToReturn(dst, batchSize)
dst = op.appendLegacyQueryDocument(dst, filter, optsElems)
// leave out returnFieldsSelector because it is optional
return bsoncore.UpdateLength(dst, wmIdx, int32(len(dst[wmIdx:]))), info, listCollectionsNamespace, nil
}
func (op Operation) transformListCollectionsFilter(filter bsoncore.Document) (bsoncore.Document, error) {
// filter out results containing $ because those represent indexes
var regexFilter bsoncore.Document
var ridx int32
ridx, regexFilter = bsoncore.AppendDocumentStart(regexFilter)
regexFilter = bsoncore.AppendRegexElement(regexFilter, "name", "^[^$]*$", "")
regexFilter, _ = bsoncore.AppendDocumentEnd(regexFilter, ridx)
if len(filter) == 0 {
return regexFilter, nil
}
convertedIdx, convertedFilter := bsoncore.AppendDocumentStart(nil)
elems, err := filter.Elements()
if err != nil {
return nil, err
}
for _, elem := range elems {
if elem.Key() != "name" {
convertedFilter = append(convertedFilter, elem...)
continue
}
// the name value in a filter for legacy list collections must be a string and has to be prepended
// with the database name
nameVal := elem.Value()
if nameVal.Type != bsontype.String {
return nil, ErrFilterType
}
convertedFilter = bsoncore.AppendStringElement(convertedFilter, "name", op.getFullCollectionName(nameVal.StringValue()))
}
convertedFilter, _ = bsoncore.AppendDocumentEnd(convertedFilter, convertedIdx)
// combine regexFilter and convertedFilter with $and
var combinedFilter bsoncore.Document
var cidx, aidx int32
cidx, combinedFilter = bsoncore.AppendDocumentStart(combinedFilter)
aidx, combinedFilter = bsoncore.AppendArrayElementStart(combinedFilter, "$and")
combinedFilter = bsoncore.AppendDocumentElement(combinedFilter, "0", regexFilter)
combinedFilter = bsoncore.AppendDocumentElement(combinedFilter, "1", convertedFilter)
combinedFilter, _ = bsoncore.AppendArrayEnd(combinedFilter, aidx)
combinedFilter, _ = bsoncore.AppendDocumentEnd(combinedFilter, cidx)
return combinedFilter, nil
}
func (op Operation) legacyListIndexes(ctx context.Context, dst []byte, srvr Server, conn Connection, desc description.SelectedServer) error {
wm, startedInfo, collName, err := op.createLegacyListIndexesWiremessage(dst, desc)
if err != nil {
return err
}
startedInfo.connID = conn.ID()
op.publishStartedEvent(ctx, startedInfo)
finishedInfo := finishedInformation{
cmdName: startedInfo.cmdName,
requestID: startedInfo.requestID,
startTime: time.Now(),
connID: startedInfo.connID,
}
finishedInfo.response, finishedInfo.cmdErr = op.roundTripLegacyCursor(ctx, wm, srvr, conn, collName, firstBatchIdentifier)
op.publishFinishedEvent(ctx, finishedInfo)
if finishedInfo.cmdErr != nil {
return finishedInfo.cmdErr
}
if op.ProcessResponseFn != nil {
// CurrentIndex is always 0 in this mode.
info := ResponseInfo{
ServerResponse: finishedInfo.response,
Server: srvr,
Connection: conn,
ConnectionDescription: desc.Server,
}
return op.ProcessResponseFn(info)
}
return nil
}
func (op Operation) createLegacyListIndexesWiremessage(dst []byte, desc description.SelectedServer) ([]byte, startedInformation, string, error) {
info := startedInformation{
cmdName: "find",
requestID: wiremessage.NextRequestID(),
}
var cmdDoc bsoncore.Document
var cmdIndex int32
var err error
cmdIndex, cmdDoc = bsoncore.AppendDocumentStart(cmdDoc)
cmdDoc, err = op.CommandFn(cmdDoc, desc)
if err != nil {
return dst, info, "", err
}
cmdDoc, _ = bsoncore.AppendDocumentEnd(cmdDoc, cmdIndex)
info.cmd, err = op.convertCommandToFind(cmdDoc, listIndexesNamespace)
if err != nil {
return nil, info, "", err
}
cmdElems, err := cmdDoc.Elements()
if err != nil {
return nil, info, "", err
}
var filterCollName string
var batchSize int32
var optsElems []byte // options elements
for _, elem := range cmdElems {
switch elem.Key() {
case "listIndexes":
filterCollName = elem.Value().StringValue()
case "cursor":
// the batchSize option is embedded in a cursor subdocument
cursorDoc := elem.Value().Document()
if val, err := cursorDoc.LookupErr("batchSize"); err == nil {
batchSize = val.Int32()
}
case "maxTimeMS":
optsElems = bsoncore.AppendValueElement(optsElems, "$maxTimeMS", elem.Value())
}
}
// always filter with {ns: db.collection}
fidx, filter := bsoncore.AppendDocumentStart(nil)
filter = bsoncore.AppendStringElement(filter, "ns", op.getFullCollectionName(filterCollName))
filter, _ = bsoncore.AppendDocumentEnd(filter, fidx)
rp, err := op.createReadPref(desc, true)
if err != nil {
return dst, info, "", err
}
if len(rp) > 0 {
optsElems = bsoncore.AppendDocumentElement(optsElems, "$readPreference", rp)
}
var wmIdx int32
wmIdx, dst = wiremessage.AppendHeaderStart(dst, info.requestID, 0, wiremessage.OpQuery)
dst = wiremessage.AppendQueryFlags(dst, op.secondaryOK(desc))
dst = wiremessage.AppendQueryFullCollectionName(dst, op.getFullCollectionName(listIndexesNamespace))
dst = wiremessage.AppendQueryNumberToSkip(dst, 0)
dst = wiremessage.AppendQueryNumberToReturn(dst, batchSize)
dst = op.appendLegacyQueryDocument(dst, filter, optsElems)
// leave out returnFieldsSelector because it is optional
return bsoncore.UpdateLength(dst, wmIdx, int32(len(dst[wmIdx:]))), info, listIndexesNamespace, nil
}
// convertCommandToFind takes a non-legacy command document for a command that needs to be run as a find on legacy
// servers and converts it to a find command document for APM.
func (op Operation) convertCommandToFind(cmdDoc bsoncore.Document, collName string) (bsoncore.Document, error) {
cidx, converted := bsoncore.AppendDocumentStart(nil)
elems, err := cmdDoc.Elements()
if err != nil {
return nil, err
}
converted = bsoncore.AppendStringElement(converted, "find", collName)
// skip the first element because that will have the old command name
for i := 1; i < len(elems); i++ {
converted = bsoncore.AppendValueElement(converted, elems[i].Key(), elems[i].Value())
}
converted, _ = bsoncore.AppendDocumentEnd(converted, cidx)
return converted, nil
}
// appendLegacyQueryDocument takes a filter and a list of options elements for a legacy find operation, creates
// a query document, and appends it to dst.
func (op Operation) appendLegacyQueryDocument(dst []byte, filter bsoncore.Document, opts []byte) []byte {
if len(opts) == 0 {
dst = append(dst, filter...)
return dst
}
// filter must be wrapped in $query if other $-modifiers are used
var qidx int32
qidx, dst = bsoncore.AppendDocumentStart(dst)
dst = bsoncore.AppendDocumentElement(dst, "$query", filter)
dst = append(dst, opts...)
dst, _ = bsoncore.AppendDocumentEnd(dst, qidx)
return dst
}
// roundTripLegacyCursor sends a wiremessage for an operation expecting a cursor result and converts the legacy
// document sequence into a cursor document.
func (op Operation) roundTripLegacyCursor(ctx context.Context, wm []byte, srvr Server, conn Connection, collName, identifier string) (bsoncore.Document, error) {
wm, err := op.roundTripLegacy(ctx, conn, wm)
if ep, ok := srvr.(ErrorProcessor); ok {
_ = ep.ProcessError(err, conn)
}
if err != nil {
return nil, err
}
return op.upconvertCursorResponse(wm, identifier, collName)
}
// roundTripLegacy handles writing a wire message and reading the response.
func (op Operation) roundTripLegacy(ctx context.Context, conn Connection, wm []byte) ([]byte, error) {
err := conn.WriteWireMessage(ctx, wm)
if err != nil {
return nil, Error{Message: err.Error(), Labels: []string{TransientTransactionError, NetworkError}, Wrapped: err}
}
wm, err = conn.ReadWireMessage(ctx, wm[:0])
if err != nil {
err = Error{Message: err.Error(), Labels: []string{TransientTransactionError, NetworkError}, Wrapped: err}
}
return wm, err
}
func (op Operation) upconvertCursorResponse(wm []byte, batchIdentifier string, collName string) (bsoncore.Document, error) {
reply := op.decodeOpReply(wm, true)
if reply.err != nil {
return nil, reply.err
}
cursorIdx, cursorDoc := bsoncore.AppendDocumentStart(nil)
// convert reply documents to BSON array
var arrIdx int32
arrIdx, cursorDoc = bsoncore.AppendArrayElementStart(cursorDoc, batchIdentifier)
for i, doc := range reply.documents {
cursorDoc = bsoncore.AppendDocumentElement(cursorDoc, strconv.Itoa(i), doc)
}
cursorDoc, _ = bsoncore.AppendArrayEnd(cursorDoc, arrIdx)
cursorDoc = bsoncore.AppendInt64Element(cursorDoc, "id", reply.cursorID)
cursorDoc = bsoncore.AppendStringElement(cursorDoc, "ns", op.getFullCollectionName(collName))
cursorDoc, _ = bsoncore.AppendDocumentEnd(cursorDoc, cursorIdx)
resIdx, resDoc := bsoncore.AppendDocumentStart(nil)
resDoc = bsoncore.AppendInt32Element(resDoc, "ok", 1)
resDoc = bsoncore.AppendDocumentElement(resDoc, "cursor", cursorDoc)
resDoc, _ = bsoncore.AppendDocumentEnd(resDoc, resIdx)
return resDoc, nil
}
|