-
Notifications
You must be signed in to change notification settings - Fork 145
/
bulk-writer.ts
663 lines (613 loc) · 20 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
/*!
* 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 assert from 'assert';
import {FieldPath, Firestore} from '.';
import {delayExecution} from './backoff';
import {RateLimiter} from './rate-limiter';
import {DocumentReference} from './reference';
import {Timestamp} from './timestamp';
import {Precondition, SetOptions, UpdateData} from './types';
import {Deferred, wrapError} from './util';
import {BatchWriteResult, WriteBatch, WriteResult} from './write-batch';
/*!
* The maximum number of writes that can be in a single batch.
*/
const MAX_BATCH_SIZE = 500;
/*!
* The starting maximum number of operations per second as allowed by the
* 500/50/5 rule.
*
* https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic.
*/
const STARTING_MAXIMUM_OPS_PER_SECOND = 500;
/*!
* The rate by which to increase the capacity as specified by the 500/50/5 rule.
*
* https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic.
*/
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.
*
* https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic.
*/
const RATE_LIMITER_MULTIPLIER_MILLIS = 5 * 60 * 1000;
/*!
* Used to represent the state of batch.
*
* 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,
}
/**
* Used to represent a batch on the BatchQueue.
*
* @private
*/
class BulkCommitBatch {
/**
* The state of the batch.
*/
state = BatchState.OPEN;
// The set of document reference paths present in the WriteBatch.
readonly docPaths = new Set<string>();
// A deferred promise that is resolved after the batch has been sent, and a
// response is received.
private completedDeferred = new Deferred<void>();
// A map from each WriteBatch operation to its corresponding result.
private resultsMap = new Map<number, Deferred<BatchWriteResult>>();
constructor(
private readonly writeBatch: WriteBatch,
private readonly maxBatchSize: number
) {}
/**
* The number of writes in this batch.
*/
get opCount(): number {
return this.resultsMap.size;
}
/**
* Adds a `create` operation to the WriteBatch. Returns a promise that
* resolves with the result of the write.
*/
create<T>(documentRef: DocumentReference<T>, data: T): Promise<WriteResult> {
this.writeBatch.create(documentRef, data);
return this.processOperation(documentRef);
}
/**
* Adds a `delete` operation to the WriteBatch. Returns a promise that
* resolves with the result of the delete.
*/
delete<T>(
documentRef: DocumentReference<T>,
precondition?: Precondition
): Promise<WriteResult> {
this.writeBatch.delete(documentRef, precondition);
return this.processOperation(documentRef);
}
/**
* Adds a `set` operation to the WriteBatch. Returns a promise that
* resolves with the result of the write.
*/
set<T>(
documentRef: DocumentReference<T>,
data: T,
options?: SetOptions
): Promise<WriteResult> {
this.writeBatch.set(documentRef, data, options);
return this.processOperation(documentRef);
}
/**
* Adds an `update` operation to the WriteBatch. Returns a promise that
* resolves with the result of the write.
*/
update<T>(
documentRef: DocumentReference<T>,
dataOrField: UpdateData | string | FieldPath,
...preconditionOrValues: Array<
{lastUpdateTime?: Timestamp} | unknown | string | FieldPath
>
): Promise<WriteResult> {
this.writeBatch.update(documentRef, dataOrField, ...preconditionOrValues);
return this.processOperation(documentRef);
}
/**
* Helper to update data structures associated with the operation and
* return the result.
*/
private processOperation<T>(
documentRef: DocumentReference<T>
): Promise<WriteResult> {
assert(
!this.docPaths.has(documentRef.path),
'Batch should not contain writes to the same document'
);
assert(
this.state === BatchState.OPEN,
'Batch should be OPEN when adding writes'
);
this.docPaths.add(documentRef.path);
const deferred = new Deferred<BatchWriteResult>();
this.resultsMap.set(this.opCount, deferred);
if (this.opCount === this.maxBatchSize) {
this.state = BatchState.READY_TO_SEND;
}
return deferred.promise.then(result => {
if (result.writeTime) {
return new WriteResult(result.writeTime);
} else {
throw result.status;
}
});
}
/**
* Commits the batch and returns a promise that resolves with the result of
* all writes in this batch.
*/
bulkCommit(): Promise<BatchWriteResult[]> {
assert(
this.state === BatchState.READY_TO_SEND,
'The batch should be marked as READY_TO_SEND before committing'
);
this.state = BatchState.SENT;
// Capture the error stack to preserve stack tracing across async calls.
const stack = Error().stack!;
return this.writeBatch.bulkCommit().catch(err => {
throw wrapError(err, stack);
});
}
/**
* Resolves the individual operations in the batch with the results.
*/
processResults(results: BatchWriteResult[], error?: Error): void {
if (error === undefined) {
for (let i = 0; i < this.opCount; i++) {
this.resultsMap.get(i)!.resolve(results[i]);
}
} else {
for (let i = 0; i < this.opCount; i++) {
this.resultsMap.get(i)!.reject(error);
}
}
this.completedDeferred.resolve();
}
/**
* Returns a promise that resolves when the batch has been sent, and a
* response is received.
*/
awaitBulkCommit(): Promise<void> {
this.markReadyToSend();
return this.completedDeferred.promise;
}
markReadyToSend(): void {
if (this.state === BatchState.OPEN) {
this.state = BatchState.READY_TO_SEND;
}
}
}
/**
* A Firestore BulkWriter than can be used to perform a large number of writes
* in parallel. Writes to the same document will be executed sequentially.
*
* @class
* @private
*/
export class BulkWriter {
/**
* The maximum number of writes that can be in a single batch.
*/
private maxBatchSize = MAX_BATCH_SIZE;
/**
* A queue of batches to be written.
*/
private batchQueue: BulkCommitBatch[] = [];
/**
* Whether this BulkWriter instance is closed. Once closed, it cannot be
* opened again.
*/
private closed = false;
/**
* Rate limiter used to throttle requests as per the 500/50/5 rule.
*/
private rateLimiter: RateLimiter;
constructor(
private readonly firestore: Firestore,
enableThrottling: boolean
) {
if (enableThrottling) {
this.rateLimiter = new RateLimiter(
STARTING_MAXIMUM_OPS_PER_SECOND,
RATE_LIMITER_MULTIPLIER,
RATE_LIMITER_MULTIPLIER_MILLIS
);
} else {
this.rateLimiter = new RateLimiter(
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY
);
}
}
/**
* 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.
* @returns {Promise<WriteResult>} A promise that resolves with the result of
* the write. Throws an error if the write fails.
*
* @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<T>(documentRef: DocumentReference<T>, data: T): Promise<WriteResult> {
this.verifyNotClosed();
const bulkCommitBatch = this.getEligibleBatch(documentRef);
const resultPromise = bulkCommitBatch.create(documentRef, data);
this.sendReadyBatches();
return resultPromise;
}
/**
* 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 write. Throws an error if the write fails.
*
* @example
* let bulkWriter = firestore.bulkWriter();
* let documentRef = firestore.doc('col/doc');
*
* bulkWriter
* .delete(documentRef)
* .then(result => {
* console.log('Successfully deleted document at: ', result);
* })
* .catch(err => {
* console.log('Delete failed with: ', err);
* });
* });
*/
delete<T>(
documentRef: DocumentReference<T>,
precondition?: Precondition
): Promise<WriteResult> {
this.verifyNotClosed();
const bulkCommitBatch = this.getEligibleBatch(documentRef);
const resultPromise = bulkCommitBatch.delete(documentRef, precondition);
this.sendReadyBatches();
return resultPromise;
}
/**
* 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.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call remain
* untouched.
* @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.
* @returns {Promise<WriteResult>} A promise that resolves with the result of
* the write. Throws an error if the write fails.
*
*
* @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<T>(
documentRef: DocumentReference<T>,
data: T,
options?: SetOptions
): Promise<WriteResult> {
this.verifyNotClosed();
const bulkCommitBatch = this.getEligibleBatch(documentRef);
const resultPromise = bulkCommitBatch.set(documentRef, data, options);
this.sendReadyBatches();
return resultPromise;
}
/**
* 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
* @returns {Promise<WriteResult>} A promise that resolves with the result of
* the write. Throws an error if the write fails.
*
*
* @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<T>(
documentRef: DocumentReference,
dataOrField: UpdateData | string | FieldPath,
...preconditionOrValues: Array<
{lastUpdateTime?: Timestamp} | unknown | string | FieldPath
>
): Promise<WriteResult> {
this.verifyNotClosed();
const bulkCommitBatch = this.getEligibleBatch(documentRef);
const resultPromise = bulkCommitBatch.update(
documentRef,
dataOrField,
...preconditionOrValues
);
this.sendReadyBatches();
return resultPromise;
}
/**
* 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');
* });
*/
async flush(): Promise<void> {
this.verifyNotClosed();
const trackedBatches = this.batchQueue;
const writePromises = trackedBatches.map(batch => batch.awaitBulkCommit());
this.sendReadyBatches();
await Promise.all(writePromises);
}
/**
* Commits all enqueued writes and marks the BulkWriter instance as closed.
*
* After calling `close()`, calling any method wil throw an error.
*
* 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> {
const flushPromise = this.flush();
this.closed = true;
return flushPromise;
}
private verifyNotClosed(): void {
if (this.closed) {
throw new Error('BulkWriter has already been closed.');
}
}
/**
* Return the first eligible batch that can hold a write to the provided
* reference, or creates one if no eligible batches are found.
*
* @private
*/
private getEligibleBatch<T>(ref: DocumentReference<T>): BulkCommitBatch {
if (this.batchQueue.length > 0) {
const lastBatch = this.batchQueue[this.batchQueue.length - 1];
if (
lastBatch.state === BatchState.OPEN &&
!lastBatch.docPaths.has(ref.path)
) {
return lastBatch;
}
}
return this.createNewBatch();
}
/**
* Creates a new batch and adds it to the BatchQueue. If there is already a
* batch enqueued, sends the batch after a new one is created.
*
* @private
*/
private createNewBatch(): BulkCommitBatch {
const newBatch = new BulkCommitBatch(
this.firestore.batch(),
this.maxBatchSize
);
if (this.batchQueue.length > 0) {
this.batchQueue[this.batchQueue.length - 1].markReadyToSend();
this.sendReadyBatches();
}
this.batchQueue.push(newBatch);
return newBatch;
}
/**
* Attempts to send batches starting from the front of the BatchQueue until a
* batch cannot be sent.
*
* After a batch is complete, try sending batches again.
*
* @private
*/
private sendReadyBatches(): void {
const unsentBatches = this.batchQueue.filter(
batch => batch.state === BatchState.READY_TO_SEND
);
let index = 0;
while (
index < unsentBatches.length &&
this.isBatchSendable(unsentBatches[index])
) {
const batch = unsentBatches[index];
// Send the batch if it is under the rate limit, or schedule another
// attempt after the appropriate timeout.
const delayMs = this.rateLimiter.getNextRequestDelayMs(batch.opCount);
assert(delayMs !== -1, 'Batch size should be under capacity');
if (delayMs === 0) {
this.sendBatch(batch);
} else {
delayExecution(() => this.sendReadyBatches(), delayMs);
break;
}
index++;
}
}
/**
* Sends the provided batch and processes the results. After the batch is
* committed, sends the next group of ready batches.
*
* @private
*/
private sendBatch(batch: BulkCommitBatch): void {
const success = this.rateLimiter.tryMakeRequest(batch.opCount);
assert(success, 'Batch should be under rate limit to be sent.');
batch
.bulkCommit()
.then(results => {
batch.processResults(results);
})
.catch((error: Error) => {
batch.processResults([], error);
})
.then(() => {
// Remove the batch from the BatchQueue after it has been processed.
const batchIndex = this.batchQueue.indexOf(batch);
assert(batchIndex !== -1, 'The batch should be in the BatchQueue');
this.batchQueue.splice(batchIndex, 1);
this.sendReadyBatches();
});
}
/**
* Checks that the provided batch is sendable. To be sendable, a batch must:
* (1) be marked as READY_TO_SEND
* (2) not write to references that are currently in flight
*
* @private
*/
private isBatchSendable(batch: BulkCommitBatch): boolean {
if (batch.state !== BatchState.READY_TO_SEND) {
return false;
}
for (const path of batch.docPaths) {
const isRefInFlight =
this.batchQueue
.filter(batch => batch.state === BatchState.SENT)
.find(batch => batch.docPaths.has(path)) !== undefined;
if (isRefInFlight) {
console.warn(
'[BulkWriter]',
`Duplicate write to document "${path}" detected.`,
'Writing to the same document multiple times will slow down BulkWriter. ' +
'Write to unique documents in order to maximize throughput.'
);
return false;
}
}
return true;
}
/**
* Sets the maximum number of allowed operations in a batch.
*
* @private
*/
// Visible for testing.
_setMaxBatchSize(size: number): void {
this.maxBatchSize = size;
}
}