-
Notifications
You must be signed in to change notification settings - Fork 937
Implement Firestore IndexBackfiller #6261
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
104964e
Integrate Document Overlay with the SDK (#6123)
ehsannas bdd3eae
Overlay migration (#6131)
ehsannas 2aabc42
Implement IndexBackfiller
tom-andersen 1ac2934
Format
tom-andersen 235564b
Fix unbound method
tom-andersen 736385e
Update overlay migration code to use DbMutationBatchStore (#6268)
ehsannas 737284a
Implement IndexBackfiller
tom-andersen 4a319ee
Format
tom-andersen d999f11
Fix unbound method
tom-andersen 5890b8c
Add Index Backfiller test
tom-andersen 0c7b979
Add more Index Backfiller tests
tom-andersen 1023247
Merge remote-tracking branch 'origin/tomandersen/index-backfiller' in…
tom-andersen 1c1c814
Add more Index Backfiller tests
tom-andersen e0a06e7
Changes by andy1
tom-andersen f613c3a
Make sqlite3 as dev dependency
tom-andersen 1a12a6e
Remove sqlite3 as dev dependency
tom-andersen e370c7b
Prettier
tom-andersen 776d95a
Revert
tom-andersen 4028824
Merge remote-tracking branch 'origin/master' into tomandersen/index-b…
tom-andersen 00dd2f7
Fix after merge. Make tests pass.
tom-andersen f24b0f6
Merge branch 'master' of https://github.com/firebase/firebase-js-sdk …
tom-andersen 05522e2
Fix according to PR comments
tom-andersen 665d71f
Keep INDEXING_ENABLED flag since Web implementation is still incomplete.
tom-andersen 6c5576f
Refactor getMinOffsetFromFieldIndexes to follow Android implementatio…
tom-andersen 90c4227
Disable IndexBackfiller and tests
tom-andersen fa1238f
Disable IndexBackfiller and tests
tom-andersen c4f87be
Lint
tom-andersen 7b8398d
Refactor with type OverlayedDocumentMap. Add Comments. Fix nit.
tom-andersen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,223 @@ | ||
/** | ||
* @license | ||
* Copyright 2022 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 { DocumentMap } from '../model/collections'; | ||
import { | ||
IndexOffset, | ||
indexOffsetComparator, | ||
newIndexOffsetFromDocument | ||
} from '../model/field_index'; | ||
import { debugAssert } from '../util/assert'; | ||
import { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue'; | ||
import { logDebug } from '../util/log'; | ||
|
||
import { INDEXING_ENABLED } from './indexeddb_schema'; | ||
import { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store'; | ||
import { LocalWriteResult } from './local_store_impl'; | ||
import { Persistence, Scheduler } from './persistence'; | ||
import { PersistencePromise } from './persistence_promise'; | ||
import { PersistenceTransaction } from './persistence_transaction'; | ||
import { isIndexedDbTransactionError } from './simple_db'; | ||
|
||
const LOG_TAG = 'IndexBackiller'; | ||
|
||
/** How long we wait to try running index backfill after SDK initialization. */ | ||
const INITIAL_BACKFILL_DELAY_MS = 15; | ||
|
||
/** Minimum amount of time between backfill checks, after the first one. */ | ||
const REGULAR_BACKFILL_DELAY_MS = 1; | ||
|
||
/** The maximum number of documents to process each time backfill() is called. */ | ||
const MAX_DOCUMENTS_TO_PROCESS = 50; | ||
|
||
/** This class is responsible for the scheduling of Index Backfiller. */ | ||
export class IndexBackfillerScheduler implements Scheduler { | ||
tom-andersen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
private task: DelayedOperation<void> | null; | ||
|
||
constructor( | ||
private readonly asyncQueue: AsyncQueue, | ||
private readonly backfiller: IndexBackfiller | ||
) { | ||
this.task = null; | ||
} | ||
|
||
start(): void { | ||
debugAssert( | ||
this.task === null, | ||
'Cannot start an already started IndexBackfillerScheduler' | ||
); | ||
if (INDEXING_ENABLED) { | ||
this.schedule(INITIAL_BACKFILL_DELAY_MS); | ||
} | ||
} | ||
|
||
stop(): void { | ||
if (this.task) { | ||
this.task.cancel(); | ||
this.task = null; | ||
} | ||
} | ||
|
||
get started(): boolean { | ||
return this.task !== null; | ||
} | ||
|
||
private schedule(delay: number): void { | ||
debugAssert( | ||
this.task === null, | ||
'Cannot schedule IndexBackiller while a task is pending' | ||
); | ||
logDebug(LOG_TAG, `Scheduled in ${delay}ms`); | ||
this.task = this.asyncQueue.enqueueAfterDelay( | ||
TimerId.IndexBackfill, | ||
delay, | ||
async () => { | ||
this.task = null; | ||
try { | ||
const documentsProcessed = await this.backfiller.backfill(); | ||
logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`); | ||
} catch (e) { | ||
if (isIndexedDbTransactionError(e)) { | ||
logDebug( | ||
LOG_TAG, | ||
'Ignoring IndexedDB error during index backfill: ', | ||
e | ||
); | ||
} else { | ||
await ignoreIfPrimaryLeaseLoss(e); | ||
} | ||
} | ||
await this.schedule(REGULAR_BACKFILL_DELAY_MS); | ||
} | ||
); | ||
} | ||
} | ||
|
||
/** Implements the steps for backfilling indexes. */ | ||
export class IndexBackfiller { | ||
tom-andersen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
constructor( | ||
/** | ||
* LocalStore provides access to IndexManager and LocalDocumentView. | ||
* These properties will update when the user changes. Consequently, | ||
* making a local copy of IndexManager and LocalDocumentView will require | ||
* updates over time. The simpler solution is to rely on LocalStore to have | ||
* an up-to-date references to IndexManager and LocalDocumentStore. | ||
*/ | ||
private readonly localStore: LocalStore, | ||
tom-andersen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
private readonly persistence: Persistence | ||
) {} | ||
|
||
async backfill( | ||
tom-andersen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS | ||
): Promise<number> { | ||
return this.persistence.runTransaction( | ||
'Backfill Indexes', | ||
'readwrite-primary', | ||
txn => this.writeIndexEntries(txn, maxDocumentsToProcess) | ||
); | ||
} | ||
|
||
/** Writes index entries until the cap is reached. Returns the number of documents processed. */ | ||
private writeIndexEntries( | ||
transation: PersistenceTransaction, | ||
maxDocumentsToProcess: number | ||
): PersistencePromise<number> { | ||
const processedCollectionGroups = new Set<string>(); | ||
let documentsRemaining = maxDocumentsToProcess; | ||
let continueLoop = true; | ||
return PersistencePromise.doWhile( | ||
() => continueLoop === true && documentsRemaining > 0, | ||
() => { | ||
return this.localStore.indexManager | ||
.getNextCollectionGroupToUpdate(transation) | ||
.next((collectionGroup: string | null) => { | ||
if ( | ||
collectionGroup === null || | ||
processedCollectionGroups.has(collectionGroup) | ||
) { | ||
continueLoop = false; | ||
} else { | ||
logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`); | ||
return this.writeEntriesForCollectionGroup( | ||
transation, | ||
collectionGroup, | ||
documentsRemaining | ||
).next(documentsProcessed => { | ||
documentsRemaining -= documentsProcessed; | ||
processedCollectionGroups.add(collectionGroup); | ||
}); | ||
} | ||
}); | ||
} | ||
).next(() => maxDocumentsToProcess - documentsRemaining); | ||
} | ||
|
||
/** | ||
* Writes entries for the provided collection group. Returns the number of documents processed. | ||
*/ | ||
private writeEntriesForCollectionGroup( | ||
transaction: PersistenceTransaction, | ||
collectionGroup: string, | ||
documentsRemainingUnderCap: number | ||
): PersistencePromise<number> { | ||
// Use the earliest offset of all field indexes to query the local cache. | ||
return this.localStore.indexManager | ||
.getMinOffsetFromCollectionGroup(transaction, collectionGroup) | ||
.next(existingOffset => | ||
this.localStore.localDocuments | ||
.getNextDocuments( | ||
transaction, | ||
collectionGroup, | ||
existingOffset, | ||
documentsRemainingUnderCap | ||
) | ||
.next(nextBatch => { | ||
const docs: DocumentMap = nextBatch.changes; | ||
return this.localStore.indexManager | ||
.updateIndexEntries(transaction, docs) | ||
.next(() => this.getNewOffset(existingOffset, nextBatch)) | ||
.next(newOffset => { | ||
logDebug(LOG_TAG, `Updating offset: ${newOffset}`); | ||
return this.localStore.indexManager.updateCollectionGroup( | ||
transaction, | ||
collectionGroup, | ||
newOffset | ||
); | ||
}) | ||
.next(() => docs.size); | ||
}) | ||
); | ||
} | ||
|
||
/** Returns the next offset based on the provided documents. */ | ||
private getNewOffset( | ||
existingOffset: IndexOffset, | ||
lookupResult: LocalWriteResult | ||
): IndexOffset { | ||
let maxOffset: IndexOffset = existingOffset; | ||
lookupResult.changes.forEach((key, document) => { | ||
const newOffset: IndexOffset = newIndexOffsetFromDocument(document); | ||
if (indexOffsetComparator(newOffset, maxOffset) > 0) { | ||
maxOffset = newOffset; | ||
} | ||
}); | ||
return new IndexOffset( | ||
maxOffset.readTime, | ||
maxOffset.documentKey, | ||
Math.max(lookupResult.batchId, existingOffset.largestBatchId) | ||
); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.