-
Notifications
You must be signed in to change notification settings - Fork 615
[Firebase Segmentation] Add custom installation id cache layer and tests for it. #524
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
Changes from 4 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
1962431
Add type arguments in StorageTaskManager (#517)
schmidt-sebastian b69b2c8
Output artifact list during local publishing. (#515)
allisonbm92 8881325
Implement Firebase segmentation SDK device local cache
diwu-arete 771d23c
fix functions (#523)
VinayGuthal dc3f410
Set test type to release only in CI. (#522)
vkryachko 864748f
[Firebase Segmentation] Add custom installation id cache layer and te…
diwu-arete 0a3ebf6
Add test for updating cache
diwu-arete 2d158ed
Switch to use SQLiteOpenHelper
diwu-arete 18d4e7e
Minor fix to error message to match the admin sdk. (#525)
rsgowman d65c21c
Added clean task to smoke tests. (#527)
allisonbm92 3e2cc89
Update deps to post-androidx gms versions. (#526)
vkryachko f118d39
Switch to use SharedPreferences from SQLite.
diwu-arete 4da5d31
Change the cache class to be singleton
diwu-arete c1f7644
Copy firebase-firestore-ktx dependencies on firestore into its own su…
d1ff0ec
Wrap shared pref commit in a async task.
diwu-arete 2c5102c
Merge branch 'master' of github.com:firebase/firebase-android-sdk int…
diwu-arete 41fbfee
Address comments
diwu-arete 097ff36
Bump firestore version for release (#530)
vkryachko 5fd2fa0
Google format fix
diwu-arete e950003
Merge branch 'master' of github.com:firebase/firebase-android-sdk int…
diwu-arete File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
.../src/androidTest/java/com/google/firebase/segmentation/CustomInstallationIdCacheTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
// Copyright 2019 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.segmentation; | ||
|
||
import static com.google.common.truth.Truth.assertThat; | ||
import static org.junit.Assert.assertNull; | ||
|
||
import androidx.test.InstrumentationRegistry; | ||
import androidx.test.ext.junit.runners.AndroidJUnit4; | ||
import com.google.firebase.FirebaseApp; | ||
import com.google.firebase.FirebaseOptions; | ||
import org.junit.After; | ||
import org.junit.Before; | ||
import org.junit.Test; | ||
import org.junit.runner.RunWith; | ||
|
||
/** Instrumented tests for {@link CustomInstallationIdCache} */ | ||
@RunWith(AndroidJUnit4.class) | ||
public class CustomInstallationIdCacheTest { | ||
|
||
private FirebaseApp firebaseApp0; | ||
private FirebaseApp firebaseApp1; | ||
private CustomInstallationIdCache cache; | ||
|
||
@Before | ||
public void setUp() { | ||
FirebaseApp.clearInstancesForTest(); | ||
firebaseApp0 = | ||
FirebaseApp.initializeApp( | ||
InstrumentationRegistry.getContext(), | ||
new FirebaseOptions.Builder().setApplicationId("1:123456789:android:abcdef").build()); | ||
firebaseApp1 = | ||
FirebaseApp.initializeApp( | ||
InstrumentationRegistry.getContext(), | ||
new FirebaseOptions.Builder().setApplicationId("1:987654321:android:abcdef").build(), | ||
"firebase_app_1"); | ||
cache = new CustomInstallationIdCache(); | ||
} | ||
|
||
@After | ||
public void cleanUp() { | ||
cache.clear(); | ||
} | ||
|
||
@Test | ||
public void testReadCacheEntry_Null() { | ||
assertNull(cache.readCacheEntryValue(firebaseApp0)); | ||
assertNull(cache.readCacheEntryValue(firebaseApp1)); | ||
} | ||
|
||
@Test | ||
public void testUpdateAndReadCacheEntry() { | ||
cache.insertOrUpdateCacheEntry( | ||
firebaseApp0, | ||
CustomInstallationIdCacheEntryValue.create( | ||
"123456", "cAAAAAAAAAA", CustomInstallationIdCache.CacheStatus.PENDING)); | ||
CustomInstallationIdCacheEntryValue entryValue = cache.readCacheEntryValue(firebaseApp0); | ||
assertThat(entryValue.getCustomInstallationId()).isEqualTo("123456"); | ||
assertThat(entryValue.getFirebaseInstanceId()).isEqualTo("cAAAAAAAAAA"); | ||
assertThat(entryValue.getCacheStatus()) | ||
.isEqualTo(CustomInstallationIdCache.CacheStatus.PENDING); | ||
assertNull(cache.readCacheEntryValue(firebaseApp1)); | ||
|
||
cache.insertOrUpdateCacheEntry( | ||
firebaseApp0, | ||
CustomInstallationIdCacheEntryValue.create( | ||
"123456", "cAAAAAAAAAA", CustomInstallationIdCache.CacheStatus.SYNCED)); | ||
entryValue = cache.readCacheEntryValue(firebaseApp0); | ||
assertThat(entryValue.getCustomInstallationId()).isEqualTo("123456"); | ||
assertThat(entryValue.getFirebaseInstanceId()).isEqualTo("cAAAAAAAAAA"); | ||
assertThat(entryValue.getCacheStatus()).isEqualTo(CustomInstallationIdCache.CacheStatus.SYNCED); | ||
} | ||
} |
208 changes: 208 additions & 0 deletions
208
...egmentation/src/main/java/com/google/firebase/segmentation/CustomInstallationIdCache.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,208 @@ | ||
// Copyright 2019 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.segmentation; | ||
|
||
import android.content.Context; | ||
import android.database.Cursor; | ||
import android.database.sqlite.SQLiteDatabase; | ||
import android.database.sqlite.SQLiteOpenHelper; | ||
import android.os.Build; | ||
import androidx.annotation.Nullable; | ||
import androidx.annotation.VisibleForTesting; | ||
import com.google.android.gms.common.internal.Preconditions; | ||
import com.google.firebase.FirebaseApp; | ||
|
||
class CustomInstallationIdCache { | ||
|
||
// Status of each cache entry | ||
// NOTE: never change the ordinal of the enum values because the enum values are stored in cache | ||
// as their ordinal numbers. | ||
enum CacheStatus { | ||
// Cache entry is synced to Firebase backend | ||
SYNCED, | ||
// Cache entry is waiting for Firebase backend response or pending internal retry for retryable | ||
// errors. | ||
PENDING, | ||
// Cache entry is not accepted by Firebase backend. | ||
ERROR | ||
} | ||
|
||
private static final String LOCAL_DB_NAME = "CustomInstallationIdCache"; | ||
private static final String TABLE_NAME = "InstallationIdMapping"; | ||
|
||
private static final String GMP_APP_ID_COLUMN_NAME = "GmpAppId"; | ||
private static final String FIREBASE_APP_NAME_COLUMN_NAME = "AppName"; | ||
private static final String CUSTOM_INSTALLATION_ID_COLUMN_NAME = "Cid"; | ||
private static final String INSTANCE_ID_COLUMN_NAME = "Iid"; | ||
private static final String CACHE_STATUS_COLUMN = "Status"; | ||
|
||
private static final String QUERY_WHERE_CLAUSE = | ||
String.format( | ||
"%s = ? " + "AND " + "%s = ?", GMP_APP_ID_COLUMN_NAME, FIREBASE_APP_NAME_COLUMN_NAME); | ||
|
||
/** | ||
* A SQLiteOpenHelper that configures database connections just the way we like them, delegating | ||
* to SQLiteSchema to actually do the work of migration. | ||
* | ||
* <p>The order of events when opening a new connection is as follows: | ||
* | ||
* <ol> | ||
* <li>New connection | ||
* <li>onConfigure (API 16 and above) | ||
* <li>onCreate / onUpgrade (optional; if version already matches these aren't called) | ||
* <li>onOpen | ||
* </ol> | ||
* | ||
* <p>This OpenHelper attempts to obtain exclusive access to the database and attempts to do so as | ||
* early as possible. On Jelly Bean devices and above (some 98% of devices at time of writing) | ||
* this happens naturally during onConfigure. On pre-Jelly Bean devices all other methods ensure | ||
* that the configuration is applied before any action is taken. | ||
*/ | ||
private static class OpenHelper extends SQLiteOpenHelper { | ||
// TODO: when we do schema upgrades in the future we need to make sure both downgrades and | ||
// upgrades work as expected, e.g. `up+down+up` is equivalent to `up`. | ||
private static int SCHEMA_VERSION = 1; | ||
|
||
private boolean configured = false; | ||
|
||
private OpenHelper(Context context) { | ||
super(context, LOCAL_DB_NAME, null, SCHEMA_VERSION); | ||
} | ||
|
||
@Override | ||
public void onConfigure(SQLiteDatabase db) { | ||
// Note that this is only called automatically by the SQLiteOpenHelper base class on Jelly | ||
// Bean and above. | ||
configured = true; | ||
|
||
db.rawQuery("PRAGMA busy_timeout=0;", new String[0]).close(); | ||
|
||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { | ||
db.setForeignKeyConstraintsEnabled(true); | ||
} | ||
} | ||
|
||
private void ensureConfigured(SQLiteDatabase db) { | ||
if (!configured) { | ||
onConfigure(db); | ||
} | ||
} | ||
|
||
@Override | ||
public void onCreate(SQLiteDatabase db) { | ||
ensureConfigured(db); | ||
// Create custom id mapping table. | ||
db.execSQL( | ||
String.format( | ||
"CREATE TABLE IF NOT EXISTS %s(%s TEXT NOT NULL, %s TEXT NOT NULL, " | ||
+ "%s TEXT NOT NULL, %s TEXT NOT NULL, %s INTEGER NOT NULL, PRIMARY KEY (%s, %s));", | ||
TABLE_NAME, | ||
GMP_APP_ID_COLUMN_NAME, | ||
FIREBASE_APP_NAME_COLUMN_NAME, | ||
CUSTOM_INSTALLATION_ID_COLUMN_NAME, | ||
INSTANCE_ID_COLUMN_NAME, | ||
CACHE_STATUS_COLUMN, | ||
GMP_APP_ID_COLUMN_NAME, | ||
FIREBASE_APP_NAME_COLUMN_NAME)); | ||
} | ||
|
||
@Override | ||
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { | ||
ensureConfigured(db); | ||
} | ||
|
||
@Override | ||
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { | ||
ensureConfigured(db); | ||
} | ||
|
||
@Override | ||
public void onOpen(SQLiteDatabase db) { | ||
ensureConfigured(db); | ||
} | ||
} | ||
|
||
private final OpenHelper openHelper; | ||
|
||
CustomInstallationIdCache() { | ||
// Since different FirebaseApp in the same Android application should | ||
diwu-arete marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// have the same application | ||
// context and same dir path, so that use the context of the default | ||
// FirebaseApp to create/open | ||
// the database. | ||
openHelper = new OpenHelper(FirebaseApp.getInstance().getApplicationContext()); | ||
} | ||
|
||
private SQLiteDatabase getReadableDb() { | ||
return openHelper.getReadableDatabase(); | ||
} | ||
|
||
private SQLiteDatabase getWritableDb() { | ||
return openHelper.getWritableDatabase(); | ||
} | ||
|
||
@Nullable | ||
CustomInstallationIdCacheEntryValue readCacheEntryValue(FirebaseApp firebaseApp) { | ||
String gmpAppId = firebaseApp.getOptions().getApplicationId(); | ||
String appName = firebaseApp.getName(); | ||
Cursor cursor = | ||
getReadableDb() | ||
.query( | ||
TABLE_NAME, | ||
new String[] { | ||
CUSTOM_INSTALLATION_ID_COLUMN_NAME, INSTANCE_ID_COLUMN_NAME, CACHE_STATUS_COLUMN | ||
}, | ||
QUERY_WHERE_CLAUSE, | ||
new String[] {gmpAppId, appName}, | ||
null, | ||
null, | ||
null); | ||
CustomInstallationIdCacheEntryValue value = null; | ||
while (cursor.moveToNext()) { | ||
Preconditions.checkArgument( | ||
value == null, "Multiple cache entries found for " + "firebase app %s", appName); | ||
value = | ||
CustomInstallationIdCacheEntryValue.create( | ||
cursor.getString(cursor.getColumnIndex(CUSTOM_INSTALLATION_ID_COLUMN_NAME)), | ||
cursor.getString(cursor.getColumnIndex(INSTANCE_ID_COLUMN_NAME)), | ||
CacheStatus.values()[cursor.getInt(cursor.getColumnIndex(CACHE_STATUS_COLUMN))]); | ||
} | ||
return value; | ||
} | ||
|
||
void insertOrUpdateCacheEntry( | ||
FirebaseApp firebaseApp, CustomInstallationIdCacheEntryValue entryValue) { | ||
getWritableDb() | ||
.execSQL( | ||
String.format( | ||
"INSERT OR REPLACE INTO %s(%s, %s, %s, %s, %s) VALUES(%s, %s, %s, %s, %s)", | ||
TABLE_NAME, | ||
GMP_APP_ID_COLUMN_NAME, | ||
FIREBASE_APP_NAME_COLUMN_NAME, | ||
CUSTOM_INSTALLATION_ID_COLUMN_NAME, | ||
INSTANCE_ID_COLUMN_NAME, | ||
CACHE_STATUS_COLUMN, | ||
"\"" + firebaseApp.getOptions().getApplicationId() + "\"", | ||
"\"" + firebaseApp.getName() + "\"", | ||
"\"" + entryValue.getCustomInstallationId() + "\"", | ||
"\"" + entryValue.getFirebaseInstanceId() + "\"", | ||
entryValue.getCacheStatus().ordinal())); | ||
} | ||
|
||
@VisibleForTesting | ||
void clear() { | ||
getWritableDb().execSQL(String.format("DELETE FROM %s", TABLE_NAME)); | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
...n/src/main/java/com/google/firebase/segmentation/CustomInstallationIdCacheEntryValue.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
// Copyright 2019 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.segmentation; | ||
|
||
import com.google.auto.value.AutoValue; | ||
import com.google.firebase.segmentation.CustomInstallationIdCache.CacheStatus; | ||
|
||
/** | ||
* This class represents a cache entry value in {@link CustomInstallationIdCache}, which contains a | ||
* Firebase instance id, a custom installation id and the cache status of this entry. | ||
*/ | ||
@AutoValue | ||
abstract class CustomInstallationIdCacheEntryValue { | ||
abstract String getCustomInstallationId(); | ||
|
||
abstract String getFirebaseInstanceId(); | ||
|
||
abstract CacheStatus getCacheStatus(); | ||
|
||
static CustomInstallationIdCacheEntryValue create( | ||
String customInstallationId, String firebaseInstanceId, CacheStatus cacheStatus) { | ||
return new AutoValue_CustomInstallationIdCacheEntryValue( | ||
customInstallationId, firebaseInstanceId, cacheStatus); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.