diff --git a/.github/workflows/android_unit_tests.yaml b/.github/workflows/android_unit_tests.yaml index c2975d226af2..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,16 +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 :firebase_crashlytics:testDebugUnitTest :cloud_functions:testDebugUnitTest :firebase_messaging:testDebugUnitTest + run: | + (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 91566d1abc18..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)}") @@ -69,6 +73,8 @@ android { exclude group: 'com.google.truth', module: 'truth' exclude group: 'com.fasterxml.jackson.core', module: 'jackson-databind' } + 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/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 new file mode 100644 index 000000000000..69cd1fa0f417 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocol.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 io.flutter.plugins.firebase.firestore.GeneratedAndroidFirebaseFirestore; +import io.flutter.plugins.firebase.firestore.PigeonCodecSizer; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +final class QuerySnapshotChunkProtocol { + // 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"; + 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; + + static final int MAX_ENCODED_ENVELOPE_BYTES = 512 * 1024; + + 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, + 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) { + return PigeonCodecSizer.encodedMessageSize(message); + } + + static int encodedEnvelopeSize(Object message) { + return PigeonCodecSizer.encodedSuccessEnvelopeSize(message); + } + + 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..73af196f89a8 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunker.java @@ -0,0 +1,69 @@ +/* + * 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; + +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..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 @@ -10,23 +10,29 @@ 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.ArrayList; +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 +40,16 @@ 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 Runnable activeTurnRelease; + private EventSink eventSink; + private boolean emissionActive; + private boolean chunkedTransport; + private boolean aborted; + private Exception pendingError; + private long listenerGeneration; public QuerySnapshotsStreamHandler( Query query, @@ -41,51 +57,469 @@ 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) { + ListenerRegistration previousRegistration; + List turnsToRelease; + final long generation; + synchronized (this) { + previousRegistration = listenerRegistration; + listenerRegistration = null; + generation = ++listenerGeneration; + emissionActive = false; + 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); 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); + onNativeError(exception, generation); } 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), generation); } }); + + retainListenerRegistration(registration, generation); + } + + private void retainListenerRegistration(ListenerRegistration registration, long generation) { + boolean removeRegistration; + synchronized (this) { + removeRegistration = + listenerGeneration != generation || eventSink == null || aborted || pendingError != null; + if (!removeRegistration) { + listenerRegistration = registration; + } + } + if (removeRegistration) { + registration.remove(); + } + } + + private void enqueueSnapshot(QuerySnapshot snapshot, long generation) { + boolean shouldStart; + boolean useChunked; + synchronized (this) { + if (listenerGeneration != generation + || eventSink == null + || aborted + || pendingError != null) { + return; + } + 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(generation); + } + } + + private void emitNextSnapshot(long generation) { + QueuedSnapshot queued; + Exception errorToDeliver = null; + synchronized (this) { + if (listenerGeneration != generation || eventSink == null || aborted) { + return; + } + queued = pendingSnapshots.pollFirst(); + if (queued == null) { + emissionActive = false; + 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(), queued.snapshot, queued.releaseTurn); + postSuccess( + QuerySnapshotChunkProtocol.start( + emission.id, emission.documentCount, emission.documentChangeCount, emission.metadata), + generation, + () -> emitNextChunk(emission, generation)); + } catch (Exception exception) { + emitErrorImmediately(exception, generation); + } catch (Error error) { + releaseAllTurns(); + throw error; + } + } + + private void emitNextChunk(SnapshotEmission emission, long generation) { + if (!isActive(generation)) { + 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), + generation, + () -> emitNextChunk(emission, generation)); + 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), + generation, + () -> emitNextChunk(emission, generation)); + return; + } + + postSuccess( + QuerySnapshotChunkProtocol.end(emission.id), + generation, + () -> finishSnapshotEmission(emission, generation)); + } catch (Exception exception) { + emitErrorImmediately(exception, generation); + } catch (Error error) { + releaseAllTurns(); + throw error; + } + } + + 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 (listenerGeneration != generation || eventSink == null || aborted) { + return; + } + sink = eventSink; + } + + eventExecutor.execute( + () -> { + if (!isActive(generation)) { + return; + } + try { + sink.success(message); + if (afterSuccess != null && isActive(generation)) { + executeSnapshotContinuation(afterSuccess); + } + } catch (Exception exception) { + emitErrorImmediately(exception, generation); + } catch (Error error) { + releaseAllTurns(); + throw error; + } + }); + } + + 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 (listenerGeneration != generation + || eventSink == null + || aborted + || pendingError != null) { + return; + } + pendingError = exception; + registration = listenerRegistration; + listenerRegistration = null; + deliverNow = !(chunkedTransport && emissionActive); + } + + if (registration != null) { + registration.remove(); + } + + 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( + () -> { + 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 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) { - if (listenerRegistration != null) { - listenerRegistration.remove(); + ListenerRegistration registration; + List turnsToRelease; + synchronized (this) { + listenerGeneration++; + turnsToRelease = drainHeldTurnsLocked(); + emissionActive = false; + aborted = false; + pendingError = null; + eventSink = null; + registration = listenerRegistration; listenerRegistration = null; } + if (registration != null) { + registration.remove(); + } + runAll(turnsToRelease); + } + + private static Executor mainThreadExecutor() { + Handler mainHandler = new Handler(Looper.getMainLooper()); + 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 { + 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; + final Runnable releaseTurn; + + SnapshotEmission(long id, QuerySnapshot snapshot, Runnable releaseTurn) { + this.id = id; + this.releaseTurn = releaseTurn; + 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/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 new file mode 100644 index 000000000000..d4fe7a311476 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotChunkProtocolTest.java @@ -0,0 +1,244 @@ +/* + * 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 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<>(); + 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); + + int realEnvelopeBytes = METHOD_CODEC.encodeSuccessEnvelope(message).position(); + assertEquals(realEnvelopeBytes, QuerySnapshotChunkProtocol.encodedEnvelopeSize(message)); + assertTrue(realEnvelopeBytes <= 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..afff1293eee8 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/android/src/test/java/io/flutter/plugins/firebase/firestore/streamhandler/QuerySnapshotsStreamHandlerTest.java @@ -0,0 +1,698 @@ +/* + * 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.ArgumentMatchers.any; +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.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 emitsOneLogicalSnapshotAsBoundedProtocolMessagesWhenOptedIn() { + 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(CHUNKED_ARGS, sink); + + listenerRef.get().onEvent(snapshot, null); + + 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 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 = + new QuerySnapshotsStreamHandler( + query, + false, + DocumentSnapshot.ServerTimestampBehavior.NONE, + ListenSource.DEFAULT, + executor, + executor); + RecordingEventSink sink = new RecordingEventSink(); + + handler.onListen(CHUNKED_ARGS, sink); + listenerRef.get().onEvent(snapshot, null); + listenerRef.get().onEvent(snapshot, null); + 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() { + 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 sink = new RecordingEventSink(); + + handler.onListen(CHUNKED_ARGS, sink); + listenerRef.get().onEvent(emptySnapshot(), null); + handler.onCancel(null); + executor.runAll(); + + assertTrue(sink.events.isEmpty()); + } + + @Test + 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( + 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); + 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); + 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 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 39843ebab95f..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 @@ -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 @@ -202,15 +203,37 @@ class MethodChannelQuery extends QueryPlatform { listenSource, ); + final assembler = QuerySnapshotChunkAssembler(); yield* MethodChannelFirebaseFirestore.querySnapshotChannel(observerId) - .receiveGuardedBroadcastStream(onError: convertPlatformException) - .map((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; - return MethodChannelQuerySnapshot(firestore, result); - }); + .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)); + } + } catch (error, stackTrace) { + assembler.reset(); + sink.addError(error, stackTrace); + 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 new file mode 100644 index 000000000000..d1c8d7353a59 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/query_snapshot_chunk_assembler.dart @@ -0,0 +1,269 @@ +// 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/src/pigeon/messages.pigeon.dart'; +import 'package:meta/meta.dart'; + +// Kept in sync with QuerySnapshotChunkProtocol.java. +const String _listenChunkedArgKey = 'firestoreQuerySnapshotChunked'; +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; + +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 { + _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 unchunked query snapshot while snapshot ' + '${_active!.snapshotId} was incomplete.', + ); + } + return event; + } + + if (event is! Map || event[_chunkMarkerKey] != true) { + throw StateError('Unexpected query snapshot event: ${event.runtimeType}'); + } + + final snapshotId = _requireInt(event, _snapshotIdKey); + final kind = _requireInt(event, _kindKey); + + switch (kind) { + case _startKind: + 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: + 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: + 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: + 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'); + } + } + + _PendingQuerySnapshot _requireActiveSnapshot( + int snapshotId, + String frameName, + ) { + final active = _active; + if (active == null) { + throw StateError( + 'Received query snapshot $snapshotId $frameName before its start.', + ); + } + if (active.snapshotId != snapshotId) { + throw StateError( + 'Received query snapshot $snapshotId $frameName while snapshot ' + '${active.snapshotId} was active.', + ); + } + return active; + } + + 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; + } + + static int _requireNonNegativeInt(Map map, String key) { + final value = _requireInt(map, key); + if (value < 0) { + throw StateError( + 'Query snapshot chunk field "$key" must be non-negative.', + ); + } + return value; + } + + 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.'); + } + 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 result; + } +} + +class _PendingQuerySnapshot { + _PendingQuerySnapshot({ + required this.snapshotId, + required this.metadata, + required this.expectedDocumentCount, + required this.expectedDocumentChangeCount, + }); + + final int snapshotId; + final InternalSnapshotMetadata metadata; + final int expectedDocumentCount; + final int expectedDocumentChangeCount; + final List documents = []; + final List documentChanges = + []; +} 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 18a9d12bbd4b..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 @@ -6,6 +6,7 @@ import 'dart:async'; import 'package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart'; import 'package:cloud_firestore_platform_interface/src/method_channel/method_channel_firestore.dart'; +import 'package:cloud_firestore_platform_interface/src/method_channel/query_snapshot_chunk_assembler.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_core_platform_interface/test.dart'; import 'package:flutter/services.dart'; @@ -368,4 +369,236 @@ void main() { 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 eventChannelCalls; + + setUp(() { + firestore = MethodChannelFirebaseFirestore( + app: app, + databaseId: '(default)', + ); + eventChannelCalls = []; + messenger.setMockMessageHandler(queryChannel, (ByteData? message) async { + eventChannelCalls.add(codec.decodeMethodCall(message)); + return codec.encodeSuccessEnvelope(null); + }); + }); + + tearDown(() { + messenger.setMockMessageHandler(queryChannel, null); + }); + + Future pushEvent(Object? event) { + return messenger.handlePlatformMessage( + queryChannel, + codec.encodeSuccessEnvelope(event), + (_) {}, + ); + } + + 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); + + await pushEvent( + querySnapshotChunkDocumentChangesMessage( + snapshotId: 1, + items: [changeB], + ), + ); + 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', + ]); + + 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('assets') + .snapshots(listenSource: ListenSource.defaultSource) + .listen(received.add, onError: errors.add); + + hostApi.snapshotObserverId.complete(observerId); + await pumpEventQueue(); + + 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)); + expect(received, hasLength(1)); + expect(received.single.docs, isEmpty); + + await subscription.cancel(); + }); + + test( + 'cancels the native stream on protocol corruption without flooding errors ' + 'for trailing chunks', + () async { + 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(); + + 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 pushEvent( + querySnapshotChunkDocumentChangesMessage( + snapshotId: 1, + items: [ + InternalDocumentChange( + type: DocumentChangeType.added, + document: docA, + oldIndex: -1, + newIndex: 0, + ), + ], + ), + ); + await pushEvent(querySnapshotChunkEndMessage(snapshotId: 1)); + await pumpEventQueue(); + + expect(received, isEmpty); + expect(errors, hasLength(1)); + expect(errors.single, isA()); + expect(eventChannelCalls.map((call) => call.method), [ + 'listen', + 'cancel', + ]); + + 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); + }); + }); +}