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 41 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
31 changes: 31 additions & 0 deletions packages/firestore-types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,40 @@ 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
): void;

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

catch<R>(
onRejected: (a: Error) => R | PromiseLike<R>
): Promise<R | LoadBundleTaskProgress>;
}

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
111 changes: 111 additions & 0 deletions packages/firestore/src/api/bundle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/**
* @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';
import { PartialObserver } from './observer';
import { debugAssert } from '../util/assert';

export class LoadBundleTask
implements
firestore.LoadBundleTask,
PromiseLike<firestore.LoadBundleTaskProgress> {
private _progressObserver?: PartialObserver<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.

Consider initializing this to an empty 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.

Done.

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.

private _taskCompletionResolver = new Deferred<
firestore.LoadBundleTaskProgress
>();

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
): void {
this._progressObserver = {
next,
error,
complete
};
}

catch<R>(
onRejected: (a: Error) => R | PromiseLike<R>
): Promise<R | firestore.LoadBundleTaskProgress> {
return this._taskCompletionResolver.promise.catch(onRejected);
}

then<T, R>(
onFulfilled?: (a: firestore.LoadBundleTaskProgress) => T | PromiseLike<T>,
onRejected?: (a: Error) => R | PromiseLike<R>
): Promise<T | R> {
return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);
}

/**
* Notifies all observers that bundle loading has completed, with a provided
* `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._progressObserver && this._progressObserver.complete) {
this._progressObserver.complete();
}

this._taskCompletionResolver.resolve(progress);
}

/**
* Notifies all observers that bundle loading has failed, with a provided
* `Error` as the reason.
*/
_failWith(error: Error): void {
this._lastProgress.taskState = 'Error';

if (this._progressObserver && this._progressObserver.next) {
this._progressObserver.next(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._progressObserver && this._progressObserver.error) {
this._progressObserver.error(error);
}

this._taskCompletionResolver.reject(error);
}

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

Choose a reason for hiding this comment

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

You may want to add 'complete' to this check as well.

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.

'Cannot update progress on a failed task'
);

this._lastProgress = progress;
if (this._progressObserver && this._progressObserver.next) {
this._progressObserver.next(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
140 changes: 139 additions & 1 deletion 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 @@ -58,7 +67,7 @@ export interface NamedQuery {
*/
interface BundledDocument {
metadata: bundleProto.BundledDocumentMetadata;
document: api.Document | undefined;
document?: api.Document;
}

/**
Expand Down Expand Up @@ -98,3 +107,132 @@ export class BundleConverter {
return fromVersion(time);
}
}

/**
* Returns a `LoadBundleTaskProgress` representing the initial progress of
* loading a bundle.
*/
export function bundleInitialProgress(
metadata: BundleMetadata
): firestore.LoadBundleTaskProgress {
return {
taskState: 'Running',
documentsLoaded: 0,
bytesLoaded: 0,
totalDocuments: metadata.totalDocuments!,
totalBytes: metadata.totalBytes!
};
}

/**
* Returns a `LoadBundleTaskProgress` representing the progress that the loading
* has succeeded.
*/
export function bundleSuccessProgress(
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;
/** Batched queries to be saved into storage */
private queries: bundleProto.NamedQuery[] = [];
/** Batched documents to be saved into storage */
private documents: BundledDocuments = [];

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

/**
* Adds an element from the bundle to the loader.
*
* Returns a new progress if adding the element leads to a new progress,
* otherwise returns null.
*/
addSizedElement(
element: SizedBundleElement
): firestore.LoadBundleTaskProgress | null {
debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');

this.progress.bytesLoaded += element.byteLength;

let documentsLoaded = this.progress.documentsLoaded;

if (element.payload.namedQuery) {
this.queries.push(element.payload.namedQuery);
} else if (element.payload.documentMetadata) {
this.documents.push({ metadata: element.payload.documentMetadata });
if (!element.payload.documentMetadata.exists) {
++documentsLoaded;
}
} else if (element.payload.document) {
debugAssert(
this.documents.length > 0 &&
this.documents[this.documents.length - 1].metadata.name ===
element.payload.document.name,
'The document being added does not match the stored metadata.'
);
this.documents[this.documents.length - 1].document =
element.payload.document;
++documentsLoaded;
}

if (documentsLoaded !== this.progress.documentsLoaded) {
this.progress.documentsLoaded = documentsLoaded;
return { ...this.progress };
}

return null;
}

/**
* Update the progress to 'Success' and return the updated progress.
*/
async complete(): Promise<LoadResult> {
const lastDocument =
this.documents.length === 0
? null
: this.documents[this.documents.length - 1];
debugAssert(
!!lastDocument ||
!lastDocument!.metadata.exists ||
(!!lastDocument!.metadata.exists && !!lastDocument!.document),
'Bundled documents ends with a document metadata.'
);
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
const lastDocument =
this.documents.length === 0
? null
: this.documents[this.documents.length - 1];
debugAssert(
!!lastDocument ||
!lastDocument!.metadata.exists ||
(!!lastDocument!.metadata.exists && !!lastDocument!.document),
'Bundled documents ends with a document metadata.'
);
debugAssert(
this.documents[this.documents.length - 1]?.metadata.exists !== true ||
this.documents[this.documents.length - 1].document),
'Bundled documents ends with a document metadata and missing document.'
);

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.


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);
}
}
31 changes: 29 additions & 2 deletions 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 @@ -26,15 +27,15 @@ import { newDatastore } from '../remote/datastore';
import { RemoteStore } from '../remote/remote_store';
import { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';
import { Code, FirestoreError } from '../util/error';
import { logDebug } from '../util/log';
import { logDebug, logWarn } from '../util/log';
import { Deferred } from '../util/promise';
import {
EventManager,
ListenOptions,
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,27 @@ 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(async () => {
loadBundle(this.syncEngine, reader, task);
return task.catch(e => {
logWarn(`Loading bundle failed with ${e}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

You should add a LOG_TAG (see most other log lines).

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.

});
});

return task;
}
}
Loading