Skip to content

Commit 07db939

Browse files
fadi-georgeclaude
andauthored
feat: [SDK-5383] enqueue a session create when a new session starts (#1779)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3a1eee6 commit 07db939

7 files changed

Lines changed: 188 additions & 22 deletions

File tree

‎iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/OSSessionService.swift‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ public final class OSSessionService: NSObject {
157157
/// Leaves any open foreground interval running: the tracker reports focus before the session
158158
/// starts asynchronously, and that visit belongs to the new session. A launch in the
159159
/// background has no interval open, so nothing counts until the app becomes active.
160-
public func startNewSession(userProvider: OSSessionUserProvider) {
160+
@discardableResult
161+
public func startNewSession(userProvider: OSSessionUserProvider) -> OSSessionRecord {
161162
let user = userProvider.sessionCurrentUser
162163
let newRecord = OSSessionRecord(
163164
sessionId: UUID().uuidString,
@@ -174,6 +175,7 @@ public final class OSSessionService: NSObject {
174175
record = newRecord
175176
persist()
176177
}
178+
return newRecord
177179
}
178180

179181
func onFocus() {
@@ -267,3 +269,54 @@ public final class OSSessionService: NSObject {
267269
storage.saveObject(forKey: OSUD_SESSION_RECORD, withValue: data)
268270
}
269271
}
272+
273+
/// Decides whether a foreground starts a new session: the app must have been closed, and the SDK
274+
/// initialized, at least `threshold` seconds ago.
275+
@objc(OSSessionStartGate)
276+
public final class OSSessionStartGate: NSObject {
277+
@objc public static let shared = OSSessionStartGate()
278+
static let threshold: TimeInterval = 30
279+
280+
private let storage: OneSignalUserDefaults
281+
private let now: () -> TimeInterval
282+
private let lock = NSLock()
283+
private var initializationTime: TimeInterval = 0
284+
private var lastStartTime: TimeInterval?
285+
286+
init(
287+
storage: OneSignalUserDefaults = .initStandard(),
288+
now: @escaping () -> TimeInterval = { Date().timeIntervalSince1970 }
289+
) {
290+
self.storage = storage
291+
self.now = now
292+
super.init()
293+
}
294+
295+
@objc public func recordInitialization() {
296+
let now = now()
297+
lock.withLock { initializationTime = now }
298+
}
299+
300+
@objc public func shouldStartNewSession() -> Bool {
301+
let now = now()
302+
let lastClosedTime = storage.getSavedDouble(forKey: OSUD_APP_LAST_CLOSED_TIME, defaultValue: 0)
303+
let initializationTime = lock.withLock { self.initializationTime }
304+
let elapsed = min(now - lastClosedTime, now - initializationTime)
305+
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSSessionStartGate seconds since last closed or initialized: \(elapsed)")
306+
return elapsed >= Self.threshold
307+
}
308+
309+
/// Records a session start, unless `deduplicate` is set and a session started within the threshold.
310+
/// Recovery from a prewarm and the foreground that triggered it each start a session, in either
311+
/// order, so both pass `deduplicate` and the later one is skipped. Returns whether to start.
312+
@objc public func beginSessionStart(deduplicate: Bool) -> Bool {
313+
let now = now()
314+
return lock.withLock {
315+
if deduplicate, let lastStartTime, now - lastStartTime < Self.threshold {
316+
return false
317+
}
318+
lastStartTime = now
319+
return true
320+
}
321+
}
322+
}

‎iOS_SDK/OneSignalSDK/OneSignalOSCoreTests/OSSessionServiceTests.swift‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,3 +337,63 @@ final class OSSessionServiceTests: XCTestCase {
337337
XCTAssertEqual(restarted.currentRecord?.activeDuration, 0)
338338
}
339339
}
340+
341+
final class OSSessionStartGateTests: XCTestCase {
342+
private var now: TimeInterval = 10_000
343+
private var gate: OSSessionStartGate!
344+
345+
override func setUp() {
346+
super.setUp()
347+
now = 10_000
348+
OneSignalUserDefaults.initStandard().removeValue(forKey: OSUD_APP_LAST_CLOSED_TIME)
349+
gate = OSSessionStartGate(now: { [unowned self] in self.now })
350+
}
351+
352+
override func tearDown() {
353+
OneSignalUserDefaults.initStandard().removeValue(forKey: OSUD_APP_LAST_CLOSED_TIME)
354+
super.tearDown()
355+
}
356+
357+
private func closeApp() {
358+
OneSignalUserDefaults.initStandard().saveDouble(forKey: OSUD_APP_LAST_CLOSED_TIME, withValue: now)
359+
}
360+
361+
func testResumingWithinTheThresholdDoesNotStartASession() {
362+
gate.recordInitialization()
363+
now += 60
364+
closeApp()
365+
366+
now += 29
367+
XCTAssertFalse(gate.shouldStartNewSession())
368+
369+
now += 1
370+
XCTAssertTrue(gate.shouldStartNewSession())
371+
}
372+
373+
func testForegroundWithinTheThresholdOfInitializationDoesNotStartASession() {
374+
closeApp()
375+
now += 60
376+
gate.recordInitialization()
377+
378+
now += 29
379+
XCTAssertFalse(gate.shouldStartNewSession())
380+
381+
now += 1
382+
XCTAssertTrue(gate.shouldStartNewSession())
383+
}
384+
385+
/// A prewarm's init start does nothing, so recovery and the foreground's gated start can both run.
386+
func testOnlyOneOfTwoDeduplicatedStartsWithinTheThresholdRuns() {
387+
XCTAssertTrue(gate.beginSessionStart(deduplicate: true))
388+
XCTAssertFalse(gate.beginSessionStart(deduplicate: true))
389+
390+
now += 30
391+
XCTAssertTrue(gate.beginSessionStart(deduplicate: true))
392+
}
393+
394+
func testStartFromInitIsNeverDeduplicated() {
395+
XCTAssertTrue(gate.beginSessionStart(deduplicate: false))
396+
XCTAssertTrue(gate.beginSessionStart(deduplicate: false))
397+
XCTAssertFalse(gate.beginSessionStart(deduplicate: true))
398+
}
399+
}

‎iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl+Session.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ extension OneSignalUserManagerImpl {
4040
userExecutor!.executePendingRequestsOnNewSession()
4141
operationRepo.paused = false
4242
updatePropertiesDeltas(property: .session_count, value: 1, flush: true)
43-
OSSessionService.shared.startNewSession(userProvider: self)
43+
enqueueSessionCreate(OSSessionService.shared.startNewSession(userProvider: self))
4444

4545
// Fetch the user's data if there is a onesignal_id
4646
if let onesignalId = onesignalId {

‎iOS_SDK/OneSignalSDK/OneSignalUser/Source/Requests/OSSessionRequests.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ final class OSRequestCreateSession: OneSignalRequest, OSSessionRequest {
129129
var parameters: [String: Any] = [
130130
"onesignal_id": onesignalId,
131131
"subscription_id": subscriptionId,
132-
"device_type": DEVICE_TYPE_PUSH,
132+
"subscription_type": OSSubscriptionType.push.rawValue,
133133
"start_time": OSSessionTimestamp.string(from: startTime),
134134
// The local session ID, so a create replayed from any process returns the same session.
135135
"idempotency_key": localSessionId

‎iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/OSSessionOperationExecutorTests.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,8 @@ final class OSSessionOperationExecutorTests: XCTestCase {
168168
XCTAssertEqual(request.method, POST)
169169
XCTAssertEqual(request.parameters?["onesignal_id"] as? String, onesignalId)
170170
XCTAssertEqual(request.parameters?["subscription_id"] as? String, testPushSubId)
171+
XCTAssertEqual(request.parameters?["subscription_type"] as? String, "iOSPush")
172+
XCTAssertNil(request.parameters?["device_type"])
171173
XCTAssertEqual(request.parameters?["start_time"] as? String, "2023-11-14T22:13:20.000Z")
172174
XCTAssertEqual(request.parameters?["idempotency_key"] as? String, "session-1")
173175
XCTAssertEqual(request.parameters?["direct_attribution_id"] as? String, "notification-id")

‎iOS_SDK/OneSignalSDK/OneSignalUserTests/SessionRecordUserTests.swift‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ final class SessionRecordUserTests: XCTestCase {
5252
OneSignalCoreMocks.waitUntil("A Request was still in flight at teardown") { self.client.isIdle }
5353
OSSessionService.reset()
5454
OneSignalCoreMocks.clearUserDefaults()
55+
OSFeatureFlagsStore.shared.clear()
56+
OSFeatureManager.reset()
5557
}
5658

5759
func testSessionStartedBeforeUserIsCreatedPinsItsIdsOnceCreated() {
@@ -151,3 +153,55 @@ final class SessionRecordUserTests: XCTestCase {
151153
XCTAssertEqual(OSSessionService.shared.currentRecord?.onesignalId, userB_OSID)
152154
}
153155
}
156+
157+
// MARK: - Session create
158+
159+
extension SessionRecordUserTests {
160+
private func enableSessionsApi() {
161+
OSFeatureFlagsStore.shared.applyRemoteFlags(["sdk_sessions_v2_api_cutover"], metadata: nil)
162+
}
163+
164+
/// With responses held the user is never created, so its session creates stay queued.
165+
private func queuedSessionCreates() -> [OSRequestCreateSession] {
166+
let manager = OneSignalUserManagerImpl.sharedInstance
167+
manager.operationRepo.flushAndWait()
168+
return manager.sessionExecutor?.queuedRequests.compactMap { $0 as? OSRequestCreateSession } ?? []
169+
}
170+
171+
func testNewSessionQueuesACreateWithItsStartTime() {
172+
enableSessionsApi()
173+
client.holdResponses = true
174+
175+
OneSignalUserManagerImpl.sharedInstance.startNewSession()
176+
177+
let record = OSSessionService.shared.currentRecord
178+
let creates = queuedSessionCreates()
179+
XCTAssertEqual(creates.count, 1)
180+
XCTAssertEqual(creates.first?.localSessionId, record?.sessionId)
181+
XCTAssertEqual(creates.first?.startTime.timeIntervalSince1970, record?.startTime)
182+
client.releaseHeldResponses()
183+
}
184+
185+
func testEachNewSessionQueuesItsOwnCreate() {
186+
enableSessionsApi()
187+
client.holdResponses = true
188+
189+
OneSignalUserManagerImpl.sharedInstance.startNewSession()
190+
let first = OSSessionService.shared.currentRecord?.sessionId
191+
OneSignalUserManagerImpl.sharedInstance.startNewSession()
192+
let second = OSSessionService.shared.currentRecord?.sessionId
193+
194+
XCTAssertNotEqual(first, second)
195+
XCTAssertEqual(queuedSessionCreates().map(\.localSessionId), [first, second].compactMap { $0 })
196+
client.releaseHeldResponses()
197+
}
198+
199+
func testNewSessionQueuesNoCreateWhenTheFlagIsOff() {
200+
client.holdResponses = true
201+
202+
OneSignalUserManagerImpl.sharedInstance.startNewSession()
203+
204+
XCTAssertTrue(queuedSessionCreates().isEmpty)
205+
client.releaseHeldResponses()
206+
}
207+
}

‎iOS_SDK/OneSignalSDK/Source/OneSignal.m‎

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,6 @@ + (DelayedConsentInitializationParameters *)delayedInitParameters {
105105
// Called after successfully calling setAppId and setLaunchOptions
106106
static BOOL initDone = false;
107107

108-
// Used to track last time SDK was initialized, for whether or not to start a new session
109-
static NSTimeInterval initializationTime;
110-
111108
//// Set when the app is launched
112109
//static NSDate *sessionLaunchTime;
113110

@@ -366,18 +363,7 @@ + (BOOL)shouldStartNewSession {
366363
return false;
367364
}
368365

369-
NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
370-
NSTimeInterval lastTimeClosed = [OneSignalUserDefaults.initStandard getSavedDoubleForKey:OSUD_APP_LAST_CLOSED_TIME defaultValue:0];
371-
372-
// Make sure last time we closed app was more than 30 secs ago
373-
const int minTimeThreshold = 30;
374-
NSTimeInterval timeSinceLastClosed = now - lastTimeClosed;
375-
NSTimeInterval timeSinceInitialization = now - initializationTime;
376-
377-
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:[NSString stringWithFormat:@"shouldStartNewSession:timeSinceLastClosed: %f", timeSinceLastClosed]];
378-
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:[NSString stringWithFormat:@"shouldStartNewSession:timeSinceInitialization: %f", timeSinceInitialization]];
379-
380-
return MIN(timeSinceLastClosed, timeSinceInitialization) >= minTimeThreshold;
366+
return [OSSessionStartGate.shared shouldStartNewSession];
381367
}
382368

383369
+ (void)startNewSession:(BOOL)fromInit {
@@ -391,17 +377,28 @@ + (void)startNewSession:(BOOL)fromInit {
391377
// Run on the main queue as it is possible for this to be called from multiple queues.
392378
// Also some of the code in the method is not thread safe such as _outcomeEventsController.
393379
[OneSignalHelper dispatch_async_on_main_queue:^{
394-
[self startNewSessionInternal];
380+
[self startNewSessionInternal:!fromInit];
381+
}];
382+
}
383+
384+
/// Starts the session init deferred during a prewarm, without the 30 second gate: the init start
385+
/// it replaces never ran.
386+
+ (void)startDeferredSession {
387+
[OneSignalHelper dispatch_async_on_main_queue:^{
388+
[self startNewSessionInternal:YES];
395389
}];
396390
}
397391

398-
+ (void)startNewSessionInternal {
392+
+ (void)startNewSessionInternal:(BOOL)deduplicate {
399393
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"OneSignal.startNewSessionInternal"];
400394

401395
// return if the user has not granted consent, or device-protected storage isn't readable yet
402396
if ([OneSignalConfig shouldAwaitAppIdAndLogMissingPrivacyConsentForMethod:nil])
403397
return;
404398

399+
if (![OSSessionStartGate.shared beginSessionStartWithDeduplicate:deduplicate])
400+
return;
401+
405402
// A new session is a fresh chance at params after the launch attempt exhausted its retries
406403
if (!_downloadedParameters && !_didCallDownloadParameters && OneSignalIdentifiers.currentAppId) {
407404
_downloadParametersAttempts = 0;
@@ -621,7 +618,7 @@ + (void)setupProtectedDataObserverOnce {
621618
[OneSignal startInAppMessages];
622619
StartFeatureFlagsRefresh();
623620
[OSDeviceGestureDetector start];
624-
[OneSignal startNewSession:YES];
621+
[OneSignal startDeferredSession];
625622
};
626623

627624
// Authoritative signal: the OS says protected data just became available.
@@ -726,7 +723,7 @@ + (void)init {
726723
}
727724
[self startNewSession:YES];
728725

729-
initializationTime = [[NSDate date] timeIntervalSince1970];
726+
[OSSessionStartGate.shared recordInitialization];
730727
initDone = true;
731728
}
732729

0 commit comments

Comments
 (0)