-
Notifications
You must be signed in to change notification settings - Fork 147
/
bulk-writer.ts
1191 lines (1090 loc) · 36.4 KB
/
bulk-writer.ts
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.
*/
import * as firestore from '@google-cloud/firestore';
import * as assert from 'assert';
import type {GoogleError} from 'google-gax';
import {google} from '../protos/firestore_v1_proto_api';
import {FieldPath, Firestore} from '.';
import {
DEFAULT_BACKOFF_FACTOR,
DEFAULT_BACKOFF_INITIAL_DELAY_MS,
DEFAULT_BACKOFF_MAX_DELAY_MS,
delayExecution,
MAX_RETRY_ATTEMPTS,
} from './backoff';
import {RateLimiter} from './rate-limiter';
import {Timestamp} from './timestamp';
import {
Deferred,
getRetryCodes,
isObject,
requestTag,
silencePromise,
wrapError,
} from './util';
import {WriteBatch, WriteResult} from './write-batch';
import {
invalidArgumentMessage,
validateInteger,
validateOptional,
} from './validate';
import {logger} from './logger';
import {StatusCode} from './status-code';
// eslint-disable-next-line no-undef
import GrpcStatus = FirebaseFirestore.GrpcStatus;
import api = google.firestore.v1;
/*!
* The maximum number of writes that can be in a single batch.
*/
const MAX_BATCH_SIZE = 20;
/*!
* The maximum number of writes can be can in a single batch that is being retried.
*/
export const RETRY_MAX_BATCH_SIZE = 10;
/*!
* The starting maximum number of operations per second as allowed by the
* 500/50/5 rule.
*
* https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic.
*/
export const DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT = 500;
/*!
* The maximum number of operations per second as allowed by the 500/50/5 rule.
* By default the rate limiter will not exceed this value.
*
* https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic.
*/
export const DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT = 10000;
/*!
* 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.
*/
export const DEFAULT_JITTER_FACTOR = 0.3;
/*!
* The rate by which to increase the capacity as specified by the 500/50/5 rule.
*/
const RATE_LIMITER_MULTIPLIER = 1.5;
/*!
* How often the operations per second capacity should increase in milliseconds
* as specified by the 500/50/5 rule.
*/
const 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.
*/
const DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT = 500;
/**
* Represents a single write for BulkWriter, encapsulating operation dispatch
* and error handling.
* @private
* @internal
*/
class BulkWriterOperation {
private deferred = new Deferred<WriteResult>();
private failedAttempts = 0;
private lastStatus?: StatusCode;
private _backoffDuration = 0;
/** Whether flush() was called when this was the last enqueued operation. */
private _flushed = false;
/**
* @param ref The document reference being written to.
* @param type The type of operation that created this write.
* @param sendFn A callback to invoke when the operation should be sent.
* @param errorFn The user provided global error callback.
* @param successFn The user provided global success callback.
*/
constructor(
readonly ref: firestore.DocumentReference<unknown>,
private readonly type: 'create' | 'set' | 'update' | 'delete',
private readonly sendFn: (op: BulkWriterOperation) => void,
private readonly errorFn: (error: BulkWriterError) => boolean,
private readonly successFn: (
ref: firestore.DocumentReference<unknown>,
result: WriteResult
) => void
) {}
get promise(): Promise<WriteResult> {
return this.deferred.promise;
}
get backoffDuration(): number {
return this._backoffDuration;
}
markFlushed(): void {
this._flushed = true;
}
get flushed(): boolean {
return this._flushed;
}
onError(error: GoogleError): void {
++this.failedAttempts;
try {
const bulkWriterError = new BulkWriterError(
error.code as number as GrpcStatus,
error.message,
this.ref,
this.type,
this.failedAttempts
);
const shouldRetry = this.errorFn(bulkWriterError);
logger(
'BulkWriter.errorFn',
null,
'Ran error callback on error code:',
error.code,
', shouldRetry:',
shouldRetry,
' for document:',
this.ref.path
);
if (shouldRetry) {
this.lastStatus = error.code as number;
this.updateBackoffDuration();
this.sendFn(this);
} else {
this.deferred.reject(bulkWriterError);
}
} catch (userCallbackError) {
this.deferred.reject(userCallbackError);
}
}
private updateBackoffDuration(): void {
if (this.lastStatus === StatusCode.RESOURCE_EXHAUSTED) {
this._backoffDuration = DEFAULT_BACKOFF_MAX_DELAY_MS;
} else if (this._backoffDuration === 0) {
this._backoffDuration = DEFAULT_BACKOFF_INITIAL_DELAY_MS;
} else {
this._backoffDuration *= DEFAULT_BACKOFF_FACTOR;
}
}
onSuccess(result: WriteResult): void {
try {
this.successFn(this.ref, result);
this.deferred.resolve(result);
} catch (userCallbackError) {
this.deferred.reject(userCallbackError);
}
}
}
/**
* Used to represent a batch on the BatchQueue.
*
* @private
* @internal
*/
class BulkCommitBatch extends WriteBatch {
// The set of document reference paths present in the WriteBatch.
readonly docPaths = new Set<string>();
// An array of pending write operations. Only contains writes that have not
// been resolved.
readonly pendingOps: Array<BulkWriterOperation> = [];
private _maxBatchSize: number;
constructor(firestore: Firestore, maxBatchSize: number) {
super(firestore);
this._maxBatchSize = maxBatchSize;
}
get maxBatchSize(): number {
return this._maxBatchSize;
}
setMaxBatchSize(size: number): void {
assert(
this.pendingOps.length <= size,
'New batch size cannot be less than the number of enqueued writes'
);
this._maxBatchSize = size;
}
has(documentRef: firestore.DocumentReference<unknown>): boolean {
return this.docPaths.has(documentRef.path);
}
async bulkCommit(options: {requestTag?: string} = {}): Promise<void> {
const tag = options?.requestTag ?? requestTag();
// Capture the error stack to preserve stack tracing across async calls.
const stack = Error().stack!;
let response: api.IBatchWriteResponse;
try {
logger(
'BulkCommitBatch.bulkCommit',
tag,
`Sending next batch with ${this._opCount} writes`
);
const retryCodes = getRetryCodes('batchWrite');
response = await this._commit<
api.BatchWriteRequest,
api.BatchWriteResponse
>({retryCodes, methodName: 'batchWrite', requestTag: tag});
} catch (err) {
// Map the failure to each individual write's result.
const ops = Array.from({length: this.pendingOps.length});
response = {
writeResults: ops.map(() => {
return {};
}),
status: ops.map(() => err),
};
}
for (let i = 0; i < (response.writeResults || []).length; ++i) {
// Since delete operations currently do not have write times, use a
// sentinel Timestamp value.
// TODO(b/158502664): Use actual delete timestamp.
const DELETE_TIMESTAMP_SENTINEL = Timestamp.fromMillis(0);
const status = (response.status || [])[i];
if (status.code === StatusCode.OK) {
const updateTime = Timestamp.fromProto(
response.writeResults![i].updateTime || DELETE_TIMESTAMP_SENTINEL
);
this.pendingOps[i].onSuccess(new WriteResult(updateTime));
} else {
const error =
new (require('google-gax/build/src/fallback').GoogleError)(
status.message || undefined
);
error.code = status.code as number;
this.pendingOps[i].onError(wrapError(error, stack));
}
}
}
/**
* Helper to update data structures associated with the operation and returns
* the result.
*/
processLastOperation(op: BulkWriterOperation): void {
assert(
!this.docPaths.has(op.ref.path),
'Batch should not contain writes to the same document'
);
this.docPaths.add(op.ref.path);
this.pendingOps.push(op);
}
}
/**
* Used to represent a buffered BulkWriterOperation.
*
* @private
* @internal
*/
class BufferedOperation {
constructor(
readonly operation: BulkWriterOperation,
readonly sendFn: () => void
) {}
}
/**
* The error thrown when a BulkWriter operation fails.
*
* @class BulkWriterError
*/
export class BulkWriterError extends Error {
/**
* @private
* @internal
*/
constructor(
/** The status code of the error. */
readonly code: GrpcStatus,
/** The error message of the error. */
readonly message: string,
/** The document reference the operation was performed on. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly documentRef: firestore.DocumentReference<any, any>,
/** The type of operation performed. */
readonly operationType: 'create' | 'set' | 'update' | 'delete',
/** How many times this operation has been attempted unsuccessfully. */
readonly failedAttempts: number
) {
super(message);
}
}
/**
* A Firestore BulkWriter that can be used to perform a large number of writes
* in parallel.
*
* @class BulkWriter
*/
export class BulkWriter {
/**
* The maximum number of writes that can be in a single batch.
* Visible for testing.
* @private
* @internal
*/
private _maxBatchSize = MAX_BATCH_SIZE;
/**
* The batch that is currently used to schedule operations. Once this batch
* reaches maximum capacity, a new batch is created.
* @private
* @internal
*/
private _bulkCommitBatch = new BulkCommitBatch(
this.firestore,
this._maxBatchSize
);
/**
* A pointer to the tail of all active BulkWriter operations. This pointer
* is advanced every time a new write is enqueued.
* @private
* @internal
*/
private _lastOp: Promise<void> = Promise.resolve();
/**
* Whether this BulkWriter instance has started to close. Afterwards, no
* new operations can be enqueued, except for retry operations scheduled by
* the error handler.
* @private
* @internal
*/
private _closing = false;
/**
* Rate limiter used to throttle requests as per the 500/50/5 rule.
* Visible for testing.
* @private
* @internal
*/
readonly _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.
* @private
* @internal
*/
private _pendingOpsCount = 0;
/**
* An array containing buffered BulkWriter operations after the maximum number
* of pending operations has been enqueued.
* @private
* @internal
*/
private _bufferedOperations: Array<BufferedOperation> = [];
/**
* Whether a custom error handler has been set. BulkWriter only swallows
* errors if an error handler is set. Otherwise, an UnhandledPromiseRejection
* is thrown by Node if an operation promise is rejected without being
* handled.
* @private
* @internal
*/
private _errorHandlerSet = false;
// Visible for testing.
/**
* @private
* @internal
*/
_getBufferedOperationsCount(): number {
return this._bufferedOperations.length;
}
// Visible for testing.
/**
* @private
* @internal
*/
_setMaxBatchSize(size: number): void {
assert(
this._bulkCommitBatch.pendingOps.length === 0,
'BulkCommitBatch should be empty'
);
this._maxBatchSize = size;
this._bulkCommitBatch = new BulkCommitBatch(this.firestore, size);
}
/**
* 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
* @internal
*/
private _maxPendingOpCount = DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT;
// Visible for testing.
/**
* @private
* @internal
*/
_setMaxPendingOpCount(newMax: number): void {
this._maxPendingOpCount = newMax;
}
/**
* The user-provided callback to be run every time a BulkWriter operation
* successfully completes.
* @private
* @internal
*/
private _successFn: (
document: firestore.DocumentReference<unknown>,
result: WriteResult
) => void = () => {};
/**
* The user-provided callback to be run every time a BulkWriter operation
* fails.
* @private
* @internal
*/
private _errorFn: (error: BulkWriterError) => boolean = error => {
const isRetryableDeleteError =
error.operationType === 'delete' &&
(error.code as number) === StatusCode.INTERNAL;
const retryCodes = getRetryCodes('batchWrite');
return (
(retryCodes.includes(error.code) || isRetryableDeleteError) &&
error.failedAttempts < MAX_RETRY_ATTEMPTS
);
};
/** @private */
constructor(
private readonly firestore: Firestore,
options?: firestore.BulkWriterOptions
) {
this.firestore._incrementBulkWritersCount();
validateBulkWriterOptions(options);
if (options?.throttling === false) {
this._rateLimiter = new RateLimiter(
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY
);
} else {
let startingRate = DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT;
let maxRate = DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT;
if (typeof options?.throttling !== 'boolean') {
if (options?.throttling?.maxOpsPerSecond !== undefined) {
maxRate = options.throttling.maxOpsPerSecond;
}
if (options?.throttling?.initialOpsPerSecond !== undefined) {
startingRate = options.throttling.initialOpsPerSecond;
}
// 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 < this._maxBatchSize) {
this._maxBatchSize = startingRate;
}
}
this._rateLimiter = new RateLimiter(
startingRate,
RATE_LIMITER_MULTIPLIER,
RATE_LIMITER_MULTIPLIER_MILLIS,
maxRate
);
}
}
/**
* Create a document with the provided data. This single operation will fail
* if a document exists at its location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {T} data The object to serialize as the document.
* @throws {Error} If the provided input is not a valid Firestore document.
* @returns {Promise<WriteResult>} A promise that resolves with the result of
* the write. If the write fails, the promise is rejected with a
* [BulkWriterError]{@link BulkWriterError}.
*
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
* let documentRef = firestore.collection('col').doc();
*
* bulkWriter
* .create(documentRef, {foo: 'bar'})
* .then(result => {
* console.log('Successfully executed write at: ', result);
* })
* .catch(err => {
* console.log('Write failed with: ', err);
* });
* });
* ```
*/
create<AppModelType, DbModelType extends firestore.DocumentData>(
documentRef: firestore.DocumentReference<AppModelType, DbModelType>,
data: firestore.WithFieldValue<AppModelType>
): Promise<WriteResult> {
this._verifyNotClosed();
return this._enqueue(documentRef, 'create', bulkCommitBatch =>
bulkCommitBatch.create(documentRef, data)
);
}
/**
* Delete a document from the database.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the batch if the
* document doesn't exist or was last updated at a different time.
* @returns {Promise<WriteResult>} A promise that resolves with the result of
* the delete. If the delete fails, the promise is rejected with a
* [BulkWriterError]{@link BulkWriterError}.
*
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
* let documentRef = firestore.doc('col/doc');
*
* bulkWriter
* .delete(documentRef)
* .then(result => {
* console.log('Successfully deleted document');
* })
* .catch(err => {
* console.log('Delete failed with: ', err);
* });
* });
* ```
*/
delete<AppModelType, DbModelType extends firestore.DocumentData>(
documentRef: firestore.DocumentReference<AppModelType, DbModelType>,
precondition?: firestore.Precondition
): Promise<WriteResult> {
this._verifyNotClosed();
return this._enqueue(documentRef, 'delete', bulkCommitBatch =>
bulkCommitBatch.delete(documentRef, precondition)
);
}
set<AppModelType, DbModelType extends firestore.DocumentData>(
documentRef: firestore.DocumentReference<AppModelType, DbModelType>,
data: Partial<AppModelType>,
options: firestore.SetOptions
): Promise<WriteResult>;
set<AppModelType, DbModelType extends firestore.DocumentData>(
documentRef: firestore.DocumentReference<AppModelType, DbModelType>,
data: AppModelType
): Promise<WriteResult>;
/**
* Write to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document does not
* exist yet, it will be created. If you pass [SetOptions]{@link SetOptions}.,
* the provided data can be merged into the existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {T} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @throws {Error} If the provided input is not a valid Firestore document.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call remain
* untouched. If your input sets any field to an empty map, all nested fields
* are overwritten.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided, set()
* only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched. If your input sets any field to
* an empty map, all nested fields are overwritten.
* @returns {Promise<WriteResult>} A promise that resolves with the result of
* the write. If the write fails, the promise is rejected with a
* [BulkWriterError]{@link BulkWriterError}.
*
*
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
* let documentRef = firestore.collection('col').doc();
*
* bulkWriter
* .set(documentRef, {foo: 'bar'})
* .then(result => {
* console.log('Successfully executed write at: ', result);
* })
* .catch(err => {
* console.log('Write failed with: ', err);
* });
* });
* ```
*/
set<AppModelType, DbModelType extends firestore.DocumentData>(
documentRef: firestore.DocumentReference<AppModelType, DbModelType>,
data: firestore.PartialWithFieldValue<AppModelType>,
options?: firestore.SetOptions
): Promise<WriteResult> {
this._verifyNotClosed();
return this._enqueue(documentRef, 'set', bulkCommitBatch => {
if (options) {
return bulkCommitBatch.set(documentRef, data, options);
} else {
return bulkCommitBatch.set(
documentRef,
data as firestore.WithFieldValue<AppModelType>
);
}
});
}
/**
* Update fields of the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document doesn't yet
* exist, the update fails and the entire batch will be rejected.
*
* 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.
*
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object containing the
* fields and values with which to update the document or the path of the
* first field to update.
* @param {...(Precondition|*|string|FieldPath)} preconditionOrValues - An
* alternating list of field paths and values to update or a Precondition to
* restrict this update
* @throws {Error} If the provided input is not valid Firestore data.
* @returns {Promise<WriteResult>} A promise that resolves with the result of
* the write. If the write fails, the promise is rejected with a
* [BulkWriterError]{@link BulkWriterError}.
*
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
* let documentRef = firestore.doc('col/doc');
*
* bulkWriter
* .update(documentRef, {foo: 'bar'})
* .then(result => {
* console.log('Successfully executed write at: ', result);
* })
* .catch(err => {
* console.log('Write failed with: ', err);
* });
* });
* ```
*/
update<AppModelType, DbModelType extends firestore.DocumentData>(
documentRef: firestore.DocumentReference<AppModelType, DbModelType>,
dataOrField: firestore.UpdateData<DbModelType> | string | FieldPath,
...preconditionOrValues: Array<
{lastUpdateTime?: Timestamp} | unknown | string | FieldPath
>
): Promise<WriteResult> {
this._verifyNotClosed();
return this._enqueue(documentRef, 'update', bulkCommitBatch =>
bulkCommitBatch.update(documentRef, dataOrField, ...preconditionOrValues)
);
}
/**
* Callback function set by {@link BulkWriter#onWriteResult} that is run
* every time a {@link BulkWriter} operation successfully completes.
*
* @callback BulkWriter~successCallback
* @param {DocumentReference} documentRef The document reference the
* operation was performed on
* @param {WriteResult} result The server write time of the operation.
*/
/**
* Attaches a listener that is run every time a BulkWriter operation
* successfully completes.
*
* @param {BulkWriter~successCallback} successCallback A callback to be
* called every time a BulkWriter operation successfully completes.
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
*
* bulkWriter
* .onWriteResult((documentRef, result) => {
* console.log(
* 'Successfully executed write on document: ',
* documentRef,
* ' at: ',
* result
* );
* });
* ```
*/
onWriteResult(
successCallback: (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
documentRef: firestore.DocumentReference<any, any>,
result: WriteResult
) => void
): void {
this._successFn = successCallback;
}
/**
* Callback function set by {@link BulkWriter#onWriteError} that is run when
* a write fails in order to determine whether {@link BulkWriter} should
* retry the operation.
*
* @callback BulkWriter~shouldRetryCallback
* @param {BulkWriterError} error The error object with information about the
* operation and error.
* @returns {boolean} Whether or not to retry the failed operation. Returning
* `true` retries the operation. Returning `false` will stop the retry loop.
*/
/**
* Attaches an error handler listener that is run every time a BulkWriter
* operation fails.
*
* 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.
*
* @param shouldRetryCallback {BulkWriter~shouldRetryCallback} A callback to
* be called every time a BulkWriter operation fails. Returning `true` will
* retry the operation. Returning `false` will stop the retry loop.
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
*
* bulkWriter
* .onWriteError((error) => {
* if (
* error.code === GrpcStatus.UNAVAILABLE &&
* error.failedAttempts < MAX_RETRY_ATTEMPTS
* ) {
* return true;
* } else {
* console.log('Failed write at document: ', error.documentRef);
* return false;
* }
* });
* ```
*/
onWriteError(shouldRetryCallback: (error: BulkWriterError) => boolean): void {
this._errorHandlerSet = true;
this._errorFn = shouldRetryCallback;
}
/**
* Commits all writes that have been enqueued up to this point in parallel.
*
* Returns a Promise that resolves when all currently queued operations have
* been committed. The Promise will never be rejected since the results for
* each individual operation are conveyed via their individual Promises.
*
* The Promise resolves immediately if there are no pending writes. Otherwise,
* the Promise 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 {Promise<void>} A promise that resolves when all enqueued writes
* up to this point have been committed.
*
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
*
* bulkWriter.create(documentRef, {foo: 'bar'});
* bulkWriter.update(documentRef2, {foo: 'bar'});
* bulkWriter.delete(documentRef3);
* await flush().then(() => {
* console.log('Executed all writes');
* });
* ```
*/
flush(): Promise<void> {
this._verifyNotClosed();
this._scheduleCurrentBatch(/* flush= */ true);
// Mark the most recent operation as flushed to ensure that the batch
// containing it will be sent once it's popped from the buffer.
if (this._bufferedOperations.length > 0) {
this._bufferedOperations[
this._bufferedOperations.length - 1
].operation.markFlushed();
}
return this._lastOp;
}
/**
* Commits all enqueued writes and marks the BulkWriter instance as closed.
*
* After calling `close()`, calling any method will throw an error. Any
* retries scheduled as part of an `onWriteError()` handler will be run
* before the `close()` promise resolves.
*
* Returns a Promise that resolves when there are no more pending writes. The
* Promise will never be rejected. Calling this method will send all requests.
* The promise resolves immediately if there are no pending writes.
*
* @return {Promise<void>} A promise that resolves when all enqueued writes
* up to this point have been committed.
*
* @example
* ```
* let bulkWriter = firestore.bulkWriter();
*
* bulkWriter.create(documentRef, {foo: 'bar'});
* bulkWriter.update(documentRef2, {foo: 'bar'});
* bulkWriter.delete(documentRef3);
* await close().then(() => {
* console.log('Executed all writes');
* });
* ```
*/
close(): Promise<void> {
this._verifyNotClosed();
this.firestore._decrementBulkWritersCount();
const flushPromise = this.flush();
this._closing = true;
return flushPromise;
}
/**
* Throws an error if the BulkWriter instance has been closed.
* @private
* @internal
*/
_verifyNotClosed(): void {
if (this._closing) {
throw new Error('BulkWriter has already been closed.');
}
}
/**
* Sends the current batch and resets `this._bulkCommitBatch`.
*
* @param flush If provided, keeps re-sending operations until no more
* operations are enqueued. This allows retries to resolve as part of a
* `flush()` or `close()` call.
* @private
* @internal
*/
private _scheduleCurrentBatch(flush = false): void {
if (this._bulkCommitBatch._opCount === 0) return;
const pendingBatch = this._bulkCommitBatch;
this._bulkCommitBatch = new BulkCommitBatch(
this.firestore,
this._maxBatchSize
);
// Use the write with the longest backoff duration when determining backoff.
const highestBackoffDuration = pendingBatch.pendingOps.reduce(
(prev, cur) => (prev.backoffDuration > cur.backoffDuration ? prev : cur)
).backoffDuration;
const backoffMsWithJitter = BulkWriter._applyJitter(highestBackoffDuration);
const delayedExecution = new Deferred<void>();
if (backoffMsWithJitter > 0) {
delayExecution(() => delayedExecution.resolve(), backoffMsWithJitter);
} else {
delayedExecution.resolve();
}
delayedExecution.promise.then(() => this._sendBatch(pendingBatch, flush));
}
/**
* Sends the provided batch once the rate limiter does not require any delay.
* @private
* @internal
*/
private async _sendBatch(
batch: BulkCommitBatch,
flush = false
): Promise<void> {
const tag = requestTag();
// Send the batch if it is does not require any delay, or schedule another
// attempt after the appropriate timeout.
const underRateLimit = this._rateLimiter.tryMakeRequest(batch._opCount);
if (underRateLimit) {
await batch.bulkCommit({requestTag: tag});
if (flush) this._scheduleCurrentBatch(flush);
} else {
const delayMs = this._rateLimiter.getNextRequestDelayMs(batch._opCount);
logger(
'BulkWriter._sendBatch',
tag,
`Backing off for ${delayMs} seconds`
);
delayExecution(() => this._sendBatch(batch, flush), delayMs);
}
}
/**
* Adds a 30% jitter to the provided backoff.
*
* @private
* @internal
*/
private static _applyJitter(backoffMs: number): number {
if (backoffMs === 0) return 0;
// Random value in [-0.3, 0.3].