forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.py
1900 lines (1621 loc) · 59.7 KB
/
message.py
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2009-present MongoDB, Inc.
#
# 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tools for creating `messages
<https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/>`_ to be sent to
MongoDB.
.. note:: This module is for internal use and is generally not needed by
application developers.
"""
from __future__ import annotations
import datetime
import random
import struct
from io import BytesIO as _BytesIO
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
Mapping,
MutableMapping,
NoReturn,
Optional,
Union,
)
import bson
from bson import CodecOptions, _dict_to_bson, _make_c_string
from bson.int64 import Int64
from bson.raw_bson import (
_RAW_ARRAY_BSON_OPTIONS,
DEFAULT_RAW_BSON_OPTIONS,
RawBSONDocument,
_inflate_bson,
)
from pymongo.hello import HelloCompat
from pymongo.monitoring import _EventListeners
try:
from pymongo import _cmessage # type: ignore[attr-defined]
_use_c = True
except ImportError:
_use_c = False
from pymongo.errors import (
ConfigurationError,
CursorNotFound,
DocumentTooLarge,
ExecutionTimeout,
InvalidOperation,
NotPrimaryError,
OperationFailure,
ProtocolError,
)
from pymongo.read_preferences import ReadPreference, _ServerMode
if TYPE_CHECKING:
from pymongo.compression_support import SnappyContext, ZlibContext, ZstdContext
from pymongo.read_concern import ReadConcern
from pymongo.typings import (
_Address,
_AgnosticClientSession,
_AgnosticConnection,
_AgnosticMongoClient,
_DocumentOut,
)
MAX_INT32 = 2147483647
MIN_INT32 = -2147483648
# Overhead allowed for encoded command documents.
_COMMAND_OVERHEAD = 16382
_INSERT = 0
_UPDATE = 1
_DELETE = 2
_EMPTY = b""
_BSONOBJ = b"\x03"
_ZERO_8 = b"\x00"
_ZERO_16 = b"\x00\x00"
_ZERO_32 = b"\x00\x00\x00\x00"
_ZERO_64 = b"\x00\x00\x00\x00\x00\x00\x00\x00"
_SKIPLIM = b"\x00\x00\x00\x00\xff\xff\xff\xff"
_OP_MAP = {
_INSERT: b"\x04documents\x00\x00\x00\x00\x00",
_UPDATE: b"\x04updates\x00\x00\x00\x00\x00",
_DELETE: b"\x04deletes\x00\x00\x00\x00\x00",
}
_FIELD_MAP = {
"insert": "documents",
"update": "updates",
"delete": "deletes",
"bulkWrite": "ops",
}
_UNICODE_REPLACE_CODEC_OPTIONS: CodecOptions[Mapping[str, Any]] = CodecOptions(
unicode_decode_error_handler="replace"
)
def _randint() -> int:
"""Generate a pseudo random 32 bit integer."""
return random.randint(MIN_INT32, MAX_INT32) # noqa: S311
def _maybe_add_read_preference(
spec: MutableMapping[str, Any], read_preference: _ServerMode
) -> MutableMapping[str, Any]:
"""Add $readPreference to spec when appropriate."""
mode = read_preference.mode
document = read_preference.document
# Only add $readPreference if it's something other than primary to avoid
# problems with mongos versions that don't support read preferences. Also,
# for maximum backwards compatibility, don't add $readPreference for
# secondaryPreferred unless tags or maxStalenessSeconds are in use (setting
# the secondaryOkay bit has the same effect).
if mode and (mode != ReadPreference.SECONDARY_PREFERRED.mode or len(document) > 1):
if "$query" not in spec:
spec = {"$query": spec}
spec["$readPreference"] = document
return spec
def _convert_exception(exception: Exception) -> dict[str, Any]:
"""Convert an Exception into a failure document for publishing."""
return {"errmsg": str(exception), "errtype": exception.__class__.__name__}
def _convert_client_bulk_exception(exception: Exception) -> dict[str, Any]:
"""Convert an Exception into a failure document for publishing,
for use in client-level bulk write API.
"""
return {
"errmsg": str(exception),
"code": exception.code, # type: ignore[attr-defined]
"errtype": exception.__class__.__name__,
}
def _convert_write_result(
operation: str, command: Mapping[str, Any], result: Mapping[str, Any]
) -> dict[str, Any]:
"""Convert a legacy write result to write command format."""
# Based on _merge_legacy from bulk.py
affected = result.get("n", 0)
res = {"ok": 1, "n": affected}
errmsg = result.get("errmsg", result.get("err", ""))
if errmsg:
# The write was successful on at least the primary so don't return.
if result.get("wtimeout"):
res["writeConcernError"] = {"errmsg": errmsg, "code": 64, "errInfo": {"wtimeout": True}}
else:
# The write failed.
error = {"index": 0, "code": result.get("code", 8), "errmsg": errmsg}
if "errInfo" in result:
error["errInfo"] = result["errInfo"]
res["writeErrors"] = [error]
return res
if operation == "insert":
# GLE result for insert is always 0 in most MongoDB versions.
res["n"] = len(command["documents"])
elif operation == "update":
if "upserted" in result:
res["upserted"] = [{"index": 0, "_id": result["upserted"]}]
# Versions of MongoDB before 2.6 don't return the _id for an
# upsert if _id is not an ObjectId.
elif result.get("updatedExisting") is False and affected == 1:
# If _id is in both the update document *and* the query spec
# the update document _id takes precedence.
update = command["updates"][0]
_id = update["u"].get("_id", update["q"].get("_id"))
res["upserted"] = [{"index": 0, "_id": _id}]
return res
_OPTIONS = {
"tailable": 2,
"oplogReplay": 8,
"noCursorTimeout": 16,
"awaitData": 32,
"allowPartialResults": 128,
}
_MODIFIERS = {
"$query": "filter",
"$orderby": "sort",
"$hint": "hint",
"$comment": "comment",
"$maxScan": "maxScan",
"$maxTimeMS": "maxTimeMS",
"$max": "max",
"$min": "min",
"$returnKey": "returnKey",
"$showRecordId": "showRecordId",
"$showDiskLoc": "showRecordId", # <= MongoDb 3.0
"$snapshot": "snapshot",
}
def _gen_find_command(
coll: str,
spec: Mapping[str, Any],
projection: Optional[Union[Mapping[str, Any], Iterable[str]]],
skip: int,
limit: int,
batch_size: Optional[int],
options: Optional[int],
read_concern: ReadConcern,
collation: Optional[Mapping[str, Any]] = None,
session: Optional[_AgnosticClientSession] = None,
allow_disk_use: Optional[bool] = None,
) -> dict[str, Any]:
"""Generate a find command document."""
cmd: dict[str, Any] = {"find": coll}
if "$query" in spec:
cmd.update(
[
(_MODIFIERS[key], val) if key in _MODIFIERS else (key, val)
for key, val in spec.items()
]
)
if "$explain" in cmd:
cmd.pop("$explain")
if "$readPreference" in cmd:
cmd.pop("$readPreference")
else:
cmd["filter"] = spec
if projection:
cmd["projection"] = projection
if skip:
cmd["skip"] = skip
if limit:
cmd["limit"] = abs(limit)
if limit < 0:
cmd["singleBatch"] = True
if batch_size:
# When limit and batchSize are equal we increase batchSize by 1 to
# avoid an unnecessary killCursors.
if limit == batch_size:
batch_size += 1
cmd["batchSize"] = batch_size
if read_concern.level and not (session and session.in_transaction):
cmd["readConcern"] = read_concern.document
if collation:
cmd["collation"] = collation
if allow_disk_use is not None:
cmd["allowDiskUse"] = allow_disk_use
if options:
cmd.update([(opt, True) for opt, val in _OPTIONS.items() if options & val])
return cmd
def _gen_get_more_command(
cursor_id: Optional[int],
coll: str,
batch_size: Optional[int],
max_await_time_ms: Optional[int],
comment: Optional[Any],
conn: _AgnosticConnection,
) -> dict[str, Any]:
"""Generate a getMore command document."""
cmd: dict[str, Any] = {"getMore": cursor_id, "collection": coll}
if batch_size:
cmd["batchSize"] = batch_size
if max_await_time_ms is not None:
cmd["maxTimeMS"] = max_await_time_ms
if comment is not None and conn.max_wire_version >= 9:
cmd["comment"] = comment
return cmd
_pack_compression_header = struct.Struct("<iiiiiiB").pack
_COMPRESSION_HEADER_SIZE = 25
def _compress(
operation: int, data: bytes, ctx: Union[SnappyContext, ZlibContext, ZstdContext]
) -> tuple[int, bytes]:
"""Takes message data, compresses it, and adds an OP_COMPRESSED header."""
compressed = ctx.compress(data)
request_id = _randint()
header = _pack_compression_header(
_COMPRESSION_HEADER_SIZE + len(compressed), # Total message length
request_id, # Request id
0, # responseTo
2012, # operation id
operation, # original operation id
len(data), # uncompressed message length
ctx.compressor_id,
) # compressor id
return request_id, header + compressed
_pack_header = struct.Struct("<iiii").pack
def __pack_message(operation: int, data: bytes) -> tuple[int, bytes]:
"""Takes message data and adds a message header based on the operation.
Returns the resultant message string.
"""
rid = _randint()
message = _pack_header(16 + len(data), rid, 0, operation)
return rid, message + data
_pack_int = struct.Struct("<i").pack
_pack_op_msg_flags_type = struct.Struct("<IB").pack
_pack_byte = struct.Struct("<B").pack
def _op_msg_no_header(
flags: int,
command: Mapping[str, Any],
identifier: str,
docs: Optional[list[Mapping[str, Any]]],
opts: CodecOptions,
) -> tuple[bytes, int, int]:
"""Get a OP_MSG message.
Note: this method handles multiple documents in a type one payload but
it does not perform batch splitting and the total message size is
only checked *after* generating the entire message.
"""
# Encode the command document in payload 0 without checking keys.
encoded = _dict_to_bson(command, False, opts)
flags_type = _pack_op_msg_flags_type(flags, 0)
total_size = len(encoded)
max_doc_size = 0
if identifier and docs is not None:
type_one = _pack_byte(1)
cstring = _make_c_string(identifier)
encoded_docs = [_dict_to_bson(doc, False, opts) for doc in docs]
size = len(cstring) + sum(len(doc) for doc in encoded_docs) + 4
encoded_size = _pack_int(size)
total_size += size
max_doc_size = max(len(doc) for doc in encoded_docs)
data = [flags_type, encoded, type_one, encoded_size, cstring, *encoded_docs]
else:
data = [flags_type, encoded]
return b"".join(data), total_size, max_doc_size
def _op_msg_compressed(
flags: int,
command: Mapping[str, Any],
identifier: str,
docs: Optional[list[Mapping[str, Any]]],
opts: CodecOptions,
ctx: Union[SnappyContext, ZlibContext, ZstdContext],
) -> tuple[int, bytes, int, int]:
"""Internal OP_MSG message helper."""
msg, total_size, max_bson_size = _op_msg_no_header(flags, command, identifier, docs, opts)
rid, msg = _compress(2013, msg, ctx)
return rid, msg, total_size, max_bson_size
def _op_msg_uncompressed(
flags: int,
command: Mapping[str, Any],
identifier: str,
docs: Optional[list[Mapping[str, Any]]],
opts: CodecOptions,
) -> tuple[int, bytes, int, int]:
"""Internal compressed OP_MSG message helper."""
data, total_size, max_bson_size = _op_msg_no_header(flags, command, identifier, docs, opts)
request_id, op_message = __pack_message(2013, data)
return request_id, op_message, total_size, max_bson_size
if _use_c:
_op_msg_uncompressed = _cmessage._op_msg
def _op_msg(
flags: int,
command: MutableMapping[str, Any],
dbname: str,
read_preference: Optional[_ServerMode],
opts: CodecOptions,
ctx: Union[SnappyContext, ZlibContext, ZstdContext, None] = None,
) -> tuple[int, bytes, int, int]:
"""Get a OP_MSG message."""
command["$db"] = dbname
# getMore commands do not send $readPreference.
if read_preference is not None and "$readPreference" not in command:
# Only send $readPreference if it's not primary (the default).
if read_preference.mode:
command["$readPreference"] = read_preference.document
name = next(iter(command))
try:
identifier = _FIELD_MAP[name]
docs = command.pop(identifier)
except KeyError:
identifier = ""
docs = None
try:
if ctx:
return _op_msg_compressed(flags, command, identifier, docs, opts, ctx)
return _op_msg_uncompressed(flags, command, identifier, docs, opts)
finally:
# Add the field back to the command.
if identifier:
command[identifier] = docs
def _query_impl(
options: int,
collection_name: str,
num_to_skip: int,
num_to_return: int,
query: Mapping[str, Any],
field_selector: Optional[Mapping[str, Any]],
opts: CodecOptions,
) -> tuple[bytes, int]:
"""Get an OP_QUERY message."""
encoded = _dict_to_bson(query, False, opts)
if field_selector:
efs = _dict_to_bson(field_selector, False, opts)
else:
efs = b""
max_bson_size = max(len(encoded), len(efs))
return (
b"".join(
[
_pack_int(options),
bson._make_c_string(collection_name),
_pack_int(num_to_skip),
_pack_int(num_to_return),
encoded,
efs,
]
),
max_bson_size,
)
def _query_compressed(
options: int,
collection_name: str,
num_to_skip: int,
num_to_return: int,
query: Mapping[str, Any],
field_selector: Optional[Mapping[str, Any]],
opts: CodecOptions,
ctx: Union[SnappyContext, ZlibContext, ZstdContext],
) -> tuple[int, bytes, int]:
"""Internal compressed query message helper."""
op_query, max_bson_size = _query_impl(
options, collection_name, num_to_skip, num_to_return, query, field_selector, opts
)
rid, msg = _compress(2004, op_query, ctx)
return rid, msg, max_bson_size
def _query_uncompressed(
options: int,
collection_name: str,
num_to_skip: int,
num_to_return: int,
query: Mapping[str, Any],
field_selector: Optional[Mapping[str, Any]],
opts: CodecOptions,
) -> tuple[int, bytes, int]:
"""Internal query message helper."""
op_query, max_bson_size = _query_impl(
options, collection_name, num_to_skip, num_to_return, query, field_selector, opts
)
rid, msg = __pack_message(2004, op_query)
return rid, msg, max_bson_size
if _use_c:
_query_uncompressed = _cmessage._query_message
def _query(
options: int,
collection_name: str,
num_to_skip: int,
num_to_return: int,
query: Mapping[str, Any],
field_selector: Optional[Mapping[str, Any]],
opts: CodecOptions,
ctx: Union[SnappyContext, ZlibContext, ZstdContext, None] = None,
) -> tuple[int, bytes, int]:
"""Get a **query** message."""
if ctx:
return _query_compressed(
options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, ctx
)
return _query_uncompressed(
options, collection_name, num_to_skip, num_to_return, query, field_selector, opts
)
_pack_long_long = struct.Struct("<q").pack
def _get_more_impl(collection_name: str, num_to_return: int, cursor_id: int) -> bytes:
"""Get an OP_GET_MORE message."""
return b"".join(
[
_ZERO_32,
bson._make_c_string(collection_name),
_pack_int(num_to_return),
_pack_long_long(cursor_id),
]
)
def _get_more_compressed(
collection_name: str,
num_to_return: int,
cursor_id: int,
ctx: Union[SnappyContext, ZlibContext, ZstdContext],
) -> tuple[int, bytes]:
"""Internal compressed getMore message helper."""
return _compress(2005, _get_more_impl(collection_name, num_to_return, cursor_id), ctx)
def _get_more_uncompressed(
collection_name: str, num_to_return: int, cursor_id: int
) -> tuple[int, bytes]:
"""Internal getMore message helper."""
return __pack_message(2005, _get_more_impl(collection_name, num_to_return, cursor_id))
if _use_c:
_get_more_uncompressed = _cmessage._get_more_message
def _get_more(
collection_name: str,
num_to_return: int,
cursor_id: int,
ctx: Union[SnappyContext, ZlibContext, ZstdContext, None] = None,
) -> tuple[int, bytes]:
"""Get a **getMore** message."""
if ctx:
return _get_more_compressed(collection_name, num_to_return, cursor_id, ctx)
return _get_more_uncompressed(collection_name, num_to_return, cursor_id)
# OP_MSG -------------------------------------------------------------
_OP_MSG_MAP = {
_INSERT: b"documents\x00",
_UPDATE: b"updates\x00",
_DELETE: b"deletes\x00",
}
class _BulkWriteContextBase:
"""Private base class for wrapping around AsyncConnection to use with write splitting functions."""
__slots__ = (
"db_name",
"conn",
"op_id",
"name",
"field",
"publish",
"start_time",
"listeners",
"session",
"compress",
"op_type",
"codec",
)
def __init__(
self,
database_name: str,
cmd_name: str,
conn: _AgnosticConnection,
operation_id: int,
listeners: _EventListeners,
session: Optional[_AgnosticClientSession],
op_type: int,
codec: CodecOptions,
):
self.db_name = database_name
self.conn = conn
self.op_id = operation_id
self.listeners = listeners
self.publish = listeners.enabled_for_commands
self.name = cmd_name
self.field = _FIELD_MAP[self.name]
self.start_time = datetime.datetime.now()
self.session = session
self.compress = bool(conn.compression_context)
self.op_type = op_type
self.codec = codec
@property
def max_bson_size(self) -> int:
"""A proxy for SockInfo.max_bson_size."""
return self.conn.max_bson_size
@property
def max_message_size(self) -> int:
"""A proxy for SockInfo.max_message_size."""
if self.compress:
# Subtract 16 bytes for the message header.
return self.conn.max_message_size - 16
return self.conn.max_message_size
@property
def max_write_batch_size(self) -> int:
"""A proxy for SockInfo.max_write_batch_size."""
return self.conn.max_write_batch_size
@property
def max_split_size(self) -> int:
"""The maximum size of a BSON command before batch splitting."""
return self.max_bson_size
def _succeed(self, request_id: int, reply: _DocumentOut, duration: datetime.timedelta) -> None:
"""Publish a CommandSucceededEvent."""
self.listeners.publish_command_success(
duration,
reply,
self.name,
request_id,
self.conn.address,
self.conn.server_connection_id,
self.op_id,
self.conn.service_id,
database_name=self.db_name,
)
def _fail(self, request_id: int, failure: _DocumentOut, duration: datetime.timedelta) -> None:
"""Publish a CommandFailedEvent."""
self.listeners.publish_command_failure(
duration,
failure,
self.name,
request_id,
self.conn.address,
self.conn.server_connection_id,
self.op_id,
self.conn.service_id,
database_name=self.db_name,
)
class _BulkWriteContext(_BulkWriteContextBase):
"""A wrapper around AsyncConnection/Connection for use with the collection-level bulk write API."""
__slots__ = ()
def __init__(
self,
database_name: str,
cmd_name: str,
conn: _AgnosticConnection,
operation_id: int,
listeners: _EventListeners,
session: Optional[_AgnosticClientSession],
op_type: int,
codec: CodecOptions,
):
super().__init__(
database_name,
cmd_name,
conn,
operation_id,
listeners,
session,
op_type,
codec,
)
def batch_command(
self, cmd: MutableMapping[str, Any], docs: list[Mapping[str, Any]]
) -> tuple[int, Union[bytes, dict[str, Any]], list[Mapping[str, Any]]]:
namespace = self.db_name + ".$cmd"
request_id, msg, to_send = _do_batched_op_msg(
namespace, self.op_type, cmd, docs, self.codec, self
)
if not to_send:
raise InvalidOperation("cannot do an empty bulk write")
return request_id, msg, to_send
def _start(
self, cmd: MutableMapping[str, Any], request_id: int, docs: list[Mapping[str, Any]]
) -> MutableMapping[str, Any]:
"""Publish a CommandStartedEvent."""
cmd[self.field] = docs
self.listeners.publish_command_start(
cmd,
self.db_name,
request_id,
self.conn.address,
self.conn.server_connection_id,
self.op_id,
self.conn.service_id,
)
return cmd
class _EncryptedBulkWriteContext(_BulkWriteContext):
__slots__ = ()
def batch_command(
self, cmd: MutableMapping[str, Any], docs: list[Mapping[str, Any]]
) -> tuple[int, dict[str, Any], list[Mapping[str, Any]]]:
namespace = self.db_name + ".$cmd"
msg, to_send = _encode_batched_write_command(
namespace, self.op_type, cmd, docs, self.codec, self
)
if not to_send:
raise InvalidOperation("cannot do an empty bulk write")
# Chop off the OP_QUERY header to get a properly batched write command.
cmd_start = msg.index(b"\x00", 4) + 9
outgoing = _inflate_bson(memoryview(msg)[cmd_start:], DEFAULT_RAW_BSON_OPTIONS)
return -1, outgoing, to_send
@property
def max_split_size(self) -> int:
"""Reduce the batch splitting size."""
return _MAX_SPLIT_SIZE_ENC
def _raise_document_too_large(operation: str, doc_size: int, max_size: int) -> NoReturn:
"""Internal helper for raising DocumentTooLarge."""
if operation == "insert":
raise DocumentTooLarge(
"BSON document too large (%d bytes)"
" - the connected server supports"
" BSON document sizes up to %d"
" bytes." % (doc_size, max_size)
)
else:
# There's nothing intelligent we can say
# about size for update and delete
raise DocumentTooLarge(f"{operation!r} command document too large")
# From the Client Side Encryption spec:
# Because automatic encryption increases the size of commands, the driver
# MUST split bulk writes at a reduced size limit before undergoing automatic
# encryption. The write payload MUST be split at 2MiB (2097152).
_MAX_SPLIT_SIZE_ENC = 2097152
def _batched_op_msg_impl(
operation: int,
command: Mapping[str, Any],
docs: list[Mapping[str, Any]],
ack: bool,
opts: CodecOptions,
ctx: _BulkWriteContext,
buf: _BytesIO,
) -> tuple[list[Mapping[str, Any]], int]:
"""Create a batched OP_MSG write."""
max_bson_size = ctx.max_bson_size
max_write_batch_size = ctx.max_write_batch_size
max_message_size = ctx.max_message_size
flags = b"\x00\x00\x00\x00" if ack else b"\x02\x00\x00\x00"
# Flags
buf.write(flags)
# Type 0 Section
buf.write(b"\x00")
buf.write(_dict_to_bson(command, False, opts))
# Type 1 Section
buf.write(b"\x01")
size_location = buf.tell()
# Save space for size
buf.write(b"\x00\x00\x00\x00")
try:
buf.write(_OP_MSG_MAP[operation])
except KeyError:
raise InvalidOperation("Unknown command") from None
to_send = []
idx = 0
for doc in docs:
# Encode the current operation
value = _dict_to_bson(doc, False, opts)
doc_length = len(value)
new_message_size = buf.tell() + doc_length
# Does first document exceed max_message_size?
doc_too_large = idx == 0 and (new_message_size > max_message_size)
# When OP_MSG is used unacknowledged we have to check
# document size client side or applications won't be notified.
# Otherwise we let the server deal with documents that are too large
# since ordered=False causes those documents to be skipped instead of
# halting the bulk write operation.
unacked_doc_too_large = not ack and (doc_length > max_bson_size)
if doc_too_large or unacked_doc_too_large:
write_op = list(_FIELD_MAP.keys())[operation]
_raise_document_too_large(write_op, len(value), max_bson_size)
# We have enough data, return this batch.
if new_message_size > max_message_size:
break
buf.write(value)
to_send.append(doc)
idx += 1
# We have enough documents, return this batch.
if idx == max_write_batch_size:
break
# Write type 1 section size
length = buf.tell()
buf.seek(size_location)
buf.write(_pack_int(length - size_location))
return to_send, length
def _encode_batched_op_msg(
operation: int,
command: Mapping[str, Any],
docs: list[Mapping[str, Any]],
ack: bool,
opts: CodecOptions,
ctx: _BulkWriteContext,
) -> tuple[bytes, list[Mapping[str, Any]]]:
"""Encode the next batched insert, update, or delete operation
as OP_MSG.
"""
buf = _BytesIO()
to_send, _ = _batched_op_msg_impl(operation, command, docs, ack, opts, ctx, buf)
return buf.getvalue(), to_send
if _use_c:
_encode_batched_op_msg = _cmessage._encode_batched_op_msg
def _batched_op_msg_compressed(
operation: int,
command: Mapping[str, Any],
docs: list[Mapping[str, Any]],
ack: bool,
opts: CodecOptions,
ctx: _BulkWriteContext,
) -> tuple[int, bytes, list[Mapping[str, Any]]]:
"""Create the next batched insert, update, or delete operation
with OP_MSG, compressed.
"""
data, to_send = _encode_batched_op_msg(operation, command, docs, ack, opts, ctx)
assert ctx.conn.compression_context is not None
request_id, msg = _compress(2013, data, ctx.conn.compression_context)
return request_id, msg, to_send
def _batched_op_msg(
operation: int,
command: Mapping[str, Any],
docs: list[Mapping[str, Any]],
ack: bool,
opts: CodecOptions,
ctx: _BulkWriteContext,
) -> tuple[int, bytes, list[Mapping[str, Any]]]:
"""OP_MSG implementation entry point."""
buf = _BytesIO()
# Save space for message length and request id
buf.write(_ZERO_64)
# responseTo, opCode
buf.write(b"\x00\x00\x00\x00\xdd\x07\x00\x00")
to_send, length = _batched_op_msg_impl(operation, command, docs, ack, opts, ctx, buf)
# Header - request id and message length
buf.seek(4)
request_id = _randint()
buf.write(_pack_int(request_id))
buf.seek(0)
buf.write(_pack_int(length))
return request_id, buf.getvalue(), to_send
if _use_c:
_batched_op_msg = _cmessage._batched_op_msg
def _do_batched_op_msg(
namespace: str,
operation: int,
command: MutableMapping[str, Any],
docs: list[Mapping[str, Any]],
opts: CodecOptions,
ctx: _BulkWriteContext,
) -> tuple[int, bytes, list[Mapping[str, Any]]]:
"""Create the next batched insert, update, or delete operation
using OP_MSG.
"""
command["$db"] = namespace.split(".", 1)[0]
if "writeConcern" in command:
ack = bool(command["writeConcern"].get("w", 1))
else:
ack = True
if ctx.conn.compression_context:
return _batched_op_msg_compressed(operation, command, docs, ack, opts, ctx)
return _batched_op_msg(operation, command, docs, ack, opts, ctx)
class _ClientBulkWriteContext(_BulkWriteContextBase):
"""A wrapper around AsyncConnection/Connection for use with the client-level bulk write API."""
__slots__ = ()
def __init__(
self,
database_name: str,
cmd_name: str,
conn: _AgnosticConnection,
operation_id: int,
listeners: _EventListeners,
session: Optional[_AgnosticClientSession],
codec: CodecOptions,
):
super().__init__(
database_name,
cmd_name,
conn,
operation_id,
listeners,
session,
0,
codec,
)
def batch_command(
self,
cmd: MutableMapping[str, Any],
operations: list[tuple[str, Mapping[str, Any]]],
namespaces: list[str],
) -> tuple[int, Union[bytes, dict[str, Any]], list[Mapping[str, Any]], list[Mapping[str, Any]]]:
request_id, msg, to_send_ops, to_send_ns = _client_do_batched_op_msg(
cmd, operations, namespaces, self.codec, self
)
if not to_send_ops:
raise InvalidOperation("cannot do an empty bulk write")
return request_id, msg, to_send_ops, to_send_ns
def _start(
self,
cmd: MutableMapping[str, Any],
request_id: int,
op_docs: list[Mapping[str, Any]],
ns_docs: list[Mapping[str, Any]],
) -> MutableMapping[str, Any]:
"""Publish a CommandStartedEvent."""
cmd["ops"] = op_docs
cmd["nsInfo"] = ns_docs
self.listeners.publish_command_start(
cmd,
self.db_name,
request_id,
self.conn.address,
self.conn.server_connection_id,
self.op_id,
self.conn.service_id,
)
return cmd
_OP_MSG_OVERHEAD = 1000
def _client_construct_op_msg(
command_encoded: bytes,
to_send_ops_encoded: list[bytes],
to_send_ns_encoded: list[bytes],
ack: bool,
buf: _BytesIO,
) -> int:
# Write flags