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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,12 @@ Aptabase.shared.initialize(appKey: "<YOUR_APP_KEY>", 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

Expand Down
1 change: 1 addition & 0 deletions Sources/Aptabase/Aptabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions Sources/Aptabase/AptabaseClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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] = [:]) {
Expand Down
10 changes: 8 additions & 2 deletions Sources/Aptabase/ConcurrentQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ class ConcurrentQueue<T> {

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()
}
Expand All @@ -28,7 +31,10 @@ class ConcurrentQueue<T> {

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())
}
Expand Down
37 changes: 37 additions & 0 deletions Tests/AptabaseTests/AptabaseClientTests.swift
Original file line number Diff line number Diff line change
@@ -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"])
}
}
58 changes: 58 additions & 0 deletions Tests/AptabaseTests/ConcurrentQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}