Skip to content

Add SessionMaintainerFollower and create in FirebaseSessions when… #5368

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

Open
wants to merge 9 commits into
base: session-maintainer
Choose a base branch
from
Open
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 @@ -21,6 +21,7 @@ import com.google.android.datatransport.Encoding
import com.google.android.datatransport.Event
import com.google.android.datatransport.TransportFactory
import com.google.firebase.inject.Provider
import com.google.firebase.sessions.leader.SessionEvent

/**
* The [EventGDTLoggerInterface] is for testing purposes so that we can mock EventGDTLogger in other
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import com.google.firebase.ktx.Firebase
import com.google.firebase.ktx.app
import com.google.firebase.sessions.api.FirebaseSessionsDependencies
import com.google.firebase.sessions.api.SessionSubscriber
import com.google.firebase.sessions.follower.SessionMaintainerFollower
import com.google.firebase.sessions.follower.SessionsDataRepository
import com.google.firebase.sessions.leader.SessionMaintainerLeader
import kotlinx.coroutines.CoroutineDispatcher

Expand All @@ -39,21 +41,35 @@ internal constructor(
backgroundDispatcher: CoroutineDispatcher,
blockingDispatcher: CoroutineDispatcher,
transportFactoryProvider: Provider<TransportFactory>,
processDetails: ProcessDetails = AndroidProcessDetails(firebaseApp.applicationContext)
) {

private val sessionMaintainer: SessionMaintainer
private val tag = "FirebaseSessions"

private val sessionsDataRepository: SessionsDataRepository
init {
// TODO(rothbutter): create a different maintainer based on the characteristics of this process
Log.d(tag, "Initializing data repository")
sessionsDataRepository = SessionsDataRepository(firebaseApp.applicationContext)

Log.d(
tag,
"Initializing data maintainer. Default process is: ${processDetails.defaultProcessName}"
)
sessionMaintainer =
SessionMaintainerLeader(
firebaseApp,
firebaseInstallations,
backgroundDispatcher,
blockingDispatcher,
transportFactoryProvider
)
if (AndroidProcessDetails.shouldProcessGenerateNewSession(processDetails)) {
Log.d(tag, "Initializing leader maintainer on process: ${processDetails.processName}")
SessionMaintainerLeader(
firebaseApp,
firebaseInstallations,
backgroundDispatcher,
blockingDispatcher,
transportFactoryProvider,
sessionsDataRepository
)
} else {
Log.d(tag, "Initializing follower maintainer on process: ${processDetails.processName}")
SessionMaintainerFollower(sessionsDataRepository)
}

sessionMaintainer.start(backgroundDispatcher)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ internal interface ProcessDetails {

/** Whether the current process is running in the foreground or not. */
val isForegroundProcess: Boolean

/** Name of this process */
val processName: String?

/** Name of the default process */
val defaultProcessName: String
}

/** Android implementation of [ProcessDetails]. */
Expand All @@ -40,23 +46,23 @@ internal class AndroidProcessDetails(context: Context) : ProcessDetails {
* This is the app's package name unless the app overrides the android:process attribute in the
* application block of its Android manifest file.
*/
private val defaultProcessName: String = context.applicationInfo.processName
override val defaultProcessName: String = context.applicationInfo.processName

/** The name of the current process, or null if it couldn't be found. */
private val currentProcessName: String? =
/** The name of this process, or null if it couldn't be found. */
override val processName: String? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Application.getProcessName()
} else {
findProcessName(context, Process.myPid())
}

override val isDefaultProcess: Boolean = currentProcessName == defaultProcessName
override val isDefaultProcess: Boolean = processName == defaultProcessName

override val isForegroundProcess: Boolean
get() {
val runningAppProcessInfo = RunningAppProcessInfo()
ActivityManager.getMyMemoryState(runningAppProcessInfo)
return runningAppProcessInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
return runningAppProcessInfo.importance <= RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this should go back to runningAppProcessInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND because IMPORTANCE_FOREGROUND_SERVICE is only available after a specific api level, and it'll make our logic complicated to also count services as leaders.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

the one integration test fails if we don't consider foreground services to be foreground processes https://github.com/firebase/firebase-android-sdk/blob/master/firebase-sessions/test-app/src/androidTest/kotlin/com/google/firebase/testing/sessions/FirebaseSessionsTest.kt

That suggests to me that we may need it. Thoughts?

}

/** Finds the process name for the given pid, or returns null if not found. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ import com.google.firebase.FirebaseApp
import com.google.firebase.encoders.DataEncoder
import com.google.firebase.encoders.json.JsonDataEncoderBuilder
import com.google.firebase.sessions.api.SessionSubscriber
import com.google.firebase.sessions.leader.AutoSessionEventEncoder
import com.google.firebase.sessions.leader.DataCollectionState
import com.google.firebase.sessions.leader.DataCollectionStatus
import com.google.firebase.sessions.leader.EventType
import com.google.firebase.sessions.leader.SessionDetails
import com.google.firebase.sessions.leader.SessionEvent
import com.google.firebase.sessions.leader.SessionInfo
import com.google.firebase.sessions.settings.SessionsSettings

/** Contains functions for [SessionEvent]s. */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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.follower

import android.util.Log
import com.google.firebase.sessions.SessionMaintainer
import com.google.firebase.sessions.api.FirebaseSessionsDependencies
import com.google.firebase.sessions.api.SessionSubscriber
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class SessionMaintainerFollower(private val sessionsDataRepository: SessionsDataRepository) :
SessionMaintainer {
val tag = "SessionMaintainerFollow"

override fun register(subscriber: SessionSubscriber) {
Copy link
Contributor

Choose a reason for hiding this comment

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

You can say = Unit instead of an empty body. Looks better in my opinion.

Copy link
Contributor

Choose a reason for hiding this comment

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

Is a no-op the right thing to do for followers? Should they still notify the subscribers on register?

Perf relies on the AQS session id being set before the call to firebaseSessions.register returns. Crashlytics is ok without an AQS session id.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Okay. We can force a lookup.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

actually, I'm unsure. We notify subscribers on init, and getRegisteredSusbscribers claims that it blocks until all subscribers are registered. Seems this should be okay, no?

// NOOP
}

override fun start(backgroundDispatcher: CoroutineDispatcher) {
CoroutineScope(backgroundDispatcher).launch {
sessionsDataRepository.firebaseSessionDataFlow.collect {
if (it.sessionId == null) {
Log.d(
tag,
"No session data available in shared storage." + " subscribers will not be notified."
)
} else {
Log.d(
tag,
"Follower process has observed a change to the repository and will notify subscribers. New session id is ${it.sessionId}"
)
notifySubscribers(it.sessionId)
}
}
}
}

private suspend fun notifySubscribers(sessionId: String) {
val subscribers = FirebaseSessionsDependencies.getRegisteredSubscribers()
if (subscribers.isEmpty()) {
Log.d(tag, "Sessions SDK did not have any subscribers. Events will not be sent.")
} else {
subscribers.values.forEach { subscriber ->
// Notify subscribers, irregardless ;) of sampling and data collection state.
Log.d(tag, "Sending session id $sessionId to subscriber $subscriber.")
subscriber.onSessionChanged(SessionSubscriber.SessionDetails(sessionId))
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* 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.follower

import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map

data class FirebaseSessionsData(val sessionId: String?)

/** Persists session data that needs to be synchronized across processes */
class SessionsDataRepository(private val context: Context) {
Copy link
Contributor

Choose a reason for hiding this comment

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

These classes should all be internal visibility.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

👍

private val tag = "FirebaseSessionsRepo"

private object FirebaseSessionDataKeys {
val SESSION_ID = stringPreferencesKey("session_id")
}

val firebaseSessionDataFlow: Flow<FirebaseSessionsData> =
context.dataStore.data
.catch { exception ->
Log.e(tag, "Error reading stored session data.", exception)
emit(emptyPreferences())
}
.map { preferences -> mapSessionsData(preferences) }
Copy link
Contributor

Choose a reason for hiding this comment

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

Can this be something like .map(::mapSessionsData) ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

that didn't work


suspend fun updateSessionId(sessionId: String) {
context.dataStore.edit { preferences ->
preferences[FirebaseSessionDataKeys.SESSION_ID] = sessionId
}
}

private fun mapSessionsData(preferences: Preferences): FirebaseSessionsData =
FirebaseSessionsData(preferences[FirebaseSessionDataKeys.SESSION_ID])
}

const val SESSION_CONFIGS_NAME = "firebase_session_settings"
Copy link
Contributor

Choose a reason for hiding this comment

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

Putting top level constants directly in the file will cause the Firebase API check to complain, because it will generate a public class to put this in for Java. Maybe this and the FirebaseSessionDataKeys can go in a companion object instead.


private val Context.dataStore: DataStore<Preferences> by
preferencesDataStore(name = SESSION_CONFIGS_NAME)
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@
* limitations under the License.
*/

package com.google.firebase.sessions
package com.google.firebase.sessions.leader

import android.util.Log
import com.google.firebase.installations.FirebaseInstallationsApi
import com.google.firebase.sessions.EventGDTLoggerInterface
import kotlinx.coroutines.tasks.await

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@
* limitations under the License.
*/

package com.google.firebase.sessions
package com.google.firebase.sessions.leader

import com.google.firebase.encoders.annotations.Encodable
import com.google.firebase.encoders.json.NumberedEnum
import com.google.firebase.sessions.ApplicationInfo

/**
* Contains the relevant information around a Firebase Session Event.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
* limitations under the License.
*/

package com.google.firebase.sessions
package com.google.firebase.sessions.leader

import com.google.firebase.sessions.TimeProvider
import java.util.UUID

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

package com.google.firebase.sessions
package com.google.firebase.sessions.leader

/** Interface for listening to the initiation of a new session. */
internal interface SessionInitiateListener {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
* limitations under the License.
*/

package com.google.firebase.sessions
package com.google.firebase.sessions.leader

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import com.google.firebase.sessions.TimeProvider
import com.google.firebase.sessions.settings.SessionsSettings
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
Expand Down
Loading