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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
|
/**
* Copyright (C) 2017 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
#include "mongo/platform/basic.h"
#include <type_traits>
#include "mongo/base/static_assert.h"
#include "mongo/bson/json.h"
#include "mongo/bson/util/builder.h"
#include "mongo/db/jsobj.h"
#include "mongo/rpc/op_msg.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/hex.h"
#include "mongo/util/log.h"
namespace mongo {
namespace {
// Makes a SharedBuffer out of arguments passed to constructor.
class Bytes {
public:
template <typename... T>
explicit Bytes(T&&... args) {
append(args...);
}
protected:
void append() {} // no-op base case
template <typename T, typename... Rest>
std::enable_if_t<std::is_integral<T>::value> append(T arg, Rest&&... rest) {
// Make sure BufBuilder has a real overload of this exact type and it isn't implicitly
// converted.
(void)static_cast<void (BufBuilder::*)(T)>(&BufBuilder::appendNum);
buffer.appendNum(arg); // automatically little endian.
append(rest...);
}
template <typename... Rest>
void append(const BSONObj& arg, Rest&&... rest) {
arg.appendSelfToBufBuilder(buffer);
append(rest...);
}
template <typename... Rest>
void append(const Bytes& arg, Rest&&... rest) {
buffer.appendBuf(arg.buffer.buf(), arg.buffer.len());
append(rest...);
}
template <typename... Rest>
void append(StringData arg, Rest&&... rest) {
buffer.appendStr(arg, /* null terminate*/ true);
append(rest...);
}
BufBuilder buffer;
};
// A Bytes that puts the size of the buffer at the front as a little-endian int32
class Sized : public Bytes {
public:
template <typename... T>
explicit Sized(T&&... args) {
buffer.skip(sizeof(int32_t));
append(args...);
DataView(buffer.buf()).write<LittleEndian<int32_t>>(buffer.len());
}
// Adds extra to the stored size. Use this to produce illegal messages.
Sized&& addToSize(int32_t extra) && {
DataView(buffer.buf()).write<LittleEndian<int32_t>>(buffer.len() + extra);
return std::move(*this);
}
};
// A Bytes that puts the standard message header at the front.
class OpMsgBytes : public Sized {
public:
template <typename... T>
explicit OpMsgBytes(T&&... args)
: Sized{int32_t{1}, // requestId
int32_t{2}, // replyId
int32_t{dbMsg}, // opCode
args...} {}
Message done() {
const auto orig = Message(buffer.release());
// Copy the message to an exact-sized allocation so ASAN can detect out-of-bounds accesses.
auto copy = SharedBuffer::allocate(orig.size());
memcpy(copy.get(), orig.buf(), orig.size());
return Message(std::move(copy));
}
OpMsg parse() {
return OpMsg::parseOwned(done());
}
OpMsgBytes&& addToSize(int32_t extra) && {
DataView(buffer.buf()).write<LittleEndian<int32_t>>(buffer.len() + extra);
return std::move(*this);
}
};
// Fixture class to raise log verbosity so that invalid messages are printed by the parser.
class OpMsgParser : public unittest::Test {
public:
void setUp() override {
_original =
logger::globalLogDomain()->getMinimumLogSeverity(logger::LogComponent::kNetwork);
logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogComponent::kNetwork,
logger::LogSeverity::Debug(1));
}
void tearDown() override {
logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogComponent::kNetwork,
_original);
}
private:
logger::LogSeverity _original = logger::LogSeverity::Debug(0);
};
// Section bytes
const char kBodySection = 0;
const char kDocSequenceSection = 1;
// Flags
const uint32_t kNoFlags = 0;
const uint32_t kHaveChecksum = 1;
// CRC filler value
const uint32_t kFakeCRC = 0; // TODO will need to compute real crc when SERVER-28679 is done.
TEST_F(OpMsgParser, SucceedsWithJustBody) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1}"));
ASSERT_EQ(msg.sequences.size(), 0u);
}
TEST_F(OpMsgParser, IgnoresCrcIfPresent) { // Until SERVER-28679 is done.
auto msg = OpMsgBytes{
kHaveChecksum, //
kBodySection,
fromjson("{ping: 1}"),
kFakeCRC, // If not ignored, this would be read as a second body.
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1}"));
ASSERT_EQ(msg.sequences.size(), 0u);
}
TEST_F(OpMsgParser, SucceedsWithBodyThenSequence) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
fromjson("{a: 2}"),
},
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1}"));
ASSERT_EQ(msg.sequences.size(), 1u);
ASSERT_EQ(msg.sequences[0].name, "docs");
ASSERT_EQ(msg.sequences[0].objs.size(), 2u);
ASSERT_BSONOBJ_EQ(msg.sequences[0].objs[0], fromjson("{a: 1}"));
ASSERT_BSONOBJ_EQ(msg.sequences[0].objs[1], fromjson("{a: 2}"));
}
TEST_F(OpMsgParser, SucceedsWithSequenceThenBody) {
auto msg = OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
},
kBodySection,
fromjson("{ping: 1}"),
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1}"));
ASSERT_EQ(msg.sequences.size(), 1u);
ASSERT_EQ(msg.sequences[0].name, "docs");
ASSERT_EQ(msg.sequences[0].objs.size(), 1u);
ASSERT_BSONOBJ_EQ(msg.sequences[0].objs[0], fromjson("{a: 1}"));
}
TEST_F(OpMsgParser, SucceedsWithSequenceThenBodyThenSequence) {
auto msg = OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"empty", //
},
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
},
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1}"));
ASSERT_EQ(msg.sequences.size(), 2u);
ASSERT_EQ(msg.sequences[0].name, "empty");
ASSERT_EQ(msg.sequences[0].objs.size(), 0u);
ASSERT_EQ(msg.sequences[1].name, "docs");
ASSERT_EQ(msg.sequences[1].objs.size(), 1u);
ASSERT_BSONOBJ_EQ(msg.sequences[1].objs[0], fromjson("{a: 1}"));
}
TEST_F(OpMsgParser, SucceedsWithSequenceThenSequenceThenBody) {
auto msg = OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"empty", //
},
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
},
kBodySection,
fromjson("{ping: 1}"),
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1}"));
ASSERT_EQ(msg.sequences.size(), 2u);
ASSERT_EQ(msg.sequences[0].name, "empty");
ASSERT_EQ(msg.sequences[0].objs.size(), 0u);
ASSERT_EQ(msg.sequences[1].name, "docs");
ASSERT_EQ(msg.sequences[1].objs.size(), 1u);
ASSERT_BSONOBJ_EQ(msg.sequences[1].objs[0], fromjson("{a: 1}"));
}
TEST_F(OpMsgParser, SucceedsWithBodyThenSequenceThenSequence) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
},
kDocSequenceSection,
Sized{
"empty", //
},
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1}"));
ASSERT_EQ(msg.sequences.size(), 2u);
ASSERT_EQ(msg.sequences[0].name, "docs");
ASSERT_EQ(msg.sequences[0].objs.size(), 1u);
ASSERT_BSONOBJ_EQ(msg.sequences[0].objs[0], fromjson("{a: 1}"));
ASSERT_EQ(msg.sequences[1].name, "empty");
ASSERT_EQ(msg.sequences[1].objs.size(), 0u);
}
TEST_F(OpMsgParser, FailsIfNoBody) {
auto msg = OpMsgBytes{
kNoFlags, //
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, 40587);
}
TEST_F(OpMsgParser, FailsIfNoBodyEvenWithSequence) {
auto msg = OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{"docs"},
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, 40587);
}
TEST_F(OpMsgParser, FailsIfTwoBodies) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kBodySection,
fromjson("{pong: 1}"),
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, 40430);
}
TEST_F(OpMsgParser, FailsIfDuplicateSequences) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{"docs"},
kDocSequenceSection,
Sized{"docs"},
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, 40431);
}
TEST_F(OpMsgParser, FailsIfDuplicateSequenceWithBody) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1, 'docs': []}"),
kDocSequenceSection,
Sized{"docs"},
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, 40433);
}
TEST_F(OpMsgParser, FailsIfDuplicateSequenceWithBodyNested) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1, a: {b:[]}}"),
kDocSequenceSection,
Sized{"a.b"},
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, 40433);
}
TEST_F(OpMsgParser, SucceedsIfSequenceAndBodyHaveCommonPrefix) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{cursor: {ns: 'foo.bar', id: 1}}"),
kDocSequenceSection,
Sized{
"cursor.firstBatch", //
fromjson("{_id: 1}"),
},
}.parse();
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{cursor: {ns: 'foo.bar', id: 1}}"));
ASSERT_EQ(msg.sequences.size(), 1u);
ASSERT_EQ(msg.sequences[0].name, "cursor.firstBatch");
ASSERT_EQ(msg.sequences[0].objs.size(), 1u);
ASSERT_BSONOBJ_EQ(msg.sequences[0].objs[0], fromjson("{_id: 1}"));
}
TEST_F(OpMsgParser, FailsIfUnknownSectionKind) {
auto msg = OpMsgBytes{
kNoFlags, //
'\x99', // This is where a section kind would go
Sized{},
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, 40432);
}
TEST_F(OpMsgParser, FailsIfBodyTooBig) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
}.addToSize(-1); // Shrink message so body extends past end.
ASSERT_THROWS_CODE(msg.parse(), AssertionException, ErrorCodes::InvalidBSON);
}
TEST_F(OpMsgParser, FailsIfBodyTooBigIntoChecksum) {
auto msg = OpMsgBytes{
kHaveChecksum, //
kBodySection,
fromjson("{ping: 1}"),
kFakeCRC,
}.addToSize(-1); // Shrink message so body extends past end.
ASSERT_THROWS_CODE(msg.parse(), AssertionException, ErrorCodes::InvalidBSON);
}
TEST_F(OpMsgParser, FailsIfDocumentSequenceTooBig) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
},
}.addToSize(-1); // Shrink message so body extends past end.
ASSERT_THROWS_CODE(msg.parse(), AssertionException, ErrorCodes::Overflow);
}
TEST_F(OpMsgParser, FailsIfDocumentSequenceTooBigIntoChecksum) {
auto msg = OpMsgBytes{
kHaveChecksum, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
},
kFakeCRC,
}.addToSize(-1); // Shrink message so body extends past end.
ASSERT_THROWS_CODE(msg.parse(), AssertionException, ErrorCodes::Overflow);
}
TEST_F(OpMsgParser, FailsIfDocumentInSequenceTooBig) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
}.addToSize(-1), // Shrink sequence so document extends past end.
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, ErrorCodes::InvalidBSON);
}
TEST_F(OpMsgParser, FailsIfNameOfDocumentSequenceTooBig) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{
"foo",
}.addToSize(-1), // Shrink sequence so document extends past end.
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, ErrorCodes::Overflow);
}
TEST_F(OpMsgParser, FailsIfNameOfDocumentSequenceHasNoNulTerminator) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{'f', 'o', 'o'},
// No '\0' at end of document. ASAN should complain if we keep looking for one.
};
ASSERT_THROWS_CODE(msg.parse(), AssertionException, ErrorCodes::Overflow);
}
TEST_F(OpMsgParser, FailsIfTooManyDocumentSequences) {
auto msg = OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
kDocSequenceSection,
Sized{"foo"},
kDocSequenceSection,
Sized{"bar"},
kDocSequenceSection,
Sized{"baz"},
};
ASSERT_THROWS_WITH_CHECK(
msg.parse(), ExceptionFor<ErrorCodes::TooManyDocumentSequences>, [](const DBException& ex) {
ASSERT(ex.isA<ErrorCategory::ConnectionFatalMessageParseError>());
});
}
TEST_F(OpMsgParser, FailsIfNoRoomForFlags) {
// Flags are 4 bytes. Try 0-3 bytes.
ASSERT_THROWS_CODE(OpMsgBytes{}.parse(), AssertionException, ErrorCodes::Overflow);
ASSERT_THROWS_CODE(OpMsgBytes{'\0'}.parse(), AssertionException, ErrorCodes::Overflow);
ASSERT_THROWS_CODE((OpMsgBytes{'\0', '\0'}.parse()), AssertionException, ErrorCodes::Overflow);
ASSERT_THROWS_CODE(
(OpMsgBytes{'\0', '\0', '\0'}.parse()), AssertionException, ErrorCodes::Overflow);
ASSERT_THROWS_CODE(OpMsg::flags(OpMsgBytes{}.done()), AssertionException, ErrorCodes::Overflow);
ASSERT_THROWS_CODE(
OpMsg::flags(OpMsgBytes{'\0'}.done()), AssertionException, ErrorCodes::Overflow);
ASSERT_THROWS_CODE(
OpMsg::flags(OpMsgBytes{'\0', '\0'}.done()), AssertionException, ErrorCodes::Overflow);
ASSERT_THROWS_CODE(OpMsg::flags(OpMsgBytes{'\0', '\0', '\0'}.done()),
AssertionException,
ErrorCodes::Overflow);
}
TEST_F(OpMsgParser, FlagExtractionWorks) {
ASSERT_EQ(OpMsg::flags(OpMsgBytes{0u}.done()), 0u); // All clear.
ASSERT_EQ(OpMsg::flags(OpMsgBytes{~0u}.done()), ~0u); // All set.
for (auto i = uint32_t(0); i < 32u; i++) {
const auto flags = uint32_t(1) << i;
ASSERT_EQ(OpMsg::flags(OpMsgBytes{flags}.done()), flags) << flags;
ASSERT(OpMsg::isFlagSet(OpMsgBytes{flags}.done(), flags)) << flags;
ASSERT(!OpMsg::isFlagSet(OpMsgBytes{~flags}.done(), flags)) << flags;
ASSERT(!OpMsg::isFlagSet(OpMsgBytes{0u}.done(), flags)) << flags;
ASSERT(OpMsg::isFlagSet(OpMsgBytes{~0u}.done(), flags)) << flags;
}
}
TEST_F(OpMsgParser, FailsWithUnknownRequiredFlags) {
// Bits 0 and 1 are known, and bits >= 16 are optional.
for (auto i = uint32_t(2); i < 16u; i++) {
auto flags = uint32_t(1) << i;
auto msg = OpMsgBytes{
flags, //
kBodySection,
fromjson("{ping: 1}"),
};
ASSERT_THROWS_WITH_CHECK(msg.parse(), AssertionException, [](const DBException& ex) {
ASSERT_EQ(ex.toStatus().code(), ErrorCodes::IllegalOpMsgFlag);
ASSERT(ErrorCodes::isConnectionFatalMessageParseError(ex.toStatus().code()));
});
}
}
TEST_F(OpMsgParser, SucceedsWithUnknownOptionalFlags) {
// bits >= 16 are optional.
for (auto i = uint32_t(16); i < 32u; i++) {
auto flags = uint32_t(1) << i;
OpMsgBytes{
flags, //
kBodySection,
fromjson("{ping: 1}"),
}.parse();
}
}
void testSerializer(const Message& fromSerializer, OpMsgBytes&& expected) {
const auto expectedMsg = expected.done();
ASSERT_EQ(fromSerializer.operation(), dbMsg);
// Ignoring request and reply ids since they aren't handled by OP_MSG code.
auto gotSD = StringData(fromSerializer.singleData().data(), fromSerializer.dataSize());
auto expectedSD = StringData(expectedMsg.singleData().data(), expectedMsg.dataSize());
if (gotSD == expectedSD)
return;
size_t commonLength =
std::mismatch(gotSD.begin(), gotSD.end(), expectedSD.begin(), expectedSD.end()).first -
gotSD.begin();
log() << "Mismatch after " << commonLength << " bytes.";
log() << "Common prefix: " << hexdump(gotSD.rawData(), commonLength);
log() << "Got suffix : "
<< hexdump(gotSD.rawData() + commonLength, gotSD.size() - commonLength);
log() << "Expected suffix: "
<< hexdump(expectedSD.rawData() + commonLength, expectedSD.size() - commonLength);
FAIL("Serialization didn't match expected data. See above for details.");
}
TEST(OpMsgSerializer, JustBody) {
OpMsg msg;
msg.body = fromjson("{ping: 1}");
testSerializer(msg.serialize(),
OpMsgBytes{
kNoFlags, //
kBodySection,
fromjson("{ping: 1}"),
});
}
TEST(OpMsgSerializer, BodyAndSequence) {
OpMsg msg;
msg.body = fromjson("{ping: 1}");
msg.sequences = {{"docs", {fromjson("{a:1}"), fromjson("{a:2}")}}};
testSerializer(msg.serialize(),
OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
fromjson("{a: 2}"),
},
kBodySection,
fromjson("{ping: 1}"),
});
}
TEST(OpMsgSerializer, BodyAndEmptySequence) {
OpMsg msg;
msg.body = fromjson("{ping: 1}");
msg.sequences = {{"docs", {}}};
testSerializer(msg.serialize(),
OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"docs", //
},
kBodySection,
fromjson("{ping: 1}"),
});
}
TEST(OpMsgSerializer, BodyAndTwoSequences) {
OpMsg msg;
msg.body = fromjson("{ping: 1}");
msg.sequences = {
{"a", {fromjson("{a: 1}")}}, //
{"b", {fromjson("{b: 1}")}},
};
testSerializer(msg.serialize(),
OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"a", //
fromjson("{a: 1}"),
},
kDocSequenceSection,
Sized{
"b", //
fromjson("{b: 1}"),
},
kBodySection,
fromjson("{ping: 1}"),
});
}
TEST(OpMsgSerializer, BodyAndSequenceInPlace) {
OpMsgBuilder builder;
auto emptySeq = builder.beginDocSequence("empty");
emptySeq.done();
{
auto seq = builder.beginDocSequence("docs");
seq.append(fromjson("{a: 1}"));
seq.appendBuilder().append("a", 2);
}
builder.beginBody().append("ping", 1);
builder.resumeBody().append("$db", "foo");
testSerializer(builder.finish(),
OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"empty",
},
kDocSequenceSection,
Sized{
"docs", //
fromjson("{a: 1}"),
fromjson("{a: 2}"),
},
kBodySection,
fromjson("{ping: 1, $db: 'foo'}"),
});
}
TEST(OpMsgSerializer, BodyAndInPlaceSequenceInPlaceWithReset) {
OpMsgBuilder builder;
auto emptySeq = builder.beginDocSequence("empty");
emptySeq.done();
{
auto seq = builder.beginDocSequence("docs");
seq.append(fromjson("{a: 1}"));
seq.appendBuilder().append("a", 2);
}
builder.beginBody().append("ping", 1);
builder.resumeBody().append("$db", "foo");
builder.reset();
// Everything above shouldn't matter.
{
auto seq = builder.beginDocSequence("docs2");
seq.append(fromjson("{b: 1}"));
seq.appendBuilder().append("b", 2);
}
builder.beginBody().append("pong", 1);
testSerializer(builder.finish(),
OpMsgBytes{
kNoFlags, //
kDocSequenceSection,
Sized{
"docs2", //
fromjson("{b: 1}"),
fromjson("{b: 2}"),
},
kBodySection,
fromjson("{pong: 1}"),
});
}
TEST(OpMsgSerializer, ReplaceFlagsWorks) {
{
auto msg = OpMsgBytes{~0u}.done();
OpMsg::replaceFlags(&msg, 0u);
ASSERT_EQ(OpMsg::flags(msg), 0u);
}
{
auto msg = OpMsgBytes{0u}.done();
OpMsg::replaceFlags(&msg, ~0u);
ASSERT_EQ(OpMsg::flags(msg), ~0u);
}
for (auto i = uint32_t(0); i < 32u; i++) {
auto flags = uint32_t(1) << i;
{
auto msg = OpMsgBytes{0u}.done();
OpMsg::replaceFlags(&msg, flags);
ASSERT_EQ(OpMsg::flags(msg), flags) << flags;
}
{
auto msg = OpMsgBytes{~0u}.done();
OpMsg::replaceFlags(&msg, flags);
ASSERT_EQ(OpMsg::flags(msg), flags) << flags;
}
{
auto msg = OpMsgBytes{~flags}.done();
OpMsg::replaceFlags(&msg, flags);
ASSERT_EQ(OpMsg::flags(msg), flags) << flags;
}
}
}
TEST(OpMsgSerializer, SetFlagWorks) {
for (auto i = uint32_t(0); i < 32u; i++) {
auto flags = uint32_t(1) << i;
{
auto msg = OpMsgBytes{0u}.done();
OpMsg::setFlag(&msg, flags);
ASSERT_EQ(OpMsg::flags(msg), flags) << flags;
}
{
auto msg = OpMsgBytes{~0u}.done();
OpMsg::setFlag(&msg, flags);
ASSERT_EQ(OpMsg::flags(msg), ~0u) << flags;
}
{
auto msg = OpMsgBytes{~flags}.done();
OpMsg::setFlag(&msg, flags);
ASSERT_EQ(OpMsg::flags(msg), ~0u) << flags;
}
}
}
TEST(OpMsgRequest, GetDatabaseWorks) {
OpMsgRequest msg;
msg.body = fromjson("{$db: 'foo'}");
ASSERT_EQ(msg.getDatabase(), "foo");
msg.body = fromjson("{before: 1, $db: 'foo'}");
ASSERT_EQ(msg.getDatabase(), "foo");
msg.body = fromjson("{before: 1, $db: 'foo', after: 1}");
ASSERT_EQ(msg.getDatabase(), "foo");
}
TEST(OpMsgRequest, GetDatabaseThrowsWrongType) {
OpMsgRequest msg;
msg.body = fromjson("{$db: 1}");
ASSERT_THROWS(msg.getDatabase(), DBException);
}
TEST(OpMsgRequest, GetDatabaseThrowsMissing) {
OpMsgRequest msg;
msg.body = fromjson("{}");
ASSERT_THROWS(msg.getDatabase(), AssertionException);
msg.body = fromjson("{$notdb: 'foo'}");
ASSERT_THROWS(msg.getDatabase(), AssertionException);
}
TEST(OpMsgRequest, FromDbAndBodyDoesNotCopy) {
auto body = fromjson("{ping: 1}");
const void* const bodyPtr = body.objdata();
auto msg = OpMsgRequest::fromDBAndBody("db", std::move(body));
ASSERT_BSONOBJ_EQ(msg.body, fromjson("{ping: 1, $db: 'db'}"));
ASSERT_EQ(static_cast<const void*>(msg.body.objdata()), bodyPtr);
}
} // namespace
} // namespace mongo
|