Skip to content

Commit

Permalink
Merge 03c70b9 into 6d0f288
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-andersen authored Jun 6, 2024
2 parents 6d0f288 + 03c70b9 commit d5cde9c
Show file tree
Hide file tree
Showing 33 changed files with 970 additions and 513 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package com.google.firebase.firestore;

import android.content.Context;
import androidx.core.util.Supplier;
import com.google.firebase.FirebaseApp;
import com.google.firebase.firestore.auth.CredentialsProvider;
import com.google.firebase.firestore.auth.User;
Expand All @@ -29,18 +30,16 @@ public static FirebaseFirestore newFirebaseFirestore(
Context context,
DatabaseId databaseId,
String persistenceKey,
CredentialsProvider<User> authProvider,
CredentialsProvider<String> appCheckProvider,
AsyncQueue asyncQueue,
Supplier<CredentialsProvider<User>> authProviderFactory,
Supplier<CredentialsProvider<String>> appCheckTokenProviderFactory,
FirebaseApp firebaseApp,
FirebaseFirestore.InstanceRegistry instanceRegistry) {
return new FirebaseFirestore(
context,
databaseId,
persistenceKey,
authProvider,
appCheckProvider,
asyncQueue,
authProviderFactory,
appCheckTokenProviderFactory,
firebaseApp,
instanceRegistry,
null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.firebase.firestore.Query.Direction;
import com.google.firebase.firestore.core.FirestoreClient;
import com.google.firebase.firestore.testutil.CompositeIndexTestHelper;
import com.google.firebase.firestore.testutil.IntegrationTestUtil;
import java.util.Map;
Expand Down Expand Up @@ -742,7 +743,7 @@ public void testMultipleInequalityReadFromCacheWhenOffline() {
assertEquals(2L, snapshot1.size());
assertFalse(snapshot1.getMetadata().isFromCache());

waitFor(collection.firestore.getClient().disableNetwork());
waitFor(collection.firestore.callClient(FirestoreClient::disableNetwork));

QuerySnapshot snapshot2 = waitFor(query.get());
assertEquals(2L, snapshot2.size());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.google.firebase.firestore;

import org.junit.runner.RunWith;

import androidx.test.ext.junit.runners.AndroidJUnit4;

@RunWith(AndroidJUnit4.class)
public class FirestoreClientProviderTest {

//TODO(requires backend/emulator support)

}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
import com.google.firebase.firestore.FirebaseFirestoreException.Code;
import com.google.firebase.firestore.Query.Direction;
import com.google.firebase.firestore.auth.User;
import com.google.firebase.firestore.core.FirestoreClient;
import com.google.firebase.firestore.model.DatabaseId;
import com.google.firebase.firestore.testutil.EventAccumulator;
import com.google.firebase.firestore.testutil.IntegrationTestUtil;
Expand Down Expand Up @@ -1132,7 +1133,7 @@ public void testAppDeleteLeadsToFirestoreTerminate() {

app.delete();

assertTrue(instance.getClient().isTerminated());
assertTrue(instance.callClient(FirestoreClient::isTerminated));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -536,12 +536,12 @@ public void testQueriesFireFromCacheWhenOffline() {
assertFalse(querySnapshot.getMetadata().isFromCache());

// offline event with fromCache=true
waitFor(collection.firestore.getClient().disableNetwork());
waitFor(collection.firestore.disableNetwork());
querySnapshot = accum.await();
assertTrue(querySnapshot.getMetadata().isFromCache());

// back online event with fromCache=false
waitFor(collection.firestore.getClient().enableNetwork());
waitFor(collection.firestore.enableNetwork());
querySnapshot = accum.await();
assertFalse(querySnapshot.getMetadata().isFromCache());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ public void testServerTimestampsCanReturnPreviousValueOfDifferentType() {
@Test
public void testServerTimestampsCanRetainPreviousValueThroughConsecutiveUpdates() {
writeInitialData();
waitFor(docRef.getFirestore().getClient().disableNetwork());
waitFor(docRef.getFirestore().disableNetwork());
accumulator.awaitRemoteEvent();

docRef.update("a", FieldValue.serverTimestamp());
Expand All @@ -226,7 +226,7 @@ public void testServerTimestampsCanRetainPreviousValueThroughConsecutiveUpdates(
localSnapshot = accumulator.awaitLocalEvent();
assertEquals(42L, localSnapshot.get("a", ServerTimestampBehavior.PREVIOUS));

waitFor(docRef.getFirestore().getClient().enableNetwork());
waitFor(docRef.getFirestore().enableNetwork());

DocumentSnapshot remoteSnapshot = accumulator.awaitRemoteEvent();
assertThat(remoteSnapshot.get("a")).isInstanceOf(Timestamp.class);
Expand All @@ -235,7 +235,7 @@ public void testServerTimestampsCanRetainPreviousValueThroughConsecutiveUpdates(
@Test
public void testServerTimestampsUsesPreviousValueFromLocalMutation() {
writeInitialData();
waitFor(docRef.getFirestore().getClient().disableNetwork());
waitFor(docRef.getFirestore().disableNetwork());
accumulator.awaitRemoteEvent();

docRef.update("a", FieldValue.serverTimestamp());
Expand All @@ -249,7 +249,7 @@ public void testServerTimestampsUsesPreviousValueFromLocalMutation() {
localSnapshot = accumulator.awaitLocalEvent();
assertEquals(1337L, localSnapshot.get("a", ServerTimestampBehavior.PREVIOUS));

waitFor(docRef.getFirestore().getClient().enableNetwork());
waitFor(docRef.getFirestore().enableNetwork());

DocumentSnapshot remoteSnapshot = accumulator.awaitRemoteEvent();
assertThat(remoteSnapshot.get("a")).isInstanceOf(Timestamp.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.firestore.Transaction.Function;
import com.google.firebase.firestore.core.FirestoreClient;
import com.google.firebase.firestore.testutil.IntegrationTestUtil;
import com.google.firebase.firestore.util.Consumer;
import java.util.Arrays;
Expand Down Expand Up @@ -453,7 +454,7 @@ public void queriesCannotBeSortedByAnUncommittedServerTimestamp() {
CollectionReference collection = testCollection();

// Ensure the server timestamp stays uncommitted for the first half of the test
waitFor(collection.firestore.getClient().disableNetwork());
waitFor(collection.firestore.callClient(FirestoreClient::disableNetwork));

TaskCompletionSource<Void> offlineCallbackDone = new TaskCompletionSource<>();
TaskCompletionSource<Void> onlineCallbackDone = new TaskCompletionSource<>();
Expand Down Expand Up @@ -497,7 +498,7 @@ public void queriesCannotBeSortedByAnUncommittedServerTimestamp() {
document.set(map("timestamp", FieldValue.serverTimestamp()));
waitFor(offlineCallbackDone.getTask());

waitFor(collection.firestore.getClient().enableNetwork());
waitFor(collection.firestore.enableNetwork());
waitFor(onlineCallbackDone.getTask());

listenerRegistration.remove();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,19 @@
import com.google.firebase.firestore.testutil.IntegrationTestUtil;
import com.google.firebase.firestore.util.AsyncQueue;
import com.google.firebase.firestore.util.AsyncQueue.TimerId;
import com.google.firestore.v1.InitResponse;
import com.google.protobuf.ByteString;

import io.grpc.Status;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;

class MockCredentialsProvider extends EmptyCredentialsProvider {
Expand All @@ -67,6 +74,10 @@ public List<String> observedStates() {

@RunWith(AndroidJUnit4.class)
public class StreamTest {

@Rule
public Timeout timeout = new Timeout(10, TimeUnit.SECONDS);

/** Single mutation to send to the write stream. */
private static final List<Mutation> mutations =
Collections.singletonList(setMutation("foo/bar", map()));
Expand Down Expand Up @@ -95,7 +106,7 @@ public void onClose(Status status) {
}

@Override
public void onHandshakeComplete() {
public void onHandshake(InitResponse initResponse) {
handshakeSemaphore.release();
}

Expand Down Expand Up @@ -127,7 +138,7 @@ private void waitForWriteStreamOpen(
AsyncQueue testQueue, WriteStream writeStream, StreamStatusCallback callback) {
testQueue.enqueueAndForget(writeStream::start);
waitFor(callback.openSemaphore);
testQueue.enqueueAndForget(writeStream::writeHandshake);
testQueue.enqueueAndForget(() -> writeStream.sendHandshake(ByteString.EMPTY));
waitFor(callback.handshakeSemaphore);
}

Expand Down Expand Up @@ -170,9 +181,9 @@ public void testWriteStreamStopAfterHandshake() throws Exception {
StreamStatusCallback streamCallback =
new StreamStatusCallback() {
@Override
public void onHandshakeComplete() {
public void onHandshake(InitResponse initResponse) {
assertThat(writeStreamWrapper[0].getLastStreamToken()).isNotEmpty();
super.onHandshakeComplete();
super.onHandshake(initResponse);
}

@Override
Expand All @@ -192,7 +203,7 @@ public void onWriteResponse(
() -> assertThrows(Throwable.class, () -> writeStream.writeMutations(mutations)));

// Handshake should always be called
testQueue.enqueueAndForget(writeStream::writeHandshake);
testQueue.enqueueAndForget(() -> writeStream.sendHandshake(ByteString.EMPTY));
waitFor(streamCallback.handshakeSemaphore);

// Now writes should succeed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,16 +305,13 @@ public static FirebaseFirestore testFirestore(

ensureStrictMode();

AsyncQueue asyncQueue = new AsyncQueue();

FirebaseFirestore firestore =
AccessHelper.newFirebaseFirestore(
context,
databaseId,
persistenceKey,
MockCredentialsProvider.instance(),
new EmptyAppCheckTokenProvider(),
asyncQueue,
() -> MockCredentialsProvider.instance(),
() -> new EmptyAppCheckTokenProvider(),
/*firebaseApp=*/ null,
/*instanceRegistry=*/ (dbId) -> {});
waitFor(firestore.clearPersistence());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,7 @@ public List<AggregateField> getAggregateFields() {
public Task<AggregateQuerySnapshot> get(@NonNull AggregateSource source) {
Preconditions.checkNotNull(source, "AggregateSource must not be null");
TaskCompletionSource<AggregateQuerySnapshot> tcs = new TaskCompletionSource<>();
query
.firestore
.getClient()
.runAggregateQuery(query.query, aggregateFieldList)
query.firestore.callClient(client -> client.runAggregateQuery(query.query, aggregateFieldList))
.continueWith(
Executors.DIRECT_EXECUTOR,
(task) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,22 @@
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.firestore.FirebaseFirestoreException.Code;
import com.google.firebase.firestore.core.ActivityScope;
import com.google.firebase.firestore.core.AsyncEventListener;
import com.google.firebase.firestore.core.EventManager.ListenOptions;
import com.google.firebase.firestore.core.ListenerRegistrationImpl;
import com.google.firebase.firestore.core.QueryListener;
import com.google.firebase.firestore.core.UserData.ParsedSetData;
import com.google.firebase.firestore.core.UserData.ParsedUpdateData;
import com.google.firebase.firestore.core.ViewSnapshot;
import com.google.firebase.firestore.model.Document;
import com.google.firebase.firestore.model.DocumentKey;
import com.google.firebase.firestore.model.ResourcePath;
import com.google.firebase.firestore.model.mutation.DeleteMutation;
import com.google.firebase.firestore.model.mutation.Mutation;
import com.google.firebase.firestore.model.mutation.Precondition;
import com.google.firebase.firestore.util.Assert;
import com.google.firebase.firestore.util.Executors;
import com.google.firebase.firestore.util.Util;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
Expand Down Expand Up @@ -165,9 +164,8 @@ public Task<Void> set(@NonNull Object data, @NonNull SetOptions options) {
options.isMerge()
? firestore.getUserDataReader().parseMergeData(data, options.getFieldMask())
: firestore.getUserDataReader().parseSetData(data);
return firestore
.getClient()
.write(Collections.singletonList(parsed.toMutation(key, Precondition.NONE)))
List<Mutation> mutations = singletonList(parsed.toMutation(key, Precondition.NONE));
return firestore.callClient(client -> client.write(mutations))
.continueWith(Executors.DIRECT_EXECUTOR, voidErrorTransformer());
}

Expand Down Expand Up @@ -229,9 +227,8 @@ public Task<Void> update(
}

private Task<Void> update(@NonNull ParsedUpdateData parsedData) {
return firestore
.getClient()
.write(Collections.singletonList(parsedData.toMutation(key, Precondition.exists(true))))
List<Mutation> mutations = singletonList(parsedData.toMutation(key, Precondition.exists(true)));
return firestore.callClient(client -> client.write(mutations))
.continueWith(Executors.DIRECT_EXECUTOR, voidErrorTransformer());
}

Expand All @@ -242,9 +239,8 @@ private Task<Void> update(@NonNull ParsedUpdateData parsedData) {
*/
@NonNull
public Task<Void> delete() {
return firestore
.getClient()
.write(singletonList(new DeleteMutation(key, Precondition.NONE)))
List<Mutation> mutations = singletonList(new DeleteMutation(key, Precondition.NONE));
return firestore.callClient(client -> client.write(mutations))
.continueWith(Executors.DIRECT_EXECUTOR, voidErrorTransformer());
}

Expand Down Expand Up @@ -273,9 +269,7 @@ public Task<DocumentSnapshot> get() {
@NonNull
public Task<DocumentSnapshot> get(@NonNull Source source) {
if (source == Source.CACHE) {
return firestore
.getClient()
.getDocumentFromLocalCache(key)
return firestore.callClient(client -> client.getDocumentFromLocalCache(key))
.continueWith(
Executors.DIRECT_EXECUTOR,
(Task<Document> task) -> {
Expand Down Expand Up @@ -531,11 +525,7 @@ private ListenerRegistration addSnapshotListenerInternal(
new AsyncEventListener<>(userExecutor, viewListener);

com.google.firebase.firestore.core.Query query = asQuery();
QueryListener queryListener = firestore.getClient().listen(query, options, asyncListener);

return ActivityScope.bind(
activity,
new ListenerRegistrationImpl(firestore.getClient(), queryListener, asyncListener));
return firestore.callClient(client -> client.listen(query, options, activity, asyncListener));
}

@Override
Expand Down
Loading

0 comments on commit d5cde9c

Please sign in to comment.