Skip to content

Commit 24ec2e1

Browse files
fadi-georgeclaude
andcommitted
feat: [SDK-5390] send a session end when a sessions API session ends
When the session uses the sessions API, enqueue an end UpdateSessionOperation with the backgrounded-at time and final duration. In the background job, flush and wait for it with a timeout so Android 15+ doesn't block the request after the job finishes. Flag off leaves the legacy end unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4fdb2a2 commit 24ec2e1

3 files changed

Lines changed: 241 additions & 18 deletions

File tree

‎OneSignalSDK/onesignal/core/src/main/java/com/onesignal/session/internal/session/SessionModel.kt‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,15 @@ class SessionModel : Model() {
4646
setLongProperty(::focusTime.name, value)
4747
}
4848

49+
/**
50+
* When this app was last unfocused, in Unix time milliseconds. Null until the first unfocus.
51+
*/
52+
var unfocusTime: Long?
53+
get() = getOptLongProperty(::unfocusTime.name)
54+
set(value) {
55+
setOptLongProperty(::unfocusTime.name, value)
56+
}
57+
4958
/**
5059
* How long this session has spent as active, in milliseconds.
5160
*/

‎OneSignalSDK/onesignal/core/src/main/java/com/onesignal/session/internal/session/impl/SessionService.kt‎

Lines changed: 58 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@ import com.onesignal.session.internal.session.ISessionService
2424
import com.onesignal.session.internal.session.SessionModel
2525
import com.onesignal.session.internal.session.SessionModelStore
2626
import com.onesignal.session.internal.session.operations.CreateSessionOperation
27+
import com.onesignal.session.internal.session.operations.UpdateSessionOperation
2728
import com.onesignal.user.internal.backend.IdentityConstants
2829
import com.onesignal.user.internal.identity.IdentityModelStore
30+
import kotlinx.coroutines.withTimeoutOrNull
2931
import java.util.UUID
3032
import kotlin.reflect.KMutableProperty1
3133

@@ -132,21 +134,30 @@ internal class SessionService(
132134
* the SDK.
133135
*/
134136
override suspend fun backgroundRun() {
135-
endSession()
137+
val end = endSession() ?: return
138+
// Android 15+ blocks network requests started after this job finishes, so send the end now
139+
// rather than after the queue's batching delay. Flushing is bounded to once per session.
140+
// On timeout the end stays queued and is sent on the next app open.
141+
val sent = withTimeoutOrNull(END_SESSION_SEND_TIMEOUT_MS) { operationRepo.enqueueAndWait(end, flush = true) }
142+
Logging.debug("SessionService.backgroundRun: session end sent: $sent")
136143
}
137144

138-
private fun endSession() {
145+
/**
146+
* @return the operation that ends the session through the sessions API, for the caller to enqueue.
147+
*/
148+
private fun endSession(): UpdateSessionOperation? {
139149
// Defensive: if bootstrap() has not run yet, there is no session state to end.
140150
// This can happen when SyncJobService races with
141151
// an in-flight initWithContext that has not yet reached bootstrapServices().
142-
val session = this.session ?: return
143-
if (!session.isValid) return
152+
val session = this.session?.takeIf { it.isValid } ?: return null
144153
val activeDuration = session.activeDuration
145154
Logging.debug("SessionService.backgroundRun: Session ended. activeDuration: $activeDuration")
146155

147156
session.isValid = false
157+
val end = if (session.usesSessionsApi) endSessionOperation(session, config?.appId) else null
148158
sessionLifeCycleNotifier.fire { it.onSessionEnded(activeDuration) }
149159
session.activeDuration = 0L
160+
return end
150161
}
151162

152163
/**
@@ -184,7 +195,7 @@ internal class SessionService(
184195
// Treat app cold starts as a new session, we attempt to end any previous session to do this.
185196
if (!hasFocused) {
186197
hasFocused = true
187-
endSession()
198+
endSession()?.let { operationRepo.enqueue(it) }
188199
}
189200

190201
if (!session.isValid) {
@@ -244,6 +255,7 @@ internal class SessionService(
244255
unfocusTimeMs - session.focusTime
245256
}
246257
session.activeDuration += dt
258+
session.unfocusTime = unfocusTimeMs
247259
Logging.log(LogLevel.DEBUG, "SessionService.onUnfocused adding time $dt for total: ${session.activeDuration}")
248260
}
249261

@@ -257,28 +269,59 @@ internal class SessionService(
257269

258270
override val hasSubscribers: Boolean
259271
get() = sessionLifeCycleNotifier.hasSubscribers
272+
273+
companion object {
274+
// Covers the post-create delay when the create is still queued, plus the request itself.
275+
private const val END_SESSION_SEND_TIMEOUT_MS = 30_000L
276+
}
260277
}
261278

262279
private fun createSessionOperation(
263280
session: SessionModel,
264281
appId: String?,
265282
externalId: String?,
266-
): CreateSessionOperation? {
283+
): CreateSessionOperation? =
284+
withSessionIds(session, appId, "creating") { resolvedAppId, onesignalId, subscriptionId ->
285+
CreateSessionOperation(
286+
appId = resolvedAppId,
287+
localSessionId = session.localSessionId,
288+
onesignalId = onesignalId,
289+
subscriptionId = subscriptionId,
290+
startTime = session.startTime,
291+
externalId = externalId,
292+
)
293+
}
294+
295+
private fun endSessionOperation(
296+
session: SessionModel,
297+
appId: String?,
298+
): UpdateSessionOperation? =
299+
withSessionIds(session, appId, "ending") { resolvedAppId, onesignalId, subscriptionId ->
300+
UpdateSessionOperation(
301+
appId = resolvedAppId,
302+
sessionId = session.serverSessionId ?: session.localSessionId,
303+
onesignalId = onesignalId,
304+
subscriptionId = subscriptionId,
305+
activeDuration = session.activeDuration,
306+
// An app killed while focused has no unfocus after its last focus.
307+
endTime = maxOf(session.unfocusTime ?: 0L, session.focusTime),
308+
)
309+
}
310+
311+
private fun <T> withSessionIds(
312+
session: SessionModel,
313+
appId: String?,
314+
action: String,
315+
block: (appId: String, onesignalId: String, subscriptionId: String) -> T,
316+
): T? {
267317
val onesignalId = session.onesignalId
268318
val subscriptionId = session.subscriptionId
269319
if (appId == null || onesignalId == null || subscriptionId == null) {
270320
Logging.warn(
271-
"SessionService: not creating session ${session.sessionId}, missing appId: ${appId == null}, " +
321+
"SessionService: not $action session ${session.sessionId}, missing appId: ${appId == null}, " +
272322
"onesignalId: ${onesignalId == null}, subscriptionId: ${subscriptionId == null}",
273323
)
274324
return null
275325
}
276-
return CreateSessionOperation(
277-
appId = appId,
278-
localSessionId = session.localSessionId,
279-
onesignalId = onesignalId,
280-
subscriptionId = subscriptionId,
281-
startTime = session.startTime,
282-
externalId = externalId,
283-
)
326+
return block(appId, onesignalId, subscriptionId)
284327
}

‎OneSignalSDK/onesignal/core/src/test/java/com/onesignal/session/internal/session/SessionServiceTests.kt‎

Lines changed: 174 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,14 @@ import com.onesignal.mocks.MockHelper
1919
import com.onesignal.mocks.MockPreferencesService
2020
import com.onesignal.session.internal.session.impl.SessionService
2121
import com.onesignal.session.internal.session.operations.CreateSessionOperation
22+
import com.onesignal.session.internal.session.operations.UpdateSessionOperation
2223
import com.onesignal.user.internal.backend.IdentityConstants
2324
import com.onesignal.user.internal.identity.IdentityModel
2425
import io.kotest.core.spec.style.FunSpec
2526
import io.kotest.matchers.shouldBe
2627
import io.kotest.matchers.shouldNotBe
28+
import io.mockk.coEvery
29+
import io.mockk.coVerify
2730
import io.mockk.every
2831
import io.mockk.just
2932
import io.mockk.mockk
@@ -37,19 +40,21 @@ import io.mockk.unmockkStatic
3740
import io.mockk.verify
3841
import io.mockk.verifyOrder
3942
import kotlinx.coroutines.Job
43+
import kotlinx.coroutines.awaitCancellation
44+
import kotlinx.coroutines.test.runTest
4045

4146
// Mocks used by every test in this file
4247
private class Mocks(
4348
var sessionsApiEnabled: Boolean = false,
4449
) {
45-
val currentTime = 1111L
50+
var currentTime = 1111L
4651
var elapsedRealtime = 5000L
4752

4853
private val mockSessionModelStore = MockHelper.sessionModelStore()
4954

5055
val time: ITime =
5156
mockk<ITime>().also {
52-
every { it.currentTimeMillis } returns currentTime
57+
every { it.currentTimeMillis } answers { currentTime }
5358
every { it.elapsedRealtimeMillis } answers { elapsedRealtime }
5459
}
5560

@@ -94,6 +99,7 @@ private class Mocks(
9499
val operationRepo: IOperationRepo =
95100
mockk<IOperationRepo>().also {
96101
every { it.enqueue(capture(enqueued), any()) } just runs
102+
coEvery { it.enqueueAndWait(capture(enqueued), any()) } returns true
97103
}
98104

99105
fun sessionModelStore(action: ((SessionModel) -> Unit)? = null): SessionModelStore {
@@ -493,7 +499,7 @@ class SessionServiceTests : FunSpec({
493499
sessionService.onFocus(false)
494500

495501
// Then
496-
val creates = mocks.enqueued.map { it as CreateSessionOperation }
502+
val creates = mocks.enqueued.filterIsInstance<CreateSessionOperation>()
497503
creates.size shouldBe 2
498504
creates.map { it.localSessionId }.distinct().size shouldBe 2
499505
creates.map { it.idempotencyKey }.distinct().size shouldBe 2
@@ -572,6 +578,169 @@ class SessionServiceTests : FunSpec({
572578
verify(exactly = 1) { mocks.spyCallback.onSessionStarted() }
573579
}
574580

581+
test("background run sends the end with the unfocus time and final duration when the flag is on") {
582+
// Given
583+
val mocks = Mocks(sessionsApiEnabled = true)
584+
val sessionService = mocks.sessionService
585+
sessionService.bootstrap()
586+
sessionService.start()
587+
val sessionModelStore = mocks.sessionModelStore { it.isValid = false }
588+
sessionService.onFocus(false)
589+
mocks.elapsedRealtime += 750L
590+
mocks.currentTime = 2222L
591+
sessionService.onUnfocused()
592+
mocks.currentTime = 32222L
593+
594+
// When
595+
sessionService.backgroundRun()
596+
597+
// Then
598+
val end = mocks.enqueued.filterIsInstance<UpdateSessionOperation>().single()
599+
end.appId shouldBe MockHelper.DEFAULT_APP_ID
600+
end.sessionId shouldBe sessionModelStore.model.localSessionId
601+
end.onesignalId shouldBe Mocks.ONESIGNAL_ID
602+
end.subscriptionId shouldBe Mocks.SUBSCRIPTION_ID
603+
end.activeDuration shouldBe 750L
604+
end.endTime shouldBe 2222L
605+
coVerify(exactly = 1) { mocks.operationRepo.enqueueAndWait(end, true) }
606+
sessionModelStore.model.isValid shouldBe false
607+
}
608+
609+
test("background run ends the session by its server session ID once created") {
610+
// Given
611+
val mocks = Mocks(sessionsApiEnabled = true)
612+
val sessionService = mocks.sessionService
613+
sessionService.bootstrap()
614+
sessionService.start()
615+
val sessionModelStore = mocks.sessionModelStore { it.isValid = false }
616+
sessionService.onFocus(false)
617+
sessionModelStore.model.serverSessionId = "server-session-id"
618+
sessionService.onUnfocused()
619+
620+
// When
621+
sessionService.backgroundRun()
622+
623+
// Then
624+
val end = mocks.enqueued.filterIsInstance<UpdateSessionOperation>().single()
625+
end.sessionId shouldBe "server-session-id"
626+
}
627+
628+
test("background run returns when the end is not sent in time and leaves it queued") {
629+
// Given
630+
val mocks = Mocks(sessionsApiEnabled = true)
631+
coEvery { mocks.operationRepo.enqueueAndWait(any(), any()) } coAnswers { awaitCancellation() }
632+
val sessionService = mocks.sessionService
633+
sessionService.bootstrap()
634+
sessionService.start()
635+
val sessionModelStore = mocks.sessionModelStore { it.isValid = false }
636+
sessionService.onFocus(false)
637+
sessionService.onUnfocused()
638+
639+
// When
640+
runTest { sessionService.backgroundRun() }
641+
642+
// Then
643+
coVerify(exactly = 1) { mocks.operationRepo.enqueueAndWait(any<UpdateSessionOperation>(), true) }
644+
sessionModelStore.model.isValid shouldBe false
645+
}
646+
647+
test("cold start ends the previous sessions API session before creating a new one") {
648+
// Given
649+
val mocks = Mocks(sessionsApiEnabled = true)
650+
mocks.sessionModelStore {
651+
it.isValid = true
652+
it.sessionId = "previous-session"
653+
it.localSessionId = "local-previous-session"
654+
it.usesSessionsApi = true
655+
it.onesignalId = Mocks.ONESIGNAL_ID
656+
it.subscriptionId = Mocks.SUBSCRIPTION_ID
657+
it.serverSessionId = "previous-server-session-id"
658+
it.focusTime = 500L
659+
it.unfocusTime = 900L
660+
it.activeDuration = 400L
661+
}
662+
val sessionService = mocks.sessionService
663+
sessionService.bootstrap()
664+
sessionService.start()
665+
666+
// When
667+
sessionService.onFocus(false)
668+
669+
// Then
670+
val end = mocks.enqueued[0] as UpdateSessionOperation
671+
end.sessionId shouldBe "previous-server-session-id"
672+
end.activeDuration shouldBe 400L
673+
end.endTime shouldBe 900L
674+
(mocks.enqueued[1] is CreateSessionOperation) shouldBe true
675+
coVerify(exactly = 0) { mocks.operationRepo.enqueueAndWait(any(), any()) }
676+
}
677+
678+
test("cold start after a kill while focused ends the previous session at its last focus") {
679+
// Given
680+
val mocks = Mocks(sessionsApiEnabled = true)
681+
mocks.sessionModelStore {
682+
it.isValid = true
683+
it.sessionId = "previous-session"
684+
it.localSessionId = "local-previous-session"
685+
it.usesSessionsApi = true
686+
it.onesignalId = Mocks.ONESIGNAL_ID
687+
it.subscriptionId = Mocks.SUBSCRIPTION_ID
688+
it.unfocusTime = 300L
689+
it.focusTime = 500L
690+
}
691+
val sessionService = mocks.sessionService
692+
sessionService.bootstrap()
693+
sessionService.start()
694+
695+
// When
696+
sessionService.onFocus(false)
697+
698+
// Then
699+
val end = mocks.enqueued.filterIsInstance<UpdateSessionOperation>().single()
700+
end.endTime shouldBe 500L
701+
}
702+
703+
test("session end does not send an end when the session uses the legacy path") {
704+
// Given
705+
val mocks = Mocks(sessionsApiEnabled = false)
706+
val sessionService = mocks.sessionService
707+
sessionService.bootstrap()
708+
sessionService.start()
709+
mocks.sessionModelStore { it.isValid = false }
710+
sessionService.subscribe(mocks.spyCallback)
711+
sessionService.onFocus(false)
712+
sessionService.onUnfocused()
713+
mocks.sessionsApiEnabled = true
714+
715+
// When
716+
sessionService.backgroundRun()
717+
718+
// Then
719+
mocks.enqueued shouldBe emptyList()
720+
coVerify(exactly = 0) { mocks.operationRepo.enqueueAndWait(any(), any()) }
721+
verify(exactly = 1) { mocks.spyCallback.onSessionEnded(any()) }
722+
}
723+
724+
test("session end does not send an end without a push subscription ID") {
725+
// Given
726+
val mocks = Mocks(sessionsApiEnabled = true)
727+
mocks.configModelStore.model.pushSubscriptionId = null
728+
val sessionService = mocks.sessionService
729+
sessionService.bootstrap()
730+
sessionService.start()
731+
mocks.sessionModelStore { it.isValid = false }
732+
sessionService.subscribe(mocks.spyCallback)
733+
sessionService.onFocus(false)
734+
sessionService.onUnfocused()
735+
736+
// When
737+
sessionService.backgroundRun()
738+
739+
// Then
740+
mocks.enqueued shouldBe emptyList()
741+
verify(exactly = 1) { mocks.spyCallback.onSessionEnded(any()) }
742+
}
743+
575744
test("sessions API active duration uses the monotonic clock") {
576745
// Given
577746
val mocks = Mocks(sessionsApiEnabled = true)
@@ -639,6 +808,7 @@ class SessionServiceTests : FunSpec({
639808
store.model.sessionId = "session-id"
640809
store.model.startTime = 123L
641810
store.model.activeDuration = 456L
811+
store.model.unfocusTime = 321L
642812
store.model.focusElapsedRealtime = 789L
643813
store.model.usesSessionsApi = true
644814
store.model.onesignalId = Mocks.ONESIGNAL_ID
@@ -652,6 +822,7 @@ class SessionServiceTests : FunSpec({
652822
reloaded.sessionId shouldBe "session-id"
653823
reloaded.startTime shouldBe 123L
654824
reloaded.activeDuration shouldBe 456L
825+
reloaded.unfocusTime shouldBe 321L
655826
reloaded.focusElapsedRealtime shouldBe 789L
656827
reloaded.usesSessionsApi shouldBe true
657828
reloaded.onesignalId shouldBe Mocks.ONESIGNAL_ID

0 commit comments

Comments
 (0)