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 17 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 @@ -45,6 +45,9 @@
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.FirebaseEmulator;
import com.google.firebase.platforminfo.UserAgentPublisher;
import com.google.firebase.testing.FirebaseAppRule;
import java.lang.reflect.InvocationTargetException;
Expand Down Expand Up @@ -417,6 +420,43 @@ public void testDirectBoot_shouldPreserveDataCollectionAfterUnlock() {
assertTrue(firebaseApp.isDataCollectionDefaultEnabled());
}

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

// A developer would call FirebaseDatabase.EMULATOR but we can't introduce that
// dependency for this test.
FirebaseEmulator emulator = FirebaseEmulator.forName("database");

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

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

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

FirebaseEmulator emulator = FirebaseEmulator.forName("database");

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

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

// 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
38 changes: 38 additions & 0 deletions firebase-common/src/main/java/com/google/firebase/FirebaseApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
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;
Expand Down Expand Up @@ -110,6 +111,9 @@ public class FirebaseApp {
private final FirebaseOptions options;
private final ComponentRuntime componentRuntime;

private final AtomicBoolean emulatorSettingsFrozen = new AtomicBoolean(false);
private EmulatorSettings emulatorSettings = EmulatorSettings.DEFAULT;

// Default disabled. We released Firebase publicly without this feature, so making it default
// enabled is a backwards incompatible change.
private final AtomicBoolean automaticResourceManagementEnabled = new AtomicBoolean(false);
Expand Down Expand Up @@ -142,6 +146,20 @@ public FirebaseOptions getOptions() {
return options;
}

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

@Override
public boolean equals(Object o) {
if (!(o instanceof FirebaseApp)) {
Expand Down Expand Up @@ -305,6 +323,26 @@ 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 FirebaseDatabase#EMULATOR},
* 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
*/
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.emulatorSettingsFrozen.get(),
"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,36 @@
// 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.
*
* <p>TODO(samstern): Un-hide this once Firestore, Database, and Functions are implemented
*
* @see EmulatorSettings
* @hide
*/
public final class EmulatedServiceSettings {

public final String host;
public final int port;

public 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,87 @@
// 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.firebase.components.Preconditions;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
* 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
*/
public final class EmulatorSettings {

/** Empty emulator settings to be used as an internal default */
public static final EmulatorSettings DEFAULT = new EmulatorSettings.Builder().build();

public static final class Builder {

private final Map<FirebaseEmulator, 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 FirebaseEmulator 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(new HashMap<>(settingsMap));
}
}

private final Map<FirebaseEmulator, EmulatedServiceSettings> settingsMap;

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

/**
* Fetch the emulation settings for a single Firebase service.
*
* @hide
*/
@Nullable
public EmulatedServiceSettings getServiceSettings(@NonNull FirebaseEmulator emulator) {
if (settingsMap.containsKey(emulator)) {
return settingsMap.get(emulator);
}

return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// 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;

/**
* Identifier Firebase services that can be emulated using the Firebase Emulator Suite.
*
* <p>TODO(samstern): Un-hide this once Firestore, Database, and Functions are implemented
*
* @see com.google.firebase.FirebaseApp#enableEmulators(EmulatorSettings)
* @see EmulatorSettings
* @see EmulatedServiceSettings
* @hide
*/
public final class FirebaseEmulator {

private final String name;

/**
* Only to be called by SDKs which support emulators in order to make constants.
*
* @hide
*/
@NonNull
public static FirebaseEmulator forName(String name) {
return new FirebaseEmulator(name);
}

private FirebaseEmulator(String name) {
this.name = name;
}

public String getName() {
return name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import com.google.firebase.database.core.persistence.MockPersistenceStorageEngine;
import com.google.firebase.database.core.persistence.PersistenceManager;
import com.google.firebase.database.future.WriteFuture;
import com.google.firebase.emulators.EmulatedServiceSettings;
import com.google.firebase.emulators.EmulatorSettings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -64,6 +66,26 @@ public void getInstanceForApp() {
assertEquals(IntegrationTestValues.getAltNamespace(), db.getReference().toString());
}

@Test
public void getInstanceForAppWithEmulator() {
FirebaseApp app =
appForDatabaseUrl(IntegrationTestValues.getAltNamespace(), "getInstanceForAppWithEmulator");

EmulatedServiceSettings serviceSettings = new EmulatedServiceSettings("10.0.2.2", 9000);
EmulatorSettings emulatorSettings =
new EmulatorSettings.Builder()
.addEmulatedService(FirebaseDatabase.EMULATOR, serviceSettings)
.build();
app.enableEmulators(emulatorSettings);

FirebaseDatabase db = FirebaseDatabase.getInstance(app);
DatabaseReference rootRef = db.getReference();
assertEquals(rootRef.toString(), "http://10.0.2.2:9000");

DatabaseReference urlReference = db.getReferenceFromUrl("https://otherns.firebaseio.com");
assertEquals(urlReference.toString(), "http://10.0.2.2:9000");
}

@Test
public void getInstanceForAppWithUrl() {
FirebaseApp app =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import androidx.annotation.NonNull;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.annotations.Nullable;
import com.google.firebase.database.core.DatabaseConfig;
import com.google.firebase.database.core.Path;
import com.google.firebase.database.core.Repo;
Expand All @@ -28,6 +29,8 @@
import com.google.firebase.database.core.utilities.ParsedUrl;
import com.google.firebase.database.core.utilities.Utilities;
import com.google.firebase.database.core.utilities.Validation;
import com.google.firebase.emulators.EmulatedServiceSettings;
import com.google.firebase.emulators.FirebaseEmulator;

/**
* The entry point for accessing a Firebase Database. You can get an instance by calling {@link
Expand All @@ -36,6 +39,8 @@
*/
public class FirebaseDatabase {

public static final FirebaseEmulator EMULATOR = FirebaseEmulator.forName("database");

private static final String SDK_VERSION = BuildConfig.VERSION_NAME;

private final FirebaseApp app;
Expand Down Expand Up @@ -99,7 +104,7 @@ public static synchronized FirebaseDatabase getInstance(
+ "FirebaseApp or from your getInstance() call.");
}

ParsedUrl parsedUrl = Utilities.parseUrl(url);
ParsedUrl parsedUrl = Utilities.parseUrl(url, getEmulatorServiceSettings(app));
if (!parsedUrl.path.isEmpty()) {
throw new DatabaseException(
"Specified Database URL '"
Expand All @@ -112,6 +117,7 @@ public static synchronized FirebaseDatabase getInstance(
checkNotNull(app, "Provided FirebaseApp must not be null.");
FirebaseDatabaseComponent component = app.get(FirebaseDatabaseComponent.class);
checkNotNull(component, "Firebase Database component is not present.");

return component.get(parsedUrl.repoInfo);
}

Expand Down Expand Up @@ -188,7 +194,7 @@ public DatabaseReference getReferenceFromUrl(@NonNull String url) {
"Can't pass null for argument 'url' in " + "FirebaseDatabase.getReferenceFromUrl()");
}

ParsedUrl parsedUrl = Utilities.parseUrl(url);
ParsedUrl parsedUrl = Utilities.parseUrl(url, getEmulatorServiceSettings(this.app));
if (!parsedUrl.repoInfo.host.equals(this.repo.getRepoInfo().host)) {
throw new DatabaseException(
"Invalid URL ("
Expand Down Expand Up @@ -288,6 +294,11 @@ public synchronized void setPersistenceCacheSizeBytes(long cacheSizeInBytes) {
this.config.setPersistenceCacheSizeBytes(cacheSizeInBytes);
}

@Nullable
private static EmulatedServiceSettings getEmulatorServiceSettings(@NonNull FirebaseApp app) {
return app.getEmulatorSettings().getServiceSettings(EMULATOR);
}

/** @return The semver version for this build of the Firebase Database client */
@NonNull
public static String getSdkVersion() {
Expand Down
Loading