Skip to content

Unified emulator settings for Database #1672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 19, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
31 changes: 31 additions & 0 deletions firebase-common/api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
package com.google.firebase {

public class FirebaseApp {
method public void enableEmulators(@NonNull com.google.firebase.emulators.EmulatorSettings);
method @NonNull public android.content.Context getApplicationContext();
method @NonNull public static java.util.List<com.google.firebase.FirebaseApp> getApps(@NonNull android.content.Context);
method @Nullable public com.google.firebase.emulators.EmulatorSettings getEmulatorSettings();
method @NonNull public static com.google.firebase.FirebaseApp getInstance();
method @NonNull public static com.google.firebase.FirebaseApp getInstance(@NonNull String);
method @NonNull public String getName();
Expand Down Expand Up @@ -47,6 +49,35 @@ package com.google.firebase {

}

package com.google.firebase.emulators {

public class EmulatedServiceSettings {
field public final String host;
field public final int port;
}

public static final class EmulatedServiceSettings.Builder {
ctor public EmulatedServiceSettings.Builder(@NonNull String, int);
method @NonNull public com.google.firebase.emulators.EmulatedServiceSettings build();
}

public class EmulatorSettings {
}

public static final class EmulatorSettings.Builder {
ctor public EmulatorSettings.Builder();
method @NonNull public com.google.firebase.emulators.EmulatorSettings.Builder addEmulatedService(@NonNull com.google.firebase.emulators.FirebaseEmulators, @NonNull com.google.firebase.emulators.EmulatedServiceSettings);
method @NonNull public com.google.firebase.emulators.EmulatorSettings build();
}

public enum FirebaseEmulators {
enum_constant public static final com.google.firebase.emulators.FirebaseEmulators DATABASE;
enum_constant public static final com.google.firebase.emulators.FirebaseEmulators FIRESTORE;
enum_constant public static final com.google.firebase.emulators.FirebaseEmulators FUNCTIONS;
}

}

package com.google.firebase.provider {

public class FirebaseInitProvider extends android.content.ContentProvider {
Expand Down
2 changes: 1 addition & 1 deletion firebase-common/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
version=19.3.1
version=19.4.0
latestReleasedVersion=19.3.0
android.enableUnitTestBinaryResources=true
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,18 @@

package com.google.firebase;

import static com.google.android.gms.common.util.Base64Utils.decodeUrlSafeNoPadding;
import static com.google.common.truth.Truth.assertThat;
import static com.google.firebase.common.testutil.Assert.assertThrows;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.UserManager;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;

import com.google.android.gms.common.api.internal.BackgroundDetector;
import com.google.common.base.Defaults;
import com.google.firebase.auth.FirebaseAuth;
Expand All @@ -45,8 +34,18 @@
import com.google.firebase.components.TestComponentOne;
import com.google.firebase.components.TestComponentTwo;
import com.google.firebase.components.TestUserAgentDependentComponent;
import com.google.firebase.emulators.EmulatedServiceSettings;
import com.google.firebase.emulators.EmulatorSettings;
import com.google.firebase.emulators.FirebaseEmulators;
import com.google.firebase.platforminfo.UserAgentPublisher;
import com.google.firebase.testing.FirebaseAppRule;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.stubbing.Answer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
Expand All @@ -56,11 +55,19 @@
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.stubbing.Answer;

import static com.google.android.gms.common.util.Base64Utils.decodeUrlSafeNoPadding;
import static com.google.common.truth.Truth.assertThat;
import static com.google.firebase.common.testutil.Assert.assertThrows;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/** Unit tests for {@link com.google.firebase.FirebaseApp}. */
// TODO(arondeak): uncomment lines when Firebase API targets are in integ.
Expand Down Expand Up @@ -417,6 +424,43 @@ public void testDirectBoot_shouldPreserveDataCollectionAfterUnlock() {
assertTrue(firebaseApp.isDataCollectionDefaultEnabled());
}

@Test
public void testEnableEmulators_shouldAllowDoubleSetBeforeAccess() {
Context mockContext = createForwardingMockContext();
FirebaseApp firebaseApp = FirebaseApp.initializeApp(mockContext);

EmulatedServiceSettings databaseSettings =
new EmulatedServiceSettings.Builder("10.0.2.2", 9000).build();
EmulatorSettings emulatorSettings =
new EmulatorSettings.Builder()
.addEmulatedService(FirebaseEmulators.DATABASE, databaseSettings)
.build();

// Set twice
firebaseApp.enableEmulators(emulatorSettings);
firebaseApp.enableEmulators(emulatorSettings);
}

@Test
public void testEnableEmulators_shouldThrowIfSetAfterAccess() {
Context mockContext = createForwardingMockContext();
FirebaseApp firebaseApp = FirebaseApp.initializeApp(mockContext);

EmulatedServiceSettings databaseSettings =
new EmulatedServiceSettings.Builder("10.0.2.2", 9000).build();
EmulatorSettings emulatorSettings =
new EmulatorSettings.Builder()
.addEmulatedService(FirebaseEmulators.DATABASE, databaseSettings)
.build();
firebaseApp.enableEmulators(emulatorSettings);

// Access (as if from the Database SDK)
firebaseApp.getEmulatorSettings().getServiceSettings(FirebaseEmulators.DATABASE);

// Try to set again
assertThrows(IllegalStateException.class, () -> firebaseApp.enableEmulators(emulatorSettings));
}

/** Returns mock context that forwards calls to targetContext and localBroadcastManager. */
private Context createForwardingMockContext() {
final UserManager spyUserManager = spy(targetContext.getSystemService(UserManager.class));
Expand Down
35 changes: 33 additions & 2 deletions firebase-common/src/main/java/com/google/firebase/FirebaseApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

package com.google.firebase;

import static com.google.android.gms.common.util.Base64Utils.encodeUrlSafeNoPadding;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.BroadcastReceiver;
Expand All @@ -27,11 +25,13 @@
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.collection.ArrayMap;
import androidx.core.os.UserManagerCompat;

import com.google.android.gms.common.annotation.KeepForSdk;
import com.google.android.gms.common.api.internal.BackgroundDetector;
import com.google.android.gms.common.internal.Objects;
Expand All @@ -44,12 +44,14 @@
import com.google.firebase.components.ComponentRegistrar;
import com.google.firebase.components.ComponentRuntime;
import com.google.firebase.components.Lazy;
import com.google.firebase.emulators.EmulatorSettings;
import com.google.firebase.events.Publisher;
import com.google.firebase.heartbeatinfo.DefaultHeartBeatInfo;
import com.google.firebase.internal.DataCollectionConfigStorage;
import com.google.firebase.platforminfo.DefaultUserAgentPublisher;
import com.google.firebase.platforminfo.KotlinDetector;
import com.google.firebase.platforminfo.LibraryVersionComponent;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -59,8 +61,11 @@
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import javax.annotation.concurrent.GuardedBy;

import static com.google.android.gms.common.util.Base64Utils.encodeUrlSafeNoPadding;

/**
* The entry point of Firebase SDKs. It holds common configuration and state for Firebase APIs. Most
* applications don't need to directly interact with FirebaseApp.
Expand Down Expand Up @@ -109,6 +114,7 @@ public class FirebaseApp {
private final String name;
private final FirebaseOptions options;
private final ComponentRuntime componentRuntime;
private EmulatorSettings emulatorSettings;

// Default disabled. We released Firebase publicly without this feature, so making it default
// enabled is a backwards incompatible change.
Expand Down Expand Up @@ -142,6 +148,13 @@ public FirebaseOptions getOptions() {
return options;
}

/** Returns the specified {@link EmulatorSettings}. */
@Nullable
public EmulatorSettings getEmulatorSettings() {
checkNotDeleted();
return emulatorSettings;
}

@Override
public boolean equals(Object o) {
if (!(o instanceof FirebaseApp)) {
Expand Down Expand Up @@ -305,6 +318,24 @@ public static FirebaseApp initializeApp(
return firebaseApp;
}

/**
* Specify which services should access local emulators for this FirebaseApp instance.
*
* <p>For example, if the {@link EmulatorSettings} contain {@link
* com.google.firebase.emulators.EmulatedServiceSettings} for {@link
* com.google.firebase.emulators.FirebaseEmulators#FIRESTORE}, then calls to Cloud Firestore will
* communicate with the emulator rather than production.
*
* @param emulatorSettings the emulator settings for all services.
*/
public void enableEmulators(@NonNull EmulatorSettings emulatorSettings) {
checkNotDeleted();
Preconditions.checkState(
Copy link
Member

Choose a reason for hiding this comment

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

How will this interact with firestore's terminate()? afaicr one can terminate one instance of firestore at which point the call to FirebaseFirestore#getInstance() will create a new firestore instance, should we allow the following sequence of calls?

firestore.terminate();
app.updateFirestoresEmulator();
Firebase.firestore.use();

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for calling this out, I resolved all the other comments since they were straightforward but I will have to look into this one more deeply.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok actually I do not want to allow that sequence of calls. One of the main reasons for this is to make sure that app developers can reason about their emulation settings at a single point before any Firebase service has done any communication.

If you call terminate() the settings should still apply. If you want to nuke them you'll need to call FirebaseApp#delete() and then make a new app.

WDYT?

Copy link
Member

Choose a reason for hiding this comment

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

That's a good point and sgtm. You may want to confirm this behavior with firestore folks though

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Will do during the Firestore PR.

!(this.emulatorSettings != null && this.emulatorSettings.isAccessed()),
"Cannot enable emulators after Firebase SDKs have already been used.");
this.emulatorSettings = emulatorSettings;
}

/**
* Deletes the {@link FirebaseApp} and all its data. All calls to this {@link FirebaseApp}
* instance will throw once it has been called.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.emulators;

import androidx.annotation.NonNull;

/**
* Settings to connect a single Firebase service to a local emulator.
*
* @see EmulatorSettings
*/
public class EmulatedServiceSettings {

public static final class Builder {

private final String host;
private final int port;

/**
* Create a new EmulatedServiceSettings builder.
*
* @param host the host where the local emulator is running. If you want to access 'localhost'
* from an Android Emulator use '10.0.2.2' instead.
* @param port the port where the local emulator is running.
*/
public Builder(@NonNull String host, int port) {
this.host = host;
this.port = port;
}

@NonNull
public EmulatedServiceSettings build() {
return new EmulatedServiceSettings(this.host, this.port);
}
}

public final String host;
public final int port;

private EmulatedServiceSettings(@NonNull String host, int port) {
this.host = host;
this.port = port;
}
}
Loading