Skip to content

Commit 8421a13

Browse files
fadi-georgeclaude
andauthored
feat: [SDK-5378] persist and retry sessions API requests through OperationRepo (#2794)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f8181e6 commit 8421a13

17 files changed

Lines changed: 1231 additions & 24 deletions

File tree

‎OneSignalSDK/onesignal/core/src/main/java/com/onesignal/core/CoreModule.kt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import com.onesignal.logger.IObservabilityEventRecorder
5555
import com.onesignal.logger.LoggerFactory
5656
import com.onesignal.notifications.INotificationsManager
5757
import com.onesignal.notifications.internal.MisconfiguredNotificationsManager
58+
import com.onesignal.session.internal.session.operations.SessionStateModelStore
5859
import com.onesignal.user.internal.jwt.JwtTokenStore
5960

6061
internal class CoreModule : IModule {
@@ -92,6 +93,7 @@ internal class CoreModule : IModule {
9293

9394
// Operations
9495
builder.register<OperationModelStore>().provides<OperationModelStore>()
96+
builder.register<SessionStateModelStore>().provides<SessionStateModelStore>()
9597
builder.register<OperationRepo>()
9698
.provides<IOperationRepo>()
9799
.provides<IStartableService>()

‎OneSignalSDK/onesignal/core/src/main/java/com/onesignal/core/internal/operations/impl/OperationModelStore.kt‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import com.onesignal.common.modeling.ModelStore
44
import com.onesignal.core.internal.operations.Operation
55
import com.onesignal.core.internal.preferences.IPreferencesService
66
import com.onesignal.debug.internal.logging.Logging
7+
import com.onesignal.session.internal.session.operations.CreateSessionOperation
8+
import com.onesignal.session.internal.session.operations.UpdateSessionOperation
9+
import com.onesignal.session.internal.session.operations.impl.SessionOperationExecutor
710
import com.onesignal.user.internal.operations.CreateSubscriptionOperation
811
import com.onesignal.user.internal.operations.DeleteAliasOperation
912
import com.onesignal.user.internal.operations.DeleteSubscriptionOperation
@@ -63,6 +66,8 @@ internal class OperationModelStore(prefs: IPreferencesService) : ModelStore<Oper
6366
UpdateUserOperationExecutor.TRACK_SESSION_END -> TrackSessionEndOperation()
6467
UpdateUserOperationExecutor.TRACK_PURCHASE -> TrackPurchaseOperation()
6568
CustomEventOperationExecutor.CUSTOM_EVENT -> TrackCustomEventOperation()
69+
SessionOperationExecutor.CREATE_SESSION -> CreateSessionOperation()
70+
SessionOperationExecutor.UPDATE_SESSION -> UpdateSessionOperation()
6671
else -> throw Exception("Unrecognized operation: $operationName")
6772
}
6873

‎OneSignalSDK/onesignal/core/src/main/java/com/onesignal/core/internal/operations/impl/OperationRepo.kt‎

Lines changed: 52 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import com.onesignal.core.internal.startup.IStartableService
1616
import com.onesignal.core.internal.time.ITime
1717
import com.onesignal.debug.LogLevel
1818
import com.onesignal.debug.internal.logging.Logging
19+
import com.onesignal.session.internal.session.operations.CreateSessionOperation
20+
import com.onesignal.session.internal.session.operations.SessionStateModelStore
1921
import com.onesignal.user.internal.jwt.JwtRequirement
2022
import com.onesignal.user.internal.jwt.JwtTokenStore
2123
import com.onesignal.user.internal.operations.LoginUserOperation
@@ -33,6 +35,7 @@ import kotlin.math.min
3335
import kotlin.random.Random
3436
import kotlin.reflect.KClass
3537

38+
@Suppress("LongParameterList")
3639
internal class OperationRepo(
3740
executors: List<IOperationExecutor>,
3841
private val _operationModelStore: OperationModelStore,
@@ -41,6 +44,7 @@ internal class OperationRepo(
4144
private val _newRecordState: NewRecordsState,
4245
private val _jwtTokenStore: JwtTokenStore,
4346
private val _identityVerificationService: IdentityVerificationService,
47+
sessionStateStore: SessionStateModelStore,
4448
) : IOperationRepo, IStartableService {
4549

4650
internal class OperationQueueItem(
@@ -107,6 +111,11 @@ internal class OperationRepo(
107111
private val inFlightLogins = mutableMapOf<String, OperationQueueItem>()
108112
private val waiter = WaiterWithValue<LoopWaiterMessage>()
109113
private var paused = false
114+
private val sessionQueuePolicy =
115+
SessionQueuePolicy(
116+
awaitingConsent = { _configModelStore.model.let { it.consentRequired == true && it.consentGiven != true } },
117+
sessions = sessionStateStore,
118+
)
110119

111120
// Guarded by queue. Set by a force that lands while ops are out of the queue executing.
112121
private var forcedDuringExecute = false
@@ -187,7 +196,7 @@ internal class OperationRepo(
187196

188197
operation.id = UUID.randomUUID().toString()
189198
scope.launch {
190-
internalEnqueue(OperationQueueItem(operation, bucket = enqueueIntoBucket), flush, true)
199+
enqueueNew(OperationQueueItem(operation, bucket = enqueueIntoBucket), flush)
191200
}
192201
}
193202

@@ -202,7 +211,7 @@ internal class OperationRepo(
202211
operation.id = UUID.randomUUID().toString()
203212
val waiter = WaiterWithValue<OperationWaitResult>()
204213
scope.launch {
205-
internalEnqueue(OperationQueueItem(operation, waiter, bucket = enqueueIntoBucket), flush, true)
214+
enqueueNew(OperationQueueItem(operation, waiter, bucket = enqueueIntoBucket), flush)
206215
}
207216
val timeoutMs = _configModelStore.model.opRepoAwaitTimeout
208217
return withTimeoutOrNull(timeoutMs) {
@@ -218,12 +227,14 @@ internal class OperationRepo(
218227
* they cannot be authenticated and would otherwise sit in the queue forever, blocked by
219228
* `hasValidJwtIfRequired`. LoginUserOperation is exempt because it's enqueued
220229
* intentionally during logout and purged later by [removeOperationsWithoutExternalId]
221-
* if needed. Outer-gated on `newCodePathsRun` so Phase 1 customers stay byte-for-byte
230+
* if needed. Ops with `requiresJwt = false` are exempt since they can still execute, except a
231+
* session create that waits on an anonymous user or subscription that will never be created.
232+
* Outer-gated on `newCodePathsRun` so Phase 1 customers stay byte-for-byte
222233
* on the legacy enqueue path.
223234
*/
224235
private fun shouldSuppressAnonymousOp(op: Operation): Boolean {
225236
if (!_identityVerificationService.newCodePathsRun) return false
226-
if (op is LoginUserOperation) return false
237+
if (op is LoginUserOperation || !(op.requiresJwt || op.waitsForAnonymousUser)) return false
227238
val suppress =
228239
_configModelStore.model.useIdentityVerification == JwtRequirement.REQUIRED &&
229240
op.externalId == null
@@ -233,6 +244,23 @@ internal class OperationRepo(
233244
return suppress
234245
}
235246

247+
private fun enqueueNew(
248+
queueItem: OperationQueueItem,
249+
flush: Boolean,
250+
) {
251+
val accepted =
252+
synchronized(queue) {
253+
val result = sessionQueuePolicy.onEnqueue(queue, queueItem)
254+
dropAndWake(result.removed)
255+
result.accept
256+
}
257+
if (accepted) {
258+
internalEnqueue(queueItem, flush, true)
259+
} else {
260+
queueItem.wakeWaiters(OperationWaitResult(false))
261+
}
262+
}
263+
236264
/**
237265
* Only used inside this class, adds OperationQueueItem to queue
238266
* WARNING: Never set flush=true until budget rules are added, even for internal use!
@@ -353,16 +381,18 @@ internal class OperationRepo(
353381
}
354382

355383
/**
356-
* Drops queued operations whose externalId is null. Called by the IV-aware HYDRATE
384+
* Drops queued operations whose externalId is null and that require a JWT, or that wait for an
385+
* anonymous user, which is never created under IV. Called by the IV-aware HYDRATE
357386
* choreography in [OperationRepoIvExtensions] when `jwt_required` becomes REQUIRED
358387
* to evict anon ops that can no longer execute.
359388
*/
360389
internal fun removeOperationsWithoutExternalId() {
361390
val removedIds: List<String> =
362391
synchronized(queue) {
363-
val anonymous = queue.filter { it.operation.externalId == null }
392+
val unsendable = queue.filter { it.operation.externalId == null && (it.operation.requiresJwt || it.operation.waitsForAnonymousUser) }
393+
queue.removeAll(unsendable)
394+
val anonymous = unsendable + unsendable.flatMap { sessionQueuePolicy.onDropped(queue, it.operation) }
364395
anonymous.forEach { it.wakeWaiters(OperationWaitResult(false)) }
365-
queue.removeAll(anonymous)
366396
// IV=ON never transfers anonymous state; clear existingOnesignalId so the
367397
// executor takes the createUser (upsert) path. The merge-anon-into-identified
368398
// path can't dispatch under IV — anon user creation requires a JWT-less call
@@ -382,6 +412,10 @@ internal class OperationRepo(
382412
removedIds.forEach { _operationModelStore.remove(it) }
383413
}
384414

415+
// Session ops take no JWT, but a create can't be sent until its user and subscription exist.
416+
private val Operation.waitsForAnonymousUser: Boolean
417+
get() = this is CreateSessionOperation && (IDManager.isLocalId(onesignalId) || IDManager.isLocalId(subscriptionId))
418+
385419
/**
386420
* Post-HYDRATE maintenance: scheduled on IO so it runs *after* `loadSavedOperations`
387421
* populates the queue (fix for an earlier race where the purge ran against an empty
@@ -454,6 +488,7 @@ internal class OperationRepo(
454488
ops.forEach { it.operation.translateIds(response.idTranslations) }
455489
synchronized(queue) {
456490
queue.forEach { it.operation.translateIds(response.idTranslations) }
491+
sessionQueuePolicy.recordTranslations(response.idTranslations)
457492
}
458493
response.idTranslations.values.forEach { _newRecordState.add(it) }
459494
}
@@ -560,7 +595,14 @@ internal class OperationRepo(
560595
}
561596

562597
if (response.idTranslations != null) {
563-
delayForPostCreate(_configModelStore.model.opRepoPostCreateDelay)
598+
val postCreateDelay = _configModelStore.model.opRepoPostCreateDelay
599+
// A new session's only dependents are its updates, which NewRecordsState holds back,
600+
// so only the wake is delayed.
601+
if (ops.all { it.operation is CreateSessionOperation }) {
602+
scope.launch { delayForPostCreate(postCreateDelay) }
603+
} else {
604+
delayForPostCreate(postCreateDelay)
605+
}
564606
}
565607
} catch (e: Throwable) {
566608
Logging.log(LogLevel.ERROR, "Error attempting to execute operation: $ops", e)
@@ -582,6 +624,8 @@ internal class OperationRepo(
582624
) {
583625
ops.forEach { _operationModelStore.remove(it.operation.id) }
584626
ops.forEach { it.wakeWaiters(response.toWaitResult(false)) }
627+
val orphans = synchronized(queue) { ops.flatMap { sessionQueuePolicy.onDropped(queue, it.operation) } }
628+
if (orphans.isNotEmpty()) dropAndWake(orphans)
585629
}
586630

587631
/**
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
package com.onesignal.core.internal.operations.impl
2+
3+
import com.onesignal.common.IDManager
4+
import com.onesignal.common.modeling.SimpleModelStore
5+
import com.onesignal.core.internal.operations.Operation
6+
import com.onesignal.debug.internal.logging.Logging
7+
import com.onesignal.session.internal.session.operations.CreateSessionOperation
8+
import com.onesignal.session.internal.session.operations.SessionStateModel
9+
import com.onesignal.session.internal.session.operations.UpdateSessionOperation
10+
11+
/**
12+
* Queue rules for sessions API operations in [OperationRepo]. Every function must be called while
13+
* holding the queue lock. Functions return the queue items they removed; the caller drops them
14+
* from the store and wakes their waiters.
15+
*/
16+
internal class SessionQueuePolicy(
17+
private val maxQueued: Int = MAX_QUEUED_SESSION_OPERATIONS,
18+
// Without consent HttpClient fails every request, so these must not be stored or sent.
19+
private val awaitingConsent: () -> Boolean = { false },
20+
private val sessions: SimpleModelStore<SessionStateModel> = SimpleModelStore({ SessionStateModel() }),
21+
) {
22+
// Recent local -> backend ID translations, for an operation built from a local ID just before
23+
// its record was created but enqueued after the queue was translated.
24+
private val recentTranslations =
25+
object : LinkedHashMap<String, String>() {
26+
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, String>?) = size > MAX_RECENT_TRANSLATIONS
27+
}
28+
29+
fun recordTranslations(idTranslations: Map<String, String>) {
30+
recentTranslations.putAll(idTranslations)
31+
sessions.list().forEach { it.translateIds(idTranslations) }
32+
}
33+
34+
class EnqueueResult(
35+
val accept: Boolean,
36+
val removed: List<OperationRepo.OperationQueueItem> = emptyList(),
37+
)
38+
39+
fun onEnqueue(
40+
queue: MutableList<OperationRepo.OperationQueueItem>,
41+
incoming: OperationRepo.OperationQueueItem,
42+
): EnqueueResult {
43+
val op = incoming.operation
44+
if (!op.isSessionOperation) return EnqueueResult(accept = true)
45+
op.translateIds(recentTranslations)
46+
47+
val result =
48+
when {
49+
awaitingConsent() -> {
50+
Logging.debug("SessionQueuePolicy: privacy consent not given, dropping $op")
51+
EnqueueResult(accept = false)
52+
}
53+
op is UpdateSessionOperation -> admitUpdate(queue, incoming, op)
54+
else -> admit(queue, incoming)
55+
}
56+
// Its updates could never be sent.
57+
if (!result.accept && op is CreateSessionOperation) updateState(op.localSessionId, queue) { it.isClosed = true }
58+
return result
59+
}
60+
61+
private fun admitUpdate(
62+
queue: MutableList<OperationRepo.OperationQueueItem>,
63+
incoming: OperationRepo.OperationQueueItem,
64+
op: UpdateSessionOperation,
65+
): EnqueueResult {
66+
val state = stateFor(op.sessionId)
67+
state?.serverSessionId?.let { op.translateIds(mapOf(op.sessionId to it)) }
68+
val rejection =
69+
when {
70+
state?.isClosed == true || hasQueuedEnd(queue, op.sessionId) -> "is closed"
71+
IDManager.isLocalId(op.sessionId) && state?.onesignalId == null -> "has no create"
72+
else -> null
73+
}
74+
if (rejection != null) {
75+
Logging.debug("SessionQueuePolicy: session ${op.sessionId} $rejection, dropping $op")
76+
return EnqueueResult(accept = false)
77+
}
78+
state?.let { op.useCreateIds(it.onesignalId, it.subscriptionId) }
79+
return admit(queue, incoming)
80+
}
81+
82+
private fun admit(
83+
queue: MutableList<OperationRepo.OperationQueueItem>,
84+
incoming: OperationRepo.OperationQueueItem,
85+
): EnqueueResult {
86+
val op = incoming.operation
87+
val removed = mutableListOf<OperationRepo.OperationQueueItem>()
88+
if (op is UpdateSessionOperation) {
89+
val unsent = queue.filter { (it.operation as? UpdateSessionOperation)?.sessionId == op.sessionId }
90+
// Durations are cumulative, so the newest update carries everything the unsent ones would.
91+
unsent.forEach {
92+
val replaced = it.operation as UpdateSessionOperation
93+
op.activeDuration = maxOf(op.activeDuration, replaced.activeDuration)
94+
incoming.retries = maxOf(incoming.retries, it.retries)
95+
incoming.retryAt = maxOf(incoming.retryAt, it.retryAt)
96+
val waiters = synchronized(it) { it.waiters.toList().also { _ -> it.waiters.clear() } }
97+
incoming.attachOrWake(waiters)
98+
}
99+
queue.removeAll(unsent)
100+
removed.addAll(unsent)
101+
}
102+
103+
var accept = true
104+
while (queue.count { it.operation.isSessionOperation } + (if (accept) 1 else 0) > maxQueued) {
105+
val oldestSession = queue.first { it.operation.isSessionOperation }.operation.sessionKey
106+
val dropped = queue.filter { it.operation.sessionKey == oldestSession }
107+
Logging.warn("SessionQueuePolicy: more than $maxQueued sessions API operations queued, dropping session $oldestSession")
108+
queue.removeAll(dropped)
109+
removed.addAll(dropped)
110+
if (op.sessionKey == oldestSession) accept = false
111+
}
112+
if (accept && op is CreateSessionOperation) {
113+
updateState(op.localSessionId, queue) {
114+
it.onesignalId = op.onesignalId
115+
it.subscriptionId = op.subscriptionId
116+
}
117+
}
118+
if (accept && op is UpdateSessionOperation && op.isEnd) updateState(op.sessionId, queue) { it.isClosed = true }
119+
return EnqueueResult(accept, removed)
120+
}
121+
122+
/** Removes and rejects updates that can never send because [dropped] was their session's create. */
123+
fun onDropped(
124+
queue: MutableList<OperationRepo.OperationQueueItem>,
125+
dropped: Operation,
126+
): List<OperationRepo.OperationQueueItem> {
127+
if (dropped !is CreateSessionOperation) return emptyList()
128+
updateState(dropped.localSessionId, queue) { it.isClosed = true }
129+
val orphans = queue.filter { (it.operation as? UpdateSessionOperation)?.sessionId == dropped.localSessionId }
130+
if (orphans.isNotEmpty()) {
131+
Logging.debug("SessionQueuePolicy: create for session ${dropped.localSessionId} was dropped, dropping ${orphans.size} updates")
132+
queue.removeAll(orphans)
133+
}
134+
return orphans
135+
}
136+
137+
private fun stateFor(sessionId: String) = sessions.list().firstOrNull { it.id == sessionId || it.serverSessionId == sessionId }
138+
139+
private fun updateState(
140+
sessionKey: String,
141+
queue: List<OperationRepo.OperationQueueItem>,
142+
change: (SessionStateModel) -> Unit,
143+
) {
144+
val existing = stateFor(sessionKey)
145+
if (existing != null) {
146+
change(existing)
147+
} else {
148+
sessions.add(SessionStateModel().also { it.id = sessionKey }.also(change))
149+
}
150+
trimSessions(queue, sessionKey)
151+
}
152+
153+
/** Drops the oldest sessions past the cap, but never one with operations still queued, which need its state. */
154+
private fun trimSessions(
155+
queue: List<OperationRepo.OperationQueueItem>,
156+
keep: String,
157+
) {
158+
val all = sessions.list()
159+
val excess = all.size - maxQueued
160+
if (excess <= 0) return
161+
val queuedSessions = queue.mapNotNull { it.operation.sessionKey }.toSet() + keep
162+
all
163+
.filter { it.id !in queuedSessions && it.serverSessionId !in queuedSessions }
164+
.take(excess)
165+
.forEach { sessions.remove(it.id) }
166+
}
167+
168+
private fun hasQueuedEnd(
169+
queue: List<OperationRepo.OperationQueueItem>,
170+
sessionId: String,
171+
) = queue.any { (it.operation as? UpdateSessionOperation)?.let { update -> update.sessionId == sessionId && update.isEnd } == true }
172+
173+
private val Operation.isSessionOperation get() = this is CreateSessionOperation || this is UpdateSessionOperation
174+
175+
private val Operation.sessionKey: String?
176+
get() =
177+
when (this) {
178+
is CreateSessionOperation -> localSessionId
179+
is UpdateSessionOperation -> sessionId
180+
else -> null
181+
}
182+
183+
companion object {
184+
const val MAX_QUEUED_SESSION_OPERATIONS = 100
185+
private const val MAX_RECENT_TRANSLATIONS = 50
186+
}
187+
}

0 commit comments

Comments
 (0)