|
| 1 | +/*! |
| 2 | + * Copyright 2021 Google LLC. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import {DocumentSnapshot, DocumentSnapshotBuilder} from './document'; |
| 18 | +import {DocumentReference} from './reference'; |
| 19 | +import {FieldPath} from './path'; |
| 20 | +import {isPermanentRpcError} from './util'; |
| 21 | +import {google} from '../protos/firestore_v1_proto_api'; |
| 22 | +import {logger} from './logger'; |
| 23 | +import {Firestore} from './index'; |
| 24 | + |
| 25 | +import api = google.firestore.v1; |
| 26 | + |
| 27 | +/** |
| 28 | + * A wrapper around BatchGetDocumentsRequest that retries request upon stream |
| 29 | + * failure and returns ordered results. |
| 30 | + * |
| 31 | + * @private |
| 32 | + */ |
| 33 | +export class DocumentReader<T> { |
| 34 | + /** An optional field mask to apply to this read. */ |
| 35 | + fieldMask?: FieldPath[]; |
| 36 | + /** An optional transaction ID to use for this read. */ |
| 37 | + transactionId?: Uint8Array; |
| 38 | + |
| 39 | + private remainingDocuments = new Set<string>(); |
| 40 | + private retrievedDocuments = new Map<string, DocumentSnapshot>(); |
| 41 | + |
| 42 | + /** |
| 43 | + * Internal method to retrieve multiple documents from Firestore, optionally |
| 44 | + * as part of a transaction. |
| 45 | + * |
| 46 | + * @param firestore The Firestore instance to use. |
| 47 | + * @param allDocuments The documents to receive. |
| 48 | + * @returns A Promise that contains an array with the resulting documents. |
| 49 | + */ |
| 50 | + constructor( |
| 51 | + private firestore: Firestore, |
| 52 | + private allDocuments: Array<DocumentReference<T>> |
| 53 | + ) { |
| 54 | + for (const docRef of this.allDocuments) { |
| 55 | + this.remainingDocuments.add(docRef.formattedName); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Invokes the BatchGetDocuments RPC and returns the results. |
| 61 | + * |
| 62 | + * @param requestTag A unique client-assigned identifier for this request. |
| 63 | + */ |
| 64 | + async get(requestTag: string): Promise<Array<DocumentSnapshot<T>>> { |
| 65 | + await this.fetchAllDocuments(requestTag); |
| 66 | + |
| 67 | + // BatchGetDocuments doesn't preserve document order. We use the request |
| 68 | + // order to sort the resulting documents. |
| 69 | + const orderedDocuments: Array<DocumentSnapshot<T>> = []; |
| 70 | + |
| 71 | + for (const docRef of this.allDocuments) { |
| 72 | + const document = this.retrievedDocuments.get(docRef.formattedName); |
| 73 | + if (document !== undefined) { |
| 74 | + // Recreate the DocumentSnapshot with the DocumentReference |
| 75 | + // containing the original converter. |
| 76 | + const finalDoc = new DocumentSnapshotBuilder( |
| 77 | + docRef as DocumentReference<T> |
| 78 | + ); |
| 79 | + finalDoc.fieldsProto = document._fieldsProto; |
| 80 | + finalDoc.readTime = document.readTime; |
| 81 | + finalDoc.createTime = document.createTime; |
| 82 | + finalDoc.updateTime = document.updateTime; |
| 83 | + orderedDocuments.push(finalDoc.build()); |
| 84 | + } else { |
| 85 | + throw new Error(`Did not receive document for "${docRef.path}".`); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + return orderedDocuments; |
| 90 | + } |
| 91 | + |
| 92 | + private async fetchAllDocuments(requestTag: string): Promise<void> { |
| 93 | + while (this.remainingDocuments.size > 0) { |
| 94 | + try { |
| 95 | + return await this.fetchMoreDocuments(requestTag); |
| 96 | + } catch (err) { |
| 97 | + // If a non-transactional read failed, attempt to restart. |
| 98 | + // Transactional reads are retried via the transaction runner. |
| 99 | + if ( |
| 100 | + this.transactionId || |
| 101 | + isPermanentRpcError(err, 'batchGetDocuments') |
| 102 | + ) { |
| 103 | + logger( |
| 104 | + 'DocumentReader.fetchAllDocuments', |
| 105 | + requestTag, |
| 106 | + 'BatchGetDocuments failed with non-retryable stream error:', |
| 107 | + err |
| 108 | + ); |
| 109 | + throw err; |
| 110 | + } else { |
| 111 | + logger( |
| 112 | + 'DocumentReader.fetchAllDocuments', |
| 113 | + requestTag, |
| 114 | + 'BatchGetDocuments failed with retryable stream error:', |
| 115 | + err |
| 116 | + ); |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private fetchMoreDocuments(requestTag: string): Promise<void> { |
| 123 | + const request: api.IBatchGetDocumentsRequest = { |
| 124 | + database: this.firestore.formattedName, |
| 125 | + transaction: this.transactionId, |
| 126 | + documents: Array.from(this.remainingDocuments), |
| 127 | + }; |
| 128 | + |
| 129 | + if (this.fieldMask) { |
| 130 | + const fieldPaths = this.fieldMask.map( |
| 131 | + fieldPath => (fieldPath as FieldPath).formattedName |
| 132 | + ); |
| 133 | + request.mask = {fieldPaths}; |
| 134 | + } |
| 135 | + |
| 136 | + let resultCount = 0; |
| 137 | + |
| 138 | + return this.firestore |
| 139 | + .requestStream('batchGetDocuments', request, requestTag) |
| 140 | + .then(stream => { |
| 141 | + return new Promise<void>((resolve, reject) => { |
| 142 | + stream |
| 143 | + .on('error', err => reject(err)) |
| 144 | + .on('data', (response: api.IBatchGetDocumentsResponse) => { |
| 145 | + try { |
| 146 | + let document; |
| 147 | + |
| 148 | + if (response.found) { |
| 149 | + logger( |
| 150 | + 'DocumentReader.fetchMoreDocuments', |
| 151 | + requestTag, |
| 152 | + 'Received document: %s', |
| 153 | + response.found.name! |
| 154 | + ); |
| 155 | + document = this.firestore.snapshot_( |
| 156 | + response.found, |
| 157 | + response.readTime! |
| 158 | + ); |
| 159 | + } else { |
| 160 | + logger( |
| 161 | + 'DocumentReader.fetchMoreDocuments', |
| 162 | + requestTag, |
| 163 | + 'Document missing: %s', |
| 164 | + response.missing! |
| 165 | + ); |
| 166 | + document = this.firestore.snapshot_( |
| 167 | + response.missing!, |
| 168 | + response.readTime! |
| 169 | + ); |
| 170 | + } |
| 171 | + |
| 172 | + const path = document.ref.formattedName; |
| 173 | + this.remainingDocuments.delete(path); |
| 174 | + this.retrievedDocuments.set(path, document); |
| 175 | + ++resultCount; |
| 176 | + } catch (err) { |
| 177 | + reject(err); |
| 178 | + } |
| 179 | + }) |
| 180 | + .on('end', () => { |
| 181 | + logger( |
| 182 | + 'DocumentReader.fetchMoreDocuments', |
| 183 | + requestTag, |
| 184 | + 'Received %d results', |
| 185 | + resultCount |
| 186 | + ); |
| 187 | + resolve(); |
| 188 | + }); |
| 189 | + stream.resume(); |
| 190 | + }); |
| 191 | + }); |
| 192 | + } |
| 193 | +} |
0 commit comments