From f12124cc999abaa559d0349185534804d8d5a45e Mon Sep 17 00:00:00 2001 From: Bogdan Ivanov Date: Fri, 23 Oct 2026 10:33:25 +0300 Subject: [PATCH 1/4] ci: run on macos-15 with Xcode 16 The macos-13 image was retired on 2025-12-04, so every run since then waited for a runner that never came and was cancelled by GitHub after 24 hours. Xcode 14 does not exist on current images either. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ed04109..c57c1a5 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,11 +9,11 @@ on: jobs: build: name: ${{ matrix.platform }} on Xcode ${{ matrix.xcode }} - runs-on: macos-13 + runs-on: macos-15 strategy: matrix: platform: [macOS, iOS, tvOS, watchOS] - xcode: [^14] # ^15 + xcode: [^16] steps: - uses: actions/checkout@v4 From d5b9b6bd66064716a49692473f7c5a5bd068f870 Mon Sep 17 00:00:00 2001 From: Bogdan Ivanov Date: Fri, 23 Oct 2026 10:33:25 +0300 Subject: [PATCH 2/4] fix: harden error reporting Follow-up to #39, bringing the Swift SDK in line with the other SDKs' error reporting: - Capture the stack trace synchronously in trackError, before the delivery Task, and strip the SDK's own frames. Captured inside the Task it contained only SDK and concurrency runtime frames. - Truncate every field to the server's limits instead of letting a long stack trace get the whole report rejected with 400. - Send error reports immediately after enqueueing instead of waiting for the next flush timer tick; failures stay queued for retry. - Report NSErrors (including URLError/CocoaError passed as Error) by domain and code, and Swift errors by type name with their LocalizedError description or String(describing:). - Enforce the 25-report queue cap when failed reports are re-enqueued. - Log the failed batch size, not the remaining queue size, in EventDispatcher. - Store one JSONEncoder per dispatcher instead of building one per request; drop the duplicated session check in trackEvent. - Make ErrorDispatcher internal, remove placeholder file headers. Co-Authored-By: Claude Fable 5.1 --- Sources/Aptabase/Aptabase.swift | 6 +- Sources/Aptabase/AptabaseClient.swift | 28 ++-- Sources/Aptabase/Dispatcher.swift | 45 +++--- Sources/Aptabase/ErrorDispatcher.swift | 116 +++++++------- Sources/Aptabase/ErrorReport.swift | 146 ++++++++++++------ Sources/Aptabase/Event.swift | 7 - Sources/Aptabase/EventDispatcher.swift | 5 +- Tests/AptabaseTests/AptabaseClientTests.swift | 46 +++++- .../AptabaseTests/ErrorDispatcherTests.swift | 8 + Tests/AptabaseTests/ErrorReportTests.swift | 111 +++++++++++++ 10 files changed, 356 insertions(+), 162 deletions(-) create mode 100644 Tests/AptabaseTests/ErrorReportTests.swift diff --git a/Sources/Aptabase/Aptabase.swift b/Sources/Aptabase/Aptabase.swift index 8f21cd9..85404dd 100644 --- a/Sources/Aptabase/Aptabase.swift +++ b/Sources/Aptabase/Aptabase.swift @@ -74,7 +74,7 @@ public class Aptabase: NSObject { /// Track errors you've caught and handled. /// - Parameters: /// - error: The error to report. - /// - fatal: Wether the app can recover from the error. + /// - fatal: Whether the app can recover from the error. Fatal errors are reported with severity `fatal` and kind `crash`. public func trackError(_ error: Error, fatal: Bool = false) { enqueueErrorReport(error, fatal: fatal) } @@ -108,9 +108,9 @@ public class Aptabase: NSObject { /// Track errors you've caught and handled. /// - Parameters: /// - error: The error to report. - /// - fatal: Wether the app can recover from the error. + /// - fatal: Whether the app can recover from the error. Fatal errors are reported with severity `fatal` and kind `crash`. @objc public func trackError(_ error: NSError, fatal: Bool = false) { - enqueueErrorReport(error, fatal: fatal) + enqueueErrorReport(error, fatal: fatal) } /// Forces all queued events to be sent to the server asynchronously. Returns before the events have been sent. diff --git a/Sources/Aptabase/AptabaseClient.swift b/Sources/Aptabase/AptabaseClient.swift index 7d51c01..d92364f 100644 --- a/Sources/Aptabase/AptabaseClient.swift +++ b/Sources/Aptabase/AptabaseClient.swift @@ -34,14 +34,8 @@ class AptabaseClient { } public func trackEvent(_ eventName: String, with props: [String: AnyCodableValue] = [:]) async { - let now = Date() - if lastTouched.distance(to: now) > AptabaseClient.sessionTimeout { - sessionId = AptabaseClient.newSessionId() - } - lastTouched = now - evaluateSessionId() - + let evt = Event(timestamp: Date(), sessionId: sessionId, eventName: eventName, @@ -60,19 +54,25 @@ class AptabaseClient { await eventDispatcher.enqueue(evt) } - /// Begins tracking an error asynchronously. + /// Begins tracking an error asynchronously. The stack trace is captured here, on the caller's + /// thread, so it points at the call site rather than at the task that delivers the report. public func trackError(_ error: any Error, fatal: Bool = false) { + let stackTrace = ErrorReport.captureStackTrace() Task { - await trackError(error, fatal: fatal) + await trackError(error, fatal: fatal, stackTrace: stackTrace) } } - - public func trackError(_ error: any Error, fatal: Bool = false) async { + + public func trackError(_ error: any Error, fatal: Bool = false, stackTrace: String? = nil) async { evaluateSessionId() - - let errorReport = ErrorReport.build(error, fatal: fatal, sessionId: sessionId, sdkVersion: AptabaseClient.sdkVersion, env: env) - + + let errorReport = ErrorReport.build(error, fatal: fatal, sessionId: sessionId, sdkVersion: AptabaseClient.sdkVersion, env: env, stackTrace: stackTrace) + await errorDispatcher.enqueue(errorReport) + + // Errors are high-value: attempt delivery right away instead of waiting for the next + // poll tick. Failures stay queued for the regular flushes. + await errorDispatcher.flush() } public func startPolling() { diff --git a/Sources/Aptabase/Dispatcher.swift b/Sources/Aptabase/Dispatcher.swift index f909840..c3c24c9 100644 --- a/Sources/Aptabase/Dispatcher.swift +++ b/Sources/Aptabase/Dispatcher.swift @@ -1,10 +1,3 @@ -// -// File.swift -// Aptabase -// -// Created by Joshua Wolfson on 6/9/2026. -// - import Foundation protocol URLSessionProtocol { @@ -13,24 +6,24 @@ protocol URLSessionProtocol { extension URLSession: URLSessionProtocol {} - protocol Dispatcher: Actor where Item: Encodable { associatedtype Item - + var maximumBatchSize: Int { get } var queue: ConcurrentQueue { get set } var apiUrl: URL { get } var headers: [String: String] { get } var session: URLSessionProtocol { get } - + var encoder: JSONEncoder { get } + func enqueue(_ newItem: Item) - + func enqueue(_ newItems: [Item]) - + func flush() async - + func sendItems(_ items: [Item]) async throws - + init(appKey: String, baseUrl: String, env: EnvironmentInfo, session: URLSessionProtocol) } @@ -38,11 +31,11 @@ extension Dispatcher { func enqueue(_ newItem: Item) { queue.enqueue(newItem) } - + func enqueue(_ newItems: [Item]) { queue.enqueue(contentsOf: newItems) } - + func flush() async { if queue.isEmpty { return @@ -64,14 +57,14 @@ extension Dispatcher { } } -extension Dispatcher { - var encoder: JSONEncoder { - let encoder = JSONEncoder() - let formatter = DateFormatter() - formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" - formatter.locale = Locale(identifier: "en_US") - formatter.timeZone = TimeZone(identifier: "UTC") - encoder.dateEncodingStrategy = .formatted(formatter) - return encoder - } +/// One encoder per dispatcher: building the date formatter is comparatively expensive, so it must +/// not happen per request. +func makeDispatcherEncoder() -> JSONEncoder { + let encoder = JSONEncoder() + let formatter = DateFormatter() + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" + formatter.locale = Locale(identifier: "en_US") + formatter.timeZone = TimeZone(identifier: "UTC") + encoder.dateEncodingStrategy = .formatted(formatter) + return encoder } diff --git a/Sources/Aptabase/ErrorDispatcher.swift b/Sources/Aptabase/ErrorDispatcher.swift index 7937407..64ac246 100644 --- a/Sources/Aptabase/ErrorDispatcher.swift +++ b/Sources/Aptabase/ErrorDispatcher.swift @@ -1,22 +1,20 @@ -// -// File.swift -// Aptabase -// -// Created by Joshua Wolfson on 5/9/2026. -// - import Foundation -// Errors have their own dispatcher because the error endpoint takes a single object per request and has different retry semantics than the events endpoint: 408/429 must be retried, while 403 (monthly error quota exhausted) must never be retried. -public actor ErrorDispatcher: Dispatcher { - internal var queue = ConcurrentQueue() - internal let maximumBatchSize = 1 - internal let headers: [String: String] - internal let apiUrl: URL - internal let session: URLSessionProtocol - - private let maximumQueueSize: Int = 25 - +// Errors have their own dispatcher because the error endpoint takes a single object per request and +// has different retry semantics than the events endpoint: 408/429 must be retried, while 403 +// (monthly error quota exhausted) must never be retried. +actor ErrorDispatcher: Dispatcher { + var queue = ConcurrentQueue() + let maximumBatchSize = 1 + let headers: [String: String] + let apiUrl: URL + let session: URLSessionProtocol + let encoder = makeDispatcherEncoder() + + // Max number of unsent reports kept in memory. New reports are dropped when full, so the first + // occurrences (closest to the root cause) are kept. + private let maximumQueueSize = 25 + init(appKey: String, baseUrl: String, env: EnvironmentInfo, session: URLSessionProtocol = URLSession.shared) { self.session = session apiUrl = URL(string: "\(baseUrl)/api/v0/error")! @@ -26,55 +24,59 @@ public actor ErrorDispatcher: Dispatcher { "User-Agent": "\(env.osName)/\(env.osVersion) \(env.locale)" ] } - + func enqueue(_ report: ErrorReport) { - if queue.count >= maximumQueueSize { - debugPrint("Aptabase: Error report queue is full. Dropping report.") - return - } + enqueue([report]) + } - queue.enqueue(report) + func enqueue(_ reports: [ErrorReport]) { + let capacity = max(0, maximumQueueSize - queue.count) + if reports.count > capacity { + debugPrint("Aptabase: Error report queue is full. Dropping \(reports.count - capacity) report(s).") + } + queue.enqueue(contentsOf: Array(reports.prefix(capacity))) } - + func sendItems(_ items: [ErrorReport]) async throws { - // only send the first error report - guard let errorReport = items.first else { - return - } + // the error endpoint takes one report per request + guard let errorReport = items.first else { + return + } - do { - let body = try encoder.encode(errorReport) + do { + let body = try encoder.encode(errorReport) - var request = URLRequest(url: apiUrl) - request.httpMethod = "POST" - request.allHTTPHeaderFields = headers - request.httpBody = body + var request = URLRequest(url: apiUrl) + request.httpMethod = "POST" + request.allHTTPHeaderFields = headers + request.httpBody = body - let (data, response) = try await session.data(for: request) - let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0 - if statusCode < 300 { - return - } + let (data, response) = try await session.data(for: request) + let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0 + if statusCode < 300 { + return + } - let responseText = String(data: data, encoding: .utf8) ?? "" - let reason = "\(statusCode) \(responseText)" - - // The server reports an exhausted monthly error quota as 403 - if statusCode == 403 { - debugPrint("Aptabase: Error report rejected because of \(reason). Will not retry.") - return - } + let responseText = String(data: data, encoding: .utf8) ?? "" + let reason = "\(statusCode) \(responseText)" - if statusCode == 408 || statusCode == 429 || statusCode >= 500 { - debugPrint("Aptabase: Failed to send error report because of \(reason). Will retry later.") - throw NSError(domain: "AptabaseError", code: statusCode, userInfo: ["reason": reason]) - } + // The server reports an exhausted monthly error quota as 403 (not 429) precisely so + // clients drop the report instead of retrying it + if statusCode == 403 { + debugPrint("Aptabase: Error report rejected because of \(reason). Will not retry.") + return + } - debugPrint("Aptabase: Failed to send error report because of \(reason). Will not retry.") - return - } catch { - debugPrint("Aptabase: Failed to send error report. Reason: \(error)") - throw error - } + if statusCode == 408 || statusCode == 429 || statusCode >= 500 { + debugPrint("Aptabase: Failed to send error report because of \(reason). Will retry later.") + throw NSError(domain: "AptabaseError", code: statusCode, userInfo: ["reason": reason]) + } + + debugPrint("Aptabase: Failed to send error report because of \(reason). Will not retry.") + return + } catch { + debugPrint("Aptabase: Failed to send error report. Reason: \(error)") + throw error + } } } diff --git a/Sources/Aptabase/ErrorReport.swift b/Sources/Aptabase/ErrorReport.swift index 61d5d46..c71c5d4 100644 --- a/Sources/Aptabase/ErrorReport.swift +++ b/Sources/Aptabase/ErrorReport.swift @@ -1,39 +1,38 @@ -// -// ErrorReport.swift -// Aptabase -// -// Created by Joshua Wolfson on 6/9/2026. -// - import Foundation -/** - * Severity of a reported error: "fatal" for errors the app cannot recover from. - */ +/// Severity of a reported error: `fatal` for errors the app cannot recover from, otherwise `error`. enum ErrorSeverity: String, Encodable { case fatal case error } -/** - * How the error was captured: "handled" (manual trackError), "unhandled" or - * "crash" (automatic crash reporting), "taskException" (async task failures). - */ +/// How an error was captured. The SDK currently produces `handled` (manual `trackError`) and +/// `crash` (manual `trackError` with `fatal: true`). `unhandled` and `taskException` are part of +/// the server contract and reserved for automatic crash reporting. enum ErrorKind: String, Encodable { - /// automatic crash reporting case crash - /// automatic crash reporting case unhandled - /// async task failures case taskException - /// Manual `.trackError` case handled } -/** - * An error report sent to the error ingestion endpoint (one object per request). - */ +/// An error report sent to the error ingestion endpoint (one object per request). struct ErrorReport: Encodable { + // Field limits enforced by the error ingestion endpoint. Exceeding any of them rejects the + // whole report with 400, so values are truncated at capture time. + static let maxErrorMessage = 5000 + static let maxErrorType = 100 + static let maxStackTrace = 10000 + static let maxPlatform = 30 + static let maxOSName = 30 + static let maxOSVersion = 100 + static let maxAppVersion = 50 + static let maxSdkVersion = 40 + static let maxSessionId = 100 + + // Identifies the SDK platform server-side; deliberately distinct from osName. + static let platform = "Apple" + var errorMessage: String var errorType: String var stackTrace: String? @@ -47,35 +46,82 @@ struct ErrorReport: Encodable { var severity: ErrorSeverity var kind: ErrorKind var isDebug: Bool - + + /// Builds a report, stamping the timestamp and session at capture time so retried sends keep + /// their original attribution, and clamping every field to the server's limits. + /// - Parameter stackTrace: A stack captured at the call site. When nil the current stack is used, + /// which is only meaningful when called synchronously from the reporting thread. static func build( - _ error: Error, - fatal: Bool, - sessionId: String, - sdkVersion: String, - env: EnvironmentInfo - ) -> ErrorReport { - let typeName = String(describing: type(of: error)) - let errorMessage = (error as NSError).localizedDescription - let prefix = fatal ? "Fatal " : "" - let severity: ErrorSeverity = fatal ? .fatal : .error - let kind: ErrorKind = fatal ? .crash : .handled - let stack = Thread.callStackSymbols.joined(separator: "\n") - - return ErrorReport( - errorMessage: "\(prefix)\(typeName): \(errorMessage)", - errorType: typeName, - stackTrace: stack.isEmpty ? nil : stack, - timestamp: Date(), - sessionId: sessionId, - platform: "Apple", - osName: env.osName.isEmpty ? nil : env.osName, - osVersion: env.osVersion.isEmpty ? nil : env.osVersion, - appVersion: env.appVersion.isEmpty ? nil : env.appVersion, - sdkVersion: sdkVersion, - severity: severity, - kind: kind, - isDebug: env.isDebug - ) + _ error: Error, + fatal: Bool, + sessionId: String, + sdkVersion: String, + env: EnvironmentInfo, + stackTrace: String? = nil + ) -> ErrorReport { + let (typeName, message) = describe(error) + let prefix = fatal ? "Fatal " : "" + let stack = stackTrace ?? captureStackTrace() + + return ErrorReport( + errorMessage: truncate("\(prefix)\(typeName): \(message)", maxErrorMessage), + errorType: truncate(typeName, maxErrorType), + stackTrace: stack.isEmpty ? nil : truncate(stack, maxStackTrace), + timestamp: Date(), + sessionId: truncate(sessionId, maxSessionId), + platform: truncate(platform, maxPlatform), + osName: truncateOptional(env.osName, maxOSName), + osVersion: truncateOptional(env.osVersion, maxOSVersion), + appVersion: truncateOptional(env.appVersion, maxAppVersion), + sdkVersion: truncate(sdkVersion, maxSdkVersion), + severity: fatal ? .fatal : .error, + kind: fatal ? .crash : .handled, + isDebug: env.isDebug + ) + } + + /// Derives a type name the dashboard can group on and a readable message from any error. + static func describe(_ error: Error) -> (type: String, message: String) { + // An NSError carries no useful Swift type, so group by domain and code the way Xcode prints + // them. This covers errors thrown by Objective-C APIs and Swift's Foundation error structs + // (URLError, CocoaError, POSIXError), which are boxed as their NSError when passed as `Error`. + if type(of: error) is NSError.Type { + let nsError = error as NSError + return ("\(nsError.domain) \(nsError.code)", nsError.localizedDescription) } + + let typeName = String(describing: type(of: error)) + + if let description = (error as? LocalizedError)?.errorDescription, !description.isEmpty { + return (typeName, description) + } + + // Bridging a plain Swift error to NSError only yields "The operation couldn't be completed.", + // so its own description (the enum case, or the struct's fields) is more useful. + return (typeName, String(describing: error)) + } + + /// Captures the current call stack with the SDK's own leading frames removed, so the first + /// frame is the caller of `trackError`. + static func captureStackTrace() -> String { + return format(Thread.callStackSymbols) + } + + static func format(_ frames: [String]) -> String { + let callerFrames = frames.drop(while: isSDKFrame) + return (callerFrames.isEmpty ? frames[...] : callerFrames).joined(separator: "\n") + } + + // Symbols from this module are mangled with the module name, e.g. "$s8Aptabase11ErrorReportV…". + private static func isSDKFrame(_ frame: String) -> Bool { + return frame.contains("$s8Aptabase") + } + + private static func truncate(_ value: String, _ maxLength: Int) -> String { + return value.count > maxLength ? String(value.prefix(maxLength)) : value + } + + private static func truncateOptional(_ value: String, _ maxLength: Int) -> String? { + return value.isEmpty ? nil : truncate(value, maxLength) + } } diff --git a/Sources/Aptabase/Event.swift b/Sources/Aptabase/Event.swift index 03b375f..73783b6 100644 --- a/Sources/Aptabase/Event.swift +++ b/Sources/Aptabase/Event.swift @@ -1,10 +1,3 @@ -// -// File.swift -// Aptabase -// -// Created by Joshua Wolfson on 6/9/2026. -// - import Foundation struct Event: Encodable { diff --git a/Sources/Aptabase/EventDispatcher.swift b/Sources/Aptabase/EventDispatcher.swift index e304be9..608e2b0 100644 --- a/Sources/Aptabase/EventDispatcher.swift +++ b/Sources/Aptabase/EventDispatcher.swift @@ -6,6 +6,7 @@ public actor EventDispatcher: Dispatcher { internal let headers: [String: String] internal let apiUrl: URL internal let session: URLSessionProtocol + internal let encoder = makeDispatcherEncoder() init(appKey: String, baseUrl: String, env: EnvironmentInfo, session: URLSessionProtocol = URLSession.shared) { self.session = session @@ -40,13 +41,13 @@ public actor EventDispatcher: Dispatcher { let reason = "\(statusCode) \(responseText)" if statusCode < 500 { - debugPrint("Aptabase: Failed to send \(queue.count) events because of \(reason). Will not retry.") + debugPrint("Aptabase: Failed to send \(items.count) events because of \(reason). Will not retry.") return } throw NSError(domain: "AptabaseError", code: statusCode, userInfo: ["reason": reason]) } catch { - debugPrint("Aptabase: Failed to send \(queue.count) events. Reason: \(error)") + debugPrint("Aptabase: Failed to send \(items.count) events. Reason: \(error)") throw error } } diff --git a/Tests/AptabaseTests/AptabaseClientTests.swift b/Tests/AptabaseTests/AptabaseClientTests.swift index 20b4307..8e4527a 100644 --- a/Tests/AptabaseTests/AptabaseClientTests.swift +++ b/Tests/AptabaseTests/AptabaseClientTests.swift @@ -1,6 +1,8 @@ import XCTest @testable import Aptabase +private enum ClientTestError: Error { case failed } + private actor DeliverySession: URLSessionProtocol { let delivered: XCTestExpectation private var events: [[String: Any]] = [] @@ -21,17 +23,55 @@ private actor DeliverySession: URLSessionProtocol { func eventNames() -> [String] { events.compactMap { $0["eventName"] as? String } } } +private actor RecordingSession: URLSessionProtocol { + let received: XCTestExpectation + private(set) var bodies: [[String: Any]] = [] + + init(received: XCTestExpectation) { self.received = received } + + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + bodies.append(try JSONSerialization.jsonObject(with: request.httpBody!) as! [String: Any]) + received.fulfill() + return (Data(), HTTPURLResponse(url: request.url!, statusCode: 202, httpVersion: nil, headerFields: nil)!) + } +} + final class AptabaseClientTests: XCTestCase { + private let env = EnvironmentInfo(isDebug: true, osName: "macOS", osVersion: "14.0", appVersion: "1.0", deviceModel: "Mac") + @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) + let client = AptabaseClient(appKey: "A-DEV-000", baseUrl: "http://localhost:3000", env: env, + options: InitOptions(flushInterval: 0.05), session: session) defer { client.stopPolling() } await client.trackEvent("finder_operation") await fulfillment(of: [delivered], timeout: 2) let names = await session.eventNames() XCTAssertEqual(names, ["finder_operation"]) } + + @MainActor func testTrackErrorSendsImmediatelyWithCallerStack() async throws { + let received = expectation(description: "Error report is sent without waiting for the flush timer") + let session = RecordingSession(received: received) + let client = AptabaseClient(appKey: "A-DEV-000", baseUrl: "http://localhost:3000", env: env, + options: InitOptions(flushInterval: 3600), session: session) + defer { client.stopPolling() } + + // the synchronous entry point used by Aptabase.shared.trackError + let trackError: (any Error, Bool) -> Void = client.trackError + trackError(ClientTestError.failed, false) + + await fulfillment(of: [received], timeout: 2) + let bodies = await session.bodies + let body = try XCTUnwrap(bodies.first) + XCTAssertEqual(body["errorType"] as? String, "ClientTestError") + XCTAssertEqual(body["errorMessage"] as? String, "ClientTestError: failed") + XCTAssertEqual(body["kind"] as? String, "handled") + + let stack = try XCTUnwrap(body["stackTrace"] as? String) + let firstFrame = stack.split(separator: "\n").first.map(String.init) ?? "" + XCTAssertTrue(firstFrame.contains("testTrackErrorSendsImmediatelyWithCallerStack"), "first frame should be the caller, got: \(firstFrame)") + XCTAssertFalse(stack.contains("$s8Aptabase0A6ClientC10trackError"), "SDK frames should be stripped") + } } diff --git a/Tests/AptabaseTests/ErrorDispatcherTests.swift b/Tests/AptabaseTests/ErrorDispatcherTests.swift index 73afb84..dc3067f 100644 --- a/Tests/AptabaseTests/ErrorDispatcherTests.swift +++ b/Tests/AptabaseTests/ErrorDispatcherTests.swift @@ -78,6 +78,14 @@ final class ErrorDispatcherTests: XCTestCase { XCTAssertEqual(session.requestCount, 25) } + func testRequeueRespectsQueueCapacity() async { + session.statusCode = 403 + await dispatcher.enqueue((0...29).map { _ in newReport() }) + + await dispatcher.flush() + XCTAssertEqual(session.requestCount, 25) + } + func testFlushShouldPostErrorEndpoint() async throws { await dispatcher.enqueue(newReport(fatal: true)) diff --git a/Tests/AptabaseTests/ErrorReportTests.swift b/Tests/AptabaseTests/ErrorReportTests.swift new file mode 100644 index 0000000..44a6cde --- /dev/null +++ b/Tests/AptabaseTests/ErrorReportTests.swift @@ -0,0 +1,111 @@ +import XCTest +@testable import Aptabase + +private enum SampleError: Error { case boom } +private struct DescribedError: LocalizedError { + let errorDescription: String? = "Could not save the document" +} +private struct LongError: LocalizedError { + let errorDescription: String? = String(repeating: "m", count: 6000) +} + +final class ErrorReportTests: XCTestCase { + private let env = EnvironmentInfo(isDebug: true, osName: "iOS", osVersion: "17.0", appVersion: "1.0.0", appBuildNumber: "1", deviceModel: "iPhone16,2") + + private func build(_ error: Error, fatal: Bool = false, sessionId: String = "1", stackTrace: String? = "frame") -> ErrorReport { + ErrorReport.build(error, fatal: fatal, sessionId: sessionId, sdkVersion: "aptabase-swift@0.0.0", env: env, stackTrace: stackTrace) + } + + func testSwiftErrorUsesTypeNameAndDescription() { + let report = build(SampleError.boom) + XCTAssertEqual(report.errorType, "SampleError") + XCTAssertEqual(report.errorMessage, "SampleError: boom") + XCTAssertEqual(report.severity, .error) + XCTAssertEqual(report.kind, .handled) + } + + func testLocalizedErrorUsesErrorDescription() { + let report = build(DescribedError()) + XCTAssertEqual(report.errorType, "DescribedError") + XCTAssertEqual(report.errorMessage, "DescribedError: Could not save the document") + } + + func testNSErrorGroupsByDomainAndCode() { + let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet, userInfo: [NSLocalizedDescriptionKey: "Offline"]) + let report = build(error) + XCTAssertEqual(report.errorType, "NSURLErrorDomain -1009") + XCTAssertEqual(report.errorMessage, "NSURLErrorDomain -1009: Offline") + } + + func testFoundationErrorStructIsReportedAsItsNSError() { + // URLError passed as `Error` is boxed as its underlying NSError + let report = build(URLError(.notConnectedToInternet)) + XCTAssertEqual(report.errorType, "NSURLErrorDomain -1009") + XCTAssertTrue(report.errorMessage.hasPrefix("NSURLErrorDomain -1009: "), report.errorMessage) + } + + func testPlainSwiftErrorUsesItsOwnDescription() { + let context = DecodingError.Context(codingPath: [], debugDescription: "Expected a number") + let report = build(DecodingError.dataCorrupted(context)) + XCTAssertEqual(report.errorType, "DecodingError") + XCTAssertTrue(report.errorMessage.contains("Expected a number"), report.errorMessage) + } + + func testFatalPrefixSeverityAndKind() { + let report = build(SampleError.boom, fatal: true) + XCTAssertEqual(report.errorMessage, "Fatal SampleError: boom") + XCTAssertEqual(report.severity, .fatal) + XCTAssertEqual(report.kind, .crash) + } + + func testFieldsAreTruncatedToServerLimits() { + let longEnv = EnvironmentInfo(isDebug: false, + osName: String(repeating: "o", count: 40), + osVersion: String(repeating: "v", count: 120), + appVersion: String(repeating: "a", count: 60), + appBuildNumber: "1", deviceModel: "x") + let report = ErrorReport.build(LongError(), fatal: false, + sessionId: String(repeating: "s", count: 150), + sdkVersion: String(repeating: "k", count: 50), + env: longEnv, + stackTrace: String(repeating: "f", count: 12000)) + XCTAssertEqual(report.errorMessage.count, ErrorReport.maxErrorMessage) + XCTAssertEqual(report.stackTrace?.count, ErrorReport.maxStackTrace) + XCTAssertEqual(report.sessionId.count, ErrorReport.maxSessionId) + XCTAssertEqual(report.sdkVersion.count, ErrorReport.maxSdkVersion) + XCTAssertEqual(report.osName?.count, ErrorReport.maxOSName) + XCTAssertEqual(report.osVersion?.count, ErrorReport.maxOSVersion) + XCTAssertEqual(report.appVersion?.count, ErrorReport.maxAppVersion) + } + + func testEmptyEnvironmentFieldsAreOmitted() { + let report = ErrorReport.build(SampleError.boom, fatal: false, sessionId: "1", sdkVersion: "s", + env: EnvironmentInfo(), stackTrace: "") + XCTAssertNil(report.osName) + XCTAssertNil(report.osVersion) + XCTAssertNil(report.appVersion) + XCTAssertNil(report.stackTrace) + } + + func testStackTraceDropsLeadingSDKFrames() { + let frames = [ + "0 App 0x0001 $s8Aptabase11ErrorReportV17captureStackTraceSSyFZ + 20", + "1 App 0x0002 $s8Aptabase0A6ClientC10trackError_5fatalys0D0_p_SbtF + 40", + "2 App 0x0003 $s8Aptabase0A0C10trackError_5fatalys0D0_p_SbtF + 60", + "3 App 0x0004 $s3App9ViewModelC4saveyyF + 80", + "4 App 0x0005 $s8Aptabase9UnrelatedV + 100" + ] + XCTAssertEqual(ErrorReport.format(frames), frames[3...].joined(separator: "\n")) + } + + func testStackTraceKeepsAllFramesWhenOnlySDKFramesAreKnown() { + let frames = ["0 App 0x0001 $s8Aptabase11ErrorReportV17captureStackTraceSSyFZ + 20"] + XCTAssertEqual(ErrorReport.format(frames), frames[0]) + } + + func testCapturedStackStartsAtTheCaller() { + let stack = ErrorReport.captureStackTrace() + let first = stack.split(separator: "\n").first.map(String.init) ?? "" + XCTAssertTrue(first.contains("testCapturedStackStartsAtTheCaller"), first) + } +} From e0bf87d372142f86c649462d132dfe7710889e7d Mon Sep 17 00:00:00 2001 From: Bogdan Ivanov Date: Fri, 23 Oct 2026 10:33:25 +0300 Subject: [PATCH 3/4] docs: describe error reporting behaviour README and llms.txt state what a report contains, how errors are grouped, that delivery is immediate and in-memory only, and that crashes are not reported automatically. CHANGELOG gains an Unreleased entry for the error reporting work and the CI runner change. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 9 +++++++++ README.md | 15 +++++++++------ llms.txt | 20 ++++++++++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cc8f06..4effb2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## Unreleased + +* Adds error reporting: `Aptabase.shared.trackError(error)` and `trackError(error, fatal: true)` post structured error reports (type, message, stack trace, severity, kind) to the `Errors` page https://github.com/aptabase/aptabase-swift/pull/39 +* Error reports are sent immediately and retried from memory on network failures; 403 (monthly error quota exhausted) is never retried +* Stack traces are captured at the `trackError` call site with the SDK's own frames removed +* Report fields are truncated to the server's limits instead of being rejected +* Errors from Apple frameworks are reported by domain and code, Swift errors by type name with their description +* CI runs on `macos-15` with Xcode 16; the retired `macos-13` image left every run queued until timeout + ## 0.3.12 * Adds an `appVersion` option to `InitOptions` to override the app version read from the bundle https://github.com/aptabase/aptabase-swift/pull/36 diff --git a/README.md b/README.md index 590124a..430f86a 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ A few important notes: > Error reporting is in beta. Reports appear on the `Errors` page of your Aptabase dashboard. -Use `.trackError()` to report errors you've caught and handled: +Use `trackError` to report errors you've caught and handled: ```swift import Aptabase @@ -120,21 +120,24 @@ import Aptabase do { try someFailingFunction() } catch { - Aptabase.shared.trackError(error) + Aptabase.shared.trackError(error) // severity: error } ``` For errors your app can't recover from, mark the report as fatal: ```swift -.trackError(error, fatal: true); // severity: fatal +Aptabase.shared.trackError(error, fatal: true) // severity: fatal ``` A few important notes about error reporting: -1. Each report includes the error type, message, stack trace, severity (`error` or `fatal`) and how it was captured (`handled`, `unhandled` or `crash`). -2. Errors count against a separate monthly error quota. When the quota is exhausted, the server rejects new reports until it resets. - +1. Each report includes the error type, message, stack trace, severity (`error` or `fatal`) and how it was captured (`handled`, or `crash` when `fatal` is set). Swift errors are reported under their type name with their description; errors from Apple frameworks (`NSError`, `URLError`, `CocoaError`) are grouped by domain and code, for example `NSURLErrorDomain -1009`. +2. The stack trace is captured where `trackError` is called, since Swift errors carry no stack of their own. The SDK's own frames are removed so the first frame is your call site. +3. Reports are sent immediately and kept in memory for retry when the network is unavailable (up to 25 pending reports). They are not persisted to disk, so a report may be lost if the app terminates right after `trackError` returns. +4. Fields longer than the server accepts (for example a 10,000 character stack trace) are truncated rather than rejected. +5. Errors count against a separate monthly error quota. When the quota is exhausted, the server rejects new reports until it resets. +6. Uncaught exceptions and crashes are not reported automatically yet. Call `trackError` from your own error handling. ## Preparing for Submission to Apple App Store diff --git a/llms.txt b/llms.txt index 57c67be..41a718a 100644 --- a/llms.txt +++ b/llms.txt @@ -93,6 +93,26 @@ Aptabase.shared.trackEvent("purchase", with: ["amount": 9.99, "currency": "USD"] Aptabase.shared.trackEvent("level_complete", with: ["level": 5, "score": 1200]) ``` +## Track Errors + +Report handled errors with `trackError`; set `fatal: true` for errors the app cannot recover from. Reports appear on the Errors page of the dashboard. + +```swift +do { + try someFailingFunction() +} catch { + Aptabase.shared.trackError(error) // severity: error, kind: handled +} + +Aptabase.shared.trackError(error, fatal: true) // severity: fatal, kind: crash +``` + +- Each report carries the error type, message, stack trace (captured at the call site), severity, kind, session, OS and app version +- Swift errors use their type name and description; errors from Apple frameworks (`NSError`, `URLError`, `CocoaError`) are grouped by domain and code (e.g. `NSURLErrorDomain -1009`) +- Reports are sent immediately and retried from memory on network failures (up to 25 pending); nothing is persisted to disk +- Errors count against a separate monthly error quota; a 403 from the server means the quota is exhausted +- Uncaught exceptions and crashes are not reported automatically + ## Configuration Pass `InitOptions` to customize behavior: From 3897dfcc287a217fb26d013bda1abc762cc53b4e Mon Sep 17 00:00:00 2001 From: Bogdan Ivanov Date: Fri, 23 Oct 2026 10:54:05 +0300 Subject: [PATCH 4/4] fix: build on Xcode 16 Swift 6.1 rejects a parameterized protocol in a conformance clause ("cannot inherit from protocol type with generic argument 'Dispatcher'"); only newer compilers accept it. Both dispatchers now conform to Dispatcher and declare Item as a typealias. This came in with #39, so current main does not compile on Xcode 16. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 1 + Sources/Aptabase/ErrorDispatcher.swift | 4 +++- Sources/Aptabase/EventDispatcher.swift | 4 +++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4effb2e..c2e8a81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ * Report fields are truncated to the server's limits instead of being rejected * Errors from Apple frameworks are reported by domain and code, Swift errors by type name with their description * CI runs on `macos-15` with Xcode 16; the retired `macos-13` image left every run queued until timeout +* Fixes the build on Xcode 16 (Swift 6.1): `Dispatcher` cannot be used in a conformance clause there, so the dispatchers declare their `Item` typealias instead ## 0.3.12 diff --git a/Sources/Aptabase/ErrorDispatcher.swift b/Sources/Aptabase/ErrorDispatcher.swift index 64ac246..0df77d7 100644 --- a/Sources/Aptabase/ErrorDispatcher.swift +++ b/Sources/Aptabase/ErrorDispatcher.swift @@ -3,7 +3,9 @@ import Foundation // Errors have their own dispatcher because the error endpoint takes a single object per request and // has different retry semantics than the events endpoint: 408/429 must be retried, while 403 // (monthly error quota exhausted) must never be retried. -actor ErrorDispatcher: Dispatcher { +actor ErrorDispatcher: Dispatcher { + typealias Item = ErrorReport + var queue = ConcurrentQueue() let maximumBatchSize = 1 let headers: [String: String] diff --git a/Sources/Aptabase/EventDispatcher.swift b/Sources/Aptabase/EventDispatcher.swift index 608e2b0..249df9e 100644 --- a/Sources/Aptabase/EventDispatcher.swift +++ b/Sources/Aptabase/EventDispatcher.swift @@ -1,6 +1,8 @@ import Foundation -public actor EventDispatcher: Dispatcher { +public actor EventDispatcher: Dispatcher { + typealias Item = Event + internal var queue = ConcurrentQueue() internal let maximumBatchSize = 25 internal let headers: [String: String]