1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package com.allanbank.mongodb.builder;
22
23 import java.io.Serializable;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.LinkedHashMap;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.SortedMap;
31 import java.util.TreeMap;
32
33 import com.allanbank.mongodb.BatchedAsyncMongoCollection;
34 import com.allanbank.mongodb.Durability;
35 import com.allanbank.mongodb.MongoCollection;
36 import com.allanbank.mongodb.Version;
37 import com.allanbank.mongodb.bson.Document;
38 import com.allanbank.mongodb.bson.DocumentAssignable;
39 import com.allanbank.mongodb.bson.Element;
40 import com.allanbank.mongodb.bson.builder.ArrayBuilder;
41 import com.allanbank.mongodb.bson.builder.BuilderFactory;
42 import com.allanbank.mongodb.bson.builder.DocumentBuilder;
43 import com.allanbank.mongodb.bson.impl.EmptyDocument;
44 import com.allanbank.mongodb.builder.write.DeleteOperation;
45 import com.allanbank.mongodb.builder.write.InsertOperation;
46 import com.allanbank.mongodb.builder.write.UpdateOperation;
47 import com.allanbank.mongodb.builder.write.WriteOperation;
48 import com.allanbank.mongodb.builder.write.WriteOperationType;
49 import com.allanbank.mongodb.error.DocumentToLargeException;
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 public class BatchedWrite implements Serializable {
92
93
94 public static final Version REQUIRED_VERSION = Version.parse("2.5.5");
95
96
97 private static final long serialVersionUID = 6984498574755719178L;
98
99
100
101
102
103
104 public static Builder builder() {
105 return new Builder();
106 }
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126 public static BatchedWrite delete(final DocumentAssignable query,
127 final boolean singleDelete, final Durability durability) {
128 final DeleteOperation op = new DeleteOperation(query, singleDelete);
129 return new BatchedWrite(op, BatchedWriteMode.SERIALIZE_AND_CONTINUE,
130 durability);
131 }
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150 public static BatchedWrite insert(final boolean continueOnError,
151 final Durability durability, final DocumentAssignable... documents) {
152 final List<WriteOperation> ops = new ArrayList<WriteOperation>(
153 documents.length);
154 for (final DocumentAssignable doc : documents) {
155 ops.add(new InsertOperation(doc));
156 }
157 return new BatchedWrite(ops,
158 continueOnError ? BatchedWriteMode.SERIALIZE_AND_CONTINUE
159 : BatchedWriteMode.SERIALIZE_AND_STOP, durability);
160 }
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179 public static BatchedWrite update(final DocumentAssignable query,
180 final DocumentAssignable update, final boolean multiUpdate,
181 final boolean upsert, final Durability durability) {
182 final UpdateOperation op = new UpdateOperation(query, update,
183 multiUpdate, upsert);
184 return new BatchedWrite(op, BatchedWriteMode.SERIALIZE_AND_CONTINUE,
185 durability);
186 }
187
188
189 private final Durability myDurability;
190
191
192 private final BatchedWriteMode myMode;
193
194
195 private final List<WriteOperation> myWrites;
196
197
198
199
200
201
202
203 protected BatchedWrite(final Builder builder) {
204 myWrites = Collections.unmodifiableList(new ArrayList<WriteOperation>(
205 builder.myWrites));
206 myMode = builder.myMode;
207 myDurability = builder.myDurability;
208 }
209
210
211
212
213
214
215
216
217
218
219
220 private BatchedWrite(final List<WriteOperation> ops,
221 final BatchedWriteMode mode, final Durability durability) {
222 myWrites = Collections.unmodifiableList(ops);
223 myMode = mode;
224 myDurability = durability;
225 }
226
227
228
229
230
231
232
233
234
235
236
237 private BatchedWrite(final WriteOperation op, final BatchedWriteMode mode,
238 final Durability durability) {
239 this(Collections.singletonList(op), mode, durability);
240 }
241
242
243
244
245
246
247 public Durability getDurability() {
248 return myDurability;
249 }
250
251
252
253
254
255
256 public BatchedWriteMode getMode() {
257 return myMode;
258 }
259
260
261
262
263
264
265 public List<WriteOperation> getWrites() {
266 return myWrites;
267 }
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282 public List<Bundle> toBundles(final String collectionName,
283 final long maxCommandSize, final int maxOperationsPerBundle) {
284 switch (getMode()) {
285 case REORDERED: {
286 return createOptimized(collectionName, maxCommandSize,
287 maxOperationsPerBundle);
288 }
289 case SERIALIZE_AND_CONTINUE: {
290 return createSerialized(collectionName, maxCommandSize,
291 maxOperationsPerBundle, false);
292 }
293 default: {
294 return createSerialized(collectionName, maxCommandSize,
295 maxOperationsPerBundle, true);
296 }
297 }
298 }
299
300
301
302
303
304
305
306
307
308 private void add(final ArrayBuilder array, final WriteOperation operation) {
309 switch (operation.getType()) {
310 case INSERT: {
311 final InsertOperation insertOperation = (InsertOperation) operation;
312
313 array.add(insertOperation.getDocument());
314 break;
315 }
316 case UPDATE: {
317 final UpdateOperation updateOperation = (UpdateOperation) operation;
318 final DocumentBuilder update = array.push();
319
320 update.add("q", updateOperation.getQuery());
321 update.add("u", updateOperation.getUpdate());
322 if (updateOperation.isUpsert()) {
323 update.add("upsert", true);
324 }
325 if (updateOperation.isMultiUpdate()) {
326 update.add("multi", true);
327 }
328 break;
329 }
330 case DELETE: {
331 final DeleteOperation deleteOperation = (DeleteOperation) operation;
332 array.push().add("q", deleteOperation.getQuery())
333 .add("limit", deleteOperation.isSingleDelete() ? 1 : 0);
334 break;
335 }
336 }
337 }
338
339
340
341
342
343
344
345
346
347 private void addDurability(final DocumentBuilder command,
348 final Durability durability) {
349 if (durability != null) {
350 final DocumentBuilder durabilityDoc = command.push("writeConcern");
351 if (durability.equals(Durability.NONE)) {
352 durabilityDoc.add("w", 0);
353 }
354 else if (durability.equals(Durability.ACK)) {
355 durabilityDoc.add("w", 1);
356 }
357 else {
358 boolean first = true;
359 for (final Element part : durability.asDocument()) {
360 if (first) {
361
362 first = false;
363 }
364 else {
365 durabilityDoc.add(part);
366 }
367 }
368 }
369 }
370 }
371
372
373
374
375
376
377
378
379
380
381
382
383 private DocumentToLargeException createDocumentToLargeException(
384 final WriteOperation operation, final int size,
385 final int maxCommandSize) {
386
387 Document doc = EmptyDocument.INSTANCE;
388
389 switch (operation.getType()) {
390 case INSERT: {
391 final InsertOperation insertOperation = (InsertOperation) operation;
392 doc = insertOperation.getDocument();
393 break;
394 }
395 case UPDATE: {
396 final UpdateOperation updateOperation = (UpdateOperation) operation;
397 doc = updateOperation.getQuery();
398 final Document update = updateOperation.getUpdate();
399 if (doc.size() < update.size()) {
400 doc = update;
401 }
402 break;
403 }
404 case DELETE: {
405 final DeleteOperation deleteOperation = (DeleteOperation) operation;
406 doc = deleteOperation.getQuery();
407 break;
408 }
409 }
410
411 return new DocumentToLargeException(size, maxCommandSize, doc);
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 private List<Bundle> createOptimized(final String collectionName,
438 final long maxCommandSize, final int maxOperationsPerBundle) {
439
440 Map<WriteOperationType, SortedMap<Long, List<WriteOperation>>> operationsBuckets;
441 operationsBuckets = new LinkedHashMap<WriteOperationType, SortedMap<Long, List<WriteOperation>>>();
442 for (final WriteOperation writeOp : getWrites()) {
443 SortedMap<Long, List<WriteOperation>> operations = operationsBuckets
444 .get(writeOp.getType());
445 if (operations == null) {
446 operations = new TreeMap<Long, List<WriteOperation>>();
447 operationsBuckets.put(writeOp.getType(), operations);
448 }
449
450 final Long size = Long.valueOf(sizeOf(-1, writeOp));
451 List<WriteOperation> list = operations.get(size);
452 if (list == null) {
453 list = new LinkedList<WriteOperation>();
454 operations.put(size, list);
455 }
456 list.add(writeOp);
457 }
458
459
460 final Long maxMessageSize = Long.valueOf(maxCommandSize + 1);
461 for (final SortedMap<Long, List<WriteOperation>> operations : operationsBuckets
462 .values()) {
463 if (!operations.tailMap(maxMessageSize).isEmpty()) {
464 final Long biggest = operations.lastKey();
465 final List<WriteOperation> operation = operations.get(biggest);
466 throw createDocumentToLargeException(operation.get(0),
467 biggest.intValue(), (int) maxCommandSize);
468 }
469 }
470
471
472
473 final List<Bundle> commands = new ArrayList<Bundle>();
474 final List<WriteOperation> bundled = new ArrayList<WriteOperation>(
475 Math.min(maxOperationsPerBundle, myWrites.size()));
476 final DocumentBuilder command = BuilderFactory.start();
477 for (final Map.Entry<WriteOperationType, SortedMap<Long, List<WriteOperation>>> entry : operationsBuckets
478 .entrySet()) {
479 final SortedMap<Long, List<WriteOperation>> operations = entry
480 .getValue();
481 while (!operations.isEmpty()) {
482 final ArrayBuilder docs = start(entry.getKey(), collectionName,
483 false, command);
484 long remaining = maxCommandSize - command.build().size();
485
486 SortedMap<Long, List<WriteOperation>> head = operations;
487 int index = 0;
488 while (!head.isEmpty()
489 && (bundled.size() < maxOperationsPerBundle)) {
490 final Long biggest = head.lastKey();
491 final List<WriteOperation> bigOps = head.get(biggest);
492 final WriteOperation operation = bigOps.remove(0);
493 if (bigOps.isEmpty()) {
494 head.remove(biggest);
495 }
496
497 add(docs, operation);
498 bundled.add(operation);
499
500 remaining -= sizeOf(index, operation);
501 index += 1;
502 head = operations.headMap(Long.valueOf(remaining
503 - sizeOfIndex(index)));
504 }
505
506 commands.add(new Bundle(command.build(), bundled));
507 bundled.clear();
508 }
509 }
510
511 return commands;
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 private List<Bundle> createSerialized(final String collectionName,
539 final long maxCommandSize, final int maxOperationsPerBundle,
540 final boolean stopOnError) {
541 final List<Bundle> commands = new ArrayList<Bundle>();
542 final DocumentBuilder command = BuilderFactory.start();
543
544 final List<WriteOperation> toSend = getWrites();
545 final List<WriteOperation> bundled = new ArrayList<WriteOperation>(
546 Math.min(maxOperationsPerBundle, myWrites.size()));
547
548 ArrayBuilder opsArray = null;
549 WriteOperationType lastType = null;
550
551 long remaining = maxCommandSize;
552 for (final WriteOperation writeOp : toSend) {
553 long size = sizeOf(-1, writeOp);
554 final long indexSize = sizeOfIndex(bundled.size());
555 if (maxCommandSize < size) {
556 throw createDocumentToLargeException(writeOp, (int) size,
557 (int) maxCommandSize);
558 }
559 size += indexSize;
560
561
562 if (!bundled.isEmpty()
563 && ((lastType != writeOp.getType())
564 || ((remaining - size) < 0) || (maxOperationsPerBundle <= bundled
565 .size()))) {
566 commands.add(new Bundle(command.build(), bundled));
567 bundled.clear();
568 }
569
570
571 if (bundled.isEmpty()) {
572 opsArray = start(writeOp.getType(), collectionName,
573 stopOnError, command);
574 lastType = writeOp.getType();
575 remaining = (maxCommandSize - command.build().size());
576 }
577
578
579 add(opsArray, writeOp);
580 bundled.add(writeOp);
581
582
583 remaining -= size;
584 }
585
586 if (!bundled.isEmpty()) {
587 commands.add(new Bundle(command.build(), bundled));
588 }
589
590 return commands;
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 private long sizeOf(final int index, final WriteOperation operation) {
631 long result = 0;
632 switch (operation.getType()) {
633 case INSERT: {
634 final InsertOperation insertOperation = (InsertOperation) operation;
635 result = sizeOfIndex(index) + insertOperation.getDocument().size();
636 break;
637 }
638 case UPDATE: {
639 final UpdateOperation updateOperation = (UpdateOperation) operation;
640 result = sizeOfIndex(index) + updateOperation.getQuery().size()
641 + updateOperation.getUpdate().size() + 29;
642 break;
643 }
644 case DELETE: {
645 final DeleteOperation deleteOperation = (DeleteOperation) operation;
646 result = sizeOfIndex(index) + deleteOperation.getQuery().size()
647 + 20;
648 break;
649 }
650 }
651
652 return result;
653 }
654
655
656
657
658
659
660
661
662
663 private long sizeOfIndex(final int index) {
664
665
666
667 if (index < 0) {
668 return 0;
669 }
670 else if (index < 10) {
671 return 3;
672 }
673 else if (index < 100) {
674 return 4;
675 }
676 else if (index < 1000) {
677 return 5;
678 }
679 else if (index < 10000) {
680 return 6;
681 }
682
683 return Integer.toString(index).length() + 2;
684 }
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701 private ArrayBuilder start(final WriteOperationType operation,
702 final String collectionName, final boolean stopOnError,
703 final DocumentBuilder command) {
704
705 String commandName = "";
706 String arrayName = "";
707 switch (operation) {
708 case INSERT: {
709 commandName = "insert";
710 arrayName = "documents";
711 break;
712 }
713 case UPDATE: {
714 commandName = "update";
715 arrayName = "updates";
716 break;
717 }
718 case DELETE: {
719 commandName = "delete";
720 arrayName = "deletes";
721 break;
722 }
723 }
724
725 command.reset();
726 command.add(commandName, collectionName);
727 if (!stopOnError) {
728 command.add("ordered", stopOnError);
729 }
730 addDurability(command, getDurability());
731
732 return command.pushArray(arrayName);
733 }
734
735
736
737
738
739
740
741
742
743
744 public static class Builder {
745
746
747 protected Durability myDurability;
748
749
750 protected BatchedWriteMode myMode;
751
752
753 protected final List<WriteOperation> myWrites;
754
755
756
757
758 public Builder() {
759 myWrites = new ArrayList<WriteOperation>();
760
761 reset();
762 }
763
764
765
766
767
768
769
770 public BatchedWrite build() {
771 return new BatchedWrite(this);
772 }
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788 public Builder delete(final DocumentAssignable query) {
789 return delete(query, false);
790 }
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806 public Builder delete(final DocumentAssignable query,
807 final boolean singleDelete) {
808 return write(new DeleteOperation(query, singleDelete));
809 }
810
811
812
813
814
815
816
817
818
819
820
821 public Builder durability(final Durability durability) {
822 return setDurability(durability);
823 }
824
825
826
827
828
829
830 public Durability getDurability() {
831 return myDurability;
832 }
833
834
835
836
837
838
839
840
841 public Builder insert(final DocumentAssignable document) {
842 return write(new InsertOperation(document));
843 }
844
845
846
847
848
849
850
851
852
853
854
855
856 public Builder mode(final BatchedWriteMode mode) {
857 return setMode(mode);
858 }
859
860
861
862
863
864
865 public Builder reset() {
866 myWrites.clear();
867 myMode = BatchedWriteMode.SERIALIZE_AND_CONTINUE;
868 myDurability = null;
869
870 return this;
871 }
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892 public Builder save(final DocumentAssignable document) {
893 final Document doc = document.asDocument();
894 final Element id = doc.get("_id");
895 if (id == null) {
896 return insert(doc);
897 }
898 return update(BuilderFactory.start().add(id), doc, false, true);
899 }
900
901
902
903
904
905
906
907
908 public Builder setDurability(final Durability durability) {
909 myDurability = durability;
910 return this;
911 }
912
913
914
915
916
917
918
919
920
921 public Builder setMode(final BatchedWriteMode mode) {
922 myMode = mode;
923 return this;
924 }
925
926
927
928
929
930
931
932
933 public Builder setWrites(final List<WriteOperation> writes) {
934 myWrites.clear();
935 if (writes != null) {
936 myWrites.addAll(writes);
937 }
938 return this;
939 }
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959 public Builder update(final DocumentAssignable query,
960 final DocumentAssignable update) {
961 return update(query, update, false, false);
962 }
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985 public Builder update(final DocumentAssignable query,
986 final DocumentAssignable update, final boolean multiUpdate,
987 final boolean upsert) {
988 return write(new UpdateOperation(query, update, multiUpdate, upsert));
989 }
990
991
992
993
994
995
996
997
998
999 public Builder write(final WriteOperation write) {
1000 myWrites.add(write);
1001 return this;
1002 }
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014 public Builder writes(final List<WriteOperation> writes) {
1015 return setWrites(writes);
1016 }
1017 }
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028 public static final class Bundle {
1029
1030 private final Document myCommand;
1031
1032
1033 private final List<WriteOperation> myWrites;
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043 protected Bundle(final Document command,
1044 final List<WriteOperation> writes) {
1045 super();
1046 myCommand = command;
1047 myWrites = Collections
1048 .unmodifiableList(new ArrayList<WriteOperation>(writes));
1049 }
1050
1051
1052
1053
1054
1055
1056 public Document getCommand() {
1057 return myCommand;
1058 }
1059
1060
1061
1062
1063
1064
1065 public List<WriteOperation> getWrites() {
1066 return myWrites;
1067 }
1068 }
1069 }