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 3 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
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
46 changes: 44 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,20 @@ public FirebaseOptions getOptions() {
return options;
}

/**
* Returns the specified {@link EmulatorSettings}.
*
* <p>TODO(samstern): Un-hide this once Firestore, Database, and Functions are implemented
*
* @hide
*/
@KeepForSdk
@Nullable
public EmulatorSettings getEmulatorSettings() {
checkNotDeleted();
return emulatorSettings;
}

@Override
public boolean equals(Object o) {
if (!(o instanceof FirebaseApp)) {
Expand Down Expand Up @@ -305,6 +325,28 @@ 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.
*
* <p>TODO(samstern): Un-hide this once Firestore, Database, and Functions are implemented
*
* @param emulatorSettings the emulator settings for all services.
* @hide
*/
@KeepForSdk
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,62 @@
// 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;

import com.google.android.gms.common.annotation.KeepForSdk;

/**
* Settings to connect a single Firebase service to a local emulator.
*
* <p>TODO(samstern): Un-hide this once Firestore, Database, and Functions are implemented
*
* @see EmulatorSettings
* @hide
*/
@KeepForSdk
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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// 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;
import androidx.annotation.Nullable;

import com.google.android.gms.common.annotation.KeepForSdk;
import com.google.firebase.components.Preconditions;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
* Settings that control which Firebase services should access a local emulator, rather than
* production.
*
* <p>TODO(samstern): Un-hide this once Firestore, Database, and Functions are implemented
*
* @see com.google.firebase.FirebaseApp#enableEmulators(EmulatorSettings)
* @hide
*/
@KeepForSdk
public class EmulatorSettings {

public static final class Builder {

private final Map<FirebaseEmulators, EmulatedServiceSettings> settingsMap = new HashMap<>();

/** Constructs an empty builder. */
public Builder() {}

/**
* Specify the emulator settings for a single service.
*
* @param emulator the emulated service.
* @param settings the emulator settings.
* @return the builder, for chaining.
*/
@NonNull
public Builder addEmulatedService(
@NonNull FirebaseEmulators emulator, @NonNull EmulatedServiceSettings settings) {
Preconditions.checkState(
!settingsMap.containsKey(emulator),
"Cannot call addEmulatedService twice for " + emulator.toString());
this.settingsMap.put(emulator, settings);
return this;
}

@NonNull
public EmulatorSettings build() {
return new EmulatorSettings(settingsMap);
}
}

private final AtomicBoolean accessed = new AtomicBoolean(false);
private final Map<FirebaseEmulators, EmulatedServiceSettings> settingsMap;

private EmulatorSettings(@NonNull Map<FirebaseEmulators, EmulatedServiceSettings> settingsMap) {
this.settingsMap = Collections.unmodifiableMap(settingsMap);
}

/**
* Determine if any Firebase SDK has already accessed the emulator settings. When true, attempting
* to change the settings should throw an error.
*
* @hide
*/
public boolean isAccessed() {
return accessed.get();
}

/**
* Fetch the emulation settings for a single Firebase service. Once this method has been called
* {@link #isAccessed()} will return true.
*
* @hide
*/
@Nullable
public EmulatedServiceSettings getServiceSettings(@NonNull FirebaseEmulators emulator) {
accessed.set(true);

if (settingsMap.containsKey(emulator)) {
return settingsMap.get(emulator);
}

return null;
}
}
Loading