Skip to content

Implement bundle loading. #3201

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 43 commits into from
Jul 11, 2020
Merged
Show file tree
Hide file tree
Changes from 36 commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
9602712
Renaming interfaces without leading I
wu-hui May 15, 2020
c5e783e
Initial commit of bundle reading - for web only.
wu-hui May 21, 2020
5e7fb89
Tests only run when it is not Node.
wu-hui May 21, 2020
1ee1615
Fix redundant imports
wu-hui May 21, 2020
18f0be1
Fix missing textencoder
wu-hui May 21, 2020
aa455bf
Remove generator.
wu-hui May 29, 2020
78248cd
Support bundle reader for Node
wu-hui May 23, 2020
83160a1
Fix rebase errors.
wu-hui May 29, 2020
24e10cb
Remote 'only'
wu-hui May 29, 2020
9d6edc5
Merge branch 'wuandy/Bundles' into wuandy/BundleReaderNode
wu-hui Jun 5, 2020
4cbe608
Merge branch 'wuandy/Bundles' into wuandy/BundleReaderNode
wu-hui Jun 5, 2020
4313e51
Added more comments, and more tests for Node.
wu-hui Jun 5, 2020
296cfc4
Implement BundleCache.
wu-hui Jun 5, 2020
fff3d36
Add applyBundleDocuments to local store.
wu-hui Jun 1, 2020
fb762de
Add rest of bundle service to localstore
wu-hui Jun 1, 2020
1ec4182
Simplify change buffer get read time logic.
wu-hui Jun 2, 2020
cd3ab7a
Fix lint errors
wu-hui Jun 2, 2020
d991c75
Add comments.
wu-hui Jun 2, 2020
af097c5
Change localstore to check for newer bundle directly.
wu-hui Jun 2, 2020
e735e23
temp checkin
wu-hui Jun 3, 2020
17ba434
Implement without async/await
wu-hui Jun 4, 2020
f808d8d
Major code complete.
wu-hui Jun 4, 2020
db1d864
Integration tests added.
wu-hui Jun 6, 2020
979ffd9
Added spec tests.
wu-hui Jun 9, 2020
f7ff495
Add comments and move types to d.ts
wu-hui Jun 9, 2020
556a007
Support loading string for real.
wu-hui Jun 9, 2020
adf1504
Makes sure SDK still works after loading bad bundles.
wu-hui Jun 11, 2020
b364ab0
Better spect test.
wu-hui Jun 12, 2020
b62e6ef
Merge branch 'wuandy/Bundles' into wuandy/BundleLoadProgress
wu-hui Jun 26, 2020
bc2021b
Merge branch 'wuandy/Bundles' into wuandy/BundleLoadProgress
wu-hui Jun 29, 2020
d5efcdf
Merge branch 'wuandy/Bundles' into wuandy/BundleLoadProgress
wu-hui Jun 29, 2020
17ab921
Set default bytesPerRead for browser
wu-hui Jun 29, 2020
21d4d7c
Finally ready for initial review.
wu-hui Jun 29, 2020
bf085ce
Address comments batch 1
wu-hui Jul 1, 2020
8fbdd3e
Fix bytesPerRead default
wu-hui Jul 1, 2020
985b205
Snapshots only once in the end.
wu-hui Jul 6, 2020
685624a
Temp addressing.
wu-hui Jul 8, 2020
5576963
Apply bundle.ts patch
wu-hui Jul 8, 2020
85e3ac6
Change how task is passed.
wu-hui Jul 8, 2020
2f639ae
From promise<void> to void
wu-hui Jul 8, 2020
57a1c63
Spec tests comments
wu-hui Jul 9, 2020
b6b261b
More feedbacks.
wu-hui Jul 10, 2020
6094153
Even more feedbacks.
wu-hui Jul 11, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions packages/firestore-types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,38 @@ export class FirebaseFirestore {

terminate(): Promise<void>;

loadBundle(
bundleData: ArrayBuffer | ReadableStream<ArrayBuffer> | string
): LoadBundleTask;

INTERNAL: { delete: () => Promise<void> };
}

export interface LoadBundleTask {
onProgress(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW, should we include an overload that takes an Observer?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's actually in the API doc. I will add it in a followup PR.

next?: (progress: LoadBundleTaskProgress) => any,
error?: (error: Error) => any,
complete?: () => void
): Promise<void>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be 'void'? What does it mean for the onProgess callback to return a Promise?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


then(
onFulfilled?: (a: LoadBundleTaskProgress) => any,
onRejected?: (a: Error) => any
): Promise<any>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
then(
onFulfilled?: (a: LoadBundleTaskProgress) => any,
onRejected?: (a: Error) => any
): Promise<any>;
then<T,R>(
onFulfilled?: (a: LoadBundleTaskProgress) => T|PromiseLike<T>,
onRejected?: (a: Error) => R|PromiseLike<R>
): Promise<T|R>;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ES5 definition for these types is:

interface Promise<T> {
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thanks!


catch(onRejected: (a: Error) => any): Promise<any>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
catch(onRejected: (a: Error) => any): Promise<any>;
catch(onRejected: (a: Error) => R|PromiseLike<R>): Promise<R>;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Although it seems it should return a Promise<R|Progress> in this case.

}

export interface LoadBundleTaskProgress {
documentsLoaded: number;
totalDocuments: number;
bytesLoaded: number;
totalBytes: number;
taskState: TaskState;
}

export type TaskState = 'Error' | 'Running' | 'Success';

export class GeoPoint {
constructor(latitude: number, longitude: number);

Expand Down
108 changes: 108 additions & 0 deletions packages/firestore/src/api/bundle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* @license
* 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 '@firebase/firestore-types';
import { Deferred } from '../util/promise';

export class LoadBundleTask implements firestore.LoadBundleTask {
private _progressResolver = new Deferred<void>();
private _userProgressHandler?: (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use a PartialObserver here?

export interface PartialObserver<T> {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

progress: firestore.LoadBundleTaskProgress
) => unknown;
private _userProgressErrorHandler?: (err: Error) => unknown;
private _userProgressCompleteHandler?: () => void;

private _promiseResolver = new Deferred<firestore.LoadBundleTaskProgress>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This name is still very non-descriptive.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed, hopefully better?


private _lastProgress: firestore.LoadBundleTaskProgress = {
taskState: 'Running',
totalBytes: 0,
totalDocuments: 0,
bytesLoaded: 0,
documentsLoaded: 0
};

onProgress(
next?: (progress: firestore.LoadBundleTaskProgress) => unknown,
error?: (err: Error) => unknown,
complete?: () => void
): Promise<void> {
this._userProgressHandler = next;
this._userProgressErrorHandler = error;
this._userProgressCompleteHandler = complete;
return this._progressResolver.promise;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need to return this promise here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

}

catch(onRejected: (a: Error) => unknown): Promise<unknown> {
return this._promiseResolver.promise.catch(onRejected);
}

then(
onFulfilled?: (a: firestore.LoadBundleTaskProgress) => unknown,
onRejected?: (a: Error) => unknown
): Promise<unknown> {
return this._promiseResolver.promise.then(onFulfilled, onRejected);
}

/**
* Notifies the completion of loading a bundle, with a provided
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* Notifies the completion of loading a bundle, with a provided
* Notifies of the completion of loading the bundle, with a provided

Or:

Notifies all observers that bundle loading has completed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

* `LoadBundleTaskProgress` object.
*/
_completeWith(progress: firestore.LoadBundleTaskProgress): void {
this._updateProgress(progress);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we not need to set the taskState here (like you did below)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The call sites set this up. I added an assert instead.

if (this._userProgressCompleteHandler) {
this._userProgressCompleteHandler();
}
this._progressResolver.resolve();

this._promiseResolver.resolve(progress);
}

/**
* Notifies a failure of loading a bundle, with a provided `Error`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* Notifies a failure of loading a bundle, with a provided `Error`
* Notifies of a failure while loading a bundle, with a provided `Error`

Or:

Notifies all observers that bundle loading has failed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

* as the reason.
*/
_failedWith(error: Error): void {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/_failedWith/failWith/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

this._lastProgress.taskState = 'Error';

if (this._userProgressHandler) {
this._userProgressHandler(this._lastProgress);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please try to match this behavior:

private notifyObserver_(observer: Observer<UploadTaskSnapshot>): void {

Basically, next doesn't get called for the Complete of Error state.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed, we would keep current behaviour because these progress updates can be considered part of the progress update series.


if (this._userProgressErrorHandler) {
this._userProgressErrorHandler(error);
}
this._progressResolver.reject(error);

this._promiseResolver.reject(error);
}

/**
* Notifies a progress update of loading a bundle.
* @param progress The new progress.
*/
_updateProgress(progress: firestore.LoadBundleTaskProgress): void {
if (this._lastProgress.taskState === 'Error') {
return;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be an assert? Why would we get additional progress updates after the task has failed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

}

this._lastProgress = progress;
if (this._userProgressHandler) {
this._userProgressHandler(progress);
}
}
}
7 changes: 7 additions & 0 deletions packages/firestore/src/api/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,13 @@ export class Firestore implements firestore.FirebaseFirestore, FirebaseService {
};
}

loadBundle(
bundleData: ArrayBuffer | ReadableStream<Uint8Array> | string
): firestore.LoadBundleTask {
this.ensureClientConfigured();
return this._firestoreClient!.loadBundle(bundleData);
}

ensureClientConfigured(): FirestoreClient {
if (!this._firestoreClient) {
// Kick off starting the client but don't actually wait for it.
Expand Down
153 changes: 153 additions & 0 deletions packages/firestore/src/core/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import * as firestore from '@firebase/firestore-types';
import { Query } from './query';
import { SnapshotVersion } from './snapshot_version';
import {
Expand All @@ -28,6 +29,14 @@ import * as api from '../protos/firestore_proto_api';
import { DocumentKey } from '../model/document_key';
import { MaybeDocument, NoDocument } from '../model/document';
import { debugAssert } from '../util/assert';
import {
applyBundleDocuments,
LocalStore,
saveNamedQuery
} from '../local/local_store';
import { SizedBundleElement } from '../util/bundle_reader';
import { MaybeDocumentMap } from '../model/collections';
import { BundleMetadata } from '../protos/firestore_bundle_proto';

/**
* Represents a Firestore bundle saved by the SDK in its local storage.
Expand Down Expand Up @@ -98,3 +107,147 @@ export class BundleConverter {
return fromVersion(time);
}
}

/**
* Returns a `LoadBundleTaskProgress` representing the initial progress of
* loading a bundle.
*/
export function initialProgress(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is an exported function, can we add "bundle" to the name?

Optional.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

metadata: BundleMetadata
): firestore.LoadBundleTaskProgress {
return {
taskState: 'Running',
documentsLoaded: 0,
bytesLoaded: 0,
totalDocuments: metadata.totalDocuments!,
totalBytes: metadata.totalBytes!
};
}

/**
* Returns a `LoadBundleTaskProgress` representing the progress if the bundle
* is already loaded, and we are skipping current loading.
*/
export function skipLoadingProgress(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be called something like "successProgress", "completedProgress" (again, preferably with Bundle in the name)?. The fact that we skipped loading the bundle seems of less importance here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

metadata: BundleMetadata
): firestore.LoadBundleTaskProgress {
return {
taskState: 'Success',
documentsLoaded: metadata.totalDocuments!,
bytesLoaded: metadata.totalBytes!,
totalDocuments: metadata.totalDocuments!,
totalBytes: metadata.totalBytes!
};
}

export class LoadResult {
constructor(
readonly progress: firestore.LoadBundleTaskProgress,
readonly changedDocs?: MaybeDocumentMap
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't need to be optional anymore, which I think leads to one more simplification.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

) {}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is an exported class, it should have a less generic name.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


/**
* A class to process the elements from a bundle, load them into local
* storage and provide progress update while loading.
*/
export class BundleLoader {
/** The current progress of loading */
private progress: firestore.LoadBundleTaskProgress;
/**
* The threshold multiplier used to determine whether enough elements are
* batched to be loaded, and a progress update is needed.
*
* Applies to both `documentsBuffered` and `bytesBuffered`, triggers storage
* update and reports progress when either of them cross the threshold.
*/
private thresholdMultiplier = 0.01;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Add "progress" to this name.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is no longer used actually.

/** Batched queries to be saved into storage */
private queries: bundleProto.NamedQuery[] = [];
/** Batched documents to be saved into storage */
private documents: BundledDocuments = [];
/**
* A BundleDocumentMetadata is added to the loader, it is saved here while
* we wait for the actual document.
*/
private unpairedDocumentMetadata: bundleProto.BundledDocumentMetadata | null = null;

constructor(
private metadata: bundleProto.BundleMetadata,
private localStore: LocalStore
) {
this.progress = initialProgress(metadata);
}

/**
* Adds an element from the bundle to the loader.
*
* If adding this element leads to actually saving the batched elements into
* storage, the returned promise will resolve to a `LoadResult`, otherwise
* it will resolve to null.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part of the documentation seems outdated.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.

*/
addSizedElement(
element: SizedBundleElement
): firestore.LoadBundleTaskProgress | null {
debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');

this.progress.bytesLoaded += element.byteLength;
if (element.payload.namedQuery) {
this.queries.push(element.payload.namedQuery);
}

if (element.payload.documentMetadata) {
if (element.payload.documentMetadata.exists) {
this.unpairedDocumentMetadata = element.payload.documentMetadata;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this push to this.documents as well? We could then add the actual document in the next call. This would remove the need for this.unpairedDocumentMetadata.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, in the next call, we would have to get the last element and make sure it is a metadata and has exists: true though. I am not sure which way is more readable, TBH.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks.

} else {
this.documents.push({
metadata: element.payload.documentMetadata,
document: undefined
});
this.progress.documentsLoaded += 1;
}
}

if (element.payload.document) {
debugAssert(
!!this.unpairedDocumentMetadata,
'Unexpected document when no pairing metadata is found'
);
this.documents.push({
metadata: this.unpairedDocumentMetadata!,
document: element.payload.document
});
this.progress.documentsLoaded += 1;
this.unpairedDocumentMetadata = null;
}

// Loading a document metadata will not update progress.
if (this.unpairedDocumentMetadata) {
return null;
}

return { ...this.progress };
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that I changed this in my diff to just retun this.progress, but I think you are correct and we need to return an immutable copy.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

}

/**
* Update the progress to 'Success' and return the updated progress.
*/
async complete(): Promise<LoadResult> {
debugAssert(
!this.unpairedDocumentMetadata,
'Unexpected document when no pairing metadata is found'
);

for (const q of this.queries) {
await saveNamedQuery(this.localStore, q);
}

let changedDocs;
if (this.documents.length > 0) {
changedDocs = await applyBundleDocuments(this.localStore, this.documents);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How often do you think bundles will be empty? If this is rare, then we could just call applyBundleDocuments, which only has a little bit of overhead but removes two if statements from your code. You already don't call into this code for skipped bundles, so I would think changedDocs would rarely be empty.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

}

this.progress.taskState = 'Success';
return new LoadResult({ ...this.progress }, changedDocs);
}
}
26 changes: 25 additions & 1 deletion packages/firestore/src/core/firestore_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import * as firestore from '@firebase/firestore-types';
import { CredentialsProvider } from '../api/credentials';
import { User } from '../auth/user';
import { LocalStore } from '../local/local_store';
Expand All @@ -34,7 +35,7 @@ import {
Observer,
QueryListener
} from './event_manager';
import { SyncEngine } from './sync_engine';
import { SyncEngine, loadBundle } from './sync_engine';
import { View } from './view';

import { SharedClientState } from '../local/shared_client_state';
Expand All @@ -47,8 +48,11 @@ import {
ComponentProvider,
MemoryComponentProvider
} from './component_provider';
import { BundleReader } from '../util/bundle_reader';
import { LoadBundleTask } from '../api/bundle';
import { newConnection } from '../platform/connection';
import { newSerializer } from '../platform/serializer';
import { toByteStreamReader } from '../platform/byte_stream_reader';

const LOG_TAG = 'FirestoreClient';
const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100;
Expand Down Expand Up @@ -512,4 +516,24 @@ export class FirestoreClient {
});
return deferred.promise;
}

loadBundle(
data: ReadableStream<Uint8Array> | ArrayBuffer | string
): firestore.LoadBundleTask {
this.verifyNotTerminated();

let content: ReadableStream<Uint8Array> | ArrayBuffer;
if (typeof data === 'string') {
content = new TextEncoder().encode(data);
} else {
content = data;
}
const reader = new BundleReader(toByteStreamReader(content));
const task = new LoadBundleTask();
this.asyncQueue.enqueueAndForget(() => {
return loadBundle(this.syncEngine, reader, task);
});

return task;
}
}
Loading