Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions .github/workflows/android_unit_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
6 changes: 6 additions & 0 deletions packages/cloud_firestore/cloud_firestore/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ android {
disable 'InvalidPackage'
}

testOptions {
unitTests.returnDefaultValues = true
}

dependencies {
api firebaseCoreProject
implementation platform("com.google.firebase:firebase-bom:${getRootProjectExtOrCoreProperty("FirebaseSDKVersion", firebaseCoreProject)}")
Expand All @@ -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'
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -95,7 +95,8 @@ public class FlutterFirebaseFirestorePlugin
private final Map<String, EventChannel> eventChannels = new HashMap<>();
private final Map<String, StreamHandler> streamHandlers = new HashMap<>();
private final Map<String, OnTransactionResultListener> transactionHandlers = new HashMap<>();
private final Map<String, ExecutorService> snapshotDeliveryExecutors = new ConcurrentHashMap<>();
private final Map<String, SnapshotDeliveryExecutor> snapshotDeliveryExecutors =
new ConcurrentHashMap<>();

// Used in the decoder to know which ServerTimestampBehavior to use
public static final Map<Integer, DocumentSnapshot.ServerTimestampBehavior>
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
Comment on lines +44 to +49

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To prevent potential integer overflow when checking array bounds in write(byte[] b, int off, int len), it is safer to use subtraction instead of addition. For example, off + len > b.length can overflow if off and len are large, whereas len > b.length - off is safe from overflow.

Suggested change
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 void write(byte[] b, int off, int len) {
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
totalBytes += len;
}


@Override
public int size() {
return totalBytes;
}
}
}
Original file line number Diff line number Diff line change
@@ -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<String, Object> start(
long snapshotId,
int documentCount,
int documentChangeCount,
GeneratedAndroidFirebaseFirestore.InternalSnapshotMetadata metadata) {
Map<String, Object> 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<String, Object> itemChunk(long snapshotId, int kind, List<?> items) {
Map<String, Object> message = base(snapshotId, kind);
message.put(PAYLOAD_KEY, items);
return message;
}

static Map<String, Object> 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<String, Object> base(long snapshotId, int kind) {
Map<String, Object> message = new LinkedHashMap<>();
message.put(CHUNK_MARKER_KEY, true);
message.put(SNAPSHOT_ID_KEY, snapshotId);
message.put(KIND_KEY, kind);
return message;
}
}
Original file line number Diff line number Diff line change
@@ -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<S, T> {
private final Iterator<S> source;
private final Function<S, T> converter;
private final ToIntFunction<T> itemSize;
private final int targetBytes;
private final ArrayDeque<T> pending = new ArrayDeque<>();

QuerySnapshotChunker(
Iterator<S> source, Function<S, T> converter, ToIntFunction<T> 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<T> nextChunk(ToIntFunction<List<T>> exactEnvelopeSize) {
if (!hasNext()) {
throw new NoSuchElementException("No snapshot items remain");
}

ArrayList<T> 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;
}
}
Loading
Loading