Skip to content

Expose operation counts from Persistence layer (take 2) #2165

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
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 3 additions & 3 deletions packages/firestore/src/local/local_documents_view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ import { RemoteDocumentCache } from './remote_document_cache';
*/
export class LocalDocumentsView {
constructor(
private remoteDocumentCache: RemoteDocumentCache,
private mutationQueue: MutationQueue,
private indexManager: IndexManager
readonly remoteDocumentCache: RemoteDocumentCache,
readonly mutationQueue: MutationQueue,
readonly indexManager: IndexManager
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm guessing this is why coverage decreased. Making these readonly probably costs us a few bytes. 😄

) {}

/**
Expand Down
153 changes: 153 additions & 0 deletions packages/firestore/test/unit/local/forwarding_counting_query_engine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/**
* @license
* Copyright 2019 Google Inc.
*
* 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 { QueryEngine } from '../../../src/local/query_engine';
import { LocalDocumentsView } from '../../../src/local/local_documents_view';
import { PersistenceTransaction } from '../../../src/local/persistence';
import { Query } from '../../../src/core/query';
import { SnapshotVersion } from '../../../src/core/snapshot_version';
import { PersistencePromise } from '../../../src/local/persistence_promise';
import { DocumentMap } from '../../../src/model/collections';
import { RemoteDocumentCache } from '../../../src/local/remote_document_cache';
import { MutationQueue } from '../../../src/local/mutation_queue';

/**
* A test-only query engine that forwards all API calls and exposes the number
* of documents and mutations read.
*/
export class CountingQueryEngine implements QueryEngine {
/**
* The number of mutations returned by the MutationQueue (since the last call
* to `resetCounts()`)
*/
mutationsRead = 0;

/**
* The number of documents returned by the RemoteDocumentCache (since the
* last call to `resetCounts()`)
*/
documentsRead = 0;

constructor(private readonly queryEngine: QueryEngine) {}

resetCounts(): void {
this.mutationsRead = 0;
this.documentsRead = 0;
}

getDocumentsMatchingQuery(
transaction: PersistenceTransaction,
query: Query,
sinceReadTime: SnapshotVersion
): PersistencePromise<DocumentMap> {
return this.queryEngine.getDocumentsMatchingQuery(
transaction,
query,
sinceReadTime
);
}

setLocalDocumentsView(localDocuments: LocalDocumentsView): void {
const view = new LocalDocumentsView(
this.wrapRemoteDocumentCache(localDocuments.remoteDocumentCache),
this.wrapMutationQueue(localDocuments.mutationQueue),
localDocuments.indexManager
);

return this.queryEngine.setLocalDocumentsView(view);
}

private wrapRemoteDocumentCache(
subject: RemoteDocumentCache
): RemoteDocumentCache {
return {
getDocumentsMatchingQuery: (transaction, query, sinceReadTime) => {
return subject
.getDocumentsMatchingQuery(transaction, query, sinceReadTime)
.next(result => {
this.documentsRead += result.size;
return result;
});
},
getEntries: (transaction, documentKeys) => {
return subject.getEntries(transaction, documentKeys).next(result => {
this.documentsRead += result.size;
return result;
});
},
getEntry: (transaction, documentKey) => {
return subject.getEntry(transaction, documentKey).next(result => {
this.documentsRead += result ? 1 : 0;
return result;
});
},
getNewDocumentChanges: subject.getNewDocumentChanges,
getSize: subject.getSize,
newChangeBuffer: subject.newChangeBuffer
};
}

private wrapMutationQueue(subject: MutationQueue): MutationQueue {
return {
acknowledgeBatch: subject.acknowledgeBatch,
addMutationBatch: subject.addMutationBatch,
checkEmpty: subject.checkEmpty,
getAllMutationBatches: transaction => {
return subject.getAllMutationBatches(transaction).next(result => {
this.mutationsRead += result.length;
return result;
});
},
getAllMutationBatchesAffectingDocumentKey: (transaction, documentKey) => {
return subject
.getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)
.next(result => {
this.mutationsRead += result.length;
return result;
});
},
getAllMutationBatchesAffectingDocumentKeys: (
transaction,
documentKeys
) => {
return subject
.getAllMutationBatchesAffectingDocumentKeys(transaction, documentKeys)
.next(result => {
this.mutationsRead += result.length;
return result;
});
},
getAllMutationBatchesAffectingQuery: (transaction, query) => {
return subject
.getAllMutationBatchesAffectingQuery(transaction, query)
.next(result => {
this.mutationsRead += result.length;
return result;
});
},
getHighestUnacknowledgedBatchId: subject.getHighestUnacknowledgedBatchId,
getLastStreamToken: subject.getLastStreamToken,
getNextMutationBatchAfterBatchId: subject.getNextMutationBatchAfterBatchId,
lookupMutationBatch: subject.lookupMutationBatch,
lookupMutationKeys: subject.lookupMutationKeys,
performConsistencyCheck: subject.performConsistencyCheck,
removeCachedMutationKeys: subject.removeCachedMutationKeys,
removeMutationBatch: subject.removeMutationBatch,
setLastStreamToken: subject.setLastStreamToken
};
}
}
115 changes: 112 additions & 3 deletions packages/firestore/test/unit/local/local_store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import {
docAddedRemoteEvent,
docUpdateRemoteEvent,
expectEqual,
filter,
key,
localViewChanges,
mapAsArray,
Expand All @@ -72,14 +73,28 @@ import {
} from '../../util/helpers';

import { FieldValue, IntegerValue } from '../../../src/model/field_value';
import { CountingQueryEngine } from './forwarding_counting_query_engine';
import * as persistenceHelpers from './persistence_test_helpers';

class LocalStoreTester {
private promiseChain: Promise<void> = Promise.resolve();
private lastChanges: MaybeDocumentMap | null = null;
private lastTargetId: TargetId | null = null;
private batches: MutationBatch[] = [];
constructor(public localStore: LocalStore, readonly gcIsEager: boolean) {}

constructor(
public localStore: LocalStore,
private readonly queryEngine: CountingQueryEngine,
readonly gcIsEager: boolean
) {}

private prepareNextStep(): void {
this.promiseChain = this.promiseChain.then(() => {
this.lastChanges = null;
this.lastTargetId = null;
this.queryEngine.resetCounts();
});
}

after(
op: Mutation | Mutation[] | RemoteEvent | LocalViewChanges
Expand All @@ -96,6 +111,8 @@ class LocalStoreTester {
}

afterMutations(mutations: Mutation[]): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain
.then(() => {
return this.localStore.localWrite(mutations);
Expand All @@ -110,6 +127,8 @@ class LocalStoreTester {
}

afterRemoteEvent(remoteEvent: RemoteEvent): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain
.then(() => {
return this.localStore.applyRemoteEvent(remoteEvent);
Expand All @@ -121,6 +140,8 @@ class LocalStoreTester {
}

afterViewChanges(viewChanges: LocalViewChanges): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain.then(() =>
this.localStore.notifyLocalViewChanges([viewChanges])
);
Expand All @@ -131,6 +152,8 @@ class LocalStoreTester {
documentVersion: TestSnapshotVersion;
transformResult?: FieldValue;
}): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain
.then(() => {
const batch = this.batches.shift()!;
Expand Down Expand Up @@ -161,6 +184,8 @@ class LocalStoreTester {
}

afterRejectingMutation(): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain
.then(() => {
return this.localStore.rejectBatch(this.batches.shift()!.batchId);
Expand All @@ -172,6 +197,8 @@ class LocalStoreTester {
}

afterAllocatingQuery(query: Query): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain.then(() => {
return this.localStore.allocateQuery(query).then(result => {
this.lastTargetId = result.targetId;
Expand All @@ -181,6 +208,8 @@ class LocalStoreTester {
}

afterReleasingQuery(query: Query): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain.then(() => {
return this.localStore.releaseQuery(
query,
Expand All @@ -190,6 +219,42 @@ class LocalStoreTester {
return this;
}

afterExecutingQuery(query: Query): LocalStoreTester {
this.prepareNextStep();

this.promiseChain = this.promiseChain.then(() => {
return this.localStore.executeQuery(query).then(results => {
this.lastChanges = results;
});
});
return this;
}

/**
* Asserts the expected number of mutations and documents read by
* the MutationQueue and the RemoteDocumentCache.
*/
toHaveRead(expectedCount: {
mutations?: number;
remoteDocuments?: number;
}): LocalStoreTester {
this.promiseChain = this.promiseChain.then(() => {
if (expectedCount.mutations !== undefined) {
expect(this.queryEngine.mutationsRead).to.be.eq(
expectedCount.mutations,
'Mutations read'
);
}
if (expectedCount.remoteDocuments !== undefined) {
expect(this.queryEngine.documentsRead).to.be.eq(
expectedCount.remoteDocuments,
'Remote documents read'
);
}
});
return this;
}

toReturnTargetId(id: TargetId): LocalStoreTester {
this.promiseChain = this.promiseChain.then(() => {
expect(this.lastTargetId).to.equal(id);
Expand Down Expand Up @@ -310,10 +375,16 @@ function genericLocalStoreTests(
): void {
let persistence: Persistence;
let localStore: LocalStore;
let countingQueryEngine: CountingQueryEngine;

beforeEach(async () => {
persistence = await getPersistence();
localStore = new LocalStore(persistence, queryEngine, User.UNAUTHENTICATED);
countingQueryEngine = new CountingQueryEngine(queryEngine);
localStore = new LocalStore(
persistence,
countingQueryEngine,
User.UNAUTHENTICATED
);
});

afterEach(async () => {
Expand All @@ -322,7 +393,7 @@ function genericLocalStoreTests(
});

function expectLocalStore(): LocalStoreTester {
return new LocalStoreTester(localStore, gcIsEager);
return new LocalStoreTester(localStore, countingQueryEngine, gcIsEager);
}

it('handles SetMutation', () => {
Expand Down Expand Up @@ -940,6 +1011,44 @@ function genericLocalStoreTests(
]);
});

it('reads all documents for initial collection queries', () => {
const firstQuery = Query.atPath(path('foo'));
const secondQuery = Query.atPath(path('foo')).addFilter(
filter('matches', '==', true)
);

return expectLocalStore()
.afterAllocatingQuery(firstQuery)
.toReturnTargetId(2)
.after(
docAddedRemoteEvent(
[
doc('foo/bar', 10, { matches: true }),
doc('foo/baz', 20, { matches: true })
],
[2]
)
)
.toReturnChanged(
doc('foo/bar', 10, { matches: true }),
doc('foo/baz', 20, { matches: true })
)
.after(setMutation('foo/bonk', { matches: true }))
.toReturnChanged(
doc('foo/bonk', 0, { matches: true }, { hasLocalMutations: true })
)
.afterAllocatingQuery(secondQuery)
.toReturnTargetId(4)
.afterExecutingQuery(secondQuery)
.toReturnChanged(
doc('foo/bar', 10, { matches: true }),
doc('foo/baz', 20, { matches: true }),
doc('foo/bonk', 0, { matches: true }, { hasLocalMutations: true })
)
.toHaveRead({ remoteDocuments: 2, mutations: 1 })
.finish();
});

it('persists resume tokens', async () => {
if (gcIsEager) {
return;
Expand Down