Skip to content

Implement remote config fetcher to fetch and cache configs. #4967

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 8 commits into from
May 5, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions firebase-sessions/firebase-sessions.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ dependencies {
implementation("com.google.firebase:firebase-encoders:17.0.0")
implementation("com.google.firebase:firebase-installations-interop:17.1.0")
implementation(libs.androidx.annotation)
testImplementation(project(mapOf("path" to ":integ-testing")))

runtimeOnly("com.google.firebase:firebase-installations:17.1.3")
runtimeOnly(project(":firebase-datatransport"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,26 @@ internal constructor(
private val firebaseApp: FirebaseApp,
firebaseInstallations: FirebaseInstallationsApi,
backgroundDispatcher: CoroutineDispatcher,
blockingDispatcher: CoroutineDispatcher,
transportFactoryProvider: Provider<TransportFactory>,
) {
private val sessionSettings = SessionsSettings(firebaseApp.applicationContext)
private val applicationInfo = SessionEvents.getApplicationInfo(firebaseApp)
private val sessionSettings =
SessionsSettings(
firebaseApp.applicationContext,
blockingDispatcher,
backgroundDispatcher,
firebaseInstallations,
applicationInfo
)
private val sessionGenerator = SessionGenerator(collectEvents = shouldCollectEvents())
private val eventGDTLogger = EventGDTLogger(transportFactoryProvider)
private val sessionCoordinator =
SessionCoordinator(firebaseInstallations, backgroundDispatcher, eventGDTLogger)
private val timeProvider: TimeProvider = Time()

init {
sessionSettings.updateSettings()
val sessionInitiator =
SessionInitiator(timeProvider, this::initiateSessionStart, sessionSettings)
val appContext = firebaseApp.applicationContext.applicationContext
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import androidx.annotation.Keep
import com.google.android.datatransport.TransportFactory
import com.google.firebase.FirebaseApp
import com.google.firebase.annotations.concurrent.Background
import com.google.firebase.annotations.concurrent.Blocking
import com.google.firebase.components.*
import com.google.firebase.components.Qualified.qualified
import com.google.firebase.components.Qualified.unqualified
Expand Down Expand Up @@ -45,6 +46,7 @@ internal class FirebaseSessionsRegistrar : ComponentRegistrar {
.add(Dependency.required(firebaseApp))
.add(Dependency.required(firebaseInstallationsApi))
.add(Dependency.required(backgroundDispatcher))
.add(Dependency.required(blockingDispatcher))
.add(Dependency.requiredProvider(transportFactory))
.factory { container ->
// Make sure FirebaseSessionsEarly has started up
Expand All @@ -53,6 +55,7 @@ internal class FirebaseSessionsRegistrar : ComponentRegistrar {
container.get(firebaseApp),
container.get(firebaseInstallationsApi),
container.get(backgroundDispatcher),
container.get(blockingDispatcher),
container.getProvider(transportFactory),
)
}
Expand All @@ -69,6 +72,8 @@ internal class FirebaseSessionsRegistrar : ComponentRegistrar {
private val firebaseInstallationsApi = unqualified(FirebaseInstallationsApi::class.java)
private val backgroundDispatcher =
qualified(Background::class.java, CoroutineDispatcher::class.java)
private val blockingDispatcher =
qualified(Blocking::class.java, CoroutineDispatcher::class.java)
private val transportFactory = unqualified(TransportFactory::class.java)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,34 @@
package com.google.firebase.sessions.settings

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.datastore.preferences.preferencesDataStore
import java.net.URL
import com.google.firebase.installations.FirebaseInstallationsApi
import com.google.firebase.sessions.ApplicationInfo
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.CoroutineContext
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.tasks.await
import org.json.JSONException
import org.json.JSONObject

internal class RemoteSettings(val context: Context) : SettingsProvider {
private val Context.dataStore by preferencesDataStore(name = SESSION_CONFIGS_NAME)
internal class RemoteSettings(
val context: Context,
val blockingDispatcher: CoroutineContext,
val backgroundDispatcher: CoroutineContext,
val firebaseInstallationsApi: FirebaseInstallationsApi,
val appInfo: ApplicationInfo,
private val configsFetcher: CrashlyticsSettingsFetcher = RemoteSettingsFetcher(appInfo),
dataStoreName: String = SESSION_CONFIGS_NAME
) : SettingsProvider {
private val Context.dataStore by preferencesDataStore(name = dataStoreName)
private val settingsCache = SettingsCache(context.dataStore)
private var fetchInProgress = AtomicBoolean(false)

override val sessionEnabled: Boolean?
get() {
Expand All @@ -47,45 +66,105 @@ internal class RemoteSettings(val context: Context) : SettingsProvider {
}

override fun updateSettings() {
fetchConfigs()
// TODO: Move to blocking coroutine dispatcher.
runBlocking(Dispatchers.Default) { launch { fetchConfigs() } }
}

override fun isSettingsStale(): Boolean {
return settingsCache.hasCacheExpired()
}

companion object SettingsFetcher {
private const val SESSION_CONFIGS_NAME = "firebase_session_settings"
private const val FIREBASE_SESSIONS_BASE_URL_STRING =
"https://firebase-settings.crashlytics.com"
private const val FIREBASE_PLATFORM = "android"
private const val fetchInProgress = false
private val settingsUrl: URL = run {
var uri =
Uri.Builder()
.scheme("https")
.authority(FIREBASE_SESSIONS_BASE_URL_STRING)
.appendPath("spi/v2/platforms")
.appendPath(FIREBASE_PLATFORM)
.appendPath("gmp")
// TODO(visum) Replace below with the GMP APPId
.appendPath("GMP_APP_ID")
.appendPath("settings")
.appendQueryParameter("build_version", "")
.appendQueryParameter("display_version", "")

URL(uri.build().toString())
internal fun clearCachedSettings() {
val scope = CoroutineScope(backgroundDispatcher)
scope.launch { settingsCache.removeConfigs() }
}

suspend private fun fetchConfigs() {
// Check if a fetch is in progress. If yes, return
if (fetchInProgress.get()) {
return
}

fun fetchConfigs() {
// Check if a fetch is in progress. If yes, return
if (fetchInProgress) {
return
}
// Check if cache is expired. If not, return
if (!settingsCache.hasCacheExpired()) {
return
}

// Check if cache is expired. If not, return
// Initiate a fetch. On successful response cache the fetched values
fetchInProgress.set(true)

// Get the installations ID before making a remote config fetch
var installationId = firebaseInstallationsApi.id.await()
if (installationId == null) {
fetchInProgress.set(false)
return
}

// All the required fields are available, start making a network request.
val options =
mapOf(
"X-Crashlytics-Installation-ID" to installationId as String,
"X-Crashlytics-Device-Model" to appInfo.deviceModel,
// TODO(visum) Add OS version parameters
// "X-Crashlytics-OS-Build-Version" to "",
// "X-Crashlytics-OS-Display-Version" to "",
"X-Crashlytics-API-Client-Version" to appInfo.sessionSdkVersion
)

configsFetcher.doConfigFetch(
headerOptions = options,
onSuccess = {
var sessionsEnabled: Boolean? = null
var sessionSamplingRate: Double? = null
var sessionTimeoutSeconds: Int? = null
var cacheDuration: Int? = null
if (it.has("app_quality")) {
val aqsSettings = it.get("app_quality") as JSONObject
try {
if (aqsSettings.has("sessions_enabled")) {
sessionsEnabled = aqsSettings.get("sessions_enabled") as Boolean?
}

if (aqsSettings.has("sampling_rate")) {
sessionSamplingRate = aqsSettings.get("sampling_rate") as Double?
}

if (aqsSettings.has("session_timeout_seconds")) {
sessionTimeoutSeconds = aqsSettings.get("session_timeout_seconds") as Int?
}

if (aqsSettings.has("cache_duration")) {
cacheDuration = aqsSettings.get("cache_duration") as Int?
}
} catch (exception: JSONException) {
Log.e(TAG, "Error parsing the configs remotely fetched: ", exception)
}
}

val scope = CoroutineScope(backgroundDispatcher)
sessionsEnabled?.let { settingsCache.updateSettingsEnabled(sessionsEnabled) }

sessionTimeoutSeconds?.let {
settingsCache.updateSessionRestartTimeout(sessionTimeoutSeconds)
}

sessionSamplingRate?.let { settingsCache.updateSamplingRate(sessionSamplingRate) }

cacheDuration?.let { settingsCache.updateSessionCacheDuration(cacheDuration) }
?: let { settingsCache.updateSessionCacheDuration(86400) }

settingsCache.updateSessionCacheUpdatedTime(System.currentTimeMillis())
fetchInProgress.set(false)
},
onFailure = {
// Network request failed here.
Log.e(TAG, "Error failing to fetch the remote configs")
fetchInProgress.set(false)
}
)
}

companion object {
private const val SESSION_CONFIGS_NAME = "firebase_session_settings"
private const val TAG = "SessionConfigFetcher"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2023 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.sessions.settings

import android.net.Uri
import com.google.firebase.sessions.ApplicationInfo
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import org.json.JSONObject

internal interface CrashlyticsSettingsFetcher {
suspend fun doConfigFetch(
headerOptions: Map<String, String>,
onSuccess: suspend ((JSONObject)) -> Unit,
onFailure: suspend () -> Unit
)
}

internal class RemoteSettingsFetcher(val appInfo: ApplicationInfo) : CrashlyticsSettingsFetcher {
override suspend fun doConfigFetch(
headerOptions: Map<String, String>,
onSuccess: suspend ((JSONObject)) -> Unit,
onFailure: suspend () -> Unit
) {
val connection = settingsUrl().openConnection() as HttpsURLConnection
connection.requestMethod = "GET"
connection.setRequestProperty("Accept", "application/json")
headerOptions.forEach { connection.setRequestProperty(it.key, it.value) }

val responseCode = connection.responseCode
if (responseCode == HttpsURLConnection.HTTP_OK) {
val inputStream = connection.inputStream
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
val response = StringBuilder()
var inputLine: String?
while (bufferedReader.readLine().also { inputLine = it } != null) {
response.append(inputLine)
}
bufferedReader.close()
inputStream.close()

val responseJson = JSONObject(response.toString())
onSuccess(responseJson)
} else {
onFailure()
}
}

fun settingsUrl(): URL {
var uri =
Uri.Builder()
.scheme("https")
.authority(FIREBASE_SESSIONS_BASE_URL_STRING)
.appendPath("spi")
.appendPath("v2")
.appendPath("platforms")
.appendPath(FIREBASE_PLATFORM)
.appendPath("gmp")
.appendPath(appInfo.appId)
.appendPath("settings")
// TODO(visum) Setup build version and display version
// .appendQueryParameter("build_version", "")
// .appendQueryParameter("display_version", "")

return URL(uri.build().toString())
}

companion object {
private const val FIREBASE_SESSIONS_BASE_URL_STRING = "firebase-settings.crashlytics.com"
private const val FIREBASE_PLATFORM = "android"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
package com.google.firebase.sessions.settings

import android.content.Context
import com.google.firebase.installations.FirebaseInstallationsApi
import com.google.firebase.sessions.ApplicationInfo
import kotlin.coroutines.CoroutineContext
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes

Expand All @@ -25,11 +28,22 @@ import kotlin.time.Duration.Companion.minutes
*
* @hide
*/
internal class SessionsSettings(val context: Context) {

private var localOverrideSettings = LocalOverrideSettings(context)
private var remoteSettings = RemoteSettings(context)

internal class SessionsSettings(
val context: Context,
val blockingDispatcher: CoroutineContext,
val backgroundDispatcher: CoroutineContext,
val firebaseInstallationsApi: FirebaseInstallationsApi,
val appInfo: ApplicationInfo,
private val localOverrideSettings: LocalOverrideSettings = LocalOverrideSettings(context),
private val remoteSettings: RemoteSettings =
RemoteSettings(
context,
blockingDispatcher,
backgroundDispatcher,
firebaseInstallationsApi,
appInfo
)
) {
// Order of preference for all the configs below:
// 1. Honor local overrides
// 2. If no local overrides, use remote config
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ internal class SettingsCache(private val store: DataStore<Preferences>) {
}

internal fun hasCacheExpired(): Boolean {
if (sessionConfigs.cacheUpdatedTime != null) {
if (sessionConfigs.cacheUpdatedTime != null && sessionConfigs.cacheDuration != null) {
val currentTimestamp = System.currentTimeMillis()
val timeDifferenceSeconds = (currentTimestamp - sessionConfigs.cacheUpdatedTime!!) / 1000
if (timeDifferenceSeconds < sessionConfigs.cacheDuration!!) return false
Expand Down
Loading