diff --git a/README.md b/README.md index 4186ccb..35b6554 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,12 @@ Aptabase.shared.initialize(appKey: "", with: InitOptions( Afterward, you can start tracking events with `trackEvent`: +Delivery starts when the SDK is initialized, including in macOS app extensions +that do not receive application activation notifications. Initialize on the main +thread so the delivery timer uses the main run loop. The configured flush interval +also controls retries after transient failures. Events remain in memory, so an +extension terminated before delivery can lose pending events. + ```swift import Aptabase diff --git a/Sources/Aptabase/Aptabase.swift b/Sources/Aptabase/Aptabase.swift index 0ba1abf..a11fceb 100644 --- a/Sources/Aptabase/Aptabase.swift +++ b/Sources/Aptabase/Aptabase.swift @@ -41,6 +41,7 @@ public class Aptabase: NSObject { env.appVersion = appVersion } + client?.stopPolling() client = AptabaseClient(appKey: appKey, baseUrl: baseUrl, env: env, options: options) let notifications = NotificationCenter.default diff --git a/Sources/Aptabase/AptabaseClient.swift b/Sources/Aptabase/AptabaseClient.swift index 6906db1..eab0b83 100644 --- a/Sources/Aptabase/AptabaseClient.swift +++ b/Sources/Aptabase/AptabaseClient.swift @@ -13,11 +13,14 @@ class AptabaseClient { private let flushInterval: Double private var pauseFlushTimer: Bool = false - init(appKey: String, baseUrl: String, env: EnvironmentInfo, options: InitOptions?) { + init(appKey: String, baseUrl: String, env: EnvironmentInfo, options: InitOptions?, session: URLSessionProtocol = URLSession.shared) { flushInterval = options?.flushInterval ?? (env.isDebug ? 2.0 : 60.0) self.env = env - dispatcher = EventDispatcher(appKey: appKey, baseUrl: baseUrl, env: env) + dispatcher = EventDispatcher(appKey: appKey, baseUrl: baseUrl, env: env, session: session) + // Extensions and clients initialized after activation may never receive + // a foreground notification. Begin normal delivery immediately. + startPolling() } public func trackEvent(_ eventName: String, with props: [String: AnyCodableValue] = [:]) { diff --git a/Sources/Aptabase/ConcurrentQueue.swift b/Sources/Aptabase/ConcurrentQueue.swift index b603f97..54c55ab 100644 --- a/Sources/Aptabase/ConcurrentQueue.swift +++ b/Sources/Aptabase/ConcurrentQueue.swift @@ -18,7 +18,10 @@ class ConcurrentQueue { func dequeue() -> T? { var result: T? - queue.sync { + // Mutation needs the barrier: on a concurrent queue a plain `sync` runs + // alongside other readers and dequeues, so two callers can both see a + // non-empty array and both `removeFirst()`. + queue.sync(flags: .barrier) { if !self.elements.isEmpty { result = self.elements.removeFirst() } @@ -28,7 +31,10 @@ class ConcurrentQueue { func dequeue(count: Int) -> [T] { var dequeuedElements = [T]() - queue.sync { + // Mutation needs the barrier — see `dequeue()`. Without it two overlapping + // flushes each read `elements.count`, then remove past each other's end and + // trap with "Array replace: subrange extends past the end". + queue.sync(flags: .barrier) { for _ in 0 ..< min(count, self.elements.count) { dequeuedElements.append(self.elements.removeFirst()) } diff --git a/Tests/AptabaseTests/AptabaseClientTests.swift b/Tests/AptabaseTests/AptabaseClientTests.swift new file mode 100644 index 0000000..771d5de --- /dev/null +++ b/Tests/AptabaseTests/AptabaseClientTests.swift @@ -0,0 +1,37 @@ +import XCTest +@testable import Aptabase + +private actor DeliverySession: URLSessionProtocol { + let delivered: XCTestExpectation + private var events: [[String: Any]] = [] + private var attempts = 0 + + init(delivered: XCTestExpectation) { self.delivered = delivered } + + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + attempts += 1 + if attempts == 1 { + return (Data(), HTTPURLResponse(url: request.url!, statusCode: 500, httpVersion: nil, headerFields: nil)!) + } + events += try JSONSerialization.jsonObject(with: request.httpBody!) as! [[String: Any]] + delivered.fulfill() + return (Data(), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } + + func eventNames() -> [String] { events.compactMap { $0["eventName"] as? String } } +} + +final class AptabaseClientTests: XCTestCase { + @MainActor func testInitializationRetriesWithoutActivationNotification() async { + let delivered = expectation(description: "Timer retries an event without app activation or manual flush") + let session = DeliverySession(delivered: delivered) + let client = AptabaseClient(appKey: "A-DEV-000", baseUrl: "http://localhost:3000", + env: EnvironmentInfo(isDebug: true, osName: "macOS", osVersion: "14.0", appVersion: "1.0", deviceModel: "Mac"), + options: InitOptions(flushInterval: 0.05), session: session) + defer { client.stopPolling() } + client.trackEvent("finder_operation") + await fulfillment(of: [delivered], timeout: 2) + let names = await session.eventNames() + XCTAssertEqual(names, ["finder_operation"]) + } +} diff --git a/Tests/AptabaseTests/ConcurrentQueueTests.swift b/Tests/AptabaseTests/ConcurrentQueueTests.swift index 67df64e..a394521 100644 --- a/Tests/AptabaseTests/ConcurrentQueueTests.swift +++ b/Tests/AptabaseTests/ConcurrentQueueTests.swift @@ -61,4 +61,62 @@ final class ConcurrentQueueTests: XCTestCase { _ = concurrentQueue.dequeue(count: 10) XCTAssertEqual(concurrentQueue.count, 0) } + + /// Two flushes overlapping is the real-world crash: `EventDispatcher.flush()` runs + /// from a repeating timer AND from app lifecycle events, so concurrent `dequeue`s + /// happen in production. Without the barrier both callers read `elements.count`, + /// then remove past each other's end and trap with + /// "Fatal error: Array replace: subrange extends past the end". + func testConcurrentDequeuesDoNotOverRemove() { + let total = 2_000 + concurrentQueue.enqueue(contentsOf: Array(0 ..< total)) + // Let the barriered enqueue land before draining. + while concurrentQueue.count < total { usleep(1_000) } + + let drained = NSMutableArray() + let lock = NSLock() + let group = DispatchGroup() + + for _ in 0 ..< 8 { + DispatchQueue.global().async(group: group) { + while true { + let batch = self.concurrentQueue.dequeue(count: 10) + if batch.isEmpty { return } + lock.lock() + drained.addObjects(from: batch) + lock.unlock() + } + } + } + + XCTAssertEqual(group.wait(timeout: .now() + 30), .success) + XCTAssertEqual(drained.count, total, "every element should be dequeued exactly once") + XCTAssertEqual(Set(drained as! [Int]).count, total, "no element should be dequeued twice") + XCTAssertTrue(concurrentQueue.isEmpty) + } + + /// Same race through the single-element path. + func testConcurrentSingleDequeuesDoNotOverRemove() { + let total = 2_000 + concurrentQueue.enqueue(contentsOf: Array(0 ..< total)) + while concurrentQueue.count < total { usleep(1_000) } + + let counter = NSCountedSet() + let lock = NSLock() + let group = DispatchGroup() + + for _ in 0 ..< 8 { + DispatchQueue.global().async(group: group) { + while let item = self.concurrentQueue.dequeue() { + lock.lock() + counter.add(item) + lock.unlock() + } + } + } + + XCTAssertEqual(group.wait(timeout: .now() + 30), .success) + XCTAssertEqual(counter.count, total) + XCTAssertTrue(concurrentQueue.isEmpty) + } }