/
UpdateBuilder.java
817 lines (711 loc) · 28.7 KB
/
UpdateBuilder.java
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
/*
* Copyright 2017 Google LLC
*
* 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.
*/
package com.google.cloud.firestore;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.core.InternalExtensionOnly;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.cloud.Timestamp;
import com.google.cloud.firestore.UserDataConverter.EncodingOptions;
import com.google.cloud.firestore.v1.FirestoreSettings;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.firestore.v1.BatchWriteRequest;
import com.google.firestore.v1.BatchWriteResponse;
import com.google.firestore.v1.CommitRequest;
import com.google.firestore.v1.CommitResponse;
import com.google.firestore.v1.Write;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.Tracing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Abstract class that collects and bundles all write operations for {@link Transaction} and {@link
* WriteBatch}.
*/
@InternalExtensionOnly
public abstract class UpdateBuilder<T> {
static class WriteOperation {
Write.Builder write;
DocumentReference documentReference;
WriteOperation(DocumentReference documentReference, Write.Builder write) {
this.documentReference = documentReference;
this.write = write;
}
}
final FirestoreImpl firestore;
protected final List<WriteOperation> writes;
private boolean committed;
private final int maxBatchSize;
protected BatchState state = BatchState.OPEN;
protected Map<DocumentReference, SettableApiFuture<WriteResult>> pendingOperations =
new HashMap<>();
/**
* Used to represent the state of batch.
*
* <p>Writes can only be added while the batch is OPEN. For a batch to be sent, the batch must be
* READY_TO_SEND. After a batch is sent, it is marked as SENT.
*/
enum BatchState {
OPEN,
READY_TO_SEND,
SENT,
}
UpdateBuilder(FirestoreImpl firestore) {
this(firestore, BulkWriter.MAX_BATCH_SIZE);
}
UpdateBuilder(FirestoreImpl firestore, int maxBatchSize) {
this.firestore = firestore;
this.maxBatchSize = maxBatchSize;
this.writes = new ArrayList<>();
}
/**
* Wraps the result of the write operation before it is returned.
*
* <p>This method is used to generate the return value for all public methods. It allows
* operations on Transaction and Writebatch to return the object for chaining, while also allowing
* BulkWriter operations to return the future directly.
*/
abstract T wrapResult(ApiFuture<WriteResult> result);
/** Whether to allow multiple writes to the same document in a batch. */
boolean allowDuplicateDocs() {
return true;
}
/**
* Turns a field map that contains field paths into a nested map. Turns {a.b : c} into {a : {b :
* c}}.
*/
private static Map<String, Object> expandObject(Map<FieldPath, Object> data) {
Map<String, Object> result = new HashMap<>();
SortedSet<FieldPath> sortedFields = new TreeSet<>(data.keySet());
FieldPath lastField = null;
for (FieldPath field : sortedFields) {
if (lastField != null && lastField.isPrefixOf(field)) {
throw new IllegalArgumentException(
String.format("Detected ambiguous definition for field '%s'.", lastField));
}
List<String> segments = field.getSegments();
Object value = data.get(field);
Map<String, Object> currentMap = result;
for (int i = 0; i < segments.size(); ++i) {
if (i == segments.size() - 1) {
currentMap.put(segments.get(i), value);
} else {
if (!currentMap.containsKey(segments.get(i))) {
currentMap.put(segments.get(i), new HashMap<>());
}
currentMap = (Map<String, Object>) currentMap.get(segments.get(i));
}
}
lastField = field;
}
return result;
}
/**
* Creates a new Document at the DocumentReference's location. It fails the write if the document
* exists.
*
* @param documentReference The DocumentReference to create.
* @param fields A map of the fields and values for the document.
* @return The instance for chaining.
*/
@Nonnull
public T create(
@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
return performCreate(documentReference, fields);
}
private T performCreate(
@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
verifyNotCommitted();
Tracing.getTracer().getCurrentSpan().addAnnotation(TraceUtil.SPAN_NAME_CREATEDOCUMENT);
DocumentSnapshot documentSnapshot =
DocumentSnapshot.fromObject(
firestore, documentReference, fields, UserDataConverter.NO_DELETES);
DocumentTransform documentTransform =
DocumentTransform.fromFieldPathMap(
documentReference, convertToFieldPaths(fields, /* splitOnDots= */ false));
Write.Builder write = documentSnapshot.toPb();
write.setCurrentDocument(Precondition.exists(false).toPb());
if (!documentTransform.isEmpty()) {
write.addAllUpdateTransforms(documentTransform.toPb());
}
writes.add(new WriteOperation(documentReference, write));
return wrapResult(processOperation(documentReference));
}
private void verifyNotCommitted() {
Preconditions.checkState(
!committed, "Cannot modify a WriteBatch that has already been committed.");
}
/**
* Creates a new Document at the DocumentReference location. It fails the write if the document
* exists.
*
* @param documentReference The DocumentReference to create.
* @param pojo The POJO that will be used to populate the document contents.
* @return The instance for chaining.
*/
@Nonnull
public T create(@Nonnull DocumentReference documentReference, @Nonnull Object pojo) {
Object data = CustomClassMapper.convertToPlainJavaTypes(pojo);
if (!(data instanceof Map)) {
throw FirestoreException.invalidState("Can't set a document's data to an array or primitive");
}
return performCreate(documentReference, (Map<String, Object>) data);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If a document already exists, it will be overwritten.
*
* @param documentReference The DocumentReference to overwrite.
* @param fields A map of the field paths and values for the document.
* @return The instance for chaining.
*/
@Nonnull
public T set(@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
return set(documentReference, fields, SetOptions.OVERWRITE);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If you pass {@link SetOptions}, the provided data can be merged into
* an existing document.
*
* @param documentReference The DocumentReference to overwrite.
* @param fields A map of the field paths and values for the document.
* @param options An object to configure the set behavior.
* @return The instance for chaining.
*/
@Nonnull
public T set(
@Nonnull DocumentReference documentReference,
@Nonnull Map<String, Object> fields,
@Nonnull SetOptions options) {
return performSet(documentReference, fields, options);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If a document already exists, it will be overwritten.
*
* @param documentReference The DocumentReference to overwrite.
* @param pojo The POJO that will be used to populate the document contents.
* @return The instance for chaining.
*/
@Nonnull
public T set(@Nonnull DocumentReference documentReference, @Nonnull Object pojo) {
return set(documentReference, pojo, SetOptions.OVERWRITE);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If you pass {@link SetOptions}, the provided data can be merged into
* an existing document.
*
* @param documentReference The DocumentReference to overwrite.
* @param pojo The POJO that will be used to populate the document contents.
* @param options An object to configure the set behavior.
* @return The instance for chaining.
*/
@Nonnull
public T set(
@Nonnull DocumentReference documentReference,
@Nonnull Object pojo,
@Nonnull SetOptions options) {
Object data = CustomClassMapper.convertToPlainJavaTypes(pojo);
if (!(data instanceof Map)) {
throw new IllegalArgumentException("Can't set a document's data to an array or primitive");
}
return performSet(documentReference, (Map<String, Object>) data, options);
}
private T performSet(
@Nonnull DocumentReference documentReference,
@Nonnull Map<String, Object> fields,
@Nonnull SetOptions options) {
verifyNotCommitted();
Map<FieldPath, Object> documentData;
if (options.getFieldMask() != null) {
documentData = applyFieldMask(fields, options.getFieldMask());
} else {
documentData = convertToFieldPaths(fields, /* splitOnDots= */ false);
}
DocumentSnapshot documentSnapshot =
DocumentSnapshot.fromObject(
firestore, documentReference, expandObject(documentData), options.getEncodingOptions());
FieldMask documentMask = FieldMask.EMPTY_MASK;
DocumentTransform documentTransform =
DocumentTransform.fromFieldPathMap(documentReference, documentData);
if (options.getFieldMask() != null) {
List<FieldPath> fieldMask = new ArrayList<>(options.getFieldMask());
fieldMask.removeAll(documentTransform.getFields());
documentMask = new FieldMask(fieldMask);
} else if (options.isMerge()) {
documentMask = FieldMask.fromObject(fields);
}
Write.Builder write = documentSnapshot.toPb();
if (!documentTransform.isEmpty()) {
write.addAllUpdateTransforms(documentTransform.toPb());
}
if (options.isMerge() || options.getFieldMask() != null) {
write.setUpdateMask(documentMask.toPb());
}
writes.add(new WriteOperation(documentReference, write));
return wrapResult(processOperation(documentReference));
}
/** Removes all values in 'fields' that are not specified in 'fieldMask'. */
private Map<FieldPath, Object> applyFieldMask(
Map<String, Object> fields, List<FieldPath> fieldMask) {
List<FieldPath> remainingFields = new ArrayList<>(fieldMask);
Map<FieldPath, Object> filteredData =
applyFieldMask(fields, remainingFields, FieldPath.empty());
if (!remainingFields.isEmpty()) {
throw new IllegalArgumentException(
String.format(
"Field masks contains invalid path. No data exist at field '%s'.",
remainingFields.get(0)));
}
return filteredData;
}
/**
* Strips all values in 'fields' that are not specified in 'fieldMask'. Modifies 'fieldMask'
* inline and removes all matched fields.
*/
private Map<FieldPath, Object> applyFieldMask(
Map<String, Object> fields, List<FieldPath> fieldMask, FieldPath root) {
Map<FieldPath, Object> filteredMap = new HashMap<>();
for (Entry<String, Object> entry : fields.entrySet()) {
FieldPath currentField = root.append(FieldPath.of(entry.getKey()));
if (fieldMask.remove(currentField)) {
filteredMap.put(currentField, entry.getValue());
} else if (entry.getValue() instanceof Map) {
filteredMap.putAll(
applyFieldMask((Map<String, Object>) entry.getValue(), fieldMask, currentField));
} else if (entry.getValue() == FieldValue.DELETE_SENTINEL) {
throw new IllegalArgumentException(
String.format(
"Cannot specify FieldValue.delete() for non-merged field '%s'.", currentField));
}
}
return filteredMap;
}
private Map<FieldPath, Object> convertToFieldPaths(
@Nonnull Map<String, Object> fields, boolean splitOnDots) {
Map<FieldPath, Object> fieldPaths = new HashMap<>();
for (Map.Entry<String, Object> entry : fields.entrySet()) {
if (splitOnDots) {
fieldPaths.put(FieldPath.fromDotSeparatedString(entry.getKey()), entry.getValue());
} else {
fieldPaths.put(FieldPath.of(entry.getKey()), entry.getValue());
}
}
return fieldPaths;
}
/**
* Updates fields in the document referred to by this DocumentReference. If the document doesn't
* exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param fields A Map containing the fields and values with which to update the document.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
return performUpdate(
documentReference,
convertToFieldPaths(fields, /* splitOnDots= */ true),
Precondition.exists(true));
}
/**
* Updates fields in the document referred to by this DocumentReference. If the document doesn't
* exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param fields A Map containing the fields and values with which to update the document.
* @param precondition Precondition to enforce on this update.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull Map<String, Object> fields,
Precondition precondition) {
Preconditions.checkArgument(
!precondition.hasExists(), "Precondition 'exists' cannot be specified for update() calls.");
return performUpdate(
documentReference, convertToFieldPaths(fields, /* splitOnDots= */ true), precondition);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param field The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull String field,
@Nullable Object value,
Object... moreFieldsAndValues) {
return performUpdate(
documentReference,
Precondition.exists(true),
FieldPath.fromDotSeparatedString(field),
value,
moreFieldsAndValues);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param fieldPath The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull FieldPath fieldPath,
@Nullable Object value,
Object... moreFieldsAndValues) {
return performUpdate(
documentReference, Precondition.exists(true), fieldPath, value, moreFieldsAndValues);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param precondition Precondition to enforce on this update.
* @param field The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull Precondition precondition,
@Nonnull String field,
@Nullable Object value,
Object... moreFieldsAndValues) {
Preconditions.checkArgument(
!precondition.hasExists(), "Precondition 'exists' cannot be specified for update() calls.");
return performUpdate(
documentReference,
precondition,
FieldPath.fromDotSeparatedString(field),
value,
moreFieldsAndValues);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param precondition Precondition to enforce on this update.
* @param fieldPath The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull Precondition precondition,
@Nonnull FieldPath fieldPath,
@Nullable Object value,
Object... moreFieldsAndValues) {
Preconditions.checkArgument(
!precondition.hasExists(), "Precondition 'exists' cannot be specified for update() calls.");
return performUpdate(documentReference, precondition, fieldPath, value, moreFieldsAndValues);
}
private T performUpdate(
@Nonnull DocumentReference documentReference,
@Nonnull Precondition precondition,
@Nonnull FieldPath fieldPath,
@Nullable Object value,
Object[] moreFieldsAndValues) {
Object data = CustomClassMapper.convertToPlainJavaTypes(value);
Map<FieldPath, Object> fields = new HashMap<>();
fields.put(fieldPath, data);
Preconditions.checkArgument(
moreFieldsAndValues.length % 2 == 0, "moreFieldsAndValues must be key-value pairs.");
for (int i = 0; i < moreFieldsAndValues.length; i += 2) {
Object objectPath = moreFieldsAndValues[i];
Object objectValue = moreFieldsAndValues[i + 1];
FieldPath currentPath;
if (objectPath instanceof String) {
currentPath = FieldPath.fromDotSeparatedString((String) objectPath);
} else if (objectPath instanceof FieldPath) {
currentPath = (FieldPath) objectPath;
} else {
throw new IllegalArgumentException(
"Field '" + objectPath + "' is not of type String or Field Path.");
}
if (fields.containsKey(currentPath)) {
throw new IllegalArgumentException(
"Field value for field '" + objectPath + "' was specified multiple times.");
}
fields.put(currentPath, objectValue);
}
return performUpdate(documentReference, fields, precondition);
}
private T performUpdate(
@Nonnull DocumentReference documentReference,
@Nonnull final Map<FieldPath, Object> fields,
@Nonnull Precondition precondition) {
verifyNotCommitted();
Preconditions.checkArgument(!fields.isEmpty(), "Data for update() cannot be empty.");
Tracing.getTracer().getCurrentSpan().addAnnotation(TraceUtil.SPAN_NAME_UPDATEDOCUMENT);
Map<String, Object> deconstructedMap = expandObject(fields);
DocumentSnapshot documentSnapshot =
DocumentSnapshot.fromObject(
firestore,
documentReference,
deconstructedMap,
new EncodingOptions() {
@Override
public boolean allowDelete(FieldPath fieldPath) {
return fields.containsKey(fieldPath);
}
@Override
public boolean allowTransform() {
return true;
}
});
List<FieldPath> fieldPaths = new ArrayList<>(fields.keySet());
DocumentTransform documentTransform =
DocumentTransform.fromFieldPathMap(documentReference, fields);
fieldPaths.removeAll(documentTransform.getFields());
FieldMask fieldMask = new FieldMask(fieldPaths);
Write.Builder write = documentSnapshot.toPb();
write.setCurrentDocument(precondition.toPb());
write.setUpdateMask(fieldMask.toPb());
if (!documentTransform.isEmpty()) {
write.addAllUpdateTransforms(documentTransform.toPb());
}
writes.add(new WriteOperation(documentReference, write));
return wrapResult(processOperation(documentReference));
}
/**
* Deletes the document referred to by this DocumentReference.
*
* @param documentReference The DocumentReference to delete.
* @param precondition Precondition for the delete operation.
* @return The instance for chaining.
*/
@Nonnull
public T delete(
@Nonnull DocumentReference documentReference, @Nonnull Precondition precondition) {
return performDelete(documentReference, precondition);
}
/**
* Deletes the document referred to by this DocumentReference.
*
* @param documentReference The DocumentReference to delete.
* @return The instance for chaining.
*/
@Nonnull
public T delete(@Nonnull DocumentReference documentReference) {
return performDelete(documentReference, Precondition.NONE);
}
private T performDelete(
@Nonnull DocumentReference documentReference, @Nonnull Precondition precondition) {
verifyNotCommitted();
Tracing.getTracer().getCurrentSpan().addAnnotation(TraceUtil.SPAN_NAME_DELETEDOCUMENT);
Write.Builder write = Write.newBuilder().setDelete(documentReference.getName());
if (!precondition.isEmpty()) {
write.setCurrentDocument(precondition.toPb());
}
writes.add(new WriteOperation(documentReference, write));
return wrapResult(processOperation(documentReference));
}
/** Commit the current batch. */
ApiFuture<List<WriteResult>> commit(@Nullable ByteString transactionId) {
Tracing.getTracer()
.getCurrentSpan()
.addAnnotation(
TraceUtil.SPAN_NAME_COMMIT,
ImmutableMap.of("numDocuments", AttributeValue.longAttributeValue(writes.size())));
final CommitRequest.Builder request = CommitRequest.newBuilder();
request.setDatabase(firestore.getDatabaseName());
for (WriteOperation writeOperation : writes) {
request.addWrites(writeOperation.write);
}
if (transactionId != null) {
request.setTransaction(transactionId);
}
committed = true;
ApiFuture<CommitResponse> response =
firestore.sendRequest(request.build(), firestore.getClient().commitCallable());
return ApiFutures.transform(
response,
new ApiFunction<CommitResponse, List<WriteResult>>() {
@Override
public List<WriteResult> apply(CommitResponse commitResponse) {
List<com.google.firestore.v1.WriteResult> writeResults =
commitResponse.getWriteResultsList();
List<WriteResult> result = new ArrayList<>();
for (com.google.firestore.v1.WriteResult writeResult : writeResults) {
result.add(WriteResult.fromProto(writeResult, commitResponse.getCommitTime()));
}
return result;
}
},
MoreExecutors.directExecutor());
}
/**
* Commits all pending operations to the database and verifies all preconditions.
*
* <p>The writes in the batch are not applied atomically and can be applied out of order.
*/
ApiFuture<List<BatchWriteResult>> bulkCommit() {
Tracing.getTracer()
.getCurrentSpan()
.addAnnotation(
TraceUtil.SPAN_NAME_BATCHWRITE,
ImmutableMap.of("numDocuments", AttributeValue.longAttributeValue(writes.size())));
final BatchWriteRequest.Builder request = BatchWriteRequest.newBuilder();
request.setDatabase(firestore.getDatabaseName());
for (WriteOperation writeOperation : writes) {
request.addWrites(writeOperation.write);
}
ApiFuture<BatchWriteResponse> response =
firestore.sendRequest(request.build(), firestore.getClient().batchWriteCallable());
return ApiFutures.transform(
response,
new ApiFunction<BatchWriteResponse, List<BatchWriteResult>>() {
@Override
public List<BatchWriteResult> apply(BatchWriteResponse batchWriteResponse) {
List<com.google.firestore.v1.WriteResult> writeResults =
batchWriteResponse.getWriteResultsList();
List<com.google.rpc.Status> statuses = batchWriteResponse.getStatusList();
List<BatchWriteResult> result = new ArrayList<>();
for (int i = 0; i < writeResults.size(); ++i) {
com.google.firestore.v1.WriteResult writeResult = writeResults.get(i);
com.google.rpc.Status status = statuses.get(i);
Status code = Status.fromCodeValue(status.getCode());
@Nullable Timestamp updateTime = null;
@Nullable Exception exception = null;
if (code == Status.OK) {
updateTime = Timestamp.fromProto(writeResult.getUpdateTime());
} else {
exception = FirestoreException.serverRejected(code, status.getMessage());
}
result.add(
new BatchWriteResult(writes.get(i).documentReference, updateTime, exception));
}
return result;
}
},
MoreExecutors.directExecutor());
}
/** Checks whether any updates have been queued. */
boolean isEmpty() {
return writes.isEmpty();
}
/** Get the number of writes. */
public int getMutationsSize() {
return writes.size();
}
BatchState getState() {
return state;
}
boolean hasDocument(DocumentReference documentReference) {
return pendingOperations.containsKey(documentReference);
}
Set<DocumentReference> getPendingDocuments() {
return pendingOperations.keySet();
}
Collection<SettableApiFuture<WriteResult>> getPendingFutures() {
return pendingOperations.values();
}
int getPendingOperationCount() {
return pendingOperations.size();
}
private ApiFuture<WriteResult> processOperation(DocumentReference documentReference) {
Preconditions.checkState(
allowDuplicateDocs() || !pendingOperations.containsKey(documentReference),
"Batch should not contain writes to the same document");
Preconditions.checkState(state == BatchState.OPEN, "Batch should be OPEN when adding writes");
SettableApiFuture<WriteResult> result = SettableApiFuture.create();
pendingOperations.put(documentReference, result);
if (getPendingOperationCount() == maxBatchSize) {
state = BatchState.READY_TO_SEND;
}
return result;
}
/**
* Resolves the individual operations in the batch with the results and removes the entry from the
* pendingOperations map if the result is not retryable.
*/
void processResults(List<BatchWriteResult> results) {
for (BatchWriteResult result : results) {
if (result.getException() == null || !shouldRetry(result.getException())) {
convertBatchWriteResult(result, pendingOperations.get(result.getDocumentReference()));
pendingOperations.remove(result.getDocumentReference());
}
}
}
void failRemainingOperations(List<BatchWriteResult> results) {
for (BatchWriteResult result : results) {
convertBatchWriteResult(result, pendingOperations.get(result.getDocumentReference()));
}
}
private boolean shouldRetry(Exception exception) {
if (!(exception instanceof FirestoreException)) {
return false;
}
Set<Code> codes = FirestoreSettings.newBuilder().batchWriteSettings().getRetryableCodes();
Status status = ((FirestoreException) exception).getStatus();
for (Code code : codes) {
if (code.equals(Code.valueOf(status.getCode().name()))) {
return true;
}
}
return false;
}
private void convertBatchWriteResult(
BatchWriteResult result, SettableApiFuture<WriteResult> future) {
if (result.getWriteTime() != null) {
future.set(new WriteResult(result.getWriteTime()));
} else {
future.setException(result.getException());
}
}
void markReadyToSend() {
if (state == BatchState.OPEN) {
state = BatchState.READY_TO_SEND;
}
}
}