Skip to content

Fix Firestore failing to return empty results from the local cache #5897

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

Closed
wants to merge 2 commits into from
Closed
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
11 changes: 7 additions & 4 deletions packages/firestore/src/core/event_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,8 @@ export class QueryListener {
snap.mutatedKeys,
snap.fromCache,
snap.syncStateChanged,
/* excludesMetadataChanges= */ true
/* excludesMetadataChanges= */ true,
snap.resumeToken
);
}
let raisedEvent = false;
Expand Down Expand Up @@ -371,8 +372,9 @@ export class QueryListener {
return false;
}

// Raise data from cache if we have any documents or we are offline
return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;
// Raise data from cache if we have previously executed the query and have
// cached data or we are offline
return snap.resumeToken.approximateByteSize() > 0 || onlineState === OnlineState.Offline;
}

private shouldRaiseEvent(snap: ViewSnapshot): boolean {
Expand Down Expand Up @@ -405,7 +407,8 @@ export class QueryListener {
snap.query,
snap.docs,
snap.mutatedKeys,
snap.fromCache
snap.fromCache,
snap.resumeToken
);
this.raisedInitialEvent = true;
this.queryObserver.next(snap);
Expand Down
23 changes: 15 additions & 8 deletions packages/firestore/src/core/sync_engine_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ import {
ViewChange
} from './view';
import { ViewSnapshot } from './view_snapshot';
import {ByteString} from '../util/byte_string';

const LOG_TAG = 'SyncEngine';

Expand Down Expand Up @@ -327,7 +328,8 @@ export async function syncEngineListen(
syncEngineImpl,
query,
targetId,
status === 'current'
status === 'current',
targetData.resumeToken
);
}

Expand All @@ -342,7 +344,8 @@ async function initializeViewAndComputeSnapshot(
syncEngineImpl: SyncEngineImpl,
query: Query,
targetId: TargetId,
current: boolean
current: boolean,
resumeToken: ByteString
): Promise<ViewSnapshot> {
// PORTING NOTE: On Web only, we inject the code that registers new Limbo
// targets based on view changes. This allows us to only depend on Limbo
Expand All @@ -360,12 +363,13 @@ async function initializeViewAndComputeSnapshot(
const synthesizedTargetChange =
TargetChange.createSynthesizedTargetChangeForCurrentChange(
targetId,
current && syncEngineImpl.onlineState !== OnlineState.Offline
current && syncEngineImpl.onlineState !== OnlineState.Offline,
resumeToken
);
const viewChange = view.applyChanges(
viewDocChanges,
/* updateLimboDocuments= */ syncEngineImpl.isPrimaryClient,
synthesizedTargetChange
synthesizedTargetChange,
);
updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);

Expand Down Expand Up @@ -1025,7 +1029,7 @@ export async function syncEngineEmitNewSnapsAndNotifyLocalStore(
if (syncEngineImpl.isPrimaryClient) {
syncEngineImpl.sharedClientState.updateQueryState(
queryView.targetId,
viewSnapshot.fromCache ? 'not-current' : 'current'
viewSnapshot.fromCache ? 'not-current' : 'current',
);
}
newSnaps.push(viewSnapshot);
Expand Down Expand Up @@ -1379,7 +1383,8 @@ async function synchronizeQueryViewsAndRaiseSnapshots(
syncEngineImpl,
synthesizeTargetToQuery(target!),
targetId,
/*current=*/ false
/*current=*/ false,
targetData.resumeToken
);
}

Expand Down Expand Up @@ -1451,7 +1456,8 @@ export async function syncEngineApplyTargetState(
const synthesizedRemoteEvent =
RemoteEvent.createSynthesizedRemoteEventForCurrentChange(
targetId,
state === 'current'
state === 'current',
ByteString.EMPTY_BYTE_STRING
);
await syncEngineEmitNewSnapsAndNotifyLocalStore(
syncEngineImpl,
Expand Down Expand Up @@ -1506,7 +1512,8 @@ export async function syncEngineApplyActiveTargetsChange(
syncEngineImpl,
synthesizeTargetToQuery(target),
targetData.targetId,
/*current=*/ false
/*current=*/ false,
targetData.resumeToken
);
remoteStoreListen(syncEngineImpl.remoteStore, targetData);
}
Expand Down
10 changes: 8 additions & 2 deletions packages/firestore/src/core/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
SyncState,
ViewSnapshot
} from './view_snapshot';
import {ByteString} from '../util/byte_string';

export type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;
export class AddedLimboDocument {
Expand Down Expand Up @@ -72,6 +73,7 @@ export interface ViewChange {
*/
export class View {
private syncState: SyncState | null = null;
private resumeToken: ByteString | null = null;
/**
* A flag whether the view is current with the backend. A view is considered
* current after it has seen the current flag from the backend and did not
Expand Down Expand Up @@ -306,11 +308,13 @@ export class View {
const newSyncState = synced ? SyncState.Synced : SyncState.Local;
const syncStateChanged = newSyncState !== this.syncState;
this.syncState = newSyncState;
this.resumeToken = targetChange?.resumeToken ?? null;

if (changes.length === 0 && !syncStateChanged) {
// no changes
return { limboChanges };
} else {

const snap: ViewSnapshot = new ViewSnapshot(
this.query,
docChanges.documentSet,
Expand All @@ -319,7 +323,8 @@ export class View {
docChanges.mutatedKeys,
newSyncState === SyncState.Local,
syncStateChanged,
/* excludesMetadataChanges= */ false
/* excludesMetadataChanges= */ false,
targetChange?.resumeToken ?? ByteString.EMPTY_BYTE_STRING
);
return {
snapshot: snap,
Expand Down Expand Up @@ -468,7 +473,8 @@ export class View {
this.query,
this.documentSet,
this.mutatedKeys,
this.syncState === SyncState.Local
this.syncState === SyncState.Local,
this.resumeToken ?? ByteString.EMPTY_BYTE_STRING
);
}
}
Expand Down
17 changes: 12 additions & 5 deletions packages/firestore/src/core/view_snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { fail } from '../util/assert';
import { SortedMap } from '../util/sorted_map';

import { Query, queryEquals } from './query';
import {ByteString} from '../util/byte_string';

export const enum ChangeType {
Added,
Expand Down Expand Up @@ -146,15 +147,19 @@ export class ViewSnapshot {
readonly mutatedKeys: DocumentKeySet,
readonly fromCache: boolean,
readonly syncStateChanged: boolean,
readonly excludesMetadataChanges: boolean
) {}
readonly excludesMetadataChanges: boolean,
readonly resumeToken: ByteString
) {
1 == 1;
}

/** Returns a view snapshot as if all documents in the snapshot were added. */
static fromInitialDocuments(
query: Query,
documents: DocumentSet,
mutatedKeys: DocumentKeySet,
fromCache: boolean
fromCache: boolean,
resumeToken: ByteString
): ViewSnapshot {
const changes: DocumentViewChange[] = [];
documents.forEach(doc => {
Expand All @@ -169,7 +174,8 @@ export class ViewSnapshot {
mutatedKeys,
fromCache,
/* syncStateChanged= */ true,
/* excludesMetadataChanges= */ false
/* excludesMetadataChanges= */ false,
resumeToken
);
}

Expand All @@ -184,7 +190,8 @@ export class ViewSnapshot {
!this.mutatedKeys.isEqual(other.mutatedKeys) ||
!queryEquals(this.query, other.query) ||
!this.docs.isEqual(other.docs) ||
!this.oldDocs.isEqual(other.oldDocs)
!this.oldDocs.isEqual(other.oldDocs) ||
this.resumeToken !== other.resumeToken
) {
return false;
}
Expand Down
11 changes: 7 additions & 4 deletions packages/firestore/src/remote/remote_event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,16 @@ export class RemoteEvent {
// PORTING NOTE: Multi-tab only
static createSynthesizedRemoteEventForCurrentChange(
targetId: TargetId,
current: boolean
current: boolean,
resumeToken: ByteString
): RemoteEvent {
const targetChanges = new Map<TargetId, TargetChange>();
targetChanges.set(
targetId,
TargetChange.createSynthesizedTargetChangeForCurrentChange(
targetId,
current
current,
resumeToken
)
);
return new RemoteEvent(
Expand Down Expand Up @@ -134,10 +136,11 @@ export class TargetChange {
*/
static createSynthesizedTargetChangeForCurrentChange(
targetId: TargetId,
current: boolean
current: boolean,
resumeToken: ByteString
): TargetChange {
return new TargetChange(
ByteString.EMPTY_BYTE_STRING,
resumeToken,
current,
documentKeySet(),
documentKeySet(),
Expand Down
19 changes: 19 additions & 0 deletions packages/firestore/test/integration/api/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1288,6 +1288,25 @@ apiDescribe('Queries', (persistence: boolean) => {
expect(toDataArray(snapshot)).to.deep.equal([{ map: { nested: 'foo' } }]);
});
});

// eslint-disable-next-line no-restricted-properties
(persistence ? it : it.skip)('empty query results are cached', () => {
// Reproduces https://github.com/firebase/firebase-js-sdk/issues/5873
return withTestCollection(persistence, {}, async coll => {
const snapshot1 = await coll.get(); // Populate the cache
expect(snapshot1.metadata.fromCache).to.be.false;
expect(toDataArray(snapshot1)).to.deep.equal([]); // Precondition check

// Add a snapshot listener whose first event should be raised from cache.
const storeEvent = new EventsAccumulator<firestore.QuerySnapshot>();
coll.onSnapshot(storeEvent.storeEvent);
const snapshot2 = await storeEvent.awaitEvent();

expect(snapshot2.metadata.fromCache).to.be.true;
expect(toDataArray(snapshot2)).to.deep.equal([]);
});
});

});

function verifyDocumentChange<T>(
Expand Down
Loading