/
BulkWriter.java
1136 lines (1050 loc) · 42.2 KB
/
BulkWriter.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
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 2020 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 static com.google.cloud.firestore.BulkWriterOperation.DEFAULT_BACKOFF_MAX_DELAY_MS;
import com.google.api.core.ApiAsyncFunction;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.core.BetaApi;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.cloud.firestore.v1.FirestoreSettings;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/** A Firestore BulkWriter that can be used to perform a large number of writes in parallel. */
@BetaApi
public final class BulkWriter implements AutoCloseable {
/**
* A callback set by `addWriteResultListener()` to be run every time an operation successfully
* completes.
*/
public interface WriteResultCallback {
/**
* @param documentReference The document the operation was performed on.
* @param result The result of the operation.
*/
void onResult(DocumentReference documentReference, WriteResult result);
};
/**
* A callback set by `addWriteErrorListener()` to be run every time an operation fails and
* determines if an operation should be retried.
*/
public interface WriteErrorCallback {
/**
* @param error The error object from the failed BulkWriter operation attempt.
* @return Whether to retry the operation or not.
*/
boolean onError(BulkWriterException error);
}
enum OperationType {
CREATE,
SET,
UPDATE,
DELETE
}
/** The maximum number of writes that can be in a single batch. */
public static final int MAX_BATCH_SIZE = 20;
/**
* The maximum number of retries that will be attempted with backoff before stopping all retry
* attempts.
*/
public static final int MAX_RETRY_ATTEMPTS = 10;
/**
* The starting maximum number of operations per second as allowed by the 500/50/5 rule.
*
* @see <a href=https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic>Ramping
* up traffic</a>
*/
static final int DEFAULT_STARTING_MAXIMUM_OPS_PER_SECOND = 500;
/**
* The rate by which to increase the capacity as specified by the 500/50/5 rule.
*
* @see <a href=https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic>Ramping
* up traffic</a>
*/
private static final double RATE_LIMITER_MULTIPLIER = 1.5;
/**
* How often the operations per second capacity should increase in milliseconds as specified by
* the 500/50/5 rule.
*
* @see <a href=https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic>Ramping
* up traffic</a>
*/
private static final int RATE_LIMITER_MULTIPLIER_MILLIS = 5 * 60 * 1000;
/**
* The default maximum number of pending operations that can be enqueued onto a BulkWriter
* instance. An operation is considered pending if BulkWriter has sent it via RPC and is awaiting
* the result. BulkWriter buffers additional writes after this many pending operations in order to
* avoiding going OOM.
*/
private static final int DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT = 500;
/**
* The default jitter to apply to the exponential backoff used in retries. For example, a factor
* of 0.3 means a 30% jitter is applied.
*/
static final double DEFAULT_JITTER_FACTOR = 0.3;
private static final WriteResultCallback DEFAULT_SUCCESS_LISTENER =
new WriteResultCallback() {
public void onResult(DocumentReference documentReference, WriteResult result) {}
};
private static final WriteErrorCallback DEFAULT_ERROR_LISTENER =
new WriteErrorCallback() {
public boolean onError(BulkWriterException error) {
if (error.getFailedAttempts() > MAX_RETRY_ATTEMPTS) {
return false;
}
Set<Code> codes = FirestoreSettings.newBuilder().batchWriteSettings().getRetryableCodes();
for (Code code : codes) {
if (code.equals(Code.valueOf(error.getStatus().getCode().name()))) {
return true;
}
}
return false;
}
};
private static final Logger logger = Logger.getLogger(BulkWriter.class.getName());
private final FirestoreImpl firestore;
// Executor used to run all BulkWriter operations. BulkWriter uses its own executor since we
// don't want to block a gax/grpc executor while running user error and success callbacks.
private final ScheduledExecutorService bulkWriterExecutor;
/** The maximum number of writes that can be in a single batch. */
private int maxBatchSize = MAX_BATCH_SIZE;
/**
* Lock object for all mutable state in bulk writer. BulkWriter state is accessed from the user
* thread and via {@code bulkWriterExecutor}.
*/
private final Object lock = new Object();
/** Rate limiter used to throttle requests as per the 500/50/5 rule. */
@GuardedBy("lock")
private final RateLimiter rateLimiter;
/**
* The number of pending operations enqueued on this BulkWriter instance. An operation is
* considered pending if BulkWriter has sent it via RPC and is awaiting the result.
*/
@GuardedBy("lock")
private int pendingOpsCount = 0;
/**
* An array containing buffered BulkWriter operations after the maximum number of pending
* operations has been enqueued.
*/
@GuardedBy("lock")
private final List<Runnable> bufferedOperations = new ArrayList<>();
/**
* The maximum number of pending operations that can be enqueued onto this BulkWriter instance.
* Once the this number of writes have been enqueued, subsequent writes are buffered.
*/
private int maxPendingOpCount = DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT;
/**
* The batch that is currently used to schedule operations. Once this batch reaches maximum
* capacity, a new batch is created.
*
* <p>Access to the BulkCommitBatch should only occur under lock as it can be accessed by both the
* user thread as well as by the backoff logic in BulkWriter.
*/
@GuardedBy("lock")
private BulkCommitBatch bulkCommitBatch;
/**
* A pointer to the tail of all active BulkWriter applications. This pointer is advanced every
* time a new write is enqueued.
*/
@GuardedBy("lock")
private ApiFuture<Void> lastOperation = ApiFutures.immediateFuture(null);
/** Whether this BulkWriter instance is closed. Once closed, it cannot be opened again. */
@GuardedBy("lock")
private boolean closed = false;
@GuardedBy("lock")
private WriteResultCallback successListener = DEFAULT_SUCCESS_LISTENER;
@GuardedBy("lock")
private WriteErrorCallback errorListener = DEFAULT_ERROR_LISTENER;
@GuardedBy("lock")
private Executor successExecutor;
@GuardedBy("lock")
private Executor errorExecutor;
/**
* Used to track when writes are enqueued. The user handler executors cannot be changed after a
* write has been enqueued.
*/
@GuardedBy("lock")
private boolean writesEnqueued = false;
BulkWriter(FirestoreImpl firestore, BulkWriterOptions options) {
this.firestore = firestore;
this.bulkWriterExecutor =
options.getExecutor() != null
? options.getExecutor()
: Executors.newSingleThreadScheduledExecutor();
this.successExecutor = MoreExecutors.directExecutor();
this.errorExecutor = MoreExecutors.directExecutor();
this.bulkCommitBatch = new BulkCommitBatch(firestore, bulkWriterExecutor);
if (!options.getThrottlingEnabled()) {
this.rateLimiter =
new RateLimiter(
Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
} else {
double startingRate = DEFAULT_STARTING_MAXIMUM_OPS_PER_SECOND;
double maxRate = Double.POSITIVE_INFINITY;
if (options.getInitialOpsPerSecond() != null) {
startingRate = options.getInitialOpsPerSecond();
}
if (options.getMaxOpsPerSecond() != null) {
maxRate = options.getMaxOpsPerSecond();
}
// The initial validation step ensures that the maxOpsPerSecond is greater than
// initialOpsPerSecond. If this inequality is true, that means initialOpsPerSecond was not
// set and maxOpsPerSecond is less than the default starting rate.
if (maxRate < startingRate) {
startingRate = maxRate;
}
// Ensure that the batch size is not larger than the number of allowed
// operations per second.
if (startingRate < maxBatchSize) {
this.maxBatchSize = (int) startingRate;
}
this.rateLimiter =
new RateLimiter(
(int) startingRate,
RATE_LIMITER_MULTIPLIER,
RATE_LIMITER_MULTIPLIER_MILLIS,
(int) maxRate);
}
}
/**
* Create a document with the provided data. This single operation will fail if a document exists
* at its location.
*
* @param documentReference A reference to the document to be created.
* @param fields A map of the fields and values for the document.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> create(
@Nonnull final DocumentReference documentReference,
@Nonnull final Map<String, Object> fields) {
return executeWrite(
documentReference,
OperationType.CREATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.create(documentReference, fields);
}
});
}
/**
* Create a document with the provided data. This single operation will fail if a document exists
* at its location.
*
* @param documentReference A reference to the document to be created.
* @param pojo The POJO that will be used to populate the document contents.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> create(
@Nonnull final DocumentReference documentReference, @Nonnull final Object pojo) {
return executeWrite(
documentReference,
OperationType.CREATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.create(documentReference, pojo);
}
});
}
/**
* Delete a document from the database.
*
* @param documentReference The DocumentReference to delete.
* @return An ApiFuture containing a sentinel value (Timestamp(0)) for the delete operation.
* Contains a {@link BulkWriterException} if the delete fails.
*/
@Nonnull
public ApiFuture<WriteResult> delete(@Nonnull final DocumentReference documentReference) {
return executeWrite(
documentReference,
OperationType.DELETE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.delete(documentReference);
}
});
}
/**
* Delete a document from the database.
*
* @param documentReference The DocumentReference to delete.
* @param precondition Precondition to enforce for this delete.
* @return An ApiFuture containing a sentinel value (Timestamp(0)) for the delete operation.
* Contains a {@link BulkWriterException} if the delete fails.
*/
@Nonnull
public ApiFuture<WriteResult> delete(
@Nonnull final DocumentReference documentReference,
@Nonnull final Precondition precondition) {
return executeWrite(
documentReference,
OperationType.DELETE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.delete(documentReference, precondition);
}
});
}
/**
* Write to the document referred to by the provided DocumentReference. If the document does not
* exist yet, it will be created.
*
* @param documentReference A reference to the document to be set.
* @param fields A map of the fields and values for the document.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> set(
@Nonnull final DocumentReference documentReference,
@Nonnull final Map<String, Object> fields) {
return executeWrite(
documentReference,
OperationType.SET,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.set(documentReference, fields);
}
});
}
/**
* Write to the document referred to by the provided DocumentReference. If the document does not
* exist yet, it will be created. If you pass a {@link SetOptions}, the provided data can be
* merged into an existing document.
*
* @param documentReference A reference to the document to be set.
* @param fields A map of the fields and values for the document.
* @param options An object to configure the set behavior.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> set(
@Nonnull final DocumentReference documentReference,
@Nonnull final Map<String, Object> fields,
@Nonnull final SetOptions options) {
return executeWrite(
documentReference,
OperationType.SET,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.set(documentReference, fields, options);
}
});
}
/**
* Write to the document referred to by the provided DocumentReference. If the document does not
* exist yet, it will be created. If you pass a {@link SetOptions}, the provided data can be
* merged into an existing document.
*
* @param documentReference A reference to the document to be set.
* @param pojo The POJO that will be used to populate the document contents.
* @param options An object to configure the set behavior.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> set(
@Nonnull final DocumentReference documentReference,
@Nonnull final Object pojo,
@Nonnull final SetOptions options) {
return executeWrite(
documentReference,
OperationType.SET,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.set(documentReference, pojo, options);
}
});
}
/**
* Write to the document referred to by the provided DocumentReference. If the document does not
* exist yet, it will be created.
*
* @param documentReference A reference to the document to be set.
* @param pojo The POJO that will be used to populate the document contents.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> set(
@Nonnull final DocumentReference documentReference, @Nonnull final Object pojo) {
return executeWrite(
documentReference,
OperationType.SET,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.set(documentReference, pojo);
}
});
}
/**
* Update fields of the document referred to by the provided {@link DocumentReference}. If the
* document doesn't yet exist, the update will fail.
*
* <p>The update() method accepts either an object with field paths encoded as keys and field
* values encoded as values, or a variable number of arguments that alternate between field paths
* and field values. Nested fields can be updated by providing dot-separated field path strings or
* by providing FieldPath objects.
*
* @param documentReference A reference to the document to be updated.
* @param fields A map of the fields and values for the document.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull final DocumentReference documentReference,
@Nonnull final Map<String, Object> fields) {
return executeWrite(
documentReference,
OperationType.UPDATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.update(documentReference, fields);
}
});
}
/**
* Update fields of the document referred to by the provided {@link DocumentReference}. If the
* document doesn't yet exist, the update will fail.
*
* <p>The update() method accepts either an object with field paths encoded as keys and field
* values encoded as values, or a variable number of arguments that alternate between field paths
* and field values. Nested fields can be updated by providing dot-separated field path strings or
* by providing FieldPath objects.
*
* @param documentReference A reference to the document to be updated.
* @param fields A map of the fields and values for the document.
* @param precondition Precondition to enforce on this update.
* @return An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull final DocumentReference documentReference,
@Nonnull final Map<String, Object> fields,
@Nonnull final Precondition precondition) {
return executeWrite(
documentReference,
OperationType.UPDATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.update(documentReference, fields, precondition);
}
});
}
/**
* Update fields of the document referred to by the provided {@link DocumentReference}. If the
* document doesn't yet exist, the update will fail.
*
* <p>The update() method accepts either an object with field paths encoded as keys and field
* values encoded as values, or a variable number of arguments that alternate between field paths
* and field values. Nested fields can be updated by providing dot-separated field path strings or
* by providing FieldPath objects.
*
* @param documentReference A reference to the document to be updated.
* @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 An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull final DocumentReference documentReference,
@Nonnull final String field,
@Nullable final Object value,
final Object... moreFieldsAndValues) {
return executeWrite(
documentReference,
OperationType.UPDATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.update(documentReference, field, value, moreFieldsAndValues);
}
});
}
/**
* Update fields of the document referred to by the provided {@link DocumentReference}. If the
* document doesn't yet exist, the update will fail.
*
* <p>The update() method accepts either an object with field paths encoded as keys and field
* values encoded as values, or a variable number of arguments that alternate between field paths
* and field values. Nested fields can be updated by providing dot-separated field path strings or
* by providing FieldPath objects.
*
* @param documentReference A reference to the document to be updated.
* @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 An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull final DocumentReference documentReference,
@Nonnull final FieldPath fieldPath,
@Nullable final Object value,
final Object... moreFieldsAndValues) {
return executeWrite(
documentReference,
OperationType.UPDATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.update(documentReference, fieldPath, value, moreFieldsAndValues);
}
});
}
/**
* Update fields of the document referred to by the provided {@link DocumentReference}. If the
* document doesn't yet exist, the update will fail.
*
* <p>The update() method accepts either an object with field paths encoded as keys and field
* values encoded as values, or a variable number of arguments that alternate between field paths
* and field values. Nested fields can be updated by providing dot-separated field path strings or
* by providing FieldPath objects.
*
* @param documentReference A reference to the document to be updated.
* @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 An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull final DocumentReference documentReference,
@Nonnull final Precondition precondition,
@Nonnull final String field,
@Nullable final Object value,
final Object... moreFieldsAndValues) {
return executeWrite(
documentReference,
OperationType.UPDATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.update(documentReference, precondition, field, value, moreFieldsAndValues);
}
});
}
/**
* Update fields of the document referred to by the provided {@link DocumentReference}. If the
* document doesn't yet exist, the update will fail.
*
* <p>The update() method accepts either an object with field paths encoded as keys and field
* values encoded as values, or a variable number of arguments that alternate between field paths
* and field values. Nested fields can be updated by providing dot-separated field path strings or
* by providing FieldPath objects.
*
* @param documentReference A reference to the document to be updated.
* @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 An ApiFuture containing the result of the write. Contains a {@link BulkWriterException}
* if the write fails.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull final DocumentReference documentReference,
@Nonnull final Precondition precondition,
@Nonnull final FieldPath fieldPath,
@Nullable final Object value,
final Object... moreFieldsAndValues) {
return executeWrite(
documentReference,
OperationType.UPDATE,
new ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>>() {
public ApiFuture<WriteResult> apply(BulkCommitBatch batch) {
return batch.update(
documentReference, precondition, fieldPath, value, moreFieldsAndValues);
}
});
}
/**
* Schedules the provided write operation and runs the user success callback when the write result
* is obtained.
*/
private ApiFuture<WriteResult> executeWrite(
final DocumentReference documentReference,
final OperationType operationType,
final ApiFunction<BulkCommitBatch, ApiFuture<WriteResult>> enqueueOperationOnBatchCallback) {
final BulkWriterOperation operation =
new BulkWriterOperation(
documentReference,
operationType,
new ApiFunction<BulkWriterOperation, Void>() {
@Override
public Void apply(BulkWriterOperation operation) {
synchronized (lock) {
sendOperationLocked(enqueueOperationOnBatchCallback, operation);
}
return null;
}
},
new ApiFunction<WriteResult, ApiFuture<Void>>() {
@Override
public ApiFuture<Void> apply(WriteResult writeResult) {
synchronized (lock) {
return invokeUserSuccessCallbackLocked(documentReference, writeResult);
}
}
},
new ApiFunction<BulkWriterException, ApiFuture<Boolean>>() {
@Override
public ApiFuture<Boolean> apply(BulkWriterException e) {
synchronized (lock) {
return invokeUserErrorCallbackLocked(e);
}
}
});
synchronized (lock) {
verifyNotClosedLocked();
writesEnqueued = true;
// Advance the lastOperation pointer. This ensures that lastOperation only completes when
// both the previous and the current write complete.
lastOperation =
ApiFutures.transformAsync(
lastOperation,
new ApiAsyncFunction<Void, Void>() {
@Override
public ApiFuture<Void> apply(Void aVoid) {
return silenceFuture(operation.getFuture());
}
},
MoreExecutors.directExecutor());
// Schedule the operation if the BulkWriter has fewer than the maximum number of allowed
// pending operations, or add the operation to the buffer.
if (pendingOpsCount < maxPendingOpCount) {
pendingOpsCount++;
sendOperationLocked(enqueueOperationOnBatchCallback, operation);
} else {
bufferedOperations.add(
new Runnable() {
@Override
public void run() {
synchronized (lock) {
pendingOpsCount++;
sendOperationLocked(enqueueOperationOnBatchCallback, operation);
}
}
});
}
}
ApiFuture<WriteResult> processedOperationFuture =
ApiFutures.transformAsync(
operation.getFuture(),
new ApiAsyncFunction<WriteResult, WriteResult>() {
public ApiFuture<WriteResult> apply(WriteResult result) throws Exception {
pendingOpsCount--;
processBufferedOperations();
return ApiFutures.immediateFuture(result);
}
},
MoreExecutors.directExecutor());
return ApiFutures.catchingAsync(
processedOperationFuture,
ApiException.class,
new ApiAsyncFunction<ApiException, WriteResult>() {
public ApiFuture<WriteResult> apply(ApiException e) throws Exception {
pendingOpsCount--;
processBufferedOperations();
throw e;
}
},
MoreExecutors.directExecutor());
}
/**
* Manages the pending operation counter and schedules the next BulkWriter operation if we're
* under the maximum limit.
*/
private void processBufferedOperations() {
if (pendingOpsCount < maxPendingOpCount && bufferedOperations.size() > 0) {
Runnable nextOp = bufferedOperations.remove(0);
nextOp.run();
}
}
/**
* Commits all writes that have been enqueued up to this point in parallel.
*
* <p>Returns an ApiFuture that completes when all currently queued operations have been
* committed. The ApiFuture will never return an error since the results for each individual
* operation are conveyed via their individual ApiFutures.
*
* <p>The ApiFuture completes immediately if there are no pending writes. Otherwise, the ApiFuture
* waits for all previously issued writes, but it does not wait for writes that were added after
* the method is called. If you want to wait for additional writes, call `flush()` again.
*
* @return An ApiFuture that completes when all enqueued writes up to this point have been
* committed.
*/
@Nonnull
public ApiFuture<Void> flush() {
synchronized (lock) {
return flushLocked();
}
}
private ApiFuture<Void> flushLocked() {
verifyNotClosedLocked();
scheduleCurrentBatchLocked(/* flush= */ true);
return lastOperation;
}
/**
* Commits all enqueued writes and marks the BulkWriter instance as closed.
*
* <p>After calling `close()`, calling any method will return an error. Any retries scheduled with
* `addWriteErrorListener()` will be run before `close()` completes.
*
* <p>This method completes when there are no more pending writes. Calling this method will send
* all requests.
*/
public void close() throws InterruptedException, ExecutionException {
ApiFuture<Void> flushFuture;
synchronized (lock) {
flushFuture = flushLocked();
closed = true;
}
flushFuture.get();
}
/**
* Used for verifying that the BulkWriter instance isn't closed when calling from outside this
* class.
*/
void verifyNotClosed() {
synchronized (lock) {
verifyNotClosedLocked();
}
}
void verifyNotClosedLocked() {
if (this.closed) {
throw new IllegalStateException("BulkWriter has already been closed.");
}
}
/**
* Attaches a listener that is run every time a BulkWriter operation successfully completes. The
* listener will be run before `close()` completes.
*
* <p>For example, see the sample code: <code>
* BulkWriter bulkWriter = firestore.bulkWriter();
* bulkWriter.addWriteResultListener(
* (DocumentReference documentReference, WriteResult result) -> {
* System.out.println(
* "Successfully executed write on document: "
* + documentReference
* + " at: "
* + result.getUpdateTime());
* }
* );
* </code>
*
* @param writeResultCallback A callback to be called every time a BulkWriter operation
* successfully completes.
*/
public void addWriteResultListener(WriteResultCallback writeResultCallback) {
synchronized (lock) {
successListener = writeResultCallback;
}
}
/**
* Attaches a listener that is run every time a BulkWriter operation successfully completes.
*
* <p>The executor cannot be changed once writes have been enqueued onto the BulkWriter.
*
* <p>For example, see the sample code: <code>
* BulkWriter bulkWriter = firestore.bulkWriter();
* bulkWriter.addWriteResultListener(
* (DocumentReference documentReference, WriteResult result) -> {
* System.out.println(
* "Successfully executed write on document: "
* + documentReference
* + " at: "
* + result.getUpdateTime());
* }
* );
* </code>
*
* @param executor The executor to run the provided callback on.
* @param writeResultCallback A callback to be called every time a BulkWriter operation
* successfully completes.
*/
public void addWriteResultListener(
@Nonnull Executor executor, WriteResultCallback writeResultCallback) {
synchronized (lock) {
if (writesEnqueued) {
throw new IllegalStateException(
"The executor cannot be changed once writes have been enqueued.");
}
successListener = writeResultCallback;
successExecutor = executor;
}
}
/**
* Attaches an error handler listener that is run every time a BulkWriter operation fails.
*
* <p>BulkWriter has a default error handler that retries UNAVAILABLE and ABORTED errors up to a
* maximum of 10 failed attempts. When an error handler is specified, the default error handler
* will be overwritten.
*
* <p>For example, see the sample code: <code>
* BulkWriter bulkWriter = firestore.bulkWriter();
* bulkWriter.addWriteErrorListener(
* (BulkWriterException error) -> {
* if (error.getStatus() == Status.UNAVAILABLE
* && error.getFailedAttempts() < MAX_RETRY_ATTEMPTS) {
* return true;
* } else {
* System.out.println("Failed write at document: " + error.getDocumentReference());
* return false;
* }
* }
* );
* </code>
*
* @param onError A callback to be called every time a BulkWriter operation fails. Returning
* `true` will retry the operation. Returning `false` will stop the retry loop.
*/
public void addWriteErrorListener(WriteErrorCallback onError) {
synchronized (lock) {
errorListener = onError;
}
}
/**
* Attaches an error handler listener that is run every time a BulkWriter operation fails.
*
* <p>The executor cannot be changed once writes have been enqueued onto the BulkWriter.
*
* <p>BulkWriter has a default error handler that retries UNAVAILABLE and ABORTED errors up to a
* maximum of 10 failed attempts. When an error handler is specified, the default error handler
* will be overwritten.
*
* <p>For example, see the sample code: <code>
* BulkWriter bulkWriter = firestore.bulkWriter();
* bulkWriter.addWriteErrorListener(
* (BulkWriterException error) -> {
* if (error.getStatus() == Status.UNAVAILABLE
* && error.getFailedAttempts() < MAX_RETRY_ATTEMPTS) {
* return true;
* } else {
* System.out.println("Failed write at document: " + error.getDocumentReference());
* return false;
* }
* }
* );
* </code>
*
* @param executor The executor to run the provided callback on.
* @param onError A callback to be called every time a BulkWriter operation fails. Returning
* `true` will retry the operation. Returning `false` will stop the retry loop.
*/
public void addWriteErrorListener(@Nonnull Executor executor, WriteErrorCallback onError) {
synchronized (lock) {
if (writesEnqueued) {
throw new IllegalStateException(
"The executor cannot be changed once writes have been enqueued.");
}
errorListener = onError;
errorExecutor = executor;
}
}
/**
* Sends the current batch and resets {@link #bulkCommitBatch}.
*
* @param flush If provided, keeps re-sending operations until no more operations are enqueued.
* This allows retries to resolve as part of a {@link BulkWriter#flush()} or {@link
* BulkWriter#close()} call.
*/
private void scheduleCurrentBatchLocked(final boolean flush) {
if (bulkCommitBatch.getMutationsSize() == 0) return;
final BulkCommitBatch pendingBatch = bulkCommitBatch;
bulkCommitBatch = new BulkCommitBatch(firestore, bulkWriterExecutor);
// Use the write with the longest backoff duration when determining backoff.
int highestBackoffDuration = 0;
for (BulkWriterOperation op : pendingBatch.pendingOperations) {
if (op.getBackoffDuration() > highestBackoffDuration) {
highestBackoffDuration = op.getBackoffDuration();
}
}
final int backoffMsWithJitter = applyJitter(highestBackoffDuration);
bulkWriterExecutor.schedule(
new Runnable() {
@Override
public void run() {
synchronized (lock) {
sendBatchLocked(pendingBatch, flush);
}
}
},
backoffMsWithJitter,
TimeUnit.MILLISECONDS);
}
/** Sends the provided batch once the rate limiter does not require any delay. */
private void sendBatchLocked(final BulkCommitBatch batch, final boolean flush) {
// Send the batch if it is does not require any delay, or schedule another attempt after the
// appropriate timeout.
boolean underRateLimit = rateLimiter.tryMakeRequest(batch.getMutationsSize());
if (underRateLimit) {
batch
.bulkCommit()
.addListener(
new Runnable() {
@Override
public void run() {