Don Newton | 379ae25 | 2019-04-01 12:17:06 -0400 | [diff] [blame^] | 1 | // Copyright (C) MongoDB, Inc. 2017-present. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | // not use this file except in compliance with the License. You may obtain |
| 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | |
| 7 | package command |
| 8 | |
| 9 | import ( |
| 10 | "github.com/mongodb/mongo-go-driver/bson" |
| 11 | "github.com/mongodb/mongo-go-driver/x/bsonx" |
| 12 | "github.com/mongodb/mongo-go-driver/x/network/wiremessage" |
| 13 | ) |
| 14 | |
| 15 | func decodeCommandOpMsg(msg wiremessage.Msg) (bson.Raw, error) { |
| 16 | var mainDoc bsonx.Doc |
| 17 | |
| 18 | for _, section := range msg.Sections { |
| 19 | switch converted := section.(type) { |
| 20 | case wiremessage.SectionBody: |
| 21 | err := mainDoc.UnmarshalBSON(converted.Document) |
| 22 | if err != nil { |
| 23 | return nil, err |
| 24 | } |
| 25 | case wiremessage.SectionDocumentSequence: |
| 26 | arr := bsonx.Arr{} |
| 27 | for _, doc := range converted.Documents { |
| 28 | newDoc := bsonx.Doc{} |
| 29 | err := newDoc.UnmarshalBSON(doc) |
| 30 | if err != nil { |
| 31 | return nil, err |
| 32 | } |
| 33 | |
| 34 | arr = append(arr, bsonx.Document(newDoc)) |
| 35 | } |
| 36 | |
| 37 | mainDoc = append(mainDoc, bsonx.Elem{converted.Identifier, bsonx.Array(arr)}) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | byteArray, err := mainDoc.MarshalBSON() |
| 42 | if err != nil { |
| 43 | return nil, err |
| 44 | } |
| 45 | |
| 46 | rdr := bson.Raw(byteArray) |
| 47 | err = rdr.Validate() |
| 48 | if err != nil { |
| 49 | return nil, NewCommandResponseError("malformed OP_MSG: invalid document", err) |
| 50 | } |
| 51 | |
| 52 | err = extractError(rdr) |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | return rdr, nil |
| 57 | } |