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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,4 @@ kfurue <pulpits.37-shims@icloud.com>
Max Wojczuk <developer@mwojczuk.xyz>
Julian Pscheid <julian@pscheid.com>
Artem Shevchenko <art.shevchen@gmail.com>
Ronald Dumeloo <47387042+KafuiDumeloo@users.noreply.github.com>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.FirebaseApp;
import com.google.firebase.concurrent.FirebaseExecutors;
import com.google.firebase.firestore.AggregateField;
import com.google.firebase.firestore.AggregateQuery;
import com.google.firebase.firestore.AggregateQuerySnapshot;
Expand Down Expand Up @@ -1019,7 +1020,9 @@ public void querySnapshot(
PigeonParser.parsePigeonServerTimestampBehavior(
options.getServerTimestampBehavior()),
PigeonParser.parseListenSource(source),
cachedThreadPool)));
// One queue per listener: on the shared pool, two snapshots of one query
// could convert at the same time and reach Dart out of order.
FirebaseExecutors.newSequentialExecutor(cachedThreadPool))));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:collection/collection.dart' show IterableExtension;
Expand All @@ -11,6 +12,37 @@ import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;

/// Sets the document at the given URL to 1, 2, 3 and so on up to the given
/// count, each write awaited before the next. Run with [compute], so that
/// handling the listener's snapshots on the main isolate doesn't slow the
/// writes down.
Future<void> _sendCounterUpdates((Uri, int) arguments) async {
final (Uri url, int updateCount) = arguments;
final client = http.Client();
try {
for (int value = 1; value <= updateCount; value++) {
final response = await client.patch(
url,
headers: const {
'Authorization': 'Bearer owner',
'Content-Type': 'application/json',
},
body: jsonEncode({
'fields': {
'value': {'integerValue': '$value'},
},
}),
);
if (response.statusCode != 200) {
throw StateError('Update $value failed: ${response.statusCode}');
}
}
} finally {
client.close();
}
}
Comment on lines +21 to +45

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.

low

To adhere to the repository style guide, functions should be kept under 20 lines and avoid unnecessary verbosity. We can simplify this helper function by using type inference and more compact map literals, which reduces the line count to 17 lines while maintaining readability.

Future<void> _sendCounterUpdates((Uri, int) arguments) async {
  final (Uri url, int updateCount) = arguments;
  final client = http.Client();
  try {
    for (int value = 1; value <= updateCount; value++) {
      final response = await client.patch(
        url,
        headers: const {
          'Authorization': 'Bearer owner',
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'fields': {
            'value': {'integerValue': '$value'},
          },
        }),
      );
      if (response.statusCode != 200) {
        throw StateError('Update $value failed: ${response.statusCode}');
      }
    }
  } finally {
    client.close();
  }
}
References
  1. Functions <20 lines. Avoid verbosity. (link)


void runQueryTests() {
group('$Query', () {
Expand Down Expand Up @@ -516,6 +548,89 @@ void runQueryTests() {
skip: kIsWeb || defaultTargetPlatform == TargetPlatform.windows,
);

test(
'delivers snapshots of server updates in order',
() async {
final String path = (await initializeTest(
'snapshot-delivery-order',
)).path;
// Its own instance, because saving every snapshot to the persistent
// cache the rest of the suite uses spaces them too far apart to overlap.
final FirebaseApp app = await Firebase.initializeApp(
name: 'snapshot-delivery-order',
options: firestore.app.options,
);
final FirebaseFirestore instance =
FirebaseFirestore.instanceFor(app: app)
..settings = const Settings(persistenceEnabled: false)
..useFirestoreEmulator('localhost', 8080);
addTearDown(() async {
await instance.terminate();
await app.delete();
});
final CollectionReference<Map<String, dynamic>> collection = instance
.collection(path);
final DocumentReference<Map<String, dynamic>> counter = collection
.doc('counter');
const int updateCount = 300;
final String payload = 'x' * 400;

final WriteBatch batch = instance.batch();
for (int index = 0; index < 20; index++) {
batch.set(collection.doc('doc-$index'), <String, Object?>{
'index': index,
'payload': payload,
});
}
batch.set(counter, <String, Object?>{'value': 0});
await batch.commit();

final Completer<void> initialSnapshot = Completer<void>();
final Completer<void> lastUpdate = Completer<void>();
final List<String> outOfOrder = <String>[];
int newest = -1;
final StreamSubscription<QuerySnapshot<Map<String, dynamic>>>
subscription = collection.snapshots().listen((snapshot) {
final int value = snapshot.docs
.firstWhere((doc) => doc.id == 'counter')
.get('value');
if (value < newest) {
outOfOrder.add('$value after $newest');
}
newest = max(newest, value);
if (!initialSnapshot.isCompleted) {
initialSnapshot.complete();
}
if (value == updateCount && !lastUpdate.isCompleted) {
lastUpdate.complete();
}
});
addTearDown(subscription.cancel);
await initialSnapshot.future.timeout(const Duration(seconds: 30));

// Each write is awaited, so the value only ever goes up. REST writes
// reach the listener over the watch stream in quick succession, which
// is when consecutive snapshots of one query can overlap.
await compute(_sendCounterUpdates, (
Uri.parse(
'http://10.0.2.2:8080/v1/projects/'
'${firestore.app.options.projectId}/databases/(default)/documents/'
'${counter.path}',
),
updateCount,
));

await lastUpdate.future.timeout(const Duration(minutes: 4));
// An older snapshot can still arrive after the newest one, which is
// what would leave a listener showing stale data.
await Future<void>.delayed(const Duration(seconds: 2));
expect(outOfOrder, isEmpty);
},
timeout: const Timeout.factor(10),
// The URL uses the Android emulator's address for the host machine.
skip: kIsWeb || defaultTargetPlatform != TargetPlatform.android,
);

test('listeners throws a [FirebaseException] with Query', () async {
CollectionReference<Map<String, dynamic>> collection = firestore
.collection('not-allowed');
Expand Down
Loading