Skip to content

Commit adef187

Browse files
authored
fix(firestore,windows): fix a crash happening when terminating the firestore instance (#18069)
* fix(firestore,windows): fix a crash happening when terminating the firestore instance * fix test * fix cached instance in Dart * fix
1 parent 5bd8a75 commit adef187

2 files changed

Lines changed: 40 additions & 2 deletions

File tree

packages/cloud_firestore/cloud_firestore/example/integration_test/instance_e2e.dart

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,43 @@ void runInstanceTests() {
148148
await firestore.terminate();
149149
await firestore.clearPersistence();
150150
},
151-
skip: kIsWeb || defaultTargetPlatform == TargetPlatform.windows,
151+
skip: kIsWeb,
152+
);
153+
154+
test(
155+
'terminate() then use Firestore again',
156+
() async {
157+
// Regression test for https://github.com/firebase/flutterfire/issues/17781
158+
// On Windows, terminate() did not remove the instance from the native
159+
// cache, so subsequent usage would crash with "The client has already
160+
// been terminated".
161+
final instance = FirebaseFirestore.instanceFor(
162+
app: Firebase.app(),
163+
databaseId: 'flutterfire-2',
164+
);
165+
166+
instance.useFirestoreEmulator('localhost', 8080);
167+
168+
// Use Firestore so it is fully initialized
169+
await instance.collection('flutterfire-2').doc('terminate-test').set(
170+
{'foo': 'bar'},
171+
);
172+
173+
await instance.terminate();
174+
await instance.clearPersistence();
175+
176+
// After terminate + clearPersistence, we should be able to use
177+
// Firestore again without crashing.
178+
await instance
179+
.collection('flutterfire-2')
180+
.doc('terminate-test')
181+
.get();
182+
183+
// Clean up: terminate so the native instance cache is cleared
184+
// for subsequent tests that may use the same databaseId.
185+
await instance.terminate();
186+
},
187+
skip: kIsWeb,
152188
);
153189

154190
test(

packages/cloud_firestore/cloud_firestore/windows/cloud_firestore_plugin.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -706,10 +706,12 @@ void CloudFirestorePlugin::EnableNetwork(
706706
void CloudFirestorePlugin::Terminate(
707707
const FirestorePigeonFirebaseApp& app,
708708
std::function<void(std::optional<FlutterError> reply)> result) {
709+
std::string cacheKey = app.app_name() + "-" + app.database_u_r_l();
709710
Firestore* firestore = GetFirestoreFromPigeon(app);
710711
firestore->Terminate().OnCompletion(
711-
[result](const Future<void>& completed_future) {
712+
[result, cacheKey](const Future<void>& completed_future) {
712713
if (completed_future.error() == firebase::firestore::kErrorOk) {
714+
CloudFirestorePlugin::firestoreInstances_.erase(cacheKey);
713715
result(std::nullopt);
714716
} else {
715717
result(CloudFirestorePlugin::ParseError(completed_future));

0 commit comments

Comments
 (0)