Repository navigation
feat: [SDK-5378] persist and retry sessions API requests through OperationRepo #2794
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
fadi-george
merged 8 commits into
new-session-events
from
fadi/SDK-5378-android-persistent-queue-retry
Oct 19, 2026
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8556e1a
feat: [SDK-5378] persist and retry sessions API requests through Oper…
fadi-george 60eccf8
fix: [SDK-5378] retry offline session requests and tighten session qu…
fadi-george b02b574
fix(session): avoid stalling queue on create delay
fadi-george 34f233c
fix(session): tighten queue rules for updates/consent
fadi-george ee433af
fix(session): drop anonymous creates at enqueue and record restored ends
fadi-george e03fff6
test: deflake post-create delay and enqueue debounce tests
fadi-george 95f3c22
test: clear prefs before each SDKInitTests case
fadi-george 355c8a0
refactor: [SDK-5378] keep a session's created and closed state in one…
fadi-george File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
187 changes: 187 additions & 0 deletions
187
...gnal/core/src/main/java/com/onesignal/core/internal/operations/impl/SessionQueuePolicy.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| package com.onesignal.core.internal.operations.impl | ||
|
|
||
| import com.onesignal.common.IDManager | ||
| import com.onesignal.common.modeling.SimpleModelStore | ||
| import com.onesignal.core.internal.operations.Operation | ||
| import com.onesignal.debug.internal.logging.Logging | ||
| import com.onesignal.session.internal.session.operations.CreateSessionOperation | ||
| import com.onesignal.session.internal.session.operations.SessionStateModel | ||
| import com.onesignal.session.internal.session.operations.UpdateSessionOperation | ||
|
|
||
| /** | ||
| * Queue rules for sessions API operations in [OperationRepo]. Every function must be called while | ||
| * holding the queue lock. Functions return the queue items they removed; the caller drops them | ||
| * from the store and wakes their waiters. | ||
| */ | ||
| internal class SessionQueuePolicy( | ||
| private val maxQueued: Int = MAX_QUEUED_SESSION_OPERATIONS, | ||
| // Without consent HttpClient fails every request, so these must not be stored or sent. | ||
| private val awaitingConsent: () -> Boolean = { false }, | ||
| private val sessions: SimpleModelStore<SessionStateModel> = SimpleModelStore({ SessionStateModel() }), | ||
| ) { | ||
| // Recent local -> backend ID translations, for an operation built from a local ID just before | ||
| // its record was created but enqueued after the queue was translated. | ||
| private val recentTranslations = | ||
| object : LinkedHashMap<String, String>() { | ||
| override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, String>?) = size > MAX_RECENT_TRANSLATIONS | ||
| } | ||
|
|
||
| fun recordTranslations(idTranslations: Map<String, String>) { | ||
| recentTranslations.putAll(idTranslations) | ||
| sessions.list().forEach { it.translateIds(idTranslations) } | ||
| } | ||
|
|
||
| class EnqueueResult( | ||
| val accept: Boolean, | ||
| val removed: List<OperationRepo.OperationQueueItem> = emptyList(), | ||
| ) | ||
|
|
||
| fun onEnqueue( | ||
| queue: MutableList<OperationRepo.OperationQueueItem>, | ||
| incoming: OperationRepo.OperationQueueItem, | ||
| ): EnqueueResult { | ||
| val op = incoming.operation | ||
| if (!op.isSessionOperation) return EnqueueResult(accept = true) | ||
| op.translateIds(recentTranslations) | ||
|
|
||
| val result = | ||
| when { | ||
| awaitingConsent() -> { | ||
| Logging.debug("SessionQueuePolicy: privacy consent not given, dropping $op") | ||
| EnqueueResult(accept = false) | ||
| } | ||
| op is UpdateSessionOperation -> admitUpdate(queue, incoming, op) | ||
| else -> admit(queue, incoming) | ||
| } | ||
| // Its updates could never be sent. | ||
| if (!result.accept && op is CreateSessionOperation) updateState(op.localSessionId, queue) { it.isClosed = true } | ||
| return result | ||
| } | ||
|
|
||
| private fun admitUpdate( | ||
| queue: MutableList<OperationRepo.OperationQueueItem>, | ||
| incoming: OperationRepo.OperationQueueItem, | ||
| op: UpdateSessionOperation, | ||
| ): EnqueueResult { | ||
| val state = stateFor(op.sessionId) | ||
| state?.serverSessionId?.let { op.translateIds(mapOf(op.sessionId to it)) } | ||
| val rejection = | ||
| when { | ||
| state?.isClosed == true || hasQueuedEnd(queue, op.sessionId) -> "is closed" | ||
| IDManager.isLocalId(op.sessionId) && state?.onesignalId == null -> "has no create" | ||
| else -> null | ||
| } | ||
| if (rejection != null) { | ||
| Logging.debug("SessionQueuePolicy: session ${op.sessionId} $rejection, dropping $op") | ||
| return EnqueueResult(accept = false) | ||
| } | ||
| state?.let { op.useCreateIds(it.onesignalId, it.subscriptionId) } | ||
| return admit(queue, incoming) | ||
| } | ||
|
|
||
| private fun admit( | ||
| queue: MutableList<OperationRepo.OperationQueueItem>, | ||
| incoming: OperationRepo.OperationQueueItem, | ||
| ): EnqueueResult { | ||
| val op = incoming.operation | ||
| val removed = mutableListOf<OperationRepo.OperationQueueItem>() | ||
| if (op is UpdateSessionOperation) { | ||
| val unsent = queue.filter { (it.operation as? UpdateSessionOperation)?.sessionId == op.sessionId } | ||
| // Durations are cumulative, so the newest update carries everything the unsent ones would. | ||
| unsent.forEach { | ||
| val replaced = it.operation as UpdateSessionOperation | ||
| op.activeDuration = maxOf(op.activeDuration, replaced.activeDuration) | ||
| incoming.retries = maxOf(incoming.retries, it.retries) | ||
| incoming.retryAt = maxOf(incoming.retryAt, it.retryAt) | ||
| val waiters = synchronized(it) { it.waiters.toList().also { _ -> it.waiters.clear() } } | ||
| incoming.attachOrWake(waiters) | ||
| } | ||
| queue.removeAll(unsent) | ||
| removed.addAll(unsent) | ||
| } | ||
|
|
||
| var accept = true | ||
| while (queue.count { it.operation.isSessionOperation } + (if (accept) 1 else 0) > maxQueued) { | ||
| val oldestSession = queue.first { it.operation.isSessionOperation }.operation.sessionKey | ||
| val dropped = queue.filter { it.operation.sessionKey == oldestSession } | ||
| Logging.warn("SessionQueuePolicy: more than $maxQueued sessions API operations queued, dropping session $oldestSession") | ||
| queue.removeAll(dropped) | ||
| removed.addAll(dropped) | ||
| if (op.sessionKey == oldestSession) accept = false | ||
| } | ||
| if (accept && op is CreateSessionOperation) { | ||
| updateState(op.localSessionId, queue) { | ||
| it.onesignalId = op.onesignalId | ||
| it.subscriptionId = op.subscriptionId | ||
| } | ||
| } | ||
| if (accept && op is UpdateSessionOperation && op.isEnd) updateState(op.sessionId, queue) { it.isClosed = true } | ||
| return EnqueueResult(accept, removed) | ||
| } | ||
|
|
||
| /** Removes and rejects updates that can never send because [dropped] was their session's create. */ | ||
| fun onDropped( | ||
| queue: MutableList<OperationRepo.OperationQueueItem>, | ||
| dropped: Operation, | ||
| ): List<OperationRepo.OperationQueueItem> { | ||
| if (dropped !is CreateSessionOperation) return emptyList() | ||
| updateState(dropped.localSessionId, queue) { it.isClosed = true } | ||
| val orphans = queue.filter { (it.operation as? UpdateSessionOperation)?.sessionId == dropped.localSessionId } | ||
| if (orphans.isNotEmpty()) { | ||
| Logging.debug("SessionQueuePolicy: create for session ${dropped.localSessionId} was dropped, dropping ${orphans.size} updates") | ||
| queue.removeAll(orphans) | ||
| } | ||
| return orphans | ||
| } | ||
|
|
||
| private fun stateFor(sessionId: String) = sessions.list().firstOrNull { it.id == sessionId || it.serverSessionId == sessionId } | ||
|
|
||
| private fun updateState( | ||
| sessionKey: String, | ||
| queue: List<OperationRepo.OperationQueueItem>, | ||
| change: (SessionStateModel) -> Unit, | ||
| ) { | ||
| val existing = stateFor(sessionKey) | ||
| if (existing != null) { | ||
| change(existing) | ||
| } else { | ||
| sessions.add(SessionStateModel().also { it.id = sessionKey }.also(change)) | ||
| } | ||
| trimSessions(queue, sessionKey) | ||
| } | ||
|
|
||
| /** Drops the oldest sessions past the cap, but never one with operations still queued, which need its state. */ | ||
| private fun trimSessions( | ||
| queue: List<OperationRepo.OperationQueueItem>, | ||
| keep: String, | ||
| ) { | ||
| val all = sessions.list() | ||
| val excess = all.size - maxQueued | ||
| if (excess <= 0) return | ||
| val queuedSessions = queue.mapNotNull { it.operation.sessionKey }.toSet() + keep | ||
| all | ||
| .filter { it.id !in queuedSessions && it.serverSessionId !in queuedSessions } | ||
| .take(excess) | ||
| .forEach { sessions.remove(it.id) } | ||
| } | ||
|
|
||
| private fun hasQueuedEnd( | ||
| queue: List<OperationRepo.OperationQueueItem>, | ||
| sessionId: String, | ||
| ) = queue.any { (it.operation as? UpdateSessionOperation)?.let { update -> update.sessionId == sessionId && update.isEnd } == true } | ||
|
|
||
| private val Operation.isSessionOperation get() = this is CreateSessionOperation || this is UpdateSessionOperation | ||
|
|
||
| private val Operation.sessionKey: String? | ||
| get() = | ||
| when (this) { | ||
| is CreateSessionOperation -> localSessionId | ||
| is UpdateSessionOperation -> sessionId | ||
| else -> null | ||
| } | ||
|
|
||
| companion object { | ||
| const val MAX_QUEUED_SESSION_OPERATIONS = 100 | ||
| private const val MAX_RECENT_TRANSLATIONS = 50 | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.