Skip to content

Add TimeProvider interface to abstract away the clock #4905

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 2 commits into from
Apr 19, 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
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,11 @@ internal constructor(
private val sessionCoordinator =
SessionCoordinator(firebaseInstallations, backgroundDispatcher, eventGDTLogger)
private val sessionSettings = SessionsSettings(firebaseApp.applicationContext)
private val timeProvider: TimeProvider = Time()

init {
val sessionInitiator =
SessionInitiator(WallClock::elapsedRealtime, this::initiateSessionStart, sessionSettings)
SessionInitiator(timeProvider, this::initiateSessionStart, sessionSettings)
val appContext = firebaseApp.applicationContext.applicationContext
if (appContext is Application) {
appContext.registerActivityLifecycleCallbacks(sessionInitiator.activityLifecycleCallbacks)
Expand All @@ -60,7 +61,8 @@ internal constructor(

private fun initiateSessionStart() {
val sessionDetails = sessionGenerator.generateNewSession()
val sessionEvent = SessionEvents.startSession(firebaseApp, sessionDetails, sessionSettings)
val sessionEvent =
SessionEvents.startSession(firebaseApp, sessionDetails, sessionSettings, timeProvider)

if (sessionDetails.collectEvents) {
sessionCoordinator.attemptLoggingSessionEvent(sessionEvent)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ internal object SessionEvents {
firebaseApp: FirebaseApp,
sessionDetails: SessionDetails,
sessionsSettings: SessionsSettings,
currentTimeUs: Long = WallClock.currentTimeUs()
timeProvider: TimeProvider
) =
SessionEvent(
eventType = EventType.SESSION_START,
Expand All @@ -114,7 +114,7 @@ internal object SessionEvents {
sessionDetails.sessionId,
sessionDetails.firstSessionId,
sessionDetails.sessionIndex,
currentTimeUs,
eventTimestampUs = timeProvider.currentTimeUs(),
DataCollectionStatus(sessionSamplingRate = sessionsSettings.samplingRate),
),
applicationInfo = getApplicationInfo(firebaseApp)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import com.google.firebase.sessions.settings.SessionsSettings
import kotlin.time.Duration

/**
* The [SessionInitiator] is responsible for calling the [initiateSessionStart] callback whenever a
Expand All @@ -30,22 +29,22 @@ import kotlin.time.Duration
* @hide
*/
internal class SessionInitiator(
private val elapsedRealtime: () -> Duration,
private val timeProvider: TimeProvider,
private val initiateSessionStart: () -> Unit,
private val sessionsSettings: SessionsSettings
) {
private var backgroundTime = elapsedRealtime()
private var backgroundTime = timeProvider.elapsedRealtime()

init {
initiateSessionStart()
}

fun appBackgrounded() {
backgroundTime = elapsedRealtime()
backgroundTime = timeProvider.elapsedRealtime()
}

fun appForegrounded() {
val interval = elapsedRealtime() - backgroundTime
val interval = timeProvider.elapsedRealtime() - backgroundTime
val sessionTimeout = sessionsSettings.sessionRestartTimeout
if (interval > sessionTimeout) {
initiateSessionStart()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* 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

import android.os.SystemClock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds

/** Time provider interface, for testing purposes. */
internal interface TimeProvider {
fun elapsedRealtime(): Duration
fun currentTimeUs(): Long
}

/** "Wall clock" time provider. */
internal class Time : TimeProvider {
/**
* Gets the [Duration] elapsed in "wall clock" time since device boot.
*
* This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power
* saving modes, so is the recommend basis for general purpose interval timing.
*/
override fun elapsedRealtime(): Duration = SystemClock.elapsedRealtime().milliseconds

/**
* Gets the current "wall clock" time in microseconds.
*
* This clock can be set by the user or the phone network, so the time may jump backwards or
* forwards unpredictably. This clock should only be used when correspondence with real-world
* dates and times is important, such as in a calendar or alarm clock application.
*/
override fun currentTimeUs(): Long = System.currentTimeMillis() * US_PER_MILLIS

companion object {
/** Microseconds per millisecond. */
private const val US_PER_MILLIS = 1000L
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import com.google.firebase.FirebaseApp
import com.google.firebase.sessions.settings.SessionsSettings
import com.google.firebase.sessions.testing.FakeFirebaseApp
import com.google.firebase.sessions.testing.FakeProvider
import com.google.firebase.sessions.testing.FakeTimeProvider
import com.google.firebase.sessions.testing.FakeTransportFactory
import com.google.firebase.sessions.testing.TestSessionEventData
import org.junit.After
Expand All @@ -42,7 +43,7 @@ class EventGDTLoggerTest {
fakeFirebaseApp.firebaseApp,
TestSessionEventData.TEST_SESSION_DETAILS,
SessionsSettings(fakeFirebaseApp.firebaseApp.applicationContext),
TestSessionEventData.TEST_SESSION_TIMESTAMP_US,
FakeTimeProvider(),
)
val fakeTransportFactory = FakeTransportFactory()
val fakeTransportFactoryProvider = FakeProvider(fakeTransportFactory as TransportFactory)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,18 @@ package com.google.firebase.sessions

import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.google.firebase.FirebaseApp
import com.google.firebase.sessions.settings.SessionsSettings
import com.google.firebase.sessions.testing.FakeEventGDTLogger
import com.google.firebase.sessions.testing.FakeFirebaseApp
import com.google.firebase.sessions.testing.FakeFirebaseInstallations
import com.google.firebase.sessions.testing.FakeTimeProvider
import com.google.firebase.sessions.testing.TestSessionEventData
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith

Expand All @@ -50,7 +53,7 @@ class SessionCoordinatorTest {
fakeFirebaseApp.firebaseApp,
TestSessionEventData.TEST_SESSION_DETAILS,
SessionsSettings(fakeFirebaseApp.firebaseApp.applicationContext),
TestSessionEventData.TEST_SESSION_TIMESTAMP_US,
FakeTimeProvider(),
)

sessionCoordinator.attemptLoggingSessionEvent(sessionEvent)
Expand All @@ -61,4 +64,9 @@ class SessionCoordinatorTest {
assertThat(fakeEventGDTLogger.loggedEvent!!.sessionData.firebaseInstallationId)
.isEqualTo("FaKeFiD")
}

@After
fun cleanUp() {
FirebaseApp.clearInstancesForTest()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import com.google.firebase.FirebaseApp
import com.google.firebase.sessions.SessionEvents.SESSION_EVENT_ENCODER
import com.google.firebase.sessions.settings.SessionsSettings
import com.google.firebase.sessions.testing.FakeFirebaseApp
import com.google.firebase.sessions.testing.FakeTimeProvider
import com.google.firebase.sessions.testing.TestSessionEventData
import org.junit.After
import org.junit.Test
Expand All @@ -43,7 +44,7 @@ class SessionEventEncoderTest {
fakeFirebaseApp.firebaseApp,
TestSessionEventData.TEST_SESSION_DETAILS,
SessionsSettings(fakeFirebaseApp.firebaseApp.applicationContext),
TestSessionEventData.TEST_SESSION_TIMESTAMP_US,
FakeTimeProvider(),
)

val json = SESSION_EVENT_ENCODER.encode(sessionEvent)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ import com.google.common.truth.Truth.assertThat
import com.google.firebase.FirebaseApp
import com.google.firebase.sessions.settings.SessionsSettings
import com.google.firebase.sessions.testing.FakeFirebaseApp
import com.google.firebase.sessions.testing.FakeTimeProvider
import com.google.firebase.sessions.testing.TestSessionEventData.TEST_DATA_COLLECTION_STATUS
import com.google.firebase.sessions.testing.TestSessionEventData.TEST_SESSION_DATA
import com.google.firebase.sessions.testing.TestSessionEventData.TEST_SESSION_DETAILS
import com.google.firebase.sessions.testing.TestSessionEventData.TEST_SESSION_EVENT
import com.google.firebase.sessions.testing.TestSessionEventData.TEST_SESSION_TIMESTAMP_US
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
Expand All @@ -41,7 +41,7 @@ class SessionEventTest {
fakeFirebaseApp.firebaseApp,
TEST_SESSION_DETAILS,
SessionsSettings(fakeFirebaseApp.firebaseApp.applicationContext),
TEST_SESSION_TIMESTAMP_US,
FakeTimeProvider(),
)

assertThat(sessionEvent).isEqualTo(TEST_SESSION_EVENT)
Expand All @@ -58,7 +58,7 @@ class SessionEventTest {
fakeFirebaseApp.firebaseApp,
TEST_SESSION_DETAILS,
SessionsSettings(fakeFirebaseApp.firebaseApp.applicationContext),
TEST_SESSION_TIMESTAMP_US,
FakeTimeProvider(),
)

assertThat(sessionEvent)
Expand Down
Loading