From 326d20a731ed9df3687d60fb819a029ccc120a94 Mon Sep 17 00:00:00 2001 From: Ben Milanko Date: Fri, 21 Aug 2026 19:05:48 +1000 Subject: [PATCH 1/2] fix(firestore): chunk Android query snapshot transport --- .github/workflows/android_unit_tests.yaml | 6 +- .../cloud_firestore/android/build.gradle | 2 + .../QuerySnapshotChunkProtocol.java | 83 ++++++ .../streamhandler/QuerySnapshotChunker.java | 78 +++++ .../QuerySnapshotsStreamHandler.java | 277 ++++++++++++++++-- .../QuerySnapshotChunkProtocolTest.java | 166 +++++++++++ .../QuerySnapshotChunkerTest.java | 92 ++++++ .../QuerySnapshotsStreamHandlerTest.java | 207 +++++++++++++ .../method_channel/method_channel_query.dart | 22 +- .../query_snapshot_chunk_assembler.dart | 249 ++++++++++++++++ .../query_snapshot_chunk_assembler_test.dart | 225 ++++++++++++++ tests/android/app/build.gradle | 1 + tests/pubspec.yaml | 2 + .../flutter/generated_plugin_registrant.cc | 3 + tests/windows/flutter/generated_plugins.cmake | 1 + 15 files changed, 1387 insertions(+), 27 deletions(-) create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkerTest.java create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java create mode 100644 packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart create mode 100644 packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart diff --git a/.github/workflows/android_unit_tests.yaml b/.github/workflows/android_unit_tests.yaml index 1ff80014f6a7..4f7db4f372d4 100644 --- a/.github/workflows/android_unit_tests.yaml +++ b/.github/workflows/android_unit_tests.yaml @@ -43,7 +43,11 @@ jobs: # Tasks are listed per package rather than using the root testDebugUnitTest # task, which would also build the Dart sources of the aggregate test app. # Add a task here when a package gains an android/src/test directory. - run: cd tests/android && ./gradlew :firebase_crashlytics:testDebugUnitTest + run: | + cd tests/android + ./gradlew \ + :cloud_firestore:testDebugUnitTest \ + :firebase_crashlytics:testDebugUnitTest - name: 'Upload test reports' if: failure() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a diff --git a/packages/cloud_firestore/cloud_firestore/android/build.gradle b/packages/cloud_firestore/cloud_firestore/android/build.gradle index 66d5b12c19c5..3d4bb93ce24e 100755 --- a/packages/cloud_firestore/cloud_firestore/android/build.gradle +++ b/packages/cloud_firestore/cloud_firestore/android/build.gradle @@ -62,6 +62,8 @@ android { api firebaseCoreProject implementation platform("com.google.firebase:firebase-bom:${getRootProjectExtOrCoreProperty("FirebaseSDKVersion", firebaseCoreProject)}") implementation 'com.google.firebase:firebase-firestore' + testImplementation 'junit:junit:4.13.2' + testImplementation 'org.mockito:mockito-core:5.14.2' } } diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java new file mode 100644 index 000000000000..a8bdc8795432 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java @@ -0,0 +1,83 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore.streamhandler; + +import io.flutter.plugin.common.StandardMethodCodec; +import io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; +import java.nio.ByteBuffer; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Wire messages for bounded Android query-snapshot transport. */ +final class QuerySnapshotChunkProtocol { + // Keep these values in sync with query_snapshot_chunk_assembler.dart. + private static final String CHUNK_MARKER_KEY = "firestoreQuerySnapshotChunk"; + private static final String SNAPSHOT_ID_KEY = "snapshotId"; + private static final String KIND_KEY = "kind"; + private static final String PAYLOAD_KEY = "payload"; + private static final String DOCUMENT_COUNT_KEY = "documentCount"; + private static final String DOCUMENT_CHANGE_COUNT_KEY = "documentChangeCount"; + + static final int START_KIND = 0; + static final int DOCUMENTS_KIND = 1; + static final int DOCUMENT_CHANGES_KIND = 2; + static final int END_KIND = 3; + + /** + * Keeps the transient platform-channel envelope far below the 18–31 MiB allocations observed in + * the crash report. A single Firestore document may exceed this target, but Firestore itself + * bounds that exceptional message to one 1 MiB document plus codec overhead. + */ + static final int MAX_ENCODED_ENVELOPE_BYTES = 512 * 1024; + + private static final StandardMethodCodec METHOD_CODEC = + new StandardMethodCodec(GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE); + + private QuerySnapshotChunkProtocol() {} + + static Map start( + long snapshotId, + int documentCount, + int documentChangeCount, + GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata metadata) { + Map message = base(snapshotId, START_KIND); + message.put(PAYLOAD_KEY, metadata); + message.put(DOCUMENT_COUNT_KEY, documentCount); + message.put(DOCUMENT_CHANGE_COUNT_KEY, documentChangeCount); + return message; + } + + static Map itemChunk(long snapshotId, int kind, List items) { + Map message = base(snapshotId, kind); + message.put(PAYLOAD_KEY, items); + return message; + } + + static Map end(long snapshotId) { + return base(snapshotId, END_KIND); + } + + static int encodedMessageSize(Object message) { + ByteBuffer encoded = + GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE.encodeMessage(message); + return encoded == null ? 0 : encoded.position(); + } + + static int encodedEnvelopeSize(Object message) { + ByteBuffer encoded = METHOD_CODEC.encodeSuccessEnvelope(message); + return encoded.position(); + } + + private static Map base(long snapshotId, int kind) { + Map message = new LinkedHashMap<>(); + message.put(CHUNK_MARKER_KEY, true); + message.put(SNAPSHOT_ID_KEY, snapshotId); + message.put(KIND_KEY, kind); + return message; + } +} diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java new file mode 100644 index 000000000000..e8103afb4091 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java @@ -0,0 +1,78 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore.streamhandler; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.function.Function; +import java.util.function.ToIntFunction; + +/** + * Incrementally converts and partitions snapshot items without retaining a converted copy of the + * complete query snapshot. + * + *

The inexpensive per-item size estimate chooses an initial boundary. The exact envelope sizer + * then removes tail items until the actual platform message fits. A single item is always allowed + * through even when it exceeds the target, because Firestore already bounds an individual document + * to 1 MiB and the stream must continue making progress. + */ +final class QuerySnapshotChunker { + private final Iterator source; + private final Function converter; + private final ToIntFunction itemSize; + private final int targetBytes; + private final ArrayDeque pending = new ArrayDeque<>(); + + QuerySnapshotChunker( + Iterator source, Function converter, ToIntFunction itemSize, int targetBytes) { + if (targetBytes <= 0) { + throw new IllegalArgumentException("targetBytes must be positive"); + } + this.source = source; + this.converter = converter; + this.itemSize = itemSize; + this.targetBytes = targetBytes; + } + + boolean hasNext() { + return !pending.isEmpty() || source.hasNext(); + } + + List nextChunk(ToIntFunction> exactEnvelopeSize) { + if (!hasNext()) { + throw new NoSuchElementException("No snapshot items remain"); + } + + ArrayList chunk = new ArrayList<>(); + int estimatedBytes = 0; + + while (hasNext()) { + T item = pending.isEmpty() ? converter.apply(source.next()) : pending.removeFirst(); + int encodedItemBytes = Math.max(0, itemSize.applyAsInt(item)); + + if (!chunk.isEmpty() && estimatedBytes + encodedItemBytes > targetBytes) { + pending.addFirst(item); + break; + } + + chunk.add(item); + estimatedBytes += encodedItemBytes; + if (estimatedBytes >= targetBytes) { + break; + } + } + + while (chunk.size() > 1 && exactEnvelopeSize.applyAsInt(chunk) > targetBytes) { + pending.addFirst(chunk.remove(chunk.size() - 1)); + } + + return chunk; + } +} diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java index 8aade3f8a9c2..0c15fda26596 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java @@ -10,23 +10,28 @@ import android.os.Handler; import android.os.Looper; +import com.google.firebase.firestore.DocumentChange; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.ListenSource; import com.google.firebase.firestore.ListenerRegistration; import com.google.firebase.firestore.MetadataChanges; import com.google.firebase.firestore.Query; +import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.SnapshotListenOptions; import io.flutter.plugin.common.EventChannel.EventSink; import io.flutter.plugin.common.EventChannel.StreamHandler; +import io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; import io.flutter.plugins.firebase.firestore.utils.ExceptionConverter; import io.flutter.plugins.firebase.firestore.utils.PigeonParser; +import java.util.ArrayDeque; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicLong; public class QuerySnapshotsStreamHandler implements StreamHandler { - ListenerRegistration listenerRegistration; - private final Handler mainHandler = new Handler(Looper.getMainLooper()); Query query; MetadataChanges metadataChanges; @@ -34,6 +39,12 @@ public class QuerySnapshotsStreamHandler implements StreamHandler { ListenSource source; Executor snapshotExecutor; + private final Executor eventExecutor; + private final AtomicLong nextSnapshotId = new AtomicLong(); + private final ArrayDeque pendingSnapshots = new ArrayDeque<>(); + private EventSink eventSink; + private boolean emissionActive; + private boolean cancelled; public QuerySnapshotsStreamHandler( Query query, @@ -41,51 +52,277 @@ public QuerySnapshotsStreamHandler( DocumentSnapshot.ServerTimestampBehavior serverTimestampBehavior, ListenSource source, Executor snapshotExecutor) { + this( + query, + includeMetadataChanges, + serverTimestampBehavior, + source, + snapshotExecutor, + mainThreadExecutor()); + } + + QuerySnapshotsStreamHandler( + Query query, + Boolean includeMetadataChanges, + DocumentSnapshot.ServerTimestampBehavior serverTimestampBehavior, + ListenSource source, + Executor snapshotExecutor, + Executor eventExecutor) { this.query = query; this.metadataChanges = includeMetadataChanges ? MetadataChanges.INCLUDE : MetadataChanges.EXCLUDE; this.serverTimestampBehavior = serverTimestampBehavior; this.source = source; this.snapshotExecutor = snapshotExecutor; + this.eventExecutor = eventExecutor; } @Override public void onListen(Object arguments, EventSink events) { + synchronized (this) { + cancelled = false; + emissionActive = false; + pendingSnapshots.clear(); + eventSink = events; + } + SnapshotListenOptions.Builder optionsBuilder = new SnapshotListenOptions.Builder(); optionsBuilder.setMetadataChanges(metadataChanges); optionsBuilder.setSource(source); optionsBuilder.setExecutor(snapshotExecutor); - listenerRegistration = + ListenerRegistration registration = query.addSnapshotListener( optionsBuilder.build(), (querySnapshot, exception) -> { if (exception != null) { - Map exceptionDetails = ExceptionConverter.createDetails(exception); - mainHandler.post( - () -> { - events.error(DEFAULT_ERROR_CODE, exception.getMessage(), exceptionDetails); - events.endOfStream(); - }); - - onCancel(null); + emitError(exception); } else { - // Emit the Pigeon object directly; the Pigeon-aware codec serializes - // nested `InternalDocumentSnapshot` / `InternalDocumentChange` / - // `InternalSnapshotMetadata` with their proper type codes. Pigeon 26 - // no longer flattens nested types via `.toList()`. - Object pigeonSnapshot = - PigeonParser.toPigeonQuerySnapshot(querySnapshot, serverTimestampBehavior); - mainHandler.post(() -> events.success(pigeonSnapshot)); + enqueueSnapshot(Objects.requireNonNull(querySnapshot)); } }); + + retainListenerRegistration(registration); + } + + void retainListenerRegistration(ListenerRegistration registration) { + boolean removeRegistration; + synchronized (this) { + removeRegistration = cancelled; + if (!removeRegistration) { + listenerRegistration = registration; + } + } + if (removeRegistration) { + registration.remove(); + } + } + + void emitSnapshotForTesting(QuerySnapshot snapshot, EventSink events) { + synchronized (this) { + if (eventSink != null && eventSink != events) { + throw new IllegalStateException("A different event sink is already active"); + } + cancelled = false; + eventSink = events; + } + enqueueSnapshot(snapshot); + } + + private void enqueueSnapshot(QuerySnapshot snapshot) { + boolean shouldStart; + synchronized (this) { + if (cancelled) { + return; + } + pendingSnapshots.addLast(snapshot); + shouldStart = !emissionActive; + if (shouldStart) { + emissionActive = true; + } + } + + if (shouldStart) { + emitNextSnapshot(); + } + } + + private void emitNextSnapshot() { + QuerySnapshot snapshot; + synchronized (this) { + if (cancelled) { + return; + } + snapshot = pendingSnapshots.pollFirst(); + if (snapshot == null) { + emissionActive = false; + return; + } + } + + try { + SnapshotEmission emission = new SnapshotEmission(nextSnapshotId.incrementAndGet(), snapshot); + postSuccess( + QuerySnapshotChunkProtocol.start( + emission.id, emission.documentCount, emission.documentChangeCount, emission.metadata), + () -> emitNextChunk(emission)); + } catch (Exception exception) { + emitError(exception); + } + } + + private void emitNextChunk(SnapshotEmission emission) { + if (isCancelled()) { + return; + } + + try { + if (emission.documents.hasNext()) { + List chunk = + emission.documents.nextChunk( + values -> + QuerySnapshotChunkProtocol.encodedEnvelopeSize( + QuerySnapshotChunkProtocol.itemChunk( + emission.id, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, values))); + postSuccess( + QuerySnapshotChunkProtocol.itemChunk( + emission.id, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, chunk), + () -> emitNextChunk(emission)); + return; + } + + if (emission.documentChanges.hasNext()) { + List chunk = + emission.documentChanges.nextChunk( + values -> + QuerySnapshotChunkProtocol.encodedEnvelopeSize( + QuerySnapshotChunkProtocol.itemChunk( + emission.id, + QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, + values))); + postSuccess( + QuerySnapshotChunkProtocol.itemChunk( + emission.id, QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, chunk), + () -> emitNextChunk(emission)); + return; + } + + postSuccess(QuerySnapshotChunkProtocol.end(emission.id), this::emitNextSnapshot); + } catch (Exception exception) { + emitError(exception); + } + } + + private void postSuccess(Object message, Runnable afterSuccess) { + EventSink sink; + synchronized (this) { + if (cancelled || eventSink == null) { + return; + } + sink = eventSink; + } + + eventExecutor.execute( + () -> { + if (isCancelled()) { + return; + } + try { + sink.success(message); + snapshotExecutor.execute(afterSuccess); + } catch (Exception exception) { + emitError(exception); + } + }); + } + + private void emitError(Exception exception) { + EventSink sink; + ListenerRegistration registration; + synchronized (this) { + if (cancelled) { + return; + } + cancelled = true; + pendingSnapshots.clear(); + emissionActive = false; + sink = eventSink; + eventSink = null; + registration = listenerRegistration; + listenerRegistration = null; + } + + if (registration != null) { + registration.remove(); + } + if (sink == null) { + return; + } + + Map exceptionDetails = ExceptionConverter.createDetails(exception); + eventExecutor.execute( + () -> { + sink.error(DEFAULT_ERROR_CODE, exception.getMessage(), exceptionDetails); + sink.endOfStream(); + }); + } + + private synchronized boolean isCancelled() { + return cancelled; } @Override public void onCancel(Object arguments) { - if (listenerRegistration != null) { - listenerRegistration.remove(); + ListenerRegistration registration; + synchronized (this) { + cancelled = true; + pendingSnapshots.clear(); + emissionActive = false; + eventSink = null; + registration = listenerRegistration; listenerRegistration = null; } + if (registration != null) { + registration.remove(); + } + } + + private static Executor mainThreadExecutor() { + Handler mainHandler = new Handler(Looper.getMainLooper()); + return command -> mainHandler.post(command); + } + + private final class SnapshotEmission { + final long id; + final int documentCount; + final int documentChangeCount; + final GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata metadata; + final QuerySnapshotChunker< + DocumentSnapshot, GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot> + documents; + final QuerySnapshotChunker< + DocumentChange, GeneratedAndroidFirebaseFirestore.InternalDocumentChange> + documentChanges; + + SnapshotEmission(long id, QuerySnapshot snapshot) { + this.id = id; + List nativeDocuments = snapshot.getDocuments(); + List nativeDocumentChanges = snapshot.getDocumentChanges(); + documentCount = nativeDocuments.size(); + documentChangeCount = nativeDocumentChanges.size(); + metadata = PigeonParser.toPigeonSnapshotMetadata(snapshot.getMetadata()); + documents = + new QuerySnapshotChunker<>( + nativeDocuments.iterator(), + value -> PigeonParser.toPigeonDocumentSnapshot(value, serverTimestampBehavior), + QuerySnapshotChunkProtocol::encodedMessageSize, + QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + documentChanges = + new QuerySnapshotChunker<>( + nativeDocumentChanges.iterator(), + value -> PigeonParser.toPigeonDocumentChange(value, serverTimestampBehavior), + QuerySnapshotChunkProtocol::encodedMessageSize, + QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + } } } diff --git a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java new file mode 100644 index 000000000000..aea52e93b574 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java @@ -0,0 +1,166 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore.streamhandler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.junit.Test; + +public class QuerySnapshotChunkProtocolTest { + @Test + public void documentChunkEnvelopesStayWithinTheTransportTarget() { + List documents = new ArrayList<>(); + String payload = String.join("", Collections.nCopies(2048, "abcdefgh")); + for (int index = 0; index < 100; index++) { + documents.add(document("projects/p/assets/" + index, payload)); + } + + QuerySnapshotChunker< + GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot, + GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot> + chunker = + new QuerySnapshotChunker<>( + documents.iterator(), + value -> value, + QuerySnapshotChunkProtocol::encodedMessageSize, + QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + List received = new ArrayList<>(); + + while (chunker.hasNext()) { + List chunk = + chunker.nextChunk( + values -> + QuerySnapshotChunkProtocol.encodedEnvelopeSize( + QuerySnapshotChunkProtocol.itemChunk( + 42, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, values))); + Map message = + QuerySnapshotChunkProtocol.itemChunk( + 42, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, chunk); + + assertTrue( + QuerySnapshotChunkProtocol.encodedEnvelopeSize(message) + <= QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + received.addAll(chunk); + } + + assertEquals(documents, received); + } + + @Test + public void oneOversizedDocumentStillProducesOneBoundedByFirestoreItemMessage() { + GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot document = + document( + "projects/p/assets/large", String.join("", Collections.nCopies(131072, "abcdefgh"))); + QuerySnapshotChunker< + GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot, + GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot> + chunker = + new QuerySnapshotChunker<>( + Collections.singletonList(document).iterator(), + value -> value, + QuerySnapshotChunkProtocol::encodedMessageSize, + QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + + List chunk = + chunker.nextChunk( + values -> + QuerySnapshotChunkProtocol.encodedEnvelopeSize( + QuerySnapshotChunkProtocol.itemChunk( + 1, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, values))); + + assertEquals(Collections.singletonList(document), chunk); + assertTrue( + QuerySnapshotChunkProtocol.encodedEnvelopeSize( + QuerySnapshotChunkProtocol.itemChunk( + 1, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, chunk)) + < 2 * 1024 * 1024); + } + + @Test + public void productionSizedSnapshotReplacesOneHugeEnvelopeWithBoundedMessages() { + int documentCount = 6112; + String payload = String.join("", Collections.nCopies(344, "abcdefgh")); + List documents = + new ArrayList<>(documentCount); + List changes = + new ArrayList<>(documentCount); + for (int index = 0; index < documentCount; index++) { + GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot document = + document("projects/p/assets/" + index, payload); + documents.add(document); + changes.add( + new GeneratedAndroidFirebaseFirestore.InternalDocumentChange.Builder() + .setType(GeneratedAndroidFirebaseFirestore.DocumentChangeType.ADDED) + .setDocument(document) + .setOldIndex(-1L) + .setNewIndex((long) index) + .build()); + } + GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata metadata = + new GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata.Builder() + .setHasPendingWrites(false) + .setIsFromCache(false) + .build(); + GeneratedAndroidFirebaseFirestore.InternalQuerySnapshot original = + new GeneratedAndroidFirebaseFirestore.InternalQuerySnapshot.Builder() + .setDocuments(documents) + .setDocumentChanges(changes) + .setMetadata(metadata) + .build(); + + int originalEnvelopeBytes = QuerySnapshotChunkProtocol.encodedEnvelopeSize(original); + assertTrue( + "Expected the original envelope to exceed 30 MiB, got " + originalEnvelopeBytes, + originalEnvelopeBytes > 30 * 1024 * 1024); + + assertBoundedChunks(documents, QuerySnapshotChunkProtocol.DOCUMENTS_KIND); + assertBoundedChunks(changes, QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND); + } + + private void assertBoundedChunks(List items, int kind) { + QuerySnapshotChunker chunker = + new QuerySnapshotChunker<>( + items.iterator(), + value -> value, + QuerySnapshotChunkProtocol::encodedMessageSize, + QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + int received = 0; + while (chunker.hasNext()) { + List chunk = + chunker.nextChunk( + values -> + QuerySnapshotChunkProtocol.encodedEnvelopeSize( + QuerySnapshotChunkProtocol.itemChunk(1, kind, values))); + assertTrue( + QuerySnapshotChunkProtocol.encodedEnvelopeSize( + QuerySnapshotChunkProtocol.itemChunk(1, kind, chunk)) + <= QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + received += chunk.size(); + } + assertEquals(items.size(), received); + } + + private GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot document( + String path, String payload) { + GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata metadata = + new GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata.Builder() + .setHasPendingWrites(false) + .setIsFromCache(false) + .build(); + return new GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot.Builder() + .setPath(path) + .setData(Collections.singletonMap("payload", payload)) + .setMetadata(metadata) + .build(); + } +} diff --git a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkerTest.java b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkerTest.java new file mode 100644 index 000000000000..7a245f935788 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkerTest.java @@ -0,0 +1,92 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore.streamhandler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; + +public class QuerySnapshotChunkerTest { + @Test + public void chunksItemsWithoutReordering() { + QuerySnapshotChunker chunker = + new QuerySnapshotChunker<>( + Arrays.asList(1, 2, 3).iterator(), value -> value, value -> 4, 10); + + assertEquals(Arrays.asList(1, 2), chunker.nextChunk(this::encodedSizeWithOneByteHeader)); + assertEquals( + Collections.singletonList(3), chunker.nextChunk(this::encodedSizeWithOneByteHeader)); + assertFalse(chunker.hasNext()); + } + + @Test + public void shrinksAChunkWhenTheExactEnvelopeExceedsTheTarget() { + QuerySnapshotChunker chunker = + new QuerySnapshotChunker<>( + Arrays.asList(1, 2, 3).iterator(), value -> value, value -> 4, 10); + + assertEquals( + Collections.singletonList(1), chunker.nextChunk(this::encodedSizeWithFourByteHeader)); + assertEquals( + Collections.singletonList(2), chunker.nextChunk(this::encodedSizeWithFourByteHeader)); + assertEquals( + Collections.singletonList(3), chunker.nextChunk(this::encodedSizeWithFourByteHeader)); + } + + @Test + public void allowsOneOversizedItemSoProgressCannotStall() { + QuerySnapshotChunker chunker = + new QuerySnapshotChunker<>( + Collections.singletonList(1).iterator(), value -> value, value -> 14, 10); + + assertEquals(Collections.singletonList(1), chunker.nextChunk(values -> 15)); + assertFalse(chunker.hasNext()); + } + + @Test + public void convertsEverySourceItemExactlyOnce() { + AtomicInteger conversions = new AtomicInteger(); + QuerySnapshotChunker chunker = + new QuerySnapshotChunker<>( + Arrays.asList(1, 2, 3).iterator(), + value -> { + conversions.incrementAndGet(); + return value; + }, + value -> 4, + 10); + + while (chunker.hasNext()) { + assertTrue(chunker.nextChunk(this::encodedSizeWithFourByteHeader).size() >= 1); + } + + assertEquals(3, conversions.get()); + } + + @Test + public void emptyInputHasNoChunk() { + QuerySnapshotChunker chunker = + new QuerySnapshotChunker<>( + Collections.emptyList().iterator(), value -> value, value -> 1, 10); + + assertFalse(chunker.hasNext()); + } + + private int encodedSizeWithOneByteHeader(List values) { + return 1 + (values.size() * 4); + } + + private int encodedSizeWithFourByteHeader(List values) { + return 4 + (values.size() * 4); + } +} diff --git a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java new file mode 100644 index 000000000000..6707aad31caf --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java @@ -0,0 +1,207 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore.streamhandler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.firebase.firestore.DocumentChange; +import com.google.firebase.firestore.DocumentReference; +import com.google.firebase.firestore.DocumentSnapshot; +import com.google.firebase.firestore.ListenSource; +import com.google.firebase.firestore.ListenerRegistration; +import com.google.firebase.firestore.Query; +import com.google.firebase.firestore.QueryDocumentSnapshot; +import com.google.firebase.firestore.QuerySnapshot; +import com.google.firebase.firestore.SnapshotMetadata; +import io.flutter.plugin.common.EventChannel; +import io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; +import org.junit.Test; + +public class QuerySnapshotsStreamHandlerTest { + @Test + public void emitsOneLogicalSnapshotAsBoundedProtocolMessages() { + Query query = mock(Query.class); + QuerySnapshot snapshot = mock(QuerySnapshot.class); + QueryDocumentSnapshot document = mock(QueryDocumentSnapshot.class); + DocumentReference reference = mock(DocumentReference.class); + SnapshotMetadata metadata = mock(SnapshotMetadata.class); + DocumentChange change = mock(DocumentChange.class); + when(snapshot.getMetadata()).thenReturn(metadata); + when(snapshot.getDocuments()).thenReturn(Collections.singletonList(document)); + when(snapshot.getDocumentChanges()).thenReturn(Collections.singletonList(change)); + when(metadata.hasPendingWrites()).thenReturn(false); + when(metadata.isFromCache()).thenReturn(false); + when(document.getMetadata()).thenReturn(metadata); + when(document.getReference()).thenReturn(reference); + when(reference.getPath()).thenReturn("projects/p/assets/a"); + when(document.getData(DocumentSnapshot.ServerTimestampBehavior.NONE)) + .thenReturn(Collections.singletonMap("title", "Asset A")); + when(change.getType()).thenReturn(DocumentChange.Type.ADDED); + when(change.getDocument()).thenReturn(document); + when(change.getOldIndex()).thenReturn(-1); + when(change.getNewIndex()).thenReturn(0); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + Runnable::run, + Runnable::run); + RecordingEventSink sink = new RecordingEventSink(); + handler.emitSnapshotForTesting(snapshot, sink); + + assertEquals(4, sink.events.size()); + for (Object event : sink.events) { + assertTrue(event instanceof Map); + assertFalse(event instanceof GeneratedAndroidFirebaseFirestore.InternalQuerySnapshot); + assertTrue( + QuerySnapshotChunkProtocol.encodedEnvelopeSize(event) + <= QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + } + assertEquals(QuerySnapshotChunkProtocol.START_KIND, kind(sink.events.get(0))); + assertEquals(QuerySnapshotChunkProtocol.DOCUMENTS_KIND, kind(sink.events.get(1))); + assertEquals(QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, kind(sink.events.get(2))); + assertEquals(QuerySnapshotChunkProtocol.END_KIND, kind(sink.events.get(3))); + assertNull(sink.errorCode); + } + + @Test + public void serializesQueuedSnapshotsWithoutInterleaving() { + Query query = mock(Query.class); + QuerySnapshot snapshot = emptySnapshot(); + ManualExecutor executor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + RecordingEventSink sink = new RecordingEventSink(); + + handler.emitSnapshotForTesting(snapshot, sink); + handler.emitSnapshotForTesting(snapshot, sink); + executor.runAll(); + + assertEquals(4, sink.events.size()); + assertEquals(QuerySnapshotChunkProtocol.START_KIND, kind(sink.events.get(0))); + assertEquals(QuerySnapshotChunkProtocol.END_KIND, kind(sink.events.get(1))); + assertEquals(QuerySnapshotChunkProtocol.START_KIND, kind(sink.events.get(2))); + assertEquals(QuerySnapshotChunkProtocol.END_KIND, kind(sink.events.get(3))); + assertEquals(1L, snapshotId(sink.events.get(0))); + assertEquals(1L, snapshotId(sink.events.get(1))); + assertEquals(2L, snapshotId(sink.events.get(2))); + assertEquals(2L, snapshotId(sink.events.get(3))); + } + + @Test + public void cancellationDropsQueuedSnapshotMessages() { + ManualExecutor executor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + mock(Query.class), + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + RecordingEventSink sink = new RecordingEventSink(); + + handler.emitSnapshotForTesting(emptySnapshot(), sink); + handler.onCancel(null); + executor.runAll(); + + assertTrue(sink.events.isEmpty()); + } + + @Test + public void registrationReturnedAfterCancellationIsRemoved() { + ListenerRegistration registration = mock(ListenerRegistration.class); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + mock(Query.class), + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + Runnable::run, + Runnable::run); + + handler.onCancel(null); + handler.retainListenerRegistration(registration); + + verify(registration).remove(); + } + + private QuerySnapshot emptySnapshot() { + QuerySnapshot snapshot = mock(QuerySnapshot.class); + SnapshotMetadata metadata = mock(SnapshotMetadata.class); + when(metadata.hasPendingWrites()).thenReturn(false); + when(metadata.isFromCache()).thenReturn(false); + when(snapshot.getMetadata()).thenReturn(metadata); + when(snapshot.getDocuments()).thenReturn(Collections.emptyList()); + when(snapshot.getDocumentChanges()).thenReturn(Collections.emptyList()); + return snapshot; + } + + private int kind(Object event) { + return (Integer) ((Map) event).get("kind"); + } + + private long snapshotId(Object event) { + return (Long) ((Map) event).get("snapshotId"); + } + + private static final class RecordingEventSink implements EventChannel.EventSink { + final List events = new ArrayList<>(); + String errorCode; + int endOfStreamCount; + + @Override + public void success(Object event) { + events.add(event); + } + + @Override + public void error(String code, String message, Object details) { + errorCode = code; + } + + @Override + public void endOfStream() { + endOfStreamCount++; + } + } + + private static final class ManualExecutor implements Executor { + final ArrayDeque pending = new ArrayDeque<>(); + + @Override + public void execute(Runnable command) { + pending.addLast(command); + } + + void runAll() { + while (!pending.isEmpty()) { + pending.removeFirst().run(); + } + } + } +} diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart index 12604b472d7c..077e7f865235 100644 --- a/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart @@ -16,6 +16,7 @@ import 'package:flutter/services.dart'; import 'method_channel_aggregate_query.dart'; import 'method_channel_firestore.dart'; import 'method_channel_query_snapshot.dart'; +import 'query_snapshot_chunk_assembler.dart'; import 'utils/exception.dart'; /// An implementation of [QueryPlatform] that uses [MethodChannel] to @@ -161,6 +162,7 @@ class MethodChannelQuery extends QueryPlatform { controller; // ignore: close_sinks StreamSubscription? snapshotStreamSubscription; + final snapshotAssembler = QuerySnapshotChunkAssembler(); controller = StreamController.broadcast( onListen: () async { @@ -185,16 +187,24 @@ class MethodChannelQuery extends QueryPlatform { ) .listen( (snapshot) { - // With Pigeon 26, the native side emits the generated Pigeon class - // directly through the Pigeon-aware codec, so we receive a fully - // decoded `InternalQuerySnapshot` here (no manual decode required). - final result = snapshot as InternalQuerySnapshot; - controller.add(MethodChannelQuerySnapshot(firestore, result)); + try { + final result = snapshotAssembler.add(snapshot); + if (result != null) { + controller.add(MethodChannelQuerySnapshot(firestore, result)); + } + } catch (error, stackTrace) { + snapshotAssembler.reset(); + controller.addError(error, stackTrace); + } + }, + onError: (Object error, StackTrace stackTrace) { + snapshotAssembler.reset(); + controller.addError(error, stackTrace); }, - onError: controller.addError, ); }, onCancel: () { + snapshotAssembler.reset(); snapshotStreamSubscription?.cancel(); }, ); diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart new file mode 100644 index 000000000000..f0afd4cbd4e2 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart @@ -0,0 +1,249 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import '../pigeon/messages.pigeon.dart'; + +// These map keys and chunk kinds are mirrored by QuerySnapshotsStreamHandler +// on Android. The chunk protocol deliberately uses types already supported by +// PigeonCodec so older Apple and desktop implementations can continue emitting +// InternalQuerySnapshot directly. +const String _chunkMarkerKey = 'firestoreQuerySnapshotChunk'; +const String _snapshotIdKey = 'snapshotId'; +const String _kindKey = 'kind'; +const String _payloadKey = 'payload'; +const String _documentCountKey = 'documentCount'; +const String _documentChangeCountKey = 'documentChangeCount'; + +const int _startKind = 0; +const int _documentsKind = 1; +const int _documentChangesKind = 2; +const int _endKind = 3; + +/// Reassembles the bounded Android transport messages for one logical query +/// snapshot. +/// +/// Other platforms still emit [InternalQuerySnapshot] directly, which is +/// passed through unchanged. A chunked snapshot is returned only after its end +/// marker and declared item counts have been received, preserving the public +/// stream's atomic snapshot contract. +class QuerySnapshotChunkAssembler { + _ActiveQuerySnapshot? _active; + + /// Adds one decoded event-channel [message]. + /// + /// Returns a complete snapshot, or `null` while a chunked snapshot is still + /// being assembled. Throws [StateError] when the transport protocol is + /// malformed or interleaved. + InternalQuerySnapshot? add(Object? message) { + if (message is InternalQuerySnapshot) { + if (_active != null) { + throw StateError( + 'Received a complete query snapshot while chunk assembly was active.', + ); + } + return message; + } + + if (message is! Map || message[_chunkMarkerKey] != true) { + throw StateError('Received an unknown query snapshot message.'); + } + + final snapshotId = _requiredInt(message, _snapshotIdKey); + final kind = _requiredInt(message, _kindKey); + + switch (kind) { + case _startKind: + _start(message, snapshotId); + case _documentsKind: + _appendDocuments(message, snapshotId); + case _documentChangesKind: + _appendDocumentChanges(message, snapshotId); + case _endKind: + return _finish(snapshotId); + default: + throw StateError('Unknown query snapshot chunk kind: $kind.'); + } + + return null; + } + + /// Abandons an interrupted snapshot after cancellation or a stream error. + void reset() { + _active = null; + } + + void _start(Map message, int snapshotId) { + if (_active != null) { + throw StateError( + 'Query snapshot $snapshotId started before the active snapshot ended.', + ); + } + + final documentCount = _requiredInt(message, _documentCountKey); + final documentChangeCount = _requiredInt(message, _documentChangeCountKey); + final metadata = message[_payloadKey]; + if (documentCount < 0 || documentChangeCount < 0) { + throw StateError('Query snapshot item counts cannot be negative.'); + } + if (metadata is! InternalSnapshotMetadata) { + throw StateError('Query snapshot start is missing metadata.'); + } + + _active = _ActiveQuerySnapshot( + id: snapshotId, + expectedDocumentCount: documentCount, + expectedDocumentChangeCount: documentChangeCount, + metadata: metadata, + ); + } + + void _appendDocuments(Map message, int snapshotId) { + final active = _requireActive(snapshotId); + final payload = message[_payloadKey]; + if (payload is! List) { + throw StateError('Query snapshot document chunk has an invalid payload.'); + } + + active.documents.addAll(payload.cast()); + if (active.documents.length > active.expectedDocumentCount) { + throw StateError('Query snapshot received too many documents.'); + } + } + + void _appendDocumentChanges( + Map message, + int snapshotId, + ) { + final active = _requireActive(snapshotId); + final payload = message[_payloadKey]; + if (payload is! List) { + throw StateError( + 'Query snapshot document-change chunk has an invalid payload.', + ); + } + + active.documentChanges.addAll(payload.cast()); + if (active.documentChanges.length > active.expectedDocumentChangeCount) { + throw StateError('Query snapshot received too many document changes.'); + } + } + + InternalQuerySnapshot _finish(int snapshotId) { + final active = _requireActive(snapshotId); + _active = null; + + if (active.documents.length != active.expectedDocumentCount || + active.documentChanges.length != active.expectedDocumentChangeCount) { + throw StateError( + 'Query snapshot $snapshotId ended with ' + '${active.documents.length}/${active.expectedDocumentCount} documents ' + 'and ${active.documentChanges.length}/' + '${active.expectedDocumentChangeCount} document changes.', + ); + } + + return InternalQuerySnapshot( + documents: active.documents, + documentChanges: active.documentChanges, + metadata: active.metadata, + ); + } + + _ActiveQuerySnapshot _requireActive(int snapshotId) { + final active = _active; + if (active == null) { + throw StateError( + 'Received a chunk for query snapshot $snapshotId before its start.', + ); + } + if (active.id != snapshotId) { + throw StateError( + 'Received a chunk for query snapshot $snapshotId while assembling ' + '${active.id}.', + ); + } + return active; + } +} + +class _ActiveQuerySnapshot { + _ActiveQuerySnapshot({ + required this.id, + required this.expectedDocumentCount, + required this.expectedDocumentChangeCount, + required this.metadata, + }); + + final int id; + final int expectedDocumentCount; + final int expectedDocumentChangeCount; + final InternalSnapshotMetadata metadata; + final List documents = + []; + final List documentChanges = + []; +} + +int _requiredInt(Map message, String key) { + final value = message[key]; + if (value is! int) { + throw StateError('Query snapshot chunk is missing integer "$key".'); + } + return value; +} + +/// Creates an Android query-snapshot start message for protocol tests. +Map querySnapshotChunkStart({ + required int snapshotId, + required int documentCount, + required int documentChangeCount, + required InternalSnapshotMetadata metadata, +}) { + return { + _chunkMarkerKey: true, + _snapshotIdKey: snapshotId, + _kindKey: _startKind, + _payloadKey: metadata, + _documentCountKey: documentCount, + _documentChangeCountKey: documentChangeCount, + }; +} + +/// Creates an Android query-snapshot document message for protocol tests. +Map querySnapshotDocumentChunk( + int snapshotId, + List documents, +) { + return _itemChunk(snapshotId, _documentsKind, documents); +} + +/// Creates an Android query-snapshot change message for protocol tests. +Map querySnapshotDocumentChangeChunk( + int snapshotId, + List documentChanges, +) { + return _itemChunk(snapshotId, _documentChangesKind, documentChanges); +} + +/// Creates an Android query-snapshot end message for protocol tests. +Map querySnapshotChunkEnd(int snapshotId) { + return { + _chunkMarkerKey: true, + _snapshotIdKey: snapshotId, + _kindKey: _endKind, + }; +} + +Map _itemChunk( + int snapshotId, + int kind, + List payload, +) { + return { + _chunkMarkerKey: true, + _snapshotIdKey: snapshotId, + _kindKey: kind, + _payloadKey: payload, + }; +} diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart new file mode 100644 index 000000000000..715e3e8a43ff --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart @@ -0,0 +1,225 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart'; +import 'package:cloud_firestore_platform_interface/src/method_channel/query_snapshot_chunk_assembler.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('QuerySnapshotChunkAssembler', () { + test('passes through the existing platform snapshot message', () { + final assembler = QuerySnapshotChunkAssembler(); + final snapshot = _snapshot('projects/p/assets/a'); + + expect(assembler.add(snapshot), same(snapshot)); + }); + + test('reassembles chunked documents and changes atomically', () { + final assembler = QuerySnapshotChunkAssembler(); + final first = _document('projects/p/assets/a', 1); + final second = _document('projects/p/assets/b', 2); + final metadata = _metadata(isFromCache: false); + + expect( + assembler.add( + querySnapshotChunkStart( + snapshotId: 7, + documentCount: 2, + documentChangeCount: 2, + metadata: metadata, + ), + ), + isNull, + ); + expect( + assembler.add(querySnapshotDocumentChunk(7, [first])), + isNull, + ); + expect( + assembler.add(querySnapshotDocumentChunk(7, [second])), + isNull, + ); + expect( + assembler.add( + querySnapshotDocumentChangeChunk(7, [ + _change(first, 0), + _change(second, 1), + ]), + ), + isNull, + ); + + final result = assembler.add(querySnapshotChunkEnd(7)); + + expect(result, isA()); + final complete = result!; + expect(complete.documents, [first, second]); + expect(complete.documentChanges, hasLength(2)); + expect(complete.metadata, metadata); + }); + + test('rejects a new snapshot before the active snapshot ends', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStart( + snapshotId: 1, + documentCount: 0, + documentChangeCount: 0, + metadata: _metadata(), + ), + ); + + expect( + () => assembler.add( + querySnapshotChunkStart( + snapshotId: 2, + documentCount: 0, + documentChangeCount: 0, + metadata: _metadata(), + ), + ), + throwsStateError, + ); + }); + + test('rejects chunks for a different snapshot', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStart( + snapshotId: 4, + documentCount: 1, + documentChangeCount: 0, + metadata: _metadata(), + ), + ); + + expect( + () => assembler.add( + querySnapshotDocumentChunk( + 5, + [_document('projects/p/assets/a', 1)], + ), + ), + throwsStateError, + ); + }); + + test('rejects an incomplete snapshot', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStart( + snapshotId: 9, + documentCount: 2, + documentChangeCount: 0, + metadata: _metadata(), + ), + ); + assembler.add( + querySnapshotDocumentChunk( + 9, + [_document('projects/p/assets/a', 1)], + ), + ); + + expect( + () => assembler.add(querySnapshotChunkEnd(9)), + throwsStateError, + ); + }); + + test('reset abandons an interrupted snapshot', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStart( + snapshotId: 1, + documentCount: 1, + documentChangeCount: 0, + metadata: _metadata(), + ), + ); + + assembler.reset(); + + expect( + assembler.add( + querySnapshotChunkStart( + snapshotId: 2, + documentCount: 0, + documentChangeCount: 0, + metadata: _metadata(), + ), + ), + isNull, + ); + expect( + assembler.add(querySnapshotChunkEnd(2)), + isA(), + ); + }); + + test('reassembles messages after a Pigeon event-channel round trip', () { + const codec = StandardMethodCodec(PigeonCodec()); + final assembler = QuerySnapshotChunkAssembler(); + final document = _document('projects/p/assets/a', 1); + final messages = [ + querySnapshotChunkStart( + snapshotId: 3, + documentCount: 1, + documentChangeCount: 1, + metadata: _metadata(), + ), + querySnapshotDocumentChunk(3, [document]), + querySnapshotDocumentChangeChunk(3, [_change(document, 0)]), + querySnapshotChunkEnd(3), + ]; + + InternalQuerySnapshot? result; + for (final message in messages) { + final envelope = codec.encodeSuccessEnvelope(message); + result = assembler.add(codec.decodeEnvelope(envelope)); + } + + expect(result, isNotNull); + expect(result!.documents.single, document); + expect(result.documentChanges.single!.document, document); + }); + }); +} + +InternalQuerySnapshot _snapshot(String path) { + final document = _document(path, 1); + return InternalQuerySnapshot( + documents: [document], + documentChanges: [_change(document, 0)], + metadata: _metadata(), + ); +} + +InternalDocumentSnapshot _document(String path, int value) { + return InternalDocumentSnapshot( + path: path, + data: {'value': value}, + metadata: _metadata(), + ); +} + +InternalDocumentChange _change( + InternalDocumentSnapshot document, + int newIndex, +) { + return InternalDocumentChange( + type: DocumentChangeType.added, + document: document, + oldIndex: -1, + newIndex: newIndex, + ); +} + +InternalSnapshotMetadata _metadata({bool isFromCache = true}) { + return InternalSnapshotMetadata( + hasPendingWrites: false, + isFromCache: isFromCache, + ); +} diff --git a/tests/android/app/build.gradle b/tests/android/app/build.gradle index fc3d9adc9b24..bd3d7d05625d 100644 --- a/tests/android/app/build.gradle +++ b/tests/android/app/build.gradle @@ -1,5 +1,6 @@ plugins { id "com.android.application" + id "org.jetbrains.kotlin.android" // The Flutter Gradle Plugin must be applied after the Android Gradle plugin. id "dev.flutter.flutter-gradle-plugin" } diff --git a/tests/pubspec.yaml b/tests/pubspec.yaml index e8735c1a8ed6..26eed1c645c2 100644 --- a/tests/pubspec.yaml +++ b/tests/pubspec.yaml @@ -10,6 +10,8 @@ environment: flutter: '>=3.22.0' dependencies: + cloud_firestore: ^6.8.0 + cloud_firestore_platform_interface: ^8.0.6 cloud_functions: ^6.3.6 cloud_functions_platform_interface: ^6.0.6 cloud_functions_web: ^5.1.12 diff --git a/tests/windows/flutter/generated_plugin_registrant.cc b/tests/windows/flutter/generated_plugin_registrant.cc index b6d55c18d245..45647a7ffb7d 100644 --- a/tests/windows/flutter/generated_plugin_registrant.cc +++ b/tests/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,7 @@ #include "generated_plugin_registrant.h" +#include #include #include #include @@ -14,6 +15,8 @@ #include void RegisterPlugins(flutter::PluginRegistry* registry) { + CloudFirestorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("CloudFirestorePluginCApi")); FirebaseAppCheckPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("FirebaseAppCheckPluginCApi")); FirebaseAuthPluginCApiRegisterWithRegistrar( diff --git a/tests/windows/flutter/generated_plugins.cmake b/tests/windows/flutter/generated_plugins.cmake index 89f9a20f171a..09c830ce9260 100644 --- a/tests/windows/flutter/generated_plugins.cmake +++ b/tests/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + cloud_firestore firebase_app_check firebase_auth firebase_core From 941160f5de89d9f3da193afe0032978a20406611 Mon Sep 17 00:00:00 2001 From: Jude Kwashie Date: Tue, 24 Nov 2026 11:35:10 +0000 Subject: [PATCH 2/2] fix(cloud_firestore): refine chunked snapshot transport and preserve snapshotsInSync ordering --- .github/workflows/android_unit_tests.yaml | 18 +- .../cloud_firestore/android/build.gradle | 4 + .../FlutterFirebaseFirestorePlugin.java | 10 +- .../firebase/firestore/PigeonCodecSizer.java | 56 ++ .../QuerySnapshotChunkProtocol.java | 29 +- .../streamhandler/QuerySnapshotChunker.java | 9 - .../QuerySnapshotsStreamHandler.java | 327 ++++++++--- .../SnapshotDeliveryExecutor.java | 95 +++ .../QuerySnapshotChunkProtocolTest.java | 84 ++- .../QuerySnapshotsStreamHandlerTest.java | 547 +++++++++++++++++- .../SnapshotDeliveryExecutorTest.java | 118 ++++ .../example/integration_test/query_e2e.dart | 41 ++ .../method_channel/method_channel_query.dart | 55 +- .../query_snapshot_chunk_assembler.dart | 389 +++++++------ .../query_snapshot_chunk_assembler_test.dart | 220 ------- .../test/method_channel_firestore_test.dart | 353 ++++++----- .../query_snapshot_chunk_assembler_test.dart | 338 +++++++++++ tests/android/app/build.gradle | 1 - tests/pubspec.yaml | 2 - 19 files changed, 1981 insertions(+), 715 deletions(-) create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/PigeonCodecSizer.java create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutor.java create mode 100644 packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutorTest.java delete mode 100644 packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart create mode 100644 packages/cloud_firestore/cloud_firestore_platform_interface/test/query_snapshot_chunk_assembler_test.dart diff --git a/.github/workflows/android_unit_tests.yaml b/.github/workflows/android_unit_tests.yaml index 625c56c1d17b..8a1c1cb765f0 100644 --- a/.github/workflows/android_unit_tests.yaml +++ b/.github/workflows/android_unit_tests.yaml @@ -32,7 +32,7 @@ jobs: - uses: ./.github/actions/setup-flutterfire with: node: 'false' - bootstrap-scope: 'tests' + bootstrap-scope: 'tests cloud_firestore_example' - name: Gradle cache uses: gradle/actions/setup-gradle@90ddb51e90a5fd9ba75f40cf85156b7b41bf76a3 - name: Robolectric android-all cache @@ -45,22 +45,22 @@ jobs: - name: 'Generate Gradle build files' # The Gradle wrapper and local.properties are gitignored, and Flutter injects # both. --config-only does that without building any Dart artifacts. - run: cd tests && flutter build apk --debug --config-only + run: | + (cd tests && flutter build apk --debug --config-only) + (cd packages/cloud_firestore/cloud_firestore/example && flutter build apk --debug --config-only) - name: 'Run Android unit tests' # Tasks are listed per package rather than using the root testDebugUnitTest # task, which would also build the Dart sources of the aggregate test app. # Add a task here when a package gains an android/src/test directory. run: | - cd tests/android - ./gradlew \ - :cloud_firestore:testDebugUnitTest \ - :cloud_functions:testDebugUnitTest \ - :firebase_crashlytics:testDebugUnitTest \ - :firebase_messaging:testDebugUnitTest + (cd tests/android && ./gradlew :firebase_crashlytics:testDebugUnitTest :cloud_functions:testDebugUnitTest :firebase_messaging:testDebugUnitTest) + (cd packages/cloud_firestore/cloud_firestore/example/android && ./gradlew :cloud_firestore:testDebugUnitTest) - name: 'Upload test reports' if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 with: name: android-unit-test-reports - path: tests/build/*/reports/tests/ + path: | + tests/build/*/reports/tests/ + packages/cloud_firestore/cloud_firestore/example/build/*/reports/tests/ retention-days: 5 diff --git a/packages/cloud_firestore/cloud_firestore/android/build.gradle b/packages/cloud_firestore/cloud_firestore/android/build.gradle index 1baa3bf8c1cc..7330e1823c69 100755 --- a/packages/cloud_firestore/cloud_firestore/android/build.gradle +++ b/packages/cloud_firestore/cloud_firestore/android/build.gradle @@ -58,6 +58,10 @@ android { disable 'InvalidPackage' } + testOptions { + unitTests.returnDefaultValues = true + } + dependencies { api firebaseCoreProject implementation platform("com.google.firebase:firebase-bom:${getRootProjectExtOrCoreProperty("FirebaseSDKVersion", firebaseCoreProject)}") diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java index 319571602041..ada7c7dcbcba 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java @@ -50,6 +50,7 @@ import io.flutter.plugins.firebase.firestore.streamhandler.LoadBundleStreamHandler; import io.flutter.plugins.firebase.firestore.streamhandler.OnTransactionResultListener; import io.flutter.plugins.firebase.firestore.streamhandler.QuerySnapshotsStreamHandler; +import io.flutter.plugins.firebase.firestore.streamhandler.SnapshotDeliveryExecutor; import io.flutter.plugins.firebase.firestore.streamhandler.SnapshotsInSyncStreamHandler; import io.flutter.plugins.firebase.firestore.streamhandler.TransactionStreamHandler; import io.flutter.plugins.firebase.firestore.utils.ExceptionConverter; @@ -64,7 +65,6 @@ import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -95,7 +95,8 @@ public class FlutterFirebaseFirestorePlugin private final Map eventChannels = new HashMap<>(); private final Map streamHandlers = new HashMap<>(); private final Map transactionHandlers = new HashMap<>(); - private final Map snapshotDeliveryExecutors = new ConcurrentHashMap<>(); + private final Map snapshotDeliveryExecutors = + new ConcurrentHashMap<>(); // Used in the decoder to know which ServerTimestampBehavior to use public static final Map @@ -381,13 +382,14 @@ public static FirebaseFirestore getFirestoreFromPigeon( } } - private ExecutorService snapshotDeliveryExecutor( + private SnapshotDeliveryExecutor snapshotDeliveryExecutor( GeneratedAndroidFirebaseFirestore.FirestorePigeonFirebaseApp app) { String key = app.getAppName() + "|" + app.getDatabaseURL(); return snapshotDeliveryExecutors.computeIfAbsent( key, ignored -> - new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>())); + new SnapshotDeliveryExecutor( + new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()))); } @Override diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/PigeonCodecSizer.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/PigeonCodecSizer.java new file mode 100644 index 000000000000..640f72927634 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/PigeonCodecSizer.java @@ -0,0 +1,56 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore; + +import java.io.ByteArrayOutputStream; + +public final class PigeonCodecSizer { + private PigeonCodecSizer() {} + + public static int encodedMessageSize(Object message) { + if (message == null) { + return 0; + } + CountingByteArrayOutputStream stream = new CountingByteArrayOutputStream(); + GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE.writeValue(stream, message); + return stream.size(); + } + + public static int encodedSuccessEnvelopeSize(Object message) { + CountingByteArrayOutputStream stream = new CountingByteArrayOutputStream(); + // StandardMethodCodec prefixes success envelopes with a single 0 byte. + stream.write(0); + GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE.writeValue(stream, message); + return stream.size(); + } + + private static final class CountingByteArrayOutputStream extends ByteArrayOutputStream { + private int totalBytes; + + CountingByteArrayOutputStream() { + super(0); + } + + @Override + public void write(int b) { + totalBytes++; + } + + @Override + public void write(byte[] b, int off, int len) { + if (len < 0 || off < 0 || off > b.length || off + len > b.length) { + throw new IndexOutOfBoundsException(); + } + totalBytes += len; + } + + @Override + public int size() { + return totalBytes; + } + } +} diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java index a8bdc8795432..69cd1fa0f417 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.java @@ -6,16 +6,15 @@ package io.flutter.plugins.firebase.firestore.streamhandler; -import io.flutter.plugin.common.StandardMethodCodec; import io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; -import java.nio.ByteBuffer; +import io.flutter.plugins.firebase.firestore.PigeonCodecSizer; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -/** Wire messages for bounded Android query-snapshot transport. */ final class QuerySnapshotChunkProtocol { - // Keep these values in sync with query_snapshot_chunk_assembler.dart. + // Kept in sync with query_snapshot_chunk_assembler.dart. + static final String LISTEN_CHUNKED_ARG_KEY = "firestoreQuerySnapshotChunked"; private static final String CHUNK_MARKER_KEY = "firestoreQuerySnapshotChunk"; private static final String SNAPSHOT_ID_KEY = "snapshotId"; private static final String KIND_KEY = "kind"; @@ -28,18 +27,17 @@ final class QuerySnapshotChunkProtocol { static final int DOCUMENT_CHANGES_KIND = 2; static final int END_KIND = 3; - /** - * Keeps the transient platform-channel envelope far below the 18–31 MiB allocations observed in - * the crash report. A single Firestore document may exceed this target, but Firestore itself - * bounds that exceptional message to one 1 MiB document plus codec overhead. - */ static final int MAX_ENCODED_ENVELOPE_BYTES = 512 * 1024; - private static final StandardMethodCodec METHOD_CODEC = - new StandardMethodCodec(GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE); - private QuerySnapshotChunkProtocol() {} + static boolean supportsChunking(Object arguments) { + if (!(arguments instanceof Map)) { + return false; + } + return Boolean.TRUE.equals(((Map) arguments).get(LISTEN_CHUNKED_ARG_KEY)); + } + static Map start( long snapshotId, int documentCount, @@ -63,14 +61,11 @@ static Map end(long snapshotId) { } static int encodedMessageSize(Object message) { - ByteBuffer encoded = - GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE.encodeMessage(message); - return encoded == null ? 0 : encoded.position(); + return PigeonCodecSizer.encodedMessageSize(message); } static int encodedEnvelopeSize(Object message) { - ByteBuffer encoded = METHOD_CODEC.encodeSuccessEnvelope(message); - return encoded.position(); + return PigeonCodecSizer.encodedSuccessEnvelopeSize(message); } private static Map base(long snapshotId, int kind) { diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java index e8103afb4091..73af196f89a8 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java @@ -14,15 +14,6 @@ import java.util.function.Function; import java.util.function.ToIntFunction; -/** - * Incrementally converts and partitions snapshot items without retaining a converted copy of the - * complete query snapshot. - * - *

The inexpensive per-item size estimate chooses an initial boundary. The exact envelope sizer - * then removes tail items until the actual platform message fits. A single item is always allowed - * through even when it exceeds the target, because Firestore already bounds an individual document - * to 1 MiB and the stream must continue making progress. - */ final class QuerySnapshotChunker { private final Iterator source; private final Function converter; diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java index 0c15fda26596..f7ebe8f809a3 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandler.java @@ -24,6 +24,7 @@ import io.flutter.plugins.firebase.firestore.utils.ExceptionConverter; import io.flutter.plugins.firebase.firestore.utils.PigeonParser; import java.util.ArrayDeque; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; @@ -41,10 +42,14 @@ public class QuerySnapshotsStreamHandler implements StreamHandler { Executor snapshotExecutor; private final Executor eventExecutor; private final AtomicLong nextSnapshotId = new AtomicLong(); - private final ArrayDeque pendingSnapshots = new ArrayDeque<>(); + private final ArrayDeque pendingSnapshots = new ArrayDeque<>(); + private Runnable activeTurnRelease; private EventSink eventSink; private boolean emissionActive; - private boolean cancelled; + private boolean chunkedTransport; + private boolean aborted; + private Exception pendingError; + private long listenerGeneration; public QuerySnapshotsStreamHandler( Query query, @@ -79,12 +84,25 @@ public QuerySnapshotsStreamHandler( @Override public void onListen(Object arguments, EventSink events) { + ListenerRegistration previousRegistration; + List turnsToRelease; + final long generation; synchronized (this) { - cancelled = false; + previousRegistration = listenerRegistration; + listenerRegistration = null; + generation = ++listenerGeneration; emissionActive = false; - pendingSnapshots.clear(); + aborted = false; + pendingError = null; + turnsToRelease = drainHeldTurnsLocked(); eventSink = events; + chunkedTransport = QuerySnapshotChunkProtocol.supportsChunking(arguments); + } + + if (previousRegistration != null) { + previousRegistration.remove(); } + runAll(turnsToRelease); SnapshotListenOptions.Builder optionsBuilder = new SnapshotListenOptions.Builder(); optionsBuilder.setMetadataChanges(metadataChanges); @@ -96,19 +114,20 @@ public void onListen(Object arguments, EventSink events) { optionsBuilder.build(), (querySnapshot, exception) -> { if (exception != null) { - emitError(exception); + onNativeError(exception, generation); } else { - enqueueSnapshot(Objects.requireNonNull(querySnapshot)); + enqueueSnapshot(Objects.requireNonNull(querySnapshot), generation); } }); - retainListenerRegistration(registration); + retainListenerRegistration(registration, generation); } - void retainListenerRegistration(ListenerRegistration registration) { + private void retainListenerRegistration(ListenerRegistration registration, long generation) { boolean removeRegistration; synchronized (this) { - removeRegistration = cancelled; + removeRegistration = + listenerGeneration != generation || eventSink == null || aborted || pendingError != null; if (!removeRegistration) { listenerRegistration = registration; } @@ -118,61 +137,91 @@ void retainListenerRegistration(ListenerRegistration registration) { } } - void emitSnapshotForTesting(QuerySnapshot snapshot, EventSink events) { - synchronized (this) { - if (eventSink != null && eventSink != events) { - throw new IllegalStateException("A different event sink is already active"); - } - cancelled = false; - eventSink = events; - } - enqueueSnapshot(snapshot); - } - - private void enqueueSnapshot(QuerySnapshot snapshot) { + private void enqueueSnapshot(QuerySnapshot snapshot, long generation) { boolean shouldStart; + boolean useChunked; synchronized (this) { - if (cancelled) { + if (listenerGeneration != generation + || eventSink == null + || aborted + || pendingError != null) { return; } - pendingSnapshots.addLast(snapshot); - shouldStart = !emissionActive; - if (shouldStart) { - emissionActive = true; + useChunked = chunkedTransport; + if (!useChunked) { + shouldStart = false; + } else { + Runnable releaseTurn = null; + if (snapshotExecutor instanceof SnapshotDeliveryExecutor) { + releaseTurn = ((SnapshotDeliveryExecutor) snapshotExecutor).deferNext(); + } + pendingSnapshots.addLast(new QueuedSnapshot(snapshot, releaseTurn)); + shouldStart = !emissionActive; + if (shouldStart) { + emissionActive = true; + } + } + } + + if (!useChunked) { + try { + Object pigeonSnapshot = + PigeonParser.toPigeonQuerySnapshot(snapshot, serverTimestampBehavior); + postSuccess(pigeonSnapshot, generation, null); + } catch (Exception exception) { + emitErrorImmediately(exception, generation); } + return; } if (shouldStart) { - emitNextSnapshot(); + emitNextSnapshot(generation); } } - private void emitNextSnapshot() { - QuerySnapshot snapshot; + private void emitNextSnapshot(long generation) { + QueuedSnapshot queued; + Exception errorToDeliver = null; synchronized (this) { - if (cancelled) { + if (listenerGeneration != generation || eventSink == null || aborted) { return; } - snapshot = pendingSnapshots.pollFirst(); - if (snapshot == null) { + queued = pendingSnapshots.pollFirst(); + if (queued == null) { emissionActive = false; - return; + activeTurnRelease = null; + errorToDeliver = pendingError; + } else { + activeTurnRelease = queued.releaseTurn; + } + } + + if (queued == null) { + if (errorToDeliver != null) { + scheduleErrorDelivery(errorToDeliver, generation); } + return; } try { - SnapshotEmission emission = new SnapshotEmission(nextSnapshotId.incrementAndGet(), snapshot); + SnapshotEmission emission = + new SnapshotEmission( + nextSnapshotId.incrementAndGet(), queued.snapshot, queued.releaseTurn); postSuccess( QuerySnapshotChunkProtocol.start( emission.id, emission.documentCount, emission.documentChangeCount, emission.metadata), - () -> emitNextChunk(emission)); + generation, + () -> emitNextChunk(emission, generation)); } catch (Exception exception) { - emitError(exception); + emitErrorImmediately(exception, generation); + } catch (Error error) { + releaseAllTurns(); + throw error; } } - private void emitNextChunk(SnapshotEmission emission) { - if (isCancelled()) { + private void emitNextChunk(SnapshotEmission emission, long generation) { + if (!isActive(generation)) { return; } @@ -187,7 +236,8 @@ private void emitNextChunk(SnapshotEmission emission) { postSuccess( QuerySnapshotChunkProtocol.itemChunk( emission.id, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, chunk), - () -> emitNextChunk(emission)); + generation, + () -> emitNextChunk(emission, generation)); return; } @@ -203,20 +253,62 @@ private void emitNextChunk(SnapshotEmission emission) { postSuccess( QuerySnapshotChunkProtocol.itemChunk( emission.id, QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, chunk), - () -> emitNextChunk(emission)); + generation, + () -> emitNextChunk(emission, generation)); return; } - postSuccess(QuerySnapshotChunkProtocol.end(emission.id), this::emitNextSnapshot); + postSuccess( + QuerySnapshotChunkProtocol.end(emission.id), + generation, + () -> finishSnapshotEmission(emission, generation)); } catch (Exception exception) { - emitError(exception); + emitErrorImmediately(exception, generation); + } catch (Error error) { + releaseAllTurns(); + throw error; } } - private void postSuccess(Object message, Runnable afterSuccess) { + private void finishSnapshotEmission(SnapshotEmission emission, long generation) { + Runnable toRelease; + Exception errorToDeliver = null; + boolean continueDraining; + synchronized (this) { + if (activeTurnRelease == emission.releaseTurn) { + activeTurnRelease = null; + } + toRelease = emission.releaseTurn; + if (listenerGeneration != generation || eventSink == null || aborted) { + continueDraining = false; + } else if (pendingSnapshots.isEmpty()) { + emissionActive = false; + continueDraining = false; + errorToDeliver = pendingError; + } else { + continueDraining = true; + } + } + + try { + if (errorToDeliver != null) { + scheduleErrorDelivery(errorToDeliver, generation); + } + } finally { + if (toRelease != null) { + toRelease.run(); + } + } + + if (continueDraining) { + emitNextSnapshot(generation); + } + } + + private void postSuccess(Object message, long generation, Runnable afterSuccess) { EventSink sink; synchronized (this) { - if (cancelled || eventSink == null) { + if (listenerGeneration != generation || eventSink == null || aborted) { return; } sink = eventSink; @@ -224,60 +316,152 @@ private void postSuccess(Object message, Runnable afterSuccess) { eventExecutor.execute( () -> { - if (isCancelled()) { + if (!isActive(generation)) { return; } try { sink.success(message); - snapshotExecutor.execute(afterSuccess); + if (afterSuccess != null && isActive(generation)) { + executeSnapshotContinuation(afterSuccess); + } } catch (Exception exception) { - emitError(exception); + emitErrorImmediately(exception, generation); + } catch (Error error) { + releaseAllTurns(); + throw error; } }); } - private void emitError(Exception exception) { - EventSink sink; + private void executeSnapshotContinuation(Runnable command) { + if (snapshotExecutor instanceof SnapshotDeliveryExecutor) { + ((SnapshotDeliveryExecutor) snapshotExecutor).executeContinuation(command); + } else { + snapshotExecutor.execute(command); + } + } + + private void onNativeError(Exception exception, long generation) { ListenerRegistration registration; + boolean deliverNow; synchronized (this) { - if (cancelled) { + if (listenerGeneration != generation + || eventSink == null + || aborted + || pendingError != null) { return; } - cancelled = true; - pendingSnapshots.clear(); - emissionActive = false; - sink = eventSink; - eventSink = null; + pendingError = exception; registration = listenerRegistration; listenerRegistration = null; + deliverNow = !(chunkedTransport && emissionActive); } if (registration != null) { registration.remove(); } - if (sink == null) { - return; + + if (deliverNow) { + scheduleErrorDelivery(exception, generation); } + } + private void emitErrorImmediately(Exception exception, long generation) { + ListenerRegistration registration; + List turnsToRelease; + synchronized (this) { + if (listenerGeneration != generation || eventSink == null || aborted) { + return; + } + aborted = true; + pendingError = exception; + turnsToRelease = drainHeldTurnsLocked(); + emissionActive = false; + registration = listenerRegistration; + listenerRegistration = null; + } + + try { + if (registration != null) { + registration.remove(); + } + scheduleErrorDelivery(exception, generation); + } finally { + runAll(turnsToRelease); + } + } + + private void scheduleErrorDelivery(Exception exception, long generation) { Map exceptionDetails = ExceptionConverter.createDetails(exception); eventExecutor.execute( () -> { - sink.error(DEFAULT_ERROR_CODE, exception.getMessage(), exceptionDetails); - sink.endOfStream(); + EventSink sink; + List turnsToRelease; + synchronized (this) { + if (listenerGeneration != generation || eventSink == null) { + return; + } + listenerGeneration++; + turnsToRelease = drainHeldTurnsLocked(); + emissionActive = false; + aborted = false; + pendingError = null; + sink = eventSink; + eventSink = null; + } + try { + sink.error(DEFAULT_ERROR_CODE, exception.getMessage(), exceptionDetails); + sink.endOfStream(); + } finally { + runAll(turnsToRelease); + } }); } - private synchronized boolean isCancelled() { - return cancelled; + private List drainHeldTurnsLocked() { + List turns = new ArrayList<>(); + if (activeTurnRelease != null) { + turns.add(activeTurnRelease); + activeTurnRelease = null; + } + while (!pendingSnapshots.isEmpty()) { + QueuedSnapshot queued = pendingSnapshots.pollFirst(); + if (queued.releaseTurn != null) { + turns.add(queued.releaseTurn); + } + } + return turns; + } + + private void releaseAllTurns() { + List turns; + synchronized (this) { + turns = drainHeldTurnsLocked(); + emissionActive = false; + } + runAll(turns); + } + + private static void runAll(List callbacks) { + for (Runnable callback : callbacks) { + callback.run(); + } + } + + private synchronized boolean isActive(long generation) { + return listenerGeneration == generation && eventSink != null && !aborted; } @Override public void onCancel(Object arguments) { ListenerRegistration registration; + List turnsToRelease; synchronized (this) { - cancelled = true; - pendingSnapshots.clear(); + listenerGeneration++; + turnsToRelease = drainHeldTurnsLocked(); emissionActive = false; + aborted = false; + pendingError = null; eventSink = null; registration = listenerRegistration; listenerRegistration = null; @@ -285,11 +469,22 @@ public void onCancel(Object arguments) { if (registration != null) { registration.remove(); } + runAll(turnsToRelease); } private static Executor mainThreadExecutor() { Handler mainHandler = new Handler(Looper.getMainLooper()); - return command -> mainHandler.post(command); + return mainHandler::post; + } + + private static final class QueuedSnapshot { + final QuerySnapshot snapshot; + final Runnable releaseTurn; + + QueuedSnapshot(QuerySnapshot snapshot, Runnable releaseTurn) { + this.snapshot = snapshot; + this.releaseTurn = releaseTurn; + } } private final class SnapshotEmission { @@ -303,9 +498,11 @@ private final class SnapshotEmission { final QuerySnapshotChunker< DocumentChange, GeneratedAndroidFirebaseFirestore.InternalDocumentChange> documentChanges; + final Runnable releaseTurn; - SnapshotEmission(long id, QuerySnapshot snapshot) { + SnapshotEmission(long id, QuerySnapshot snapshot, Runnable releaseTurn) { this.id = id; + this.releaseTurn = releaseTurn; List nativeDocuments = snapshot.getDocuments(); List nativeDocumentChanges = snapshot.getDocumentChanges(); documentCount = nativeDocuments.size(); diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutor.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutor.java new file mode 100644 index 000000000000..68d76c24348a --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutor.java @@ -0,0 +1,95 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore.streamhandler; + +import java.util.ArrayDeque; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; + +public final class SnapshotDeliveryExecutor implements Executor { + private final Executor delegate; + private final ArrayDeque queue = new ArrayDeque<>(); + private boolean running; + private int activeDeferrals; + + public SnapshotDeliveryExecutor(Executor delegate) { + this.delegate = delegate; + } + + @Override + public void execute(Runnable command) { + Runnable next; + synchronized (this) { + queue.addLast(command); + next = pollNextLocked(); + } + if (next != null) { + dispatch(next); + } + } + + public void executeContinuation(Runnable command) { + delegate.execute(command); + } + + public Runnable deferNext() { + synchronized (this) { + activeDeferrals++; + } + AtomicBoolean completed = new AtomicBoolean(false); + return () -> { + if (!completed.compareAndSet(false, true)) { + return; + } + Runnable next; + synchronized (this) { + activeDeferrals--; + next = pollNextLocked(); + } + if (next != null) { + dispatch(next); + } + }; + } + + private Runnable pollNextLocked() { + if (running || activeDeferrals > 0) { + return null; + } + Runnable next = queue.pollFirst(); + if (next == null) { + return null; + } + running = true; + return next; + } + + private void dispatch(Runnable task) { + try { + delegate.execute( + () -> { + Runnable next = null; + try { + task.run(); + } finally { + synchronized (this) { + running = false; + next = pollNextLocked(); + } + if (next != null) { + dispatch(next); + } + } + }); + } catch (RuntimeException | Error error) { + synchronized (this) { + running = false; + } + throw error; + } + } +} diff --git a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java index aea52e93b574..d4fe7a311476 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java @@ -7,16 +7,94 @@ package io.flutter.plugins.firebase.firestore.streamhandler; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import com.google.firebase.Timestamp; +import com.google.firebase.firestore.GeoPoint; +import io.flutter.plugin.common.StandardMethodCodec; import io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class QuerySnapshotChunkProtocolTest { + private static final StandardMethodCodec METHOD_CODEC = + new StandardMethodCodec(GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE); + + @Test + public void supportsChunkingMatchesListenArgument() { + assertTrue( + QuerySnapshotChunkProtocol.supportsChunking( + Collections.singletonMap(QuerySnapshotChunkProtocol.LISTEN_CHUNKED_ARG_KEY, true))); + assertFalse( + QuerySnapshotChunkProtocol.supportsChunking( + Collections.singletonMap(QuerySnapshotChunkProtocol.LISTEN_CHUNKED_ARG_KEY, false))); + assertFalse(QuerySnapshotChunkProtocol.supportsChunking(Collections.emptyMap())); + assertFalse(QuerySnapshotChunkProtocol.supportsChunking("chunked")); + assertFalse(QuerySnapshotChunkProtocol.supportsChunking(null)); + } + + @Test + public void sizerMatchesStandardMethodCodecByteForByte() { + Map fields = new LinkedHashMap<>(); + fields.put("string", "hello-world"); + fields.put("int", 42); + fields.put("long", 1L << 40); + fields.put("double", 3.141592653589793); + fields.put("bool", true); + fields.put("null", null); + fields.put("geo", new GeoPoint(37.7749, -122.4194)); + fields.put("timestamp", new Timestamp(1700000000L, 123456000)); + fields.put("list", Collections.singletonList(1.5)); + + GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata metadata = + new GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata.Builder() + .setHasPendingWrites(true) + .setIsFromCache(false) + .build(); + GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot doc = + new GeneratedAndroidFirebaseFirestore.InternalDocumentSnapshot.Builder() + .setPath("projects/p/assets/aligned") + .setData(fields) + .setMetadata(metadata) + .build(); + GeneratedAndroidFirebaseFirestore.InternalDocumentChange change = + new GeneratedAndroidFirebaseFirestore.InternalDocumentChange.Builder() + .setType(GeneratedAndroidFirebaseFirestore.DocumentChangeType.MODIFIED) + .setDocument(doc) + .setOldIndex(0L) + .setNewIndex(1L) + .build(); + + List messages = new ArrayList<>(); + messages.add(QuerySnapshotChunkProtocol.start(7L, 1, 1, metadata)); + messages.add( + QuerySnapshotChunkProtocol.itemChunk( + 7L, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, Collections.singletonList(doc))); + messages.add( + QuerySnapshotChunkProtocol.itemChunk( + 7L, + QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, + Collections.singletonList(change))); + messages.add(QuerySnapshotChunkProtocol.end(7L)); + + for (Object message : messages) { + ByteBuffer encodedMessage = + GeneratedAndroidFirebaseFirestore.PigeonCodec.INSTANCE.encodeMessage(message); + assertEquals( + encodedMessage.position(), QuerySnapshotChunkProtocol.encodedMessageSize(message)); + + ByteBuffer encodedEnvelope = METHOD_CODEC.encodeSuccessEnvelope(message); + assertEquals( + encodedEnvelope.position(), QuerySnapshotChunkProtocol.encodedEnvelopeSize(message)); + } + } + @Test public void documentChunkEnvelopesStayWithinTheTransportTarget() { List documents = new ArrayList<>(); @@ -47,9 +125,9 @@ public void documentChunkEnvelopesStayWithinTheTransportTarget() { QuerySnapshotChunkProtocol.itemChunk( 42, QuerySnapshotChunkProtocol.DOCUMENTS_KIND, chunk); - assertTrue( - QuerySnapshotChunkProtocol.encodedEnvelopeSize(message) - <= QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); + int realEnvelopeBytes = METHOD_CODEC.encodeSuccessEnvelope(message).position(); + assertEquals(realEnvelopeBytes, QuerySnapshotChunkProtocol.encodedEnvelopeSize(message)); + assertTrue(realEnvelopeBytes <= QuerySnapshotChunkProtocol.MAX_ENCODED_ENVELOPE_BYTES); received.addAll(chunk); } diff --git a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java index 6707aad31caf..afff1293eee8 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java @@ -10,6 +10,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -17,45 +18,37 @@ import com.google.firebase.firestore.DocumentChange; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; +import com.google.firebase.firestore.EventListener; +import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.ListenSource; import com.google.firebase.firestore.ListenerRegistration; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; +import com.google.firebase.firestore.SnapshotListenOptions; import com.google.firebase.firestore.SnapshotMetadata; import io.flutter.plugin.common.EventChannel; import io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; public class QuerySnapshotsStreamHandlerTest { + private static final Map CHUNKED_ARGS = + Collections.singletonMap(QuerySnapshotChunkProtocol.LISTEN_CHUNKED_ARG_KEY, true); + @Test - public void emitsOneLogicalSnapshotAsBoundedProtocolMessages() { + public void emitsOneLogicalSnapshotAsBoundedProtocolMessagesWhenOptedIn() { Query query = mock(Query.class); - QuerySnapshot snapshot = mock(QuerySnapshot.class); - QueryDocumentSnapshot document = mock(QueryDocumentSnapshot.class); - DocumentReference reference = mock(DocumentReference.class); - SnapshotMetadata metadata = mock(SnapshotMetadata.class); - DocumentChange change = mock(DocumentChange.class); - when(snapshot.getMetadata()).thenReturn(metadata); - when(snapshot.getDocuments()).thenReturn(Collections.singletonList(document)); - when(snapshot.getDocumentChanges()).thenReturn(Collections.singletonList(change)); - when(metadata.hasPendingWrites()).thenReturn(false); - when(metadata.isFromCache()).thenReturn(false); - when(document.getMetadata()).thenReturn(metadata); - when(document.getReference()).thenReturn(reference); - when(reference.getPath()).thenReturn("projects/p/assets/a"); - when(document.getData(DocumentSnapshot.ServerTimestampBehavior.NONE)) - .thenReturn(Collections.singletonMap("title", "Asset A")); - when(change.getType()).thenReturn(DocumentChange.Type.ADDED); - when(change.getDocument()).thenReturn(document); - when(change.getOldIndex()).thenReturn(-1); - when(change.getNewIndex()).thenReturn(0); + AtomicReference> listenerRef = captureListener(query); + QuerySnapshot snapshot = singleDocumentSnapshot(); + QuerySnapshotsStreamHandler handler = new QuerySnapshotsStreamHandler( query, @@ -65,7 +58,9 @@ public void emitsOneLogicalSnapshotAsBoundedProtocolMessages() { Runnable::run, Runnable::run); RecordingEventSink sink = new RecordingEventSink(); - handler.emitSnapshotForTesting(snapshot, sink); + handler.onListen(CHUNKED_ARGS, sink); + + listenerRef.get().onEvent(snapshot, null); assertEquals(4, sink.events.size()); for (Object event : sink.events) { @@ -82,9 +77,35 @@ public void emitsOneLogicalSnapshotAsBoundedProtocolMessages() { assertNull(sink.errorCode); } + @Test + public void emitsLegacyInternalQuerySnapshotWhenClientDoesNotOptIn() { + Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); + QuerySnapshot snapshot = singleDocumentSnapshot(); + + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + Runnable::run, + Runnable::run); + RecordingEventSink sink = new RecordingEventSink(); + handler.onListen(null, sink); + + listenerRef.get().onEvent(snapshot, null); + + assertEquals(1, sink.events.size()); + assertTrue( + sink.events.get(0) instanceof GeneratedAndroidFirebaseFirestore.InternalQuerySnapshot); + assertNull(sink.errorCode); + } + @Test public void serializesQueuedSnapshotsWithoutInterleaving() { Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); QuerySnapshot snapshot = emptySnapshot(); ManualExecutor executor = new ManualExecutor(); QuerySnapshotsStreamHandler handler = @@ -97,8 +118,9 @@ public void serializesQueuedSnapshotsWithoutInterleaving() { executor); RecordingEventSink sink = new RecordingEventSink(); - handler.emitSnapshotForTesting(snapshot, sink); - handler.emitSnapshotForTesting(snapshot, sink); + handler.onListen(CHUNKED_ARGS, sink); + listenerRef.get().onEvent(snapshot, null); + listenerRef.get().onEvent(snapshot, null); executor.runAll(); assertEquals(4, sink.events.size()); @@ -114,10 +136,12 @@ public void serializesQueuedSnapshotsWithoutInterleaving() { @Test public void cancellationDropsQueuedSnapshotMessages() { + Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); ManualExecutor executor = new ManualExecutor(); QuerySnapshotsStreamHandler handler = new QuerySnapshotsStreamHandler( - mock(Query.class), + query, false, DocumentSnapshot.ServerTimestampBehavior.NONE, ListenSource.DEFAULT, @@ -125,7 +149,8 @@ public void cancellationDropsQueuedSnapshotMessages() { executor); RecordingEventSink sink = new RecordingEventSink(); - handler.emitSnapshotForTesting(emptySnapshot(), sink); + handler.onListen(CHUNKED_ARGS, sink); + listenerRef.get().onEvent(emptySnapshot(), null); handler.onCancel(null); executor.runAll(); @@ -133,23 +158,485 @@ public void cancellationDropsQueuedSnapshotMessages() { } @Test - public void registrationReturnedAfterCancellationIsRemoved() { + public void staleQueuedFramesFromCancelledGenerationDoNotEmitAfterRelisten() { + Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); + ManualExecutor executor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + RecordingEventSink firstSink = new RecordingEventSink(); + RecordingEventSink secondSink = new RecordingEventSink(); + + handler.onListen(CHUNKED_ARGS, firstSink); + EventListener firstListener = listenerRef.get(); + firstListener.onEvent(emptySnapshot(), null); + + handler.onCancel(null); + handler.onListen(CHUNKED_ARGS, secondSink); + EventListener secondListener = listenerRef.get(); + secondListener.onEvent(emptySnapshot(), null); + + executor.runAll(); + + assertTrue(firstSink.events.isEmpty()); + assertEquals(2, secondSink.events.size()); + assertEquals(QuerySnapshotChunkProtocol.START_KIND, kind(secondSink.events.get(0))); + assertEquals(QuerySnapshotChunkProtocol.END_KIND, kind(secondSink.events.get(1))); + } + + @Test + public void registrationReturnedAfterCancellationDuringSubscribeIsRemoved() { + Query query = mock(Query.class); + ListenerRegistration registration = mock(ListenerRegistration.class); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + Runnable::run, + Runnable::run); + when(query.addSnapshotListener(any(SnapshotListenOptions.class), any())) + .thenAnswer( + invocation -> { + handler.onCancel(null); + return registration; + }); + + handler.onListen(CHUNKED_ARGS, new RecordingEventSink()); + + verify(registration).remove(); + } + + @Test + public void nativeExceptionEmitsErrorEndsStreamAndRemovesRegistration() { + Query query = mock(Query.class); ListenerRegistration registration = mock(ListenerRegistration.class); + AtomicReference> listenerRef = + captureListener(query, registration); QuerySnapshotsStreamHandler handler = new QuerySnapshotsStreamHandler( - mock(Query.class), + query, false, DocumentSnapshot.ServerTimestampBehavior.NONE, ListenSource.DEFAULT, Runnable::run, Runnable::run); + RecordingEventSink sink = new RecordingEventSink(); + + handler.onListen(CHUNKED_ARGS, sink); + FirebaseFirestoreException error = + new FirebaseFirestoreException("denied", FirebaseFirestoreException.Code.PERMISSION_DENIED); + listenerRef.get().onEvent(null, error); + + assertTrue(sink.events.isEmpty()); + assertEquals("firebase_firestore", sink.errorCode); + assertEquals(1, sink.endOfStreamCount); + verify(registration).remove(); + } + + @Test + public void nativeErrorAfterQueuedSnapshotDeliversSnapshotBeforeErrorInChunkedMode() { + Query query = mock(Query.class); + ListenerRegistration registration = mock(ListenerRegistration.class); + AtomicReference> listenerRef = + captureListener(query, registration); + ManualExecutor executor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + RecordingEventSink sink = new RecordingEventSink(); + + handler.onListen(CHUNKED_ARGS, sink); + listenerRef.get().onEvent(singleDocumentSnapshot(), null); + listenerRef + .get() + .onEvent( + null, + new FirebaseFirestoreException( + "denied", FirebaseFirestoreException.Code.PERMISSION_DENIED)); + executor.runAll(); + + assertEquals(4, sink.events.size()); + assertEquals(QuerySnapshotChunkProtocol.START_KIND, kind(sink.events.get(0))); + assertEquals(QuerySnapshotChunkProtocol.DOCUMENTS_KIND, kind(sink.events.get(1))); + assertEquals(QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, kind(sink.events.get(2))); + assertEquals(QuerySnapshotChunkProtocol.END_KIND, kind(sink.events.get(3))); + assertEquals("firebase_firestore", sink.errorCode); + assertEquals(1, sink.endOfStreamCount); + verify(registration).remove(); + } + + @Test + public void nativeErrorAfterQueuedSnapshotDeliversSnapshotBeforeErrorInLegacyMode() { + Query query = mock(Query.class); + ListenerRegistration registration = mock(ListenerRegistration.class); + AtomicReference> listenerRef = + captureListener(query, registration); + ManualExecutor executor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + RecordingEventSink sink = new RecordingEventSink(); + + handler.onListen(null, sink); + listenerRef.get().onEvent(singleDocumentSnapshot(), null); + listenerRef + .get() + .onEvent( + null, + new FirebaseFirestoreException( + "denied", FirebaseFirestoreException.Code.PERMISSION_DENIED)); + executor.runAll(); + assertEquals(1, sink.events.size()); + assertTrue( + sink.events.get(0) instanceof GeneratedAndroidFirebaseFirestore.InternalQuerySnapshot); + assertEquals("firebase_firestore", sink.errorCode); + assertEquals(1, sink.endOfStreamCount); + verify(registration).remove(); + } + + @Test + public void cancellationBeforeQueuedErrorDeliverySuppressesError() { + Query query = mock(Query.class); + ListenerRegistration registration = mock(ListenerRegistration.class); + AtomicReference> listenerRef = + captureListener(query, registration); + ManualExecutor executor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + RecordingEventSink sink = new RecordingEventSink(); + + handler.onListen(CHUNKED_ARGS, sink); + listenerRef + .get() + .onEvent( + null, + new FirebaseFirestoreException( + "denied", FirebaseFirestoreException.Code.PERMISSION_DENIED)); handler.onCancel(null); - handler.retainListenerRegistration(registration); + executor.runAll(); + + assertNull(sink.errorCode); + assertEquals(0, sink.endOfStreamCount); + verify(registration).remove(); + } + + @Test + public void legacySinkFailureSuppressesSubsequentQueuedSnapshotsBeforeError() { + Query query = mock(Query.class); + ListenerRegistration registration = mock(ListenerRegistration.class); + AtomicReference> listenerRef = + captureListener(query, registration); + ManualExecutor executor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + List delivered = new ArrayList<>(); + String[] errorCode = new String[1]; + int[] endOfStreamCount = new int[1]; + EventChannel.EventSink failingSink = + new EventChannel.EventSink() { + @Override + public void success(Object event) { + delivered.add(event); + throw new IllegalStateException("sink failed"); + } + + @Override + public void error(String code, String message, Object details) { + errorCode[0] = code; + } + @Override + public void endOfStream() { + endOfStreamCount[0]++; + } + }; + + handler.onListen(null, failingSink); + listenerRef.get().onEvent(singleDocumentSnapshot(), null); + listenerRef.get().onEvent(singleDocumentSnapshot(), null); + executor.runAll(); + + assertEquals(1, delivered.size()); + assertEquals("firebase_firestore", errorCode[0]); + assertEquals(1, endOfStreamCount[0]); verify(registration).remove(); } + @Test + public void chunkedSnapshotCompletesBeforeSnapshotsInSyncOnSharedDeliveryExecutor() { + Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); + ManualExecutor workerDelegate = new ManualExecutor(); + SnapshotDeliveryExecutor deliveryExecutor = new SnapshotDeliveryExecutor(workerDelegate); + ManualExecutor mainExecutor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + deliveryExecutor, + mainExecutor); + List timeline = new ArrayList<>(); + EventChannel.EventSink querySink = + new EventChannel.EventSink() { + @Override + public void success(Object event) { + timeline.add("query:" + kind(event)); + } + + @Override + public void error(String code, String message, Object details) {} + + @Override + public void endOfStream() {} + }; + + handler.onListen(CHUNKED_ARGS, querySink); + QuerySnapshot snapshot = singleDocumentSnapshot(); + deliveryExecutor.execute(() -> listenerRef.get().onEvent(snapshot, null)); + deliveryExecutor.execute(() -> mainExecutor.execute(() -> timeline.add("sync"))); + + drainBoth(workerDelegate, mainExecutor); + + assertEquals( + Arrays.asList( + "query:" + QuerySnapshotChunkProtocol.START_KIND, + "query:" + QuerySnapshotChunkProtocol.DOCUMENTS_KIND, + "query:" + QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, + "query:" + QuerySnapshotChunkProtocol.END_KIND, + "sync"), + timeline); + } + + @Test + public void multipleChunkedSnapshotsAndSyncEventsPreserveStrictInterleavingOrder() { + Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); + ManualExecutor workerDelegate = new ManualExecutor(); + SnapshotDeliveryExecutor deliveryExecutor = new SnapshotDeliveryExecutor(workerDelegate); + ManualExecutor mainExecutor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + deliveryExecutor, + mainExecutor); + List timeline = new ArrayList<>(); + EventChannel.EventSink querySink = + new EventChannel.EventSink() { + @Override + public void success(Object event) { + timeline.add("q" + snapshotId(event) + ":" + kind(event)); + } + + @Override + public void error(String code, String message, Object details) {} + + @Override + public void endOfStream() {} + }; + + handler.onListen(CHUNKED_ARGS, querySink); + QuerySnapshot firstSnapshot = singleDocumentSnapshot(); + QuerySnapshot secondSnapshot = singleDocumentSnapshot(); + deliveryExecutor.execute(() -> listenerRef.get().onEvent(firstSnapshot, null)); + deliveryExecutor.execute(() -> mainExecutor.execute(() -> timeline.add("sync1"))); + deliveryExecutor.execute(() -> listenerRef.get().onEvent(secondSnapshot, null)); + deliveryExecutor.execute(() -> mainExecutor.execute(() -> timeline.add("sync2"))); + + drainBoth(workerDelegate, mainExecutor); + + assertEquals( + Arrays.asList( + "q1:" + QuerySnapshotChunkProtocol.START_KIND, + "q1:" + QuerySnapshotChunkProtocol.DOCUMENTS_KIND, + "q1:" + QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, + "q1:" + QuerySnapshotChunkProtocol.END_KIND, + "sync1", + "q2:" + QuerySnapshotChunkProtocol.START_KIND, + "q2:" + QuerySnapshotChunkProtocol.DOCUMENTS_KIND, + "q2:" + QuerySnapshotChunkProtocol.DOCUMENT_CHANGES_KIND, + "q2:" + QuerySnapshotChunkProtocol.END_KIND, + "sync2"), + timeline); + } + + @Test + public void cancellationMidChunkedSnapshotReleasesSharedDeliveryExecutorForSync() { + Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); + ManualExecutor workerDelegate = new ManualExecutor(); + SnapshotDeliveryExecutor deliveryExecutor = new SnapshotDeliveryExecutor(workerDelegate); + ManualExecutor mainExecutor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + deliveryExecutor, + mainExecutor); + List timeline = new ArrayList<>(); + EventChannel.EventSink querySink = + new EventChannel.EventSink() { + @Override + public void success(Object event) { + timeline.add("query:" + kind(event)); + } + + @Override + public void error(String code, String message, Object details) {} + + @Override + public void endOfStream() {} + }; + + handler.onListen(CHUNKED_ARGS, querySink); + QuerySnapshot snapshot = singleDocumentSnapshot(); + deliveryExecutor.execute(() -> listenerRef.get().onEvent(snapshot, null)); + deliveryExecutor.execute(() -> mainExecutor.execute(() -> timeline.add("sync"))); + + workerDelegate.runAll(); + mainExecutor.runOne(); + handler.onCancel(null); + drainBoth(workerDelegate, mainExecutor); + + assertEquals(Arrays.asList("query:" + QuerySnapshotChunkProtocol.START_KIND, "sync"), timeline); + } + + @Test + public void sinkFailureMidChunkedSnapshotReleasesSharedDeliveryExecutorForSync() { + Query query = mock(Query.class); + AtomicReference> listenerRef = captureListener(query); + ManualExecutor workerDelegate = new ManualExecutor(); + SnapshotDeliveryExecutor deliveryExecutor = new SnapshotDeliveryExecutor(workerDelegate); + ManualExecutor mainExecutor = new ManualExecutor(); + QuerySnapshotsStreamHandler handler = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + deliveryExecutor, + mainExecutor); + List timeline = new ArrayList<>(); + EventChannel.EventSink failingSink = + new EventChannel.EventSink() { + @Override + public void success(Object event) { + timeline.add("query:" + kind(event)); + throw new IllegalStateException("sink failed"); + } + + @Override + public void error(String code, String message, Object details) { + timeline.add("error:" + code); + } + + @Override + public void endOfStream() { + timeline.add("endOfStream"); + } + }; + + handler.onListen(CHUNKED_ARGS, failingSink); + QuerySnapshot snapshot = singleDocumentSnapshot(); + deliveryExecutor.execute(() -> listenerRef.get().onEvent(snapshot, null)); + deliveryExecutor.execute(() -> mainExecutor.execute(() -> timeline.add("sync"))); + + drainBoth(workerDelegate, mainExecutor); + + assertEquals( + Arrays.asList( + "query:" + QuerySnapshotChunkProtocol.START_KIND, + "error:firebase_firestore", + "endOfStream", + "sync"), + timeline); + } + + private void drainBoth(ManualExecutor first, ManualExecutor second) { + while (!first.pending.isEmpty() || !second.pending.isEmpty()) { + first.runAll(); + second.runAll(); + } + } + + @SuppressWarnings("unchecked") + private AtomicReference> captureListener(Query query) { + return captureListener(query, mock(ListenerRegistration.class)); + } + + @SuppressWarnings("unchecked") + private AtomicReference> captureListener( + Query query, ListenerRegistration registration) { + AtomicReference> listenerRef = new AtomicReference<>(); + when(query.addSnapshotListener(any(SnapshotListenOptions.class), any())) + .thenAnswer( + invocation -> { + listenerRef.set(invocation.getArgument(1)); + return registration; + }); + return listenerRef; + } + + private QuerySnapshot singleDocumentSnapshot() { + QuerySnapshot snapshot = mock(QuerySnapshot.class); + QueryDocumentSnapshot document = mock(QueryDocumentSnapshot.class); + DocumentReference reference = mock(DocumentReference.class); + SnapshotMetadata metadata = mock(SnapshotMetadata.class); + DocumentChange change = mock(DocumentChange.class); + when(snapshot.getMetadata()).thenReturn(metadata); + when(snapshot.getDocuments()).thenReturn(Collections.singletonList(document)); + when(snapshot.getDocumentChanges()).thenReturn(Collections.singletonList(change)); + when(metadata.hasPendingWrites()).thenReturn(false); + when(metadata.isFromCache()).thenReturn(false); + when(document.getMetadata()).thenReturn(metadata); + when(document.getReference()).thenReturn(reference); + when(reference.getPath()).thenReturn("projects/p/assets/a"); + when(document.getData(DocumentSnapshot.ServerTimestampBehavior.NONE)) + .thenReturn(Collections.singletonMap("title", "Asset A")); + when(change.getType()).thenReturn(DocumentChange.Type.ADDED); + when(change.getDocument()).thenReturn(document); + when(change.getOldIndex()).thenReturn(-1); + when(change.getNewIndex()).thenReturn(0); + return snapshot; + } + private QuerySnapshot emptySnapshot() { QuerySnapshot snapshot = mock(QuerySnapshot.class); SnapshotMetadata metadata = mock(SnapshotMetadata.class); @@ -198,6 +685,10 @@ public void execute(Runnable command) { pending.addLast(command); } + void runOne() { + pending.removeFirst().run(); + } + void runAll() { while (!pending.isEmpty()) { pending.removeFirst().run(); diff --git a/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutorTest.java b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutorTest.java new file mode 100644 index 000000000000..23cd5a62e495 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/SnapshotDeliveryExecutorTest.java @@ -0,0 +1,118 @@ +/* + * Copyright 2026, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +package io.flutter.plugins.firebase.firestore.streamhandler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Executor; +import org.junit.Test; + +public class SnapshotDeliveryExecutorTest { + + @Test + public void executesQueuedTasksInFifoOrder() { + ManualExecutor delegate = new ManualExecutor(); + SnapshotDeliveryExecutor executor = new SnapshotDeliveryExecutor(delegate); + List events = new ArrayList<>(); + + executor.execute(() -> events.add("first")); + executor.execute(() -> events.add("second")); + executor.execute(() -> events.add("third")); + delegate.runAll(); + + assertEquals(Arrays.asList("first", "second", "third"), events); + } + + @Test + public void deferralHoldsSubsequentTasksUntilCompletedWhileAllowingContinuations() { + ManualExecutor delegate = new ManualExecutor(); + SnapshotDeliveryExecutor executor = new SnapshotDeliveryExecutor(delegate); + List events = new ArrayList<>(); + + executor.execute( + () -> { + events.add("start"); + Runnable complete = executor.deferNext(); + executor.executeContinuation( + () -> { + events.add("chunk"); + executor.executeContinuation( + () -> { + events.add("end"); + complete.run(); + }); + }); + }); + executor.execute(() -> events.add("sync")); + delegate.runAll(); + + assertEquals(Arrays.asList("start", "chunk", "end", "sync"), events); + } + + @Test + public void deferralCompletionIsIdempotent() { + ManualExecutor delegate = new ManualExecutor(); + SnapshotDeliveryExecutor executor = new SnapshotDeliveryExecutor(delegate); + List events = new ArrayList<>(); + + Runnable first = executor.deferNext(); + Runnable second = executor.deferNext(); + executor.execute(() -> events.add("sync")); + + first.run(); + first.run(); + delegate.runAll(); + assertEquals(Arrays.asList(), events); + + second.run(); + delegate.runAll(); + assertEquals(Arrays.asList("sync"), events); + } + + @Test + public void uncaughtTaskExceptionDoesNotStallSubsequentQueuedTasks() { + ManualExecutor delegate = new ManualExecutor(); + SnapshotDeliveryExecutor executor = new SnapshotDeliveryExecutor(delegate); + List events = new ArrayList<>(); + + executor.execute( + () -> { + events.add("failing"); + throw new IllegalStateException("boom"); + }); + executor.execute(() -> events.add("after")); + + assertThrows(IllegalStateException.class, delegate::runOne); + delegate.runAll(); + + assertEquals(Arrays.asList("failing", "after"), events); + } + + private static final class ManualExecutor implements Executor { + final ArrayDeque pending = new ArrayDeque<>(); + + @Override + public void execute(Runnable command) { + pending.addLast(command); + } + + void runOne() { + pending.removeFirst().run(); + } + + void runAll() { + while (!pending.isEmpty()) { + pending.removeFirst().run(); + } + } + } +} diff --git a/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart b/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart index c86f14b77cd3..ae74c5c33b6e 100644 --- a/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart +++ b/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart @@ -344,6 +344,47 @@ void runQueryTests() { await expectLater(value2, completion('value2')); }); + test('receives large query snapshots exceeding chunk boundary', () async { + final collection = await initializeTest('large-chunked-snapshot'); + const documentCount = 30; + final payload = 'a' * (24 * 1024); + + final writeBatch = firestore.batch(); + for (var i = 0; i < documentCount; i++) { + writeBatch.set( + collection.doc('doc-${i.toString().padLeft(3, '0')}'), + {'index': i, 'payload': payload}, + ); + } + await writeBatch.commit(); + + addTearDown(() async { + final deleteBatch = firestore.batch(); + for (var i = 0; i < documentCount; i++) { + deleteBatch.delete( + collection.doc('doc-${i.toString().padLeft(3, '0')}'), + ); + } + await deleteBatch.commit(); + }); + + final snapshot = await collection + .orderBy('index') + .snapshots() + .firstWhere((s) => s.docs.length == documentCount) + .timeout(const Duration(seconds: 30)); + + expect(snapshot.docs.length, documentCount); + expect(snapshot.docChanges.length, documentCount); + for (var i = 0; i < documentCount; i++) { + final data = snapshot.docs[i].data(); + expect(data['index'], i); + expect(data['payload'], payload); + expect(snapshot.docChanges[i].type, DocumentChangeType.added); + expect(snapshot.docChanges[i].newIndex, i); + } + }); + test('listens to a multiple changes response', () async { CollectionReference> collection = await initializeTest('get-multiple'); diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart index fbdae37c4c6f..c84872a8649f 100644 --- a/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/method_channel_query.dart @@ -203,34 +203,37 @@ class MethodChannelQuery extends QueryPlatform { listenSource, ); - // Keep assembly state local to this listener generation. A cancel or - // re-listen while Pigeon setup is pending must not reuse partial chunks. - final snapshotAssembler = QuerySnapshotChunkAssembler(); - try { - yield* MethodChannelFirebaseFirestore.querySnapshotChannel(observerId) - .receiveGuardedBroadcastStream(onError: convertPlatformException) - .transform( - StreamTransformer.fromHandlers( - handleData: (snapshot, sink) { - try { - final result = snapshotAssembler.add(snapshot); - if (result != null) { - sink.add(MethodChannelQuerySnapshot(firestore, result)); - } - } catch (error, stackTrace) { - snapshotAssembler.reset(); - sink.addError(error, stackTrace); + final assembler = QuerySnapshotChunkAssembler(); + yield* MethodChannelFirebaseFirestore.querySnapshotChannel(observerId) + .receiveGuardedBroadcastStream( + arguments: querySnapshotChunkListenArguments, + onError: convertPlatformException, + ) + .transform( + StreamTransformer.fromHandlers( + handleData: (Object? event, EventSink sink) { + try { + final snapshot = assembler.add(event); + if (snapshot != null) { + sink.add(MethodChannelQuerySnapshot(firestore, snapshot)); } - }, - handleError: (error, stackTrace, sink) { - snapshotAssembler.reset(); + } catch (error, stackTrace) { + assembler.reset(); sink.addError(error, stackTrace); - }, - ), - ); - } finally { - snapshotAssembler.reset(); - } + sink.close(); + } + }, + handleError: + ( + Object error, + StackTrace stackTrace, + EventSink sink, + ) { + assembler.reset(); + sink.addError(error, stackTrace); + }, + ), + ); } @override diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart index 8de52302c16b..d1c8d7353a59 100644 --- a/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart @@ -2,12 +2,11 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import '../pigeon/messages.pigeon.dart'; +import 'package:cloud_firestore_platform_interface/src/pigeon/messages.pigeon.dart'; +import 'package:meta/meta.dart'; -// These map keys and chunk kinds are mirrored by QuerySnapshotsStreamHandler -// on Android. The chunk protocol deliberately uses types already supported by -// PigeonCodec so older Apple and desktop implementations can continue emitting -// InternalQuerySnapshot directly. +// Kept in sync with QuerySnapshotChunkProtocol.java. +const String _listenChunkedArgKey = 'firestoreQuerySnapshotChunked'; const String _chunkMarkerKey = 'firestoreQuerySnapshotChunk'; const String _snapshotIdKey = 'snapshotId'; const String _kindKey = 'kind'; @@ -20,227 +19,251 @@ const int _documentsKind = 1; const int _documentChangesKind = 2; const int _endKind = 3; -/// Reassembles the bounded Android transport messages for one logical query -/// snapshot. -/// -/// Other platforms still emit [InternalQuerySnapshot] directly, which is -/// passed through unchanged. A chunked snapshot is returned only after its end -/// marker and declared item counts have been received, preserving the public -/// stream's atomic snapshot contract. +const Map querySnapshotChunkListenArguments = + {_listenChunkedArgKey: true}; + +@visibleForTesting +Map querySnapshotChunkStartMessage({ + required int snapshotId, + required InternalSnapshotMetadata metadata, + required int documentCount, + required int documentChangeCount, +}) { + return { + _chunkMarkerKey: true, + _snapshotIdKey: snapshotId, + _kindKey: _startKind, + _payloadKey: metadata, + _documentCountKey: documentCount, + _documentChangeCountKey: documentChangeCount, + }; +} + +@visibleForTesting +Map querySnapshotChunkDocumentsMessage({ + required int snapshotId, + required List items, +}) { + return { + _chunkMarkerKey: true, + _snapshotIdKey: snapshotId, + _kindKey: _documentsKind, + _payloadKey: items, + }; +} + +@visibleForTesting +Map querySnapshotChunkDocumentChangesMessage({ + required int snapshotId, + required List items, +}) { + return { + _chunkMarkerKey: true, + _snapshotIdKey: snapshotId, + _kindKey: _documentChangesKind, + _payloadKey: items, + }; +} + +@visibleForTesting +Map querySnapshotChunkEndMessage({required int snapshotId}) { + return { + _chunkMarkerKey: true, + _snapshotIdKey: snapshotId, + _kindKey: _endKind, + }; +} + class QuerySnapshotChunkAssembler { - _ActiveQuerySnapshot? _active; - - /// Adds one decoded event-channel [message]. - /// - /// Returns a complete snapshot, or `null` while a chunked snapshot is still - /// being assembled. Throws [StateError] when the transport protocol is - /// malformed or interleaved. - InternalQuerySnapshot? add(Object? message) { - if (message is InternalQuerySnapshot) { + _PendingQuerySnapshot? _active; + + bool get hasPendingSnapshot => _active != null; + + void reset() { + _active = null; + } + + InternalQuerySnapshot? add(Object? event) { + if (event is InternalQuerySnapshot) { if (_active != null) { throw StateError( - 'Received a complete query snapshot while chunk assembly was active.', + 'Received unchunked query snapshot while snapshot ' + '${_active!.snapshotId} was incomplete.', ); } - return message; + return event; } - if (message is! Map || message[_chunkMarkerKey] != true) { - throw StateError('Received an unknown query snapshot message.'); + if (event is! Map || event[_chunkMarkerKey] != true) { + throw StateError('Unexpected query snapshot event: ${event.runtimeType}'); } - final snapshotId = _requiredInt(message, _snapshotIdKey); - final kind = _requiredInt(message, _kindKey); + final snapshotId = _requireInt(event, _snapshotIdKey); + final kind = _requireInt(event, _kindKey); switch (kind) { case _startKind: - _start(message, snapshotId); + if (_active != null) { + throw StateError( + 'Received query snapshot $snapshotId start before snapshot ' + '${_active!.snapshotId} completed.', + ); + } + final metadata = event[_payloadKey]; + if (metadata is! InternalSnapshotMetadata) { + throw StateError( + 'Missing or invalid metadata for query snapshot $snapshotId.', + ); + } + final documentCount = _requireNonNegativeInt(event, _documentCountKey); + final documentChangeCount = _requireNonNegativeInt( + event, + _documentChangeCountKey, + ); + _active = _PendingQuerySnapshot( + snapshotId: snapshotId, + metadata: metadata, + expectedDocumentCount: documentCount, + expectedDocumentChangeCount: documentChangeCount, + ); + return null; + case _documentsKind: - _appendDocuments(message, snapshotId); + final active = _requireActiveSnapshot(snapshotId, 'document chunk'); + final items = _requireList( + event, + _payloadKey, + 'InternalDocumentSnapshot', + ); + if (active.documents.length + items.length > + active.expectedDocumentCount) { + throw StateError( + 'Query snapshot $snapshotId received more documents than ' + 'expected (${active.documents.length + items.length} > ' + '${active.expectedDocumentCount}).', + ); + } + active.documents.addAll(items); + return null; + case _documentChangesKind: - _appendDocumentChanges(message, snapshotId); + final active = _requireActiveSnapshot( + snapshotId, + 'document change chunk', + ); + final items = _requireList( + event, + _payloadKey, + 'InternalDocumentChange', + ); + if (active.documentChanges.length + items.length > + active.expectedDocumentChangeCount) { + throw StateError( + 'Query snapshot $snapshotId received more document changes than ' + 'expected (${active.documentChanges.length + items.length} > ' + '${active.expectedDocumentChangeCount}).', + ); + } + active.documentChanges.addAll(items); + return null; + case _endKind: - return _finish(snapshotId); + final active = _requireActiveSnapshot(snapshotId, 'end marker'); + _active = null; + if (active.documents.length != active.expectedDocumentCount || + active.documentChanges.length != + active.expectedDocumentChangeCount) { + throw StateError( + 'Query snapshot $snapshotId ended incomplete: expected ' + '${active.expectedDocumentCount} documents and ' + '${active.expectedDocumentChangeCount} document changes, got ' + '${active.documents.length} and ${active.documentChanges.length}.', + ); + } + return InternalQuerySnapshot( + documents: active.documents, + documentChanges: active.documentChanges, + metadata: active.metadata, + ); + default: - throw StateError('Unknown query snapshot chunk kind: $kind.'); + throw StateError('Unknown query snapshot chunk kind: $kind'); } - - return null; } - /// Abandons an interrupted snapshot after cancellation or a stream error. - void reset() { - _active = null; - } - - void _start(Map message, int snapshotId) { - if (_active != null) { + _PendingQuerySnapshot _requireActiveSnapshot( + int snapshotId, + String frameName, + ) { + final active = _active; + if (active == null) { throw StateError( - 'Query snapshot $snapshotId started before the active snapshot ended.', + 'Received query snapshot $snapshotId $frameName before its start.', ); } - - final documentCount = _requiredInt(message, _documentCountKey); - final documentChangeCount = _requiredInt(message, _documentChangeCountKey); - final metadata = message[_payloadKey]; - if (documentCount < 0 || documentChangeCount < 0) { - throw StateError('Query snapshot item counts cannot be negative.'); - } - if (metadata is! InternalSnapshotMetadata) { - throw StateError('Query snapshot start is missing metadata.'); - } - - _active = _ActiveQuerySnapshot( - id: snapshotId, - expectedDocumentCount: documentCount, - expectedDocumentChangeCount: documentChangeCount, - metadata: metadata, - ); - } - - void _appendDocuments(Map message, int snapshotId) { - final active = _requireActive(snapshotId); - final payload = message[_payloadKey]; - if (payload is! List) { - throw StateError('Query snapshot document chunk has an invalid payload.'); - } - - active.documents.addAll(payload.cast()); - if (active.documents.length > active.expectedDocumentCount) { - throw StateError('Query snapshot received too many documents.'); - } - } - - void _appendDocumentChanges(Map message, int snapshotId) { - final active = _requireActive(snapshotId); - final payload = message[_payloadKey]; - if (payload is! List) { + if (active.snapshotId != snapshotId) { throw StateError( - 'Query snapshot document-change chunk has an invalid payload.', + 'Received query snapshot $snapshotId $frameName while snapshot ' + '${active.snapshotId} was active.', ); } + return active; + } - active.documentChanges.addAll(payload.cast()); - if (active.documentChanges.length > active.expectedDocumentChangeCount) { - throw StateError('Query snapshot received too many document changes.'); + static int _requireInt(Map map, String key) { + final value = map[key]; + if (value is! int) { + throw StateError('Query snapshot chunk field "$key" must be an int.'); } + return value; } - InternalQuerySnapshot _finish(int snapshotId) { - final active = _requireActive(snapshotId); - _active = null; - - if (active.documents.length != active.expectedDocumentCount || - active.documentChanges.length != active.expectedDocumentChangeCount) { + static int _requireNonNegativeInt(Map map, String key) { + final value = _requireInt(map, key); + if (value < 0) { throw StateError( - 'Query snapshot $snapshotId ended with ' - '${active.documents.length}/${active.expectedDocumentCount} documents ' - 'and ${active.documentChanges.length}/' - '${active.expectedDocumentChangeCount} document changes.', + 'Query snapshot chunk field "$key" must be non-negative.', ); } - - return InternalQuerySnapshot( - documents: active.documents, - documentChanges: active.documentChanges, - metadata: active.metadata, - ); + return value; } - _ActiveQuerySnapshot _requireActive(int snapshotId) { - final active = _active; - if (active == null) { - throw StateError( - 'Received a chunk for query snapshot $snapshotId before its start.', - ); + static List _requireList( + Map map, + String key, + String elementTypeName, + ) { + final value = map[key]; + if (value is! List) { + throw StateError('Query snapshot chunk field "$key" must be a List.'); } - if (active.id != snapshotId) { - throw StateError( - 'Received a chunk for query snapshot $snapshotId while assembling ' - '${active.id}.', - ); + final result = []; + for (final item in value) { + if (item is! T) { + throw StateError( + 'Query snapshot chunk field "$key" contains non-$elementTypeName ' + 'element: ${item.runtimeType}.', + ); + } + result.add(item); } - return active; + return result; } } -class _ActiveQuerySnapshot { - _ActiveQuerySnapshot({ - required this.id, +class _PendingQuerySnapshot { + _PendingQuerySnapshot({ + required this.snapshotId, + required this.metadata, required this.expectedDocumentCount, required this.expectedDocumentChangeCount, - required this.metadata, }); - final int id; + final int snapshotId; + final InternalSnapshotMetadata metadata; final int expectedDocumentCount; final int expectedDocumentChangeCount; - final InternalSnapshotMetadata metadata; - final List documents = - []; - final List documentChanges = - []; -} - -int _requiredInt(Map message, String key) { - final value = message[key]; - if (value is! int) { - throw StateError('Query snapshot chunk is missing integer "$key".'); - } - return value; -} - -/// Creates an Android query-snapshot start message for protocol tests. -Map querySnapshotChunkStart({ - required int snapshotId, - required int documentCount, - required int documentChangeCount, - required InternalSnapshotMetadata metadata, -}) { - return { - _chunkMarkerKey: true, - _snapshotIdKey: snapshotId, - _kindKey: _startKind, - _payloadKey: metadata, - _documentCountKey: documentCount, - _documentChangeCountKey: documentChangeCount, - }; -} - -/// Creates an Android query-snapshot document message for protocol tests. -Map querySnapshotDocumentChunk( - int snapshotId, - List documents, -) { - return _itemChunk(snapshotId, _documentsKind, documents); -} - -/// Creates an Android query-snapshot change message for protocol tests. -Map querySnapshotDocumentChangeChunk( - int snapshotId, - List documentChanges, -) { - return _itemChunk(snapshotId, _documentChangesKind, documentChanges); -} - -/// Creates an Android query-snapshot end message for protocol tests. -Map querySnapshotChunkEnd(int snapshotId) { - return { - _chunkMarkerKey: true, - _snapshotIdKey: snapshotId, - _kindKey: _endKind, - }; -} - -Map _itemChunk( - int snapshotId, - int kind, - List payload, -) { - return { - _chunkMarkerKey: true, - _snapshotIdKey: snapshotId, - _kindKey: kind, - _payloadKey: payload, - }; + final List documents = []; + final List documentChanges = + []; } diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart deleted file mode 100644 index 50157377fab2..000000000000 --- a/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel/query_snapshot_chunk_assembler_test.dart +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright 2026, the Chromium project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart'; -import 'package:cloud_firestore_platform_interface/src/method_channel/query_snapshot_chunk_assembler.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('QuerySnapshotChunkAssembler', () { - test('passes through the existing platform snapshot message', () { - final assembler = QuerySnapshotChunkAssembler(); - final snapshot = _snapshot('projects/p/assets/a'); - - expect(assembler.add(snapshot), same(snapshot)); - }); - - test('reassembles chunked documents and changes atomically', () { - final assembler = QuerySnapshotChunkAssembler(); - final first = _document('projects/p/assets/a', 1); - final second = _document('projects/p/assets/b', 2); - final metadata = _metadata(isFromCache: false); - - expect( - assembler.add( - querySnapshotChunkStart( - snapshotId: 7, - documentCount: 2, - documentChangeCount: 2, - metadata: metadata, - ), - ), - isNull, - ); - expect( - assembler.add(querySnapshotDocumentChunk(7, [first])), - isNull, - ); - expect( - assembler.add(querySnapshotDocumentChunk(7, [second])), - isNull, - ); - expect( - assembler.add( - querySnapshotDocumentChangeChunk(7, [ - _change(first, 0), - _change(second, 1), - ]), - ), - isNull, - ); - - final result = assembler.add(querySnapshotChunkEnd(7)); - - expect(result, isA()); - final complete = result!; - expect(complete.documents, [first, second]); - expect(complete.documentChanges, hasLength(2)); - expect(complete.metadata, metadata); - }); - - test('rejects a new snapshot before the active snapshot ends', () { - final assembler = QuerySnapshotChunkAssembler(); - assembler.add( - querySnapshotChunkStart( - snapshotId: 1, - documentCount: 0, - documentChangeCount: 0, - metadata: _metadata(), - ), - ); - - expect( - () => assembler.add( - querySnapshotChunkStart( - snapshotId: 2, - documentCount: 0, - documentChangeCount: 0, - metadata: _metadata(), - ), - ), - throwsStateError, - ); - }); - - test('rejects chunks for a different snapshot', () { - final assembler = QuerySnapshotChunkAssembler(); - assembler.add( - querySnapshotChunkStart( - snapshotId: 4, - documentCount: 1, - documentChangeCount: 0, - metadata: _metadata(), - ), - ); - - expect( - () => assembler.add( - querySnapshotDocumentChunk(5, [ - _document('projects/p/assets/a', 1), - ]), - ), - throwsStateError, - ); - }); - - test('rejects an incomplete snapshot', () { - final assembler = QuerySnapshotChunkAssembler(); - assembler.add( - querySnapshotChunkStart( - snapshotId: 9, - documentCount: 2, - documentChangeCount: 0, - metadata: _metadata(), - ), - ); - assembler.add( - querySnapshotDocumentChunk(9, [ - _document('projects/p/assets/a', 1), - ]), - ); - - expect(() => assembler.add(querySnapshotChunkEnd(9)), throwsStateError); - }); - - test('reset abandons an interrupted snapshot', () { - final assembler = QuerySnapshotChunkAssembler(); - assembler.add( - querySnapshotChunkStart( - snapshotId: 1, - documentCount: 1, - documentChangeCount: 0, - metadata: _metadata(), - ), - ); - - assembler.reset(); - - expect( - assembler.add( - querySnapshotChunkStart( - snapshotId: 2, - documentCount: 0, - documentChangeCount: 0, - metadata: _metadata(), - ), - ), - isNull, - ); - expect( - assembler.add(querySnapshotChunkEnd(2)), - isA(), - ); - }); - - test('reassembles messages after a Pigeon event-channel round trip', () { - const codec = StandardMethodCodec(PigeonCodec()); - final assembler = QuerySnapshotChunkAssembler(); - final document = _document('projects/p/assets/a', 1); - final messages = [ - querySnapshotChunkStart( - snapshotId: 3, - documentCount: 1, - documentChangeCount: 1, - metadata: _metadata(), - ), - querySnapshotDocumentChunk(3, [document]), - querySnapshotDocumentChangeChunk(3, [_change(document, 0)]), - querySnapshotChunkEnd(3), - ]; - - InternalQuerySnapshot? result; - for (final message in messages) { - final envelope = codec.encodeSuccessEnvelope(message); - result = assembler.add(codec.decodeEnvelope(envelope)); - } - - expect(result, isNotNull); - expect(result!.documents.single, document); - expect(result.documentChanges.single!.document, document); - }); - }); -} - -InternalQuerySnapshot _snapshot(String path) { - final document = _document(path, 1); - return InternalQuerySnapshot( - documents: [document], - documentChanges: [_change(document, 0)], - metadata: _metadata(), - ); -} - -InternalDocumentSnapshot _document(String path, int value) { - return InternalDocumentSnapshot( - path: path, - data: {'value': value}, - metadata: _metadata(), - ); -} - -InternalDocumentChange _change( - InternalDocumentSnapshot document, - int newIndex, -) { - return InternalDocumentChange( - type: DocumentChangeType.added, - document: document, - oldIndex: -1, - newIndex: newIndex, - ); -} - -InternalSnapshotMetadata _metadata({bool isFromCache = true}) { - return InternalSnapshotMetadata( - hasPendingWrites: false, - isFromCache: isFromCache, - ); -} diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel_firestore_test.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel_firestore_test.dart index 3470291771aa..2196b9cd8a89 100644 --- a/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel_firestore_test.dart +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/test/method_channel_firestore_test.dart @@ -337,59 +337,6 @@ void main() { await secondSubscription.cancel(); }); - test('query re-listen while the first pigeon call is still pending attaches only ' - 'the second listener', () async { - const firstObserverId = 'observer-id-1'; - const secondObserverId = 'observer-id-2'; - - final firstObserver = Completer(); - final secondObserver = Completer(); - hostApi.queuedSnapshotObserverIds - ..add(firstObserver) - ..add(secondObserver); - - final relistenChannels = >{ - 'plugins.flutter.io/firebase_firestore/query/$firstObserverId': - [], - 'plugins.flutter.io/firebase_firestore/query/$secondObserverId': - [], - }; - relistenChannels.forEach((channel, calls) { - messenger.setMockMessageHandler(channel, (ByteData? message) async { - calls.add(codec.decodeMethodCall(message).method); - return codec.encodeSuccessEnvelope(null); - }); - }); - addTearDown(() { - for (final channel in relistenChannels.keys) { - messenger.setMockMessageHandler(channel, null); - } - }); - - final stream = firestore - .collection('foo') - .snapshots(listenSource: ListenSource.defaultSource); - - await stream.listen((_) {}).cancel(); - final secondSubscription = stream.listen((_) {}); - - firstObserver.complete(firstObserverId); - await pumpEventQueue(); - secondObserver.complete(secondObserverId); - await pumpEventQueue(); - - expect( - relistenChannels['plugins.flutter.io/firebase_firestore/query/$firstObserverId'], - isEmpty, - ); - expect( - relistenChannels['plugins.flutter.io/firebase_firestore/query/$secondObserverId'], - ['listen'], - ); - - await secondSubscription.cancel(); - }); - test('snapshotsInSync() does not attach a native listener when cancelled ' 'before setup completes', () async { const syncObserverId = 'sync-observer-id'; @@ -410,138 +357,248 @@ void main() { }); }); - group('query snapshot chunks over the event channel', () { - const observerId = 'chunk-observer'; - const channel = 'plugins.flutter.io/firebase_firestore/query/$observerId'; + test('namedQueryGet binds the snapshot to the calling instance', () async { + final firestore = MethodChannelFirebaseFirestore( + app: app, + databaseId: 'named-query-db', + ); + + final snapshot = await firestore.namedQueryGet('named-query'); + + final reference = snapshot.docs.single.reference; + expect(reference.firestore.app.name, 'test-app'); + expect(reference.firestore.databaseId, 'named-query-db'); + }); + + group('Query.snapshots() chunked delivery', () { + const observerId = 'chunked-observer-id'; + const queryChannel = + 'plugins.flutter.io/firebase_firestore/query/$observerId'; + late MethodChannelFirebaseFirestore firestore; - late List snapshots; - late List errors; + late List eventChannelCalls; setUp(() { firestore = MethodChannelFirebaseFirestore( app: app, databaseId: '(default)', ); - snapshots = []; - errors = []; - messenger.setMockMessageHandler(channel, (ByteData? message) async { + eventChannelCalls = []; + messenger.setMockMessageHandler(queryChannel, (ByteData? message) async { + eventChannelCalls.add(codec.decodeMethodCall(message)); return codec.encodeSuccessEnvelope(null); }); }); - tearDown(() => messenger.setMockMessageHandler(channel, null)); + tearDown(() { + messenger.setMockMessageHandler(queryChannel, null); + }); - Future send(Object? frame) async { - unawaited( - messenger.handlePlatformMessage( - channel, - codec.encodeSuccessEnvelope(frame), - (_) {}, - ), + Future pushEvent(Object? event) { + return messenger.handlePlatformMessage( + queryChannel, + codec.encodeSuccessEnvelope(event), + (_) {}, ); - await pumpEventQueue(); } - Map start(int id, {int documentCount = 0}) => - querySnapshotChunkStart( - snapshotId: id, - documentCount: documentCount, - documentChangeCount: 0, - metadata: InternalSnapshotMetadata( - hasPendingWrites: false, - isFromCache: true, + Future pushError(String code, String message) { + return messenger.handlePlatformMessage( + queryChannel, + codec.encodeErrorEnvelope(code: code, message: message), + (_) {}, + ); + } + + InternalSnapshotMetadata snapshotMetadata() => + InternalSnapshotMetadata(hasPendingWrites: false, isFromCache: false); + + InternalDocumentSnapshot docSnapshot(String path, String title) => + InternalDocumentSnapshot( + path: path, + data: {'title': title}, + metadata: snapshotMetadata(), + ); + + test( + 'advertises chunking support and reassembles chunked snapshots atomically', + () async { + final received = []; + final subscription = firestore + .collection('assets') + .snapshots(listenSource: ListenSource.defaultSource) + .listen(received.add); + + hostApi.snapshotObserverId.complete(observerId); + await pumpEventQueue(); + + expect(eventChannelCalls, hasLength(1)); + expect(eventChannelCalls.single.method, 'listen'); + expect( + eventChannelCalls.single.arguments, + equals(querySnapshotChunkListenArguments), + ); + + final docA = docSnapshot('assets/a', 'A'); + final docB = docSnapshot('assets/b', 'B'); + final changeA = InternalDocumentChange( + type: DocumentChangeType.added, + document: docA, + oldIndex: -1, + newIndex: 0, + ); + final changeB = InternalDocumentChange( + type: DocumentChangeType.added, + document: docB, + oldIndex: -1, + newIndex: 1, + ); + + await pushEvent( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: snapshotMetadata(), + documentCount: 2, + documentChangeCount: 2, + ), + ); + await pushEvent( + querySnapshotChunkDocumentsMessage( + snapshotId: 1, + items: [docA], + ), + ); + await pushEvent( + querySnapshotChunkDocumentsMessage( + snapshotId: 1, + items: [docB], + ), + ); + await pushEvent( + querySnapshotChunkDocumentChangesMessage( + snapshotId: 1, + items: [changeA], ), ); + await pumpEventQueue(); + expect(received, isEmpty); - test('publishes only the complete logical snapshot', () async { - final subscription = firestore - .collection('foo') - .snapshots(listenSource: ListenSource.defaultSource) - .listen(snapshots.add, onError: errors.add); - addTearDown(subscription.cancel); - hostApi.snapshotObserverId.complete(observerId); - await pumpEventQueue(); - await send(start(1, documentCount: 1)); - await send( - querySnapshotDocumentChunk(1, [ - InternalDocumentSnapshot( - path: 'foo/bar', - data: {'value': 1}, - metadata: InternalSnapshotMetadata( - hasPendingWrites: false, - isFromCache: true, - ), + await pushEvent( + querySnapshotChunkDocumentChangesMessage( + snapshotId: 1, + items: [changeB], ), - ]), - ); - expect(snapshots, isEmpty); - await send(querySnapshotChunkEnd(1)); - expect(snapshots, hasLength(1)); - expect(snapshots.single.docs.single.data(), { - 'value': 1, - }); - expect(errors, isEmpty); - }); + ); + await pushEvent(querySnapshotChunkEndMessage(snapshotId: 1)); + await pumpEventQueue(); + + expect(received, hasLength(1)); + expect(received.single.docs.map((d) => d.id), ['a', 'b']); + expect(received.single.docChanges.map((c) => c.document.id), [ + 'a', + 'b', + ]); - test('resets incomplete assembly after a native stream error', () async { + await subscription.cancel(); + }, + ); + + test('resets partial chunk state after a native stream error so subsequent ' + 'snapshots assemble cleanly', () async { + final received = []; + final errors = []; final subscription = firestore - .collection('foo') + .collection('assets') .snapshots(listenSource: ListenSource.defaultSource) - .listen(snapshots.add, onError: errors.add); - addTearDown(subscription.cancel); + .listen(received.add, onError: errors.add); + hostApi.snapshotObserverId.complete(observerId); await pumpEventQueue(); - await send(start(1, documentCount: 1)); - unawaited( - messenger.handlePlatformMessage( - channel, - codec.encodeErrorEnvelope(code: 'unavailable', message: 'Retry'), - (_) {}, + + await pushEvent( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: snapshotMetadata(), + documentCount: 1, + documentChangeCount: 0, ), ); + await pushError('unavailable', 'transient error'); + await pushEvent( + querySnapshotChunkStartMessage( + snapshotId: 2, + metadata: snapshotMetadata(), + documentCount: 0, + documentChangeCount: 0, + ), + ); + await pushEvent(querySnapshotChunkEndMessage(snapshotId: 2)); await pumpEventQueue(); + expect(errors, hasLength(1)); - await send(start(2)); - await send(querySnapshotChunkEnd(2)); - expect(snapshots, hasLength(1)); - expect(snapshots.single.docs, isEmpty); - expect(errors, hasLength(1)); + expect(received, hasLength(1)); + expect(received.single.docs, isEmpty); + + await subscription.cancel(); }); test( - 're-listening does not inherit a cancelled partial snapshot', + 'cancels the native stream on protocol corruption without flooding errors ' + 'for trailing chunks', () async { - final stream = firestore - .collection('foo') - .snapshots(listenSource: ListenSource.defaultSource); - final subscription = stream.listen(snapshots.add, onError: errors.add); + final received = []; + final errors = []; + final subscription = firestore + .collection('assets') + .snapshots(listenSource: ListenSource.defaultSource) + .listen(received.add, onError: errors.add); + hostApi.snapshotObserverId.complete(observerId); await pumpEventQueue(); - await send(start(1, documentCount: 1)); - await subscription.cancel(); - await pumpEventQueue(); - final second = stream.listen(snapshots.add, onError: errors.add); - addTearDown(second.cancel); + + final docA = docSnapshot('assets/a', 'A'); + await pushEvent( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: snapshotMetadata(), + documentCount: 1, + documentChangeCount: 1, + ), + ); + await pushEvent( + querySnapshotChunkDocumentsMessage( + snapshotId: 999, + items: [docA], + ), + ); await pumpEventQueue(); - await send(start(2)); - await send(querySnapshotChunkEnd(2)); - expect(snapshots, hasLength(1)); - expect(snapshots.single.docs, isEmpty); - expect(errors, isEmpty); - }, - ); - }); - test('namedQueryGet binds the snapshot to the calling instance', () async { - final firestore = MethodChannelFirebaseFirestore( - app: app, - databaseId: 'named-query-db', - ); + await pushEvent( + querySnapshotChunkDocumentChangesMessage( + snapshotId: 1, + items: [ + InternalDocumentChange( + type: DocumentChangeType.added, + document: docA, + oldIndex: -1, + newIndex: 0, + ), + ], + ), + ); + await pushEvent(querySnapshotChunkEndMessage(snapshotId: 1)); + await pumpEventQueue(); - final snapshot = await firestore.namedQueryGet('named-query'); + expect(received, isEmpty); + expect(errors, hasLength(1)); + expect(errors.single, isA()); + expect(eventChannelCalls.map((call) => call.method), [ + 'listen', + 'cancel', + ]); - final reference = snapshot.docs.single.reference; - expect(reference.firestore.app.name, 'test-app'); - expect(reference.firestore.databaseId, 'named-query-db'); + await subscription.cancel(); + }, + ); }); } diff --git a/packages/cloud_firestore/cloud_firestore_platform_interface/test/query_snapshot_chunk_assembler_test.dart b/packages/cloud_firestore/cloud_firestore_platform_interface/test/query_snapshot_chunk_assembler_test.dart new file mode 100644 index 000000000000..d192c699e4de --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/test/query_snapshot_chunk_assembler_test.dart @@ -0,0 +1,338 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart'; +import 'package:cloud_firestore_platform_interface/src/method_channel/query_snapshot_chunk_assembler.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + InternalSnapshotMetadata metadata({ + bool hasPendingWrites = false, + bool isFromCache = false, + }) { + return InternalSnapshotMetadata( + hasPendingWrites: hasPendingWrites, + isFromCache: isFromCache, + ); + } + + InternalDocumentSnapshot document(String path, String title) { + return InternalDocumentSnapshot( + path: path, + data: {'title': title}, + metadata: metadata(), + ); + } + + InternalDocumentChange change( + InternalDocumentSnapshot doc, { + DocumentChangeType type = DocumentChangeType.added, + int oldIndex = -1, + int newIndex = 0, + }) { + return InternalDocumentChange( + type: type, + document: doc, + oldIndex: oldIndex, + newIndex: newIndex, + ); + } + + group('$QuerySnapshotChunkAssembler', () { + test('passes unchunked snapshots through unchanged', () { + final assembler = QuerySnapshotChunkAssembler(); + final doc = document('projects/p/assets/a', 'A'); + final snapshot = InternalQuerySnapshot( + documents: [doc], + documentChanges: [change(doc)], + metadata: metadata(isFromCache: true), + ); + + expect(assembler.add(snapshot), same(snapshot)); + expect(assembler.hasPendingSnapshot, isFalse); + }); + + test('reassembles a multi-chunk snapshot atomically in order', () { + final assembler = QuerySnapshotChunkAssembler(); + final docA = document('projects/p/assets/a', 'A'); + final docB = document('projects/p/assets/b', 'B'); + final docC = document('projects/p/assets/c', 'C'); + final changeA = change(docA); + final changeB = change(docB, newIndex: 1); + final changeC = change(docC, newIndex: 2); + final snapshotMeta = metadata(hasPendingWrites: true, isFromCache: true); + + expect( + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: snapshotMeta, + documentCount: 3, + documentChangeCount: 3, + ), + ), + isNull, + ); + expect(assembler.hasPendingSnapshot, isTrue); + + expect( + assembler.add( + querySnapshotChunkDocumentsMessage( + snapshotId: 1, + items: [docA, docB], + ), + ), + isNull, + ); + expect( + assembler.add( + querySnapshotChunkDocumentsMessage( + snapshotId: 1, + items: [docC], + ), + ), + isNull, + ); + expect( + assembler.add( + querySnapshotChunkDocumentChangesMessage( + snapshotId: 1, + items: [changeA], + ), + ), + isNull, + ); + expect( + assembler.add( + querySnapshotChunkDocumentChangesMessage( + snapshotId: 1, + items: [changeB, changeC], + ), + ), + isNull, + ); + + final assembled = assembler.add( + querySnapshotChunkEndMessage(snapshotId: 1), + ); + expect(assembled, isNotNull); + expect(assembler.hasPendingSnapshot, isFalse); + expect(assembled!.metadata.hasPendingWrites, isTrue); + expect(assembled.metadata.isFromCache, isTrue); + expect(assembled.documents.map((d) => d!.path), [ + 'projects/p/assets/a', + 'projects/p/assets/b', + 'projects/p/assets/c', + ]); + expect(assembled.documentChanges.map((c) => c!.newIndex), [0, 1, 2]); + }); + + test('reassembles an empty snapshot from start and end messages', () { + final assembler = QuerySnapshotChunkAssembler(); + final snapshotMeta = metadata(); + + expect( + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: snapshotMeta, + documentCount: 0, + documentChangeCount: 0, + ), + ), + isNull, + ); + + final assembled = assembler.add( + querySnapshotChunkEndMessage(snapshotId: 1), + ); + expect(assembled, isNotNull); + expect(assembled!.documents, isEmpty); + expect(assembled.documentChanges, isEmpty); + }); + + test('rejects chunk before start', () { + final assembler = QuerySnapshotChunkAssembler(); + + expect( + () => assembler.add( + querySnapshotChunkDocumentsMessage( + snapshotId: 1, + items: [ + document('projects/p/assets/a', 'A'), + ], + ), + ), + throwsStateError, + ); + }); + + test('rejects mismatched snapshot id', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: metadata(), + documentCount: 1, + documentChangeCount: 0, + ), + ); + + expect( + () => assembler.add( + querySnapshotChunkDocumentsMessage( + snapshotId: 2, + items: [ + document('projects/p/assets/a', 'A'), + ], + ), + ), + throwsStateError, + ); + }); + + test('rejects overlapping start before previous snapshot ends', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: metadata(), + documentCount: 1, + documentChangeCount: 0, + ), + ); + + expect( + () => assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 2, + metadata: metadata(), + documentCount: 0, + documentChangeCount: 0, + ), + ), + throwsStateError, + ); + }); + + test('rejects unchunked snapshot while chunked snapshot is in flight', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: metadata(), + documentCount: 1, + documentChangeCount: 0, + ), + ); + + expect( + () => assembler.add( + InternalQuerySnapshot( + documents: [], + documentChanges: [], + metadata: metadata(), + ), + ), + throwsStateError, + ); + }); + + test('rejects end when counts do not match', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: metadata(), + documentCount: 2, + documentChangeCount: 0, + ), + ); + assembler.add( + querySnapshotChunkDocumentsMessage( + snapshotId: 1, + items: [ + document('projects/p/assets/a', 'A'), + ], + ), + ); + + expect( + () => assembler.add(querySnapshotChunkEndMessage(snapshotId: 1)), + throwsStateError, + ); + expect(assembler.hasPendingSnapshot, isFalse); + }); + + test('rejects chunks exceeding declared count', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: metadata(), + documentCount: 1, + documentChangeCount: 0, + ), + ); + + expect( + () => assembler.add( + querySnapshotChunkDocumentsMessage( + snapshotId: 1, + items: [ + document('projects/p/assets/a', 'A'), + document('projects/p/assets/b', 'B'), + ], + ), + ), + throwsStateError, + ); + }); + + test('rejects unknown event types and unknown chunk kinds', () { + final assembler = QuerySnapshotChunkAssembler(); + + expect(() => assembler.add('unexpected'), throwsStateError); + expect( + () => assembler.add({'snapshotId': 1, 'kind': 0}), + throwsStateError, + ); + expect( + () => assembler.add({ + 'firestoreQuerySnapshotChunk': true, + 'snapshotId': 1, + 'kind': 99, + }), + throwsStateError, + ); + }); + + test('reset clears partial state so next snapshot succeeds', () { + final assembler = QuerySnapshotChunkAssembler(); + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 1, + metadata: metadata(), + documentCount: 1, + documentChangeCount: 0, + ), + ); + assembler.reset(); + + expect(assembler.hasPendingSnapshot, isFalse); + assembler.add( + querySnapshotChunkStartMessage( + snapshotId: 2, + metadata: metadata(), + documentCount: 0, + documentChangeCount: 0, + ), + ); + final assembled = assembler.add( + querySnapshotChunkEndMessage(snapshotId: 2), + ); + expect(assembled, isNotNull); + }); + }); +} diff --git a/tests/android/app/build.gradle b/tests/android/app/build.gradle index e5059736a91a..ca9e6054660b 100644 --- a/tests/android/app/build.gradle +++ b/tests/android/app/build.gradle @@ -1,6 +1,5 @@ plugins { id "com.android.application" - id "org.jetbrains.kotlin.android" // The Flutter Gradle Plugin must be applied after the Android Gradle plugin. id "dev.flutter.flutter-gradle-plugin" } diff --git a/tests/pubspec.yaml b/tests/pubspec.yaml index b1531b17a24b..340255b335d0 100644 --- a/tests/pubspec.yaml +++ b/tests/pubspec.yaml @@ -10,8 +10,6 @@ environment: flutter: '>=3.44.0' dependencies: - cloud_firestore: ^7.1.0 - cloud_firestore_platform_interface: ^8.1.0 cloud_functions: ^7.0.1 cloud_functions_platform_interface: ^6.1.1 cloud_functions_web: ^5.1.15