Skip to content

Adding a FidListener that propagates fid changes to the clients. #2195

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 12 commits into from
Dec 1, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -16,6 +16,7 @@

import androidx.annotation.NonNull;
import com.google.android.gms.tasks.Task;
import com.google.firebase.installations.internal.FidListener;

/**
* This is an interface of {@code FirebaseInstallations} that is only exposed to 2p via component
Expand Down Expand Up @@ -51,4 +52,12 @@ public interface FirebaseInstallationsApi {
*/
@NonNull
Task<Void> delete();

/**
* Register a listener to receive fid changes.
*
* @param listener implementation of the {@code FidListener} to handle fid changes.
* @hide
*/
void registerFidListener(FidListener listener);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// 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.installations.internal;

import androidx.annotation.NonNull;

/**
* <aside class="warning"><strong>Provides an inter-operational interface only</strong>; instead,
* use {@link FidListener} to call a listener when a Fid changes.</aside>
*
* @hide
*/
public interface FidListener {
/**
* <aside class="warning">Provides an inter-operational interface only; instead use {@link
* FidListener}.</aside>
*
* <p>This method gets invoked when a Fid changes.
*
* @param fid represents the newly generated installation id.
*/
void onFidChanged(@NonNull String fid);
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.google.firebase.heartbeatinfo.HeartBeatInfo;
import com.google.firebase.inject.Provider;
import com.google.firebase.installations.FirebaseInstallationsException.Status;
import com.google.firebase.installations.internal.FidListener;
import com.google.firebase.installations.local.IidStore;
import com.google.firebase.installations.local.PersistedInstallation;
import com.google.firebase.installations.local.PersistedInstallationEntry;
Expand Down Expand Up @@ -72,6 +73,9 @@ public class FirebaseInstallations implements FirebaseInstallationsApi {
@GuardedBy("this")
private String cachedFid;

@GuardedBy("this")
private FidListener fidListener;

@GuardedBy("lock")
private final List<StateListener> listeners = new ArrayList<>();

Expand Down Expand Up @@ -271,6 +275,14 @@ public Task<Void> delete() {
return Tasks.call(backgroundExecutor, this::deleteFirebaseInstallationId);
}

/** Register a callback {@link FidListener} to receive fid changes. */
@Override
public void registerFidListener(@Nullable FidListener listener) {
synchronized (this) {
this.fidListener = listener;
}
}

private Task<String> addGetIdListener() {
TaskCompletionSource<String> taskCompletionSource = new TaskCompletionSource<>();
StateListener l = new GetIdListener(taskCompletionSource);
Expand Down Expand Up @@ -356,11 +368,12 @@ private void doNetworkCallIfNecessary(boolean forceRefresh) {
// There are two possible cleanup steps to perform at this stage: the FID may need to
// be registered with the server or the FID is registered but we need a fresh authtoken.
// Registering will also result in a fresh authtoken. Do the appropriate step here.
PersistedInstallationEntry updatedPrefs;
try {
if (prefs.isErrored() || prefs.isUnregistered()) {
prefs = registerFidWithServer(prefs);
updatedPrefs = registerFidWithServer(prefs);
} else if (forceRefresh || utils.isAuthTokenExpired(prefs)) {
prefs = fetchAuthTokenFromServer(prefs);
updatedPrefs = fetchAuthTokenFromServer(prefs);
} else {
// nothing more to do, get out now
return;
Expand All @@ -371,7 +384,12 @@ private void doNetworkCallIfNecessary(boolean forceRefresh) {
}

// Store the prefs to persist the result of the previous step.
insertOrUpdatePrefs(prefs);
insertOrUpdatePrefs(updatedPrefs);

// Update FidListener if a fid has changed.
updateFidListener(prefs, updatedPrefs);

prefs = updatedPrefs;

// Update cachedFID, if FID is successfully REGISTERED and persisted.
if (prefs.isRegistered()) {
Expand All @@ -390,6 +408,14 @@ private void doNetworkCallIfNecessary(boolean forceRefresh) {
}
}

private synchronized void updateFidListener(
PersistedInstallationEntry prefs, PersistedInstallationEntry updatedPrefs) {
if (fidListener != null
&& !prefs.getFirebaseInstallationId().equals(updatedPrefs.getFirebaseInstallationId())) {
fidListener.onFidChanged(updatedPrefs.getFirebaseInstallationId());
}
}

/**
* Inserting or Updating the prefs. This operation is made cross-process and cross-thread safe by
* wrapping all the processing first in a java synchronization block and wrapping that in a
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 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.installations;

import androidx.annotation.NonNull;
import com.google.firebase.installations.internal.FidListener;

class FakeFidListener implements FidListener {
private String currentFid;

@Override
public void onFidChanged(@NonNull String fid) {
currentFid = fid;
}

public String getLatestFid() {
return currentFid;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public class FirebaseInstallationsTest {
@Mock private RandomFidGenerator mockFidGenerator;

public static final String TEST_FID_1 = "cccccccccccccccccccccc";
public static final String TEST_FID_2 = "dccccccccccccccccccccd";

public static final String TEST_PROJECT_ID = "777777777777";

Expand Down Expand Up @@ -453,6 +454,40 @@ public void testReadToken_withJsonformatting() {
assertThat(iidStore.readToken(), equalTo("thetoken"));
}

@Test
public void testFidListener_fidChanged_successful() throws Exception {
when(mockIidStore.readIid()).thenReturn(null);
when(mockIidStore.readToken()).thenReturn(null);
when(mockBackend.createFirebaseInstallation(
anyString(), anyString(), anyString(), anyString(), any()))
.thenReturn(
TEST_INSTALLATION_RESPONSE
.toBuilder()
.setUri("/projects/" + TEST_PROJECT_ID + "/installations/" + TEST_FID_2)
.setFid(TEST_FID_2)
.build());

FakeFidListener fidListener = new FakeFidListener();
// Register the FidListener
firebaseInstallations.registerFidListener(fidListener);
Copy link
Member

Choose a reason for hiding this comment

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

Please consider adding a test for removing a registration as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated this test to check the removing registration code as well. PTAL. Thanks


// Do the actual getId() call under test.
// Confirm both that it returns the expected ID, as does reading the prefs from storage.
TestOnCompleteListener<String> onCompleteListener = new TestOnCompleteListener<>();
Task<String> task = firebaseInstallations.getId();
task.addOnCompleteListener(executor, onCompleteListener);
String fid = onCompleteListener.await();
assertWithMessage("getId Task failed.").that(fid).isEqualTo(TEST_FID_1);

// Waiting for Task that registers FID on the FIS Servers
executor.awaitTermination(500, TimeUnit.MILLISECONDS);
PersistedInstallationEntry entry = persistedInstallation.readPersistedInstallationEntryValue();
assertThat(entry.getFirebaseInstallationId(), equalTo(TEST_FID_2));

// Verify FidListener receives fid changes.
assertThat(fidListener.getLatestFid(), equalTo(TEST_FID_2));
}

@Test
public void testGetId_migrateIid_successful() throws Exception {
when(mockIidStore.readIid()).thenReturn(TEST_INSTANCE_ID_1);
Expand Down