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 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
5 changes: 4 additions & 1 deletion .github/workflows/post_release_cleanup.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,8 @@ jobs:
**/*.gradle
**/*.gradle.kts
title: '${{ inputs.name}} mergeback'
body: 'Auto-generated PR for cleaning up release ${{ inputs.name}}'
body: |
Auto-generated PR for cleaning up release ${{ inputs.name}}

NO_RELEASE_CHANGE
commit-message: 'Post release cleanup for ${{ inputs.name }}'
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 @@ -40,20 +42,33 @@ internal constructor(
blockingDispatcher: CoroutineDispatcher,
transportFactoryProvider: Provider<TransportFactory>,
) {

private val 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 @@ -25,11 +25,14 @@ import android.os.Process

/** Provides details about the current process. */
internal interface ProcessDetails {
/** Whether the current process is the app's default process or not. */
val isDefaultProcess: Boolean

/** 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,18 +43,16 @@ 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 isForegroundProcess: Boolean
get() {
val runningAppProcessInfo = RunningAppProcessInfo()
Expand All @@ -69,6 +70,7 @@ internal class AndroidProcessDetails(context: Context) : ProcessDetails {
internal companion object {
/** Returns whether the current process should generate a new session or not. */
fun shouldProcessGenerateNewSession(processDetails: ProcessDetails): Boolean =
processDetails.isDefaultProcess && processDetails.isForegroundProcess
(processDetails.processName == processDetails.defaultProcessName) &&
processDetails.isForegroundProcess
}
}
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
Expand Up @@ -24,7 +24,7 @@ import kotlinx.coroutines.CoroutineDispatcher
* that includes data synchronizing across processes, sending events to our backend, and
* broadcasting AQS related events to listeners
*/
interface SessionMaintainer {
internal interface SessionMaintainer {

/** Register a listener for updates to the session being maintained by this class */
fun register(subscriber: SessionSubscriber)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* 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

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

override fun register(subscriber: SessionSubscriber) = Unit

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,60 @@
/*
* 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

internal data class FirebaseSessionsData(val sessionId: String?)

/** Persists session data that needs to be synchronized across processes */
internal class SessionsDataRepository(private val context: Context) {
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])
}

private val Context.dataStore: DataStore<Preferences> by
preferencesDataStore(name = "firebase_session_data_repository")
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