Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ THE SOFTWARE.

+ (OSRemoteParamController *)sharedController;

@property (strong, nonatomic, readonly, nonnull) NSDictionary *remoteParams;
@property (strong, atomic, readonly, nonnull) NSDictionary *remoteParams;

- (void)saveRemoteParams:(NSDictionary *_Nonnull)params;
- (BOOL)hasLocationKey;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,38 @@ of this software and associated documentation files (the "Software"), to deal
#import "OneSignalUserDefaults.h"
#import "OSPrivacyConsentController.h"

@implementation OSRemoteParamController
@implementation OSRemoteParamController {
NSDictionary *_remoteParams;
}

static OSRemoteParamController *_sharedController;
+ (OSRemoteParamController *)sharedController {
if (!_sharedController)
_sharedController = [OSRemoteParamController new];
return _sharedController;
static OSRemoteParamController *sharedController;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedController = [OSRemoteParamController new];
});
return sharedController;
}

// Read from background queues while a params fetch replaces it.
- (NSDictionary *)remoteParams {
@synchronized (self) {
return _remoteParams ?: @{};
}
}

- (void)saveRemoteParams:(NSDictionary *)params {
_remoteParams = params;
@synchronized (self) {
_remoteParams = params;
}
}

- (BOOL)hasLocationKey {
return _remoteParams && _remoteParams[IOS_LOCATION_SHARED];
return self.remoteParams[IOS_LOCATION_SHARED] != nil;
}

- (BOOL)hasPrivacyConsentKey {
return _remoteParams && _remoteParams[IOS_REQUIRES_USER_PRIVACY_CONSENT];
return self.remoteParams[IOS_REQUIRES_USER_PRIVACY_CONSENT] != nil;
}

- (BOOL)isLocationShared {
Expand Down
60 changes: 54 additions & 6 deletions iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/OSSessionService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,11 @@ public struct OSSessionStart {

/// Owns the persisted record of the current session. Nothing reads the record while
/// `usesSessionsApi` is false, so with the flag off session behavior is unchanged.
/// While in the foreground, a sessions API session reports its duration every `heartbeatInterval`
/// of foreground time, so the backend keeps it open and a crash loses little of it.
/// While in the foreground, a sessions API session reports its duration every heartbeat interval of
/// foreground time, so the backend keeps it open and a crash loses little of it. The interval comes
/// from the params' `sessions.heartbeat_interval_seconds`.
@objc(OSSessionService)
public final class OSSessionService: NSObject {
static let heartbeatInterval: TimeInterval = 30 * 60

private static let lock = NSLock()
private static var _shared: OSSessionService?

Expand All @@ -144,6 +143,8 @@ public final class OSSessionService: NSObject {
private let monotonicNow: () -> TimeInterval
private let wallNow: () -> TimeInterval
private let schedule: (TimeInterval, @escaping () -> Void) -> Void
/// Read on every check, so a later params fetch applies once the current wait ends.
private let heartbeatInterval: () -> TimeInterval

private let stateLock = NSLock()
private weak var userProvider: OSSessionUserProvider?
Expand All @@ -157,6 +158,8 @@ public final class OSSessionService: NSObject {
private var recordStartedInThisProcess = false
/// Bumped whenever the heartbeat restarts or stops, so a check scheduled before then does nothing.
private var heartbeatGeneration = 0
/// The generation a running heartbeat was armed with. Stale once the generation moves on.
private var armedHeartbeatGeneration: Int?
/// A notification opened from the background, for the session its focus starts or first brings to
/// the foreground. A focus that continues a focused session, or a later unfocus, discards it. A
/// background action from Notification Center arrives after the unfocus and brings no focus, so it
Expand All @@ -172,13 +175,17 @@ public final class OSSessionService: NSObject {
wallNow: @escaping () -> TimeInterval = { Date().timeIntervalSince1970 },
schedule: @escaping (TimeInterval, @escaping () -> Void) -> Void = { delay, block in
DispatchQueue.global().asyncAfter(deadline: .now() + delay, execute: block)
},
heartbeatInterval: @escaping () -> TimeInterval = {
OSSessionService.heartbeatInterval(remoteParams: OSRemoteParamController.shared().remoteParams)
}
) {
self.storage = storage
self.featureManager = featureManager
self.monotonicNow = monotonicNow
self.wallNow = wallNow
self.schedule = schedule
self.heartbeatInterval = heartbeatInterval
super.init()
}

Expand Down Expand Up @@ -463,6 +470,45 @@ extension OSSessionService {
// MARK: - Heartbeat

extension OSSessionService {
static let defaultHeartbeatInterval: TimeInterval = 30 * 60
// Bounds a misconfigured value so it can neither flood requests nor stop heartbeats.
static let minHeartbeatInterval: TimeInterval = 60
static let maxHeartbeatInterval: TimeInterval = 24 * 60 * 60

/// A missing, non-positive, or non-numeric value falls back to the default. A JSON boolean
/// bridges to an `NSNumber` of 1, so it is rejected explicitly.
static func heartbeatInterval(remoteParams: [AnyHashable: Any]) -> TimeInterval {
let sessions = remoteParams["sessions"] as? [AnyHashable: Any]
guard let number = sessions?["heartbeat_interval_seconds"] as? NSNumber,
CFGetTypeID(number) != CFBooleanGetTypeID(),
number.doubleValue > 0 else {
return defaultHeartbeatInterval
}
return min(max(number.doubleValue, minHeartbeatInterval), maxHeartbeatInterval)
}

/// A cold launch arms the heartbeat before params arrive, so the wait is re-armed with the new
/// interval. Only a running heartbeat is re-armed: a focus that is about to start a new session
/// must not send one for the record it replaces.
@objc public static func onRemoteParamsUpdated() {
shared.rescheduleHeartbeat()
}

func rescheduleHeartbeat() {
let generation: Int? = stateLock.withLock {
guard let armed = armedHeartbeatGeneration, armed == heartbeatGeneration else {
return nil
}
heartbeatGeneration += 1
armedHeartbeatGeneration = heartbeatGeneration
return heartbeatGeneration
}
guard let generation else {
return
}
checkHeartbeat(generation: generation)
}

private func stopHeartbeat() {
stateLock.withLock { heartbeatGeneration += 1 }
}
Expand All @@ -474,6 +520,7 @@ extension OSSessionService {
guard continuesRecord, focusedAt != nil, let record, record.usesSessionsApi else {
return nil
}
armedHeartbeatGeneration = heartbeatGeneration
return (heartbeatGeneration, record.sessionId)
}
guard let armed else {
Expand All @@ -488,22 +535,23 @@ extension OSSessionService {
private func checkHeartbeat(generation: Int) {
let now = monotonicNow()
let ids = pinnableIds()
let interval = heartbeatInterval()
let next: (due: (record: OSSessionRecord, provider: OSSessionUserProvider?)?, wait: TimeInterval)? = stateLock.withLock {
guard generation == heartbeatGeneration, let start = focusedAt, let focusTime = openFocusTime,
let current = record, current.usesSessionsApi else {
return nil
}
let focusDuration = max(0, now - start)
let duration = current.activeDuration + focusDuration
let remaining = (current.lastHeartbeatDuration ?? 0) + Self.heartbeatInterval - duration
let remaining = (current.lastHeartbeatDuration ?? 0) + interval - duration
guard remaining <= 0 else {
return (nil, remaining)
}
fillPinnedIds(ids)
record?.lastHeartbeatDuration = duration
record?.lastHeartbeatTime = focusTime + focusDuration
persist()
return (record.map { ($0, userProvider) }, Self.heartbeatInterval)
return (record.map { ($0, userProvider) }, interval)
}
guard let next else {
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private final class HeartbeatRecorder: OSSessionUserProvider {
}

final class OSSessionHeartbeatTests: XCTestCase {
private let interval = OSSessionService.heartbeatInterval
private var interval = OSSessionService.defaultHeartbeatInterval
private let wallStart: TimeInterval = 1_700_000_000
private var user: HeartbeatRecorder!
private var flagsStore: OSFeatureFlagsStore!
Expand Down Expand Up @@ -94,7 +94,8 @@ final class OSSessionHeartbeatTests: XCTestCase {
featureManager: { manager },
monotonicNow: { [unowned self] in self.monotonicNow },
wallNow: { [unowned self] in self.wallStart + self.monotonicNow + self.wallClockJump },
schedule: { [unowned self] delay, block in self.pending.append((self.monotonicNow + delay, block)) }
schedule: { [unowned self] delay, block in self.pending.append((self.monotonicNow + delay, block)) },
heartbeatInterval: { [unowned self] in self.interval }
)
}

Expand Down Expand Up @@ -140,6 +141,116 @@ final class OSSessionHeartbeatTests: XCTestCase {
XCTAssertEqual(heartbeatDurations(for: record), [interval, 2 * interval])
}

func testHeartbeatUsesTheConfiguredInterval() {
interval = 5 * 60
let record = startForegroundSession()

advance(by: interval - 1)
XCTAssertTrue(user.heartbeats.isEmpty)

advance(by: interval + 1)
XCTAssertEqual(heartbeatDurations(for: record), [5 * 60, 10 * 60])
}

func testIntervalChangeAppliesAfterTheCurrentWait() {
let record = startForegroundSession()
advance(by: 60)
interval = 5 * 60

advance(by: 30 * 60 - 61)
XCTAssertTrue(user.heartbeats.isEmpty)

advance(by: 1)
XCTAssertEqual(heartbeatDurations(for: record), [30 * 60])

advance(by: 5 * 60)
XCTAssertEqual(heartbeatDurations(for: record), [30 * 60, 35 * 60])
}

func testParamsUpdateReArmsARunningHeartbeatWithTheNewInterval() {
let record = startForegroundSession()
advance(by: 60)
interval = 5 * 60

service.rescheduleHeartbeat()
advance(by: 4 * 60 - 1)
XCTAssertTrue(user.heartbeats.isEmpty)

advance(by: 1)
XCTAssertEqual(heartbeatDurations(for: record), [5 * 60])

advance(by: 30 * 60)
XCTAssertEqual(heartbeatDurations(for: record), (1...7).map { TimeInterval($0) * 5 * 60 })
}

func testParamsUpdateSendsAnOverdueHeartbeatImmediately() {
let record = startForegroundSession()
advance(by: 10 * 60)
interval = 5 * 60

service.rescheduleHeartbeat()

XCTAssertEqual(heartbeatDurations(for: record), [10 * 60])
}

func testParamsUpdateDoesNotStartAStoppedHeartbeat() {
startForegroundSession()
service.onUnfocus()
pending.removeAll()

service.rescheduleHeartbeat()

XCTAssertTrue(pending.isEmpty)
XCTAssertTrue(user.heartbeats.isEmpty)
}

/// The focus that starts a new session leaves the heartbeat to that session's start, so params
/// arriving in between must not heartbeat the record it replaces.
func testParamsUpdateBeforeTheSessionStartsDoesNotStartAHeartbeat() {
startForegroundSession()
service.onUnfocus()
advance(by: 60 * 60)
pending.removeAll()
service.onFocus()

service.rescheduleHeartbeat()

XCTAssertTrue(pending.isEmpty)
XCTAssertTrue(user.heartbeats.isEmpty)
}

func testHeartbeatIntervalParsesFromRemoteParams() {
XCTAssertEqual(OSSessionService.heartbeatInterval(remoteParams: ["sessions": ["heartbeat_interval_seconds": 300]]), 300)
}

func testHeartbeatIntervalIsClampedToBetweenOneMinuteAndOneDay() {
let cases: [(seconds: Any, expected: TimeInterval)] = [
(1, 60),
(0.5, 60),
(86_401, 86_400),
(Int64.max, 86_400)
]
for (seconds, expected) in cases {
XCTAssertEqual(OSSessionService.heartbeatInterval(remoteParams: ["sessions": ["heartbeat_interval_seconds": seconds]]), expected)
}
}

func testMissingOrInvalidHeartbeatIntervalFallsBackToTheDefault() {
let payloads: [[AnyHashable: Any]] = [
[:],
["sessions": [:] as [String: Any]],
["sessions": ["heartbeat_interval_seconds": 0]],
["sessions": ["heartbeat_interval_seconds": -60]],
["sessions": ["heartbeat_interval_seconds": "abc"]],
["sessions": ["heartbeat_interval_seconds": true]],
["sessions": ["heartbeat_interval_seconds": NSNull()]],
["sessions": "abc"]
]
for payload in payloads {
XCTAssertEqual(OSSessionService.heartbeatInterval(remoteParams: payload), OSSessionService.defaultHeartbeatInterval)
}
}

/// A return within the new-session threshold continues the session. The background checkpoint
/// reported the time so far, so the next heartbeat is a full interval of foreground time after it.
func testBackgroundPausesHeartbeatAndOnlyForegroundTimeCounts() {
Expand Down
2 changes: 2 additions & 0 deletions iOS_SDK/OneSignalSDK/Source/OneSignal.m
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,7 @@ + (void)handleAppIdChange:(NSString*)appId {
// within a process, so both the cache and the latch have to go.
[OSFeatureManager resetAndClearCachedFlags];
[OSSessionService resetAndClearStoredRecord];
[[OSRemoteParamController sharedController] saveRemoteParams:@{}];

let sharedUserDefaults = OneSignalUserDefaults.initShared;

Expand Down Expand Up @@ -860,6 +861,7 @@ + (void)downloadIOSParamsWithAppId:(NSString *)appId {

[[OSRemoteParamController sharedController] saveRemoteParams:result];
[OSRemoteLoggingController configure];
[OSSessionService onRemoteParamsUpdated];
if ([[OSRemoteParamController sharedController] hasLocationKey]) {
BOOL shared = [result[IOS_LOCATION_SHARED] boolValue];
let oneSignalLocation = NSClassFromString(ONE_SIGNAL_LOCATION_CLASS_NAME);
Expand Down
Loading