@@ -16,6 +16,8 @@ import com.onesignal.core.internal.startup.IStartableService
1616import com.onesignal.core.internal.time.ITime
1717import com.onesignal.debug.LogLevel
1818import com.onesignal.debug.internal.logging.Logging
19+ import com.onesignal.session.internal.session.operations.CreateSessionOperation
20+ import com.onesignal.session.internal.session.operations.SessionStateModelStore
1921import com.onesignal.user.internal.jwt.JwtRequirement
2022import com.onesignal.user.internal.jwt.JwtTokenStore
2123import com.onesignal.user.internal.operations.LoginUserOperation
@@ -33,6 +35,7 @@ import kotlin.math.min
3335import kotlin.random.Random
3436import kotlin.reflect.KClass
3537
38+ @Suppress(" LongParameterList" )
3639internal 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 /* *
0 commit comments