Repository navigation
Conversation
…pshot-transport-chunks-upstream # Conflicts: # .github/workflows/android_unit_tests.yaml # tests/pubspec.yaml
…fecycle Resolve Android unit-task and dependency updates without losing new upstream coverage. Scope chunk assembly to each query listener generation; cover cancellation, pending re-listens, complete event delivery, and native stream errors. Co-authored-by: ben-milanko <20643387+ben-milanko@users.noreply.github.com>
…ssions Resolve the two Dart formatting conflicts without changing upstream semantics or the chunk assembly and listener-cancellation coverage. Retain the current SDK floor and upstream changes. Prepared on Ben Milanko's behalf by Alder, his AI assistant, with Codex assistance.
There was a problem hiding this comment.
Code Review
This pull request introduces chunked transport for Firestore query snapshots to prevent exceeding platform channel message size limits when transmitting large datasets. It implements a chunking protocol on the Android side and a reassembly mechanism on the Dart side, backed by comprehensive unit and integration tests. The review feedback suggests refactoring the Dart assembler's add method to comply with style guide rules (keeping functions under 20 lines and avoiding the ! operator), securing array bounds checks in PigeonCodecSizer.java against integer overflow, and caching the main thread executor in QuerySnapshotsStreamHandler.java to reduce garbage collection overhead.
| 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<Object?, Object?> || 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<InternalDocumentSnapshot>( | ||
| 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<InternalDocumentChange>( | ||
| 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'); | ||
| } | ||
| } |
There was a problem hiding this comment.
To adhere to the repository style guide rule regarding function conciseness (functions should be under 20 lines) and to avoid the use of the ! operator by leveraging Dart's flow analysis on local variables, we can refactor the add method. By extracting each switch case into its own private helper method, we keep the code highly modular, readable, and clean.
InternalQuerySnapshot? add(Object? event) {
if (event is InternalQuerySnapshot) {
final active = _active;
if (active != null) {
throw StateError(
'Received unchunked query snapshot while snapshot '
'${active.snapshotId} was incomplete.',
);
}
return event;
}
if (event is! Map<Object?, Object?> || 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:
_handleStart(snapshotId, event);
return null;
case _documentsKind:
_handleDocuments(snapshotId, event);
return null;
case _documentChangesKind:
_handleDocumentChanges(snapshotId, event);
return null;
case _endKind:
return _handleEnd(snapshotId);
default:
throw StateError('Unknown query snapshot chunk kind: $kind');
}
}
void _handleStart(int snapshotId, Map<Object?, Object?> event) {
final active = _active;
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.',
);
}
_active = _PendingQuerySnapshot(
snapshotId: snapshotId,
metadata: metadata,
expectedDocumentCount: _requireNonNegativeInt(event, _documentCountKey),
expectedDocumentChangeCount: _requireNonNegativeInt(
event,
_documentChangeCountKey,
),
);
}
void _handleDocuments(int snapshotId, Map<Object?, Object?> event) {
final active = _requireActiveSnapshot(snapshotId, 'document chunk');
final items = _requireList<InternalDocumentSnapshot>(
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);
}
void _handleDocumentChanges(int snapshotId, Map<Object?, Object?> event) {
final active = _requireActiveSnapshot(
snapshotId,
'document change chunk',
);
final items = _requireList<InternalDocumentChange>(
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);
}
InternalQuerySnapshot _handleEnd(int snapshotId) {
final active = _requireActiveSnapshot(snapshotId, 'end marker');
_active = null;
if (active.documents.length != active.expectedDocumentCount ||
active.documentChanges.length !=
active.expectedDocumentChangeCount) {
throw StateError(
'Query snapshot $snapshotId ended incomplete: expected '
'${active.expectedDocumentCount} documents and '
'${active.expectedDocumentChangeCount} document changes, got '
'${active.documents.length} and ${active.documentChanges.length}.',
);
}
return InternalQuerySnapshot(
documents: active.documents,
documentChanges: active.documentChanges,
metadata: active.metadata,
);
}| 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; | ||
| } |
There was a problem hiding this comment.
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.
| 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; | |
| } |
| Handler mainHandler = new Handler(Looper.getMainLooper()); | ||
| return mainHandler::post; | ||
| } | ||
|
|
There was a problem hiding this comment.
Instead of creating a new Handler and a new lambda instance every time mainThreadExecutor() is called, we can cache a single static final Executor instance. This improves efficiency and reduces garbage collection overhead.
private static final Executor MAIN_THREAD_EXECUTOR = new Executor() {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
handler.post(command);
}
};
private static Executor mainThreadExecutor() {
return MAIN_THREAD_EXECUTOR;
}…ndroid-query-snapshots
…snapshotsInSync ordering
9d9cc20 to
941160f
Compare
Description
Supersedes #18601 (preserving @ben-milanko's original commits in branch history because the source fork
Railway-Engineering-Solutions/flutterfireis organization-owned and rejects maintainer pushes), merged with currentmain(including Gradle 9 / built-in Kotlin and Pigeon 30.0.4) and addressing review feedback.Previously,
QuerySnapshotsStreamHandleron Android converted an entire FirestoreQuerySnapshotinto oneInternalQuerySnapshotand emitted it through a single EventChannel envelope (StandardMethodCodec.encodeSuccessEnvelope). On large query results, holding the converted Pigeon structures and the single encoded buffer in memory at once can exhaust the Android Java heap (OutOfMemoryErrorinStandardMessageCodec.writeValue).This PR incrementally converts and chunks Android query snapshots across bounded EventChannel frames (
start,documents,documentChanges,end) and reassembles them atomically incloud_firestore_platform_interface:512 KiB):QuerySnapshotChunkerpacks documents and document changes up to512 KiBper encodedStandardMethodCodecenvelope. If a single Firestore document (bounded by Firestore's 1 MiB document size limit) exceeds512 KiBon its own, it is emitted as a single-item chunk so delivery cannot stall.PigeonCodecSizercounts exact encoded bytes through aCountingByteArrayOutputStreamagainstPigeonCodec.INSTANCE.writeValueinstead of allocating temporaryByteBuffers per item/chunk.MethodChannelQuerypasses{'firestoreQuerySnapshotChunked': true}as the EventChannellistenargument.QuerySnapshotsStreamHandleronly emits chunked frames when that flag is present, falling back to legacy single-messageInternalQuerySnapshotemission for oldercloud_firestore_platform_interfaceversions (and Dart continues to accept legacy unchunkedInternalQuerySnapshotevents for iOS/macOS/Windows and older Android builds).snapshotsInSyncordering, and error handling:SnapshotDeliveryExecutorwrapping each Firestore instance's single-thread delivery executor so chunked query snapshots non-blockingly hold their FIFO turn acrossstart->documents->documentChanges->endframes, preventingSnapshotsInSyncStreamHandler(and subsequent snapshots) from overtaking an in-flight chunked snapshot while releasing the turn on completion, cancel, re-listen, or error.abortedstate inQuerySnapshotsStreamHandlerso stale queued chunks/registrations cannot leak across cancel/re-listen, native Firestore errors drain already-accepted snapshots before emitting the error, and internal sink/conversion failures suppress subsequent queued successes.MethodChannelQuery), resets the assembler, emits theStateErroronce, and closes the transformed sink so the native listener cancels instead of flooding cascading errors for trailing chunks.:cloud_firestore:testDebugUnitTestfrompackages/cloud_firestore/cloud_firestore/example/androidin.github/workflows/android_unit_tests.yamlwithout addingcloud_firestoretotests/.emitSnapshotForTesting) by drivingQuerySnapshotsStreamHandlerTestthroughonListen/onCancelwithtestOptions { unitTests.returnDefaultValues = true }.QuerySnapshotChunkProtocolTest,QuerySnapshotChunkerTest,QuerySnapshotsStreamHandlerTest,SnapshotDeliveryExecutorTest), Dart unit tests (query_snapshot_chunk_assembler_test.dart,method_channel_firestore_test.dart), and an Android/cross-platform e2e test inquery_e2e.dartexercising >512 KiB snapshot delivery.Related Issues
Supersedes #18601.
Checklist
Before you create this PR confirm that it meets all requirements listed below by checking the relevant checkboxes (
[x]).This will ensure a smooth and quick review process. Updating the
pubspec.yamland changelogs is not required.///).melos run analyze) does not report any problems on my PR.Breaking Change
Does your PR require plugin users to manually update their apps to accommodate your change?