@anglerai/react-native-analytics 0.0.0-stage → 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AnglerAnalyticsRN.podspec +25 -0
- package/LICENSE +21 -0
- package/README.md +92 -2
- package/android/build.gradle +64 -0
- package/android/src/main/java/ai/getangler/analytics/reactnative/AnglerAnalyticsModule.kt +51 -0
- package/android/src/main/java/ai/getangler/analytics/reactnative/AnglerAnalyticsPackage.kt +25 -0
- package/android/src/main/java/ai/getangler/analytics/reactnative/ConfigParser.kt +58 -0
- package/android/src/test/java/ai/getangler/analytics/reactnative/ConfigParserTest.kt +51 -0
- package/ios/AnglerAnalyticsBridge.swift +58 -0
- package/ios/AnglerAnalyticsRN.mm +84 -0
- package/ios/vendor/AnglerAnalytics/Angler.swift +132 -0
- package/ios/vendor/AnglerAnalytics/AnglerCore.swift +398 -0
- package/ios/vendor/AnglerAnalytics/Attribution/AttributionStore.swift +109 -0
- package/ios/vendor/AnglerAnalytics/Attribution/ClickIdParser.swift +52 -0
- package/ios/vendor/AnglerAnalytics/Device/AdIdProvider.swift +36 -0
- package/ios/vendor/AnglerAnalytics/Device/DeviceContext.swift +111 -0
- package/ios/vendor/AnglerAnalytics/Device/FirebaseIdProvider.swift +35 -0
- package/ios/vendor/AnglerAnalytics/Lifecycle/LifecycleObserver.swift +77 -0
- package/ios/vendor/AnglerAnalytics/Lifecycle/SharedApplication.swift +15 -0
- package/ios/vendor/AnglerAnalytics/Log.swift +24 -0
- package/ios/vendor/AnglerAnalytics/Network/Flusher.swift +112 -0
- package/ios/vendor/AnglerAnalytics/Network/ResponsePolicy.swift +29 -0
- package/ios/vendor/AnglerAnalytics/Network/Scheduler.swift +13 -0
- package/ios/vendor/AnglerAnalytics/Network/Transport.swift +55 -0
- package/ios/vendor/AnglerAnalytics/Payload/JSONValue.swift +81 -0
- package/ios/vendor/AnglerAnalytics/Payload/Models.generated.swift +580 -0
- package/ios/vendor/AnglerAnalytics/Payload/PayloadBuilder.swift +148 -0
- package/ios/vendor/AnglerAnalytics/Payload/StandardEvent.swift +26 -0
- package/ios/vendor/AnglerAnalytics/Payload/TypedModels.swift +14 -0
- package/ios/vendor/AnglerAnalytics/Resources/PrivacyInfo.xcprivacy +77 -0
- package/ios/vendor/AnglerAnalytics/Storage/Clock.swift +14 -0
- package/ios/vendor/AnglerAnalytics/Storage/EventQueue.swift +85 -0
- package/ios/vendor/AnglerAnalytics/Storage/IdentityStore.swift +76 -0
- package/ios/vendor/AnglerAnalytics/Storage/KeyValueStore.swift +38 -0
- package/ios/vendor/AnglerAnalytics/Version.swift +4 -0
- package/package.json +46 -4
- package/src/NativeAnglerAnalytics.ts +21 -0
- package/src/index.ts +159 -0
- package/src/models.generated.ts +347 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(UIKit)
|
|
3
|
+
import UIKit
|
|
4
|
+
#endif
|
|
5
|
+
|
|
6
|
+
/// Collects device properties (design §5.2, iOS column) and the user agent.
|
|
7
|
+
enum DeviceContext {
|
|
8
|
+
struct Screen {
|
|
9
|
+
var width: Int
|
|
10
|
+
var height: Int
|
|
11
|
+
var scale: Double
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
private static let lock = NSLock()
|
|
15
|
+
private static var cachedScreen: Screen?
|
|
16
|
+
|
|
17
|
+
static func collect(wrapper: String, appStoreId: String? = nil, adTrackingEnabled: Bool, applicationTrackingEnabled: Bool) -> DeviceSnapshot {
|
|
18
|
+
var props: [DeviceProperty] = []
|
|
19
|
+
func add(_ name: String, _ value: String?) {
|
|
20
|
+
if let value, !value.isEmpty { props.append(DeviceProperty(name: name, value: value)) }
|
|
21
|
+
}
|
|
22
|
+
let tz = TimeZone.current
|
|
23
|
+
let model = modelIdentifier()
|
|
24
|
+
let osVersion = Self.osVersion()
|
|
25
|
+
|
|
26
|
+
#if os(iOS)
|
|
27
|
+
let info = Bundle.main.infoDictionary
|
|
28
|
+
add("app_id", normalizeAppStoreId(appStoreId))
|
|
29
|
+
add("app_package", Bundle.main.bundleIdentifier)
|
|
30
|
+
add("app_version_short", info?["CFBundleShortVersionString"] as? String)
|
|
31
|
+
add("app_version_long", info?["CFBundleVersion"] as? String)
|
|
32
|
+
add("os", "ios")
|
|
33
|
+
add("os_version", osVersion)
|
|
34
|
+
add("device_model_name", model)
|
|
35
|
+
add("device_timezone", tz.identifier)
|
|
36
|
+
add("timezone_abbreviation", tz.abbreviation())
|
|
37
|
+
add("locale", Locale.current.identifier)
|
|
38
|
+
if let screen = screen() {
|
|
39
|
+
add("screen_width", String(screen.width))
|
|
40
|
+
add("screen_height", String(screen.height))
|
|
41
|
+
add("screen_density", String(screen.scale))
|
|
42
|
+
}
|
|
43
|
+
add("cpu_cores", String(ProcessInfo.processInfo.activeProcessorCount))
|
|
44
|
+
#else
|
|
45
|
+
// macOS host (tests only): no app or hardware details.
|
|
46
|
+
add("os", "ios")
|
|
47
|
+
add("device_timezone", tz.identifier)
|
|
48
|
+
add("timezone_abbreviation", tz.abbreviation())
|
|
49
|
+
add("locale", Locale.current.identifier)
|
|
50
|
+
#endif
|
|
51
|
+
add("advertiser_tracking_enabled", adTrackingEnabled ? "1" : "0")
|
|
52
|
+
add("application_tracking_enabled", applicationTrackingEnabled ? "1" : "0")
|
|
53
|
+
|
|
54
|
+
let ua = userAgent(sdkVersion: SDKVersion.current, os: "iOS", osVersion: osVersion, model: model, wrapper: wrapper)
|
|
55
|
+
return DeviceSnapshot(properties: props, userAgent: ua)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// `id` plus the digits, the form AppsFlyer reports: `1234567890` and `id1234567890` both
|
|
59
|
+
/// become `id1234567890`. Anything else is sent as given (trimmed).
|
|
60
|
+
static func normalizeAppStoreId(_ appId: String?) -> String? {
|
|
61
|
+
guard let id = appId?.trimmingCharacters(in: .whitespacesAndNewlines), !id.isEmpty else { return nil }
|
|
62
|
+
if id.allSatisfy({ $0.isASCII && $0.isNumber }) { return "id" + id }
|
|
63
|
+
return id
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
static func userAgent(sdkVersion: String, os: String, osVersion: String, model: String, wrapper: String) -> String {
|
|
67
|
+
"AnglerAnalytics/\(sdkVersion) (\(os) \(osVersion); \(model); \(wrapper))"
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// Reads and caches the screen size. UIKit is main-thread only, so off the main thread
|
|
71
|
+
/// this returns the value cached by an earlier main-thread call (`Angler.configure`).
|
|
72
|
+
@discardableResult
|
|
73
|
+
static func captureScreenIfOnMain() -> Screen? {
|
|
74
|
+
#if canImport(UIKit) && os(iOS)
|
|
75
|
+
if Thread.isMainThread {
|
|
76
|
+
let screen = MainActor.assumeIsolated { () -> Screen in
|
|
77
|
+
let s = UIScreen.main
|
|
78
|
+
let px = s.nativeBounds.size // portrait pixels
|
|
79
|
+
return Screen(width: Int(min(px.width, px.height)), height: Int(max(px.width, px.height)),
|
|
80
|
+
scale: Double(s.scale))
|
|
81
|
+
}
|
|
82
|
+
lock.lock(); cachedScreen = screen; lock.unlock()
|
|
83
|
+
return screen
|
|
84
|
+
}
|
|
85
|
+
#endif
|
|
86
|
+
return nil
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private static func screen() -> Screen? {
|
|
90
|
+
if let s = captureScreenIfOnMain() { return s }
|
|
91
|
+
lock.lock(); defer { lock.unlock() }
|
|
92
|
+
return cachedScreen
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Same format as `UIDevice.systemVersion` ("17.4", "17.4.1"), without main-actor UIKit.
|
|
96
|
+
private static func osVersion() -> String {
|
|
97
|
+
let v = ProcessInfo.processInfo.operatingSystemVersion
|
|
98
|
+
return v.patchVersion > 0 ? "\(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"
|
|
99
|
+
: "\(v.majorVersion).\(v.minorVersion)"
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/// `utsname.machine`, e.g. `iPhone15,2`. The simulator reports the simulated model.
|
|
103
|
+
private static func modelIdentifier() -> String {
|
|
104
|
+
if let sim = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"], !sim.isEmpty { return sim }
|
|
105
|
+
var info = utsname()
|
|
106
|
+
uname(&info)
|
|
107
|
+
return withUnsafeBytes(of: &info.machine) { raw in
|
|
108
|
+
String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
protocol FirebaseIdProviding {
|
|
4
|
+
/// Firebase Analytics' app instance ID, or nil when the app doesn't use Firebase Analytics.
|
|
5
|
+
func appInstanceId() -> String?
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
struct NoFirebaseIdProvider: FirebaseIdProviding {
|
|
9
|
+
func appInstanceId() -> String? { nil }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/// Reads `Analytics.appInstanceID()` when the host app links Firebase Analytics, without the SDK
|
|
13
|
+
/// depending on Firebase: the classes are looked up at runtime. Nil until the app has called
|
|
14
|
+
/// `FirebaseApp.configure()`, and nil while analytics storage consent is denied. A found ID is
|
|
15
|
+
/// cached for the process.
|
|
16
|
+
final class SystemFirebaseIdProvider: FirebaseIdProviding {
|
|
17
|
+
private let lock = NSLock()
|
|
18
|
+
private var cached: String?
|
|
19
|
+
|
|
20
|
+
func appInstanceId() -> String? {
|
|
21
|
+
lock.lock()
|
|
22
|
+
defer { lock.unlock() }
|
|
23
|
+
if let cached { return cached }
|
|
24
|
+
guard let app = NSClassFromString("FIRApp") as AnyObject?,
|
|
25
|
+
app.responds(to: NSSelectorFromString("defaultApp")),
|
|
26
|
+
app.perform(NSSelectorFromString("defaultApp"))?.takeUnretainedValue() != nil,
|
|
27
|
+
let analytics = NSClassFromString("FIRAnalytics") as AnyObject?,
|
|
28
|
+
analytics.responds(to: NSSelectorFromString("appInstanceID")),
|
|
29
|
+
let id = analytics.perform(NSSelectorFromString("appInstanceID"))?.takeUnretainedValue() as? String,
|
|
30
|
+
!id.isEmpty
|
|
31
|
+
else { return nil }
|
|
32
|
+
cached = id
|
|
33
|
+
return id
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(UIKit)
|
|
3
|
+
import UIKit
|
|
4
|
+
#endif
|
|
5
|
+
|
|
6
|
+
/// Which notifications mean "app went to the background / became active".
|
|
7
|
+
struct LifecycleNotifications {
|
|
8
|
+
var center: NotificationCenter
|
|
9
|
+
var background: Notification.Name
|
|
10
|
+
var foreground: Notification.Name
|
|
11
|
+
/// Whether the app is in the foreground right now. Called on the main thread at configure,
|
|
12
|
+
/// because wrappers (React Native, Flutter) configure after the app is already active.
|
|
13
|
+
var isActive: (() -> Bool)? = nil
|
|
14
|
+
|
|
15
|
+
/// UIKit's notifications on iOS; nil on the macOS test host.
|
|
16
|
+
static var system: LifecycleNotifications? {
|
|
17
|
+
#if canImport(UIKit) && os(iOS)
|
|
18
|
+
return LifecycleNotifications(
|
|
19
|
+
center: .default,
|
|
20
|
+
background: UIApplication.didEnterBackgroundNotification,
|
|
21
|
+
// didBecomeActive (not willEnterForeground): it also fires on a cold start, and after
|
|
22
|
+
// a URL that opened the app has been delivered.
|
|
23
|
+
foreground: UIApplication.didBecomeActiveNotification,
|
|
24
|
+
isActive: {
|
|
25
|
+
guard Thread.isMainThread, let app = UIApplication.anglerShared else { return false }
|
|
26
|
+
return MainActor.assumeIsolated { app.applicationState == .active }
|
|
27
|
+
}
|
|
28
|
+
)
|
|
29
|
+
#else
|
|
30
|
+
return nil
|
|
31
|
+
#endif
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Foreground/background notifications → callbacks, run synchronously on the posting thread
|
|
36
|
+
/// (the main thread for UIKit). Session timing lives in `AnglerCore`, which persists it.
|
|
37
|
+
final class LifecycleObserver {
|
|
38
|
+
static let sessionGap: TimeInterval = 1800
|
|
39
|
+
|
|
40
|
+
static func isNewSession(backgroundedFor: TimeInterval) -> Bool { backgroundedFor >= sessionGap }
|
|
41
|
+
|
|
42
|
+
private var tokens: [NSObjectProtocol] = []
|
|
43
|
+
private let center: NotificationCenter
|
|
44
|
+
|
|
45
|
+
init(notifications: LifecycleNotifications, onForeground: @escaping () -> Void, onBackground: @escaping () -> Void) {
|
|
46
|
+
center = notifications.center
|
|
47
|
+
tokens.append(center.addObserver(forName: notifications.background, object: nil, queue: nil) { _ in onBackground() })
|
|
48
|
+
tokens.append(center.addObserver(forName: notifications.foreground, object: nil, queue: nil) { _ in onForeground() })
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
deinit { tokens.forEach(center.removeObserver) }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// Whether protected files and UserDefaults can be read. They can't before the first unlock
|
|
55
|
+
/// after a reboot, when the app may still be launched in the background (VoIP, location).
|
|
56
|
+
struct ProtectedDataGate {
|
|
57
|
+
var center: NotificationCenter
|
|
58
|
+
var becameAvailable: Notification.Name
|
|
59
|
+
var isAvailable: () -> Bool
|
|
60
|
+
|
|
61
|
+
/// UIKit's protected-data state on iOS; nil on the macOS test host.
|
|
62
|
+
static var system: ProtectedDataGate? {
|
|
63
|
+
#if canImport(UIKit) && os(iOS)
|
|
64
|
+
return ProtectedDataGate(
|
|
65
|
+
center: .default,
|
|
66
|
+
becameAvailable: UIApplication.protectedDataDidBecomeAvailableNotification,
|
|
67
|
+
isAvailable: {
|
|
68
|
+
// Only knowable on the main thread; elsewhere assume the common case.
|
|
69
|
+
guard Thread.isMainThread, let app = UIApplication.anglerShared else { return true }
|
|
70
|
+
return MainActor.assumeIsolated { app.isProtectedDataAvailable }
|
|
71
|
+
}
|
|
72
|
+
)
|
|
73
|
+
#else
|
|
74
|
+
return nil
|
|
75
|
+
#endif
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#if canImport(UIKit) && os(iOS)
|
|
2
|
+
import UIKit
|
|
3
|
+
|
|
4
|
+
extension UIApplication {
|
|
5
|
+
/// `UIApplication.shared`, looked up at run time. The symbol is unavailable to app
|
|
6
|
+
/// extensions, which this package must also compile for. Nil inside an extension, where
|
|
7
|
+
/// there is no application object to observe or keep alive.
|
|
8
|
+
static var anglerShared: UIApplication? {
|
|
9
|
+
guard !Bundle.main.bundlePath.hasSuffix(".appex") else { return nil }
|
|
10
|
+
let selector = NSSelectorFromString("sharedApplication")
|
|
11
|
+
guard UIApplication.responds(to: selector) else { return nil }
|
|
12
|
+
return UIApplication.perform(selector)?.takeUnretainedValue() as? UIApplication
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
#endif
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
/// SDK logging. Debug messages only print when `debugLogging` is on; warnings and errors
|
|
5
|
+
/// always go to the unified log.
|
|
6
|
+
enum Log {
|
|
7
|
+
private static let logger = os.Logger(subsystem: "ai.getangler.analytics", category: "Angler")
|
|
8
|
+
private static let lock = NSLock()
|
|
9
|
+
private static var _debugEnabled = false
|
|
10
|
+
|
|
11
|
+
static var debugEnabled: Bool {
|
|
12
|
+
get { lock.lock(); defer { lock.unlock() }; return _debugEnabled }
|
|
13
|
+
set { lock.lock(); _debugEnabled = newValue; lock.unlock() }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
static func debug(_ message: @autoclosure () -> String) {
|
|
17
|
+
guard debugEnabled else { return }
|
|
18
|
+
let m = message()
|
|
19
|
+
logger.debug("\(m, privacy: .public)")
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
static func warning(_ message: String) { logger.warning("\(message, privacy: .public)") }
|
|
23
|
+
static func error(_ message: String) { logger.error("\(message, privacy: .public)") }
|
|
24
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Batches queued events, sends them, and applies the response policy and backoff
|
|
4
|
+
/// (design §7). Every call, and every transport callback, must happen on the owner's
|
|
5
|
+
/// serial queue; `AnglerCore` wraps its transport so callbacks hop back onto it.
|
|
6
|
+
final class Flusher {
|
|
7
|
+
private let queue: EventQueue
|
|
8
|
+
private let transport: Transport
|
|
9
|
+
private let src: String
|
|
10
|
+
private let batchSize: Int
|
|
11
|
+
private let scheduler: Scheduler
|
|
12
|
+
private let random: () -> Double
|
|
13
|
+
|
|
14
|
+
private(set) var isPaused = false
|
|
15
|
+
/// True while a request is in flight or a retry is waiting.
|
|
16
|
+
private(set) var isFlushing = false
|
|
17
|
+
private var attempt = 0
|
|
18
|
+
private var waitingForRetry = false
|
|
19
|
+
private var completions: [() -> Void] = []
|
|
20
|
+
/// Event groups still to send in this cycle (after isolate or split), last = next.
|
|
21
|
+
private var pendingGroups: [[QueuedEvent]] = []
|
|
22
|
+
|
|
23
|
+
init(queue: EventQueue, transport: Transport, src: String, batchSize: Int,
|
|
24
|
+
scheduler: Scheduler, random: @escaping () -> Double) {
|
|
25
|
+
self.queue = queue
|
|
26
|
+
self.transport = transport
|
|
27
|
+
self.src = src
|
|
28
|
+
self.batchSize = max(1, batchSize)
|
|
29
|
+
self.scheduler = scheduler
|
|
30
|
+
self.random = random
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/// Starts a flush unless one is already running (single flight) or the flusher is
|
|
34
|
+
/// paused. `completion` runs when the current cycle ends: the queue is drained,
|
|
35
|
+
/// sending is paused, or a retry has been scheduled.
|
|
36
|
+
func flush(completion: (() -> Void)?) {
|
|
37
|
+
if let completion { completions.append(completion) }
|
|
38
|
+
guard !isPaused else { return finish() }
|
|
39
|
+
guard !isFlushing else {
|
|
40
|
+
if waitingForRetry { runCompletions() }
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
isFlushing = true
|
|
44
|
+
sendNext()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private func sendNext() {
|
|
48
|
+
let group: [QueuedEvent]
|
|
49
|
+
if let next = pendingGroups.popLast() {
|
|
50
|
+
group = next
|
|
51
|
+
} else {
|
|
52
|
+
group = queue.peek(batchSize)
|
|
53
|
+
}
|
|
54
|
+
guard !group.isEmpty else { return finish() }
|
|
55
|
+
|
|
56
|
+
let body = PayloadBuilder.buildBody(src: src, events: group.map(\.body)).encoded()
|
|
57
|
+
transport.send(body) { [weak self] status in
|
|
58
|
+
self?.handle(status: status, group: group)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private func handle(status: Int?, group: [QueuedEvent]) {
|
|
63
|
+
let decision = ResponsePolicy.decide(status: status, batchSize: group.count)
|
|
64
|
+
switch decision {
|
|
65
|
+
case .remove:
|
|
66
|
+
attempt = 0
|
|
67
|
+
queue.remove(seqs: Set(group.map(\.seq)))
|
|
68
|
+
Log.debug("delivered \(group.count) event(s)")
|
|
69
|
+
case .drop:
|
|
70
|
+
attempt = 0
|
|
71
|
+
queue.remove(seqs: Set(group.map(\.seq)))
|
|
72
|
+
Log.error("dropping \(group.count) event(s) rejected with HTTP \(status.map(String.init) ?? "-")")
|
|
73
|
+
case .isolate:
|
|
74
|
+
pendingGroups.append(contentsOf: group.reversed().map { [$0] })
|
|
75
|
+
case .split:
|
|
76
|
+
let mid = group.count / 2
|
|
77
|
+
pendingGroups.append(Array(group[mid...]))
|
|
78
|
+
pendingGroups.append(Array(group[..<mid]))
|
|
79
|
+
case .pause:
|
|
80
|
+
isPaused = true
|
|
81
|
+
pendingGroups.removeAll()
|
|
82
|
+
Log.error("HTTP \(status.map(String.init) ?? "-"): check the workspace token; sending paused until next launch")
|
|
83
|
+
return finish()
|
|
84
|
+
case .retry:
|
|
85
|
+
pendingGroups.removeAll()
|
|
86
|
+
attempt += 1
|
|
87
|
+
let delay = Backoff.delay(attempt: attempt, r: random())
|
|
88
|
+
Log.debug("send failed (\(status.map(String.init) ?? "network error")); retrying in \(delay)s")
|
|
89
|
+
waitingForRetry = true
|
|
90
|
+
scheduler.schedule(after: delay) { [weak self] in
|
|
91
|
+
guard let self else { return }
|
|
92
|
+
self.waitingForRetry = false
|
|
93
|
+
self.isPaused ? self.finish() : self.sendNext()
|
|
94
|
+
}
|
|
95
|
+
// The attempt is over: release callers (e.g. a background task) while the
|
|
96
|
+
// retry waits. isFlushing stays true so no second cycle starts meanwhile.
|
|
97
|
+
return runCompletions()
|
|
98
|
+
}
|
|
99
|
+
sendNext()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private func finish() {
|
|
103
|
+
isFlushing = false
|
|
104
|
+
runCompletions()
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private func runCompletions() {
|
|
108
|
+
let done = completions
|
|
109
|
+
completions.removeAll()
|
|
110
|
+
done.forEach { $0() }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
enum FlushDecision: String {
|
|
4
|
+
case remove, isolate, drop, split, pause, retry
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/// HTTP result → what to do with the batch (design §7.2). Pure.
|
|
8
|
+
enum ResponsePolicy {
|
|
9
|
+
/// `status` nil means a network error or timeout.
|
|
10
|
+
static func decide(status: Int?, batchSize: Int) -> FlushDecision {
|
|
11
|
+
guard let status else { return .retry }
|
|
12
|
+
switch status {
|
|
13
|
+
case 200..<300: return .remove
|
|
14
|
+
case 400: return batchSize > 1 ? .isolate : .drop
|
|
15
|
+
case 413: return batchSize > 1 ? .split : .drop
|
|
16
|
+
case 401, 403: return .pause
|
|
17
|
+
case 429, 500..<600: return .retry
|
|
18
|
+
default: return .drop
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
enum Backoff {
|
|
24
|
+
/// `min(300, 2^(attempt-1)) × (0.5 + 0.5·r)` seconds, `r` in [0, 1).
|
|
25
|
+
static func delay(attempt: Int, r: Double) -> TimeInterval {
|
|
26
|
+
let base = min(300, pow(2, Double(max(1, attempt) - 1)))
|
|
27
|
+
return base * (0.5 + 0.5 * r)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
protocol Scheduler {
|
|
4
|
+
func schedule(after: TimeInterval, _ work: @escaping () -> Void)
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
struct DispatchScheduler: Scheduler {
|
|
8
|
+
let queue: DispatchQueue
|
|
9
|
+
|
|
10
|
+
func schedule(after delay: TimeInterval, _ work: @escaping () -> Void) {
|
|
11
|
+
queue.asyncAfter(deadline: .now() + delay, execute: work)
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
protocol Transport {
|
|
4
|
+
/// Calls back with the HTTP status, or nil for a network error or timeout.
|
|
5
|
+
func send(_ body: Data, completion: @escaping (Int?) -> Void)
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
final class URLSessionTransport: Transport {
|
|
9
|
+
static let timeout: TimeInterval = 15
|
|
10
|
+
|
|
11
|
+
private let endpoint: URL
|
|
12
|
+
private let token: String
|
|
13
|
+
private let session: URLSession
|
|
14
|
+
|
|
15
|
+
init(endpoint: URL, token: String) {
|
|
16
|
+
self.endpoint = endpoint
|
|
17
|
+
self.token = token
|
|
18
|
+
let config = URLSessionConfiguration.ephemeral
|
|
19
|
+
config.timeoutIntervalForRequest = Self.timeout
|
|
20
|
+
config.timeoutIntervalForResource = Self.timeout
|
|
21
|
+
config.waitsForConnectivity = false
|
|
22
|
+
session = URLSession(configuration: config)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// `https://{domain}/v1/workspaces/{workspaceId}/events`. Accepts a bare host (optionally
|
|
26
|
+
/// with a port) and tolerates a leading `https://` / `http://` and a trailing `/`. Nil for
|
|
27
|
+
/// anything else, so a typo fails loudly at configure instead of losing every event.
|
|
28
|
+
static func endpoint(domain: String, workspaceId: String) -> URL? {
|
|
29
|
+
var host = domain.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
30
|
+
for scheme in ["https://", "http://"] where host.lowercased().hasPrefix(scheme) {
|
|
31
|
+
host = String(host.dropFirst(scheme.count))
|
|
32
|
+
}
|
|
33
|
+
while host.hasSuffix("/") { host.removeLast() }
|
|
34
|
+
guard host.range(of: #"^[A-Za-z0-9.-]+(:[0-9]{1,5})?$"#, options: .regularExpression) != nil else { return nil }
|
|
35
|
+
let parts = host.split(separator: ":", maxSplits: 1)
|
|
36
|
+
var c = URLComponents()
|
|
37
|
+
c.scheme = "https"
|
|
38
|
+
c.host = String(parts[0])
|
|
39
|
+
if parts.count == 2 { c.port = Int(parts[1]) }
|
|
40
|
+
c.path = "/v1/workspaces/\(workspaceId)/events"
|
|
41
|
+
return c.url
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
func send(_ body: Data, completion: @escaping (Int?) -> Void) {
|
|
45
|
+
var request = URLRequest(url: endpoint, timeoutInterval: Self.timeout)
|
|
46
|
+
request.httpMethod = "POST"
|
|
47
|
+
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
48
|
+
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
|
49
|
+
request.httpBody = body
|
|
50
|
+
session.dataTask(with: request) { _, response, error in
|
|
51
|
+
if error != nil { return completion(nil) }
|
|
52
|
+
completion((response as? HTTPURLResponse)?.statusCode)
|
|
53
|
+
}.resume()
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// A JSON value. Events are built as `JSONValue` at `track()` time and stored in the
|
|
4
|
+
/// queue exactly as they will be sent.
|
|
5
|
+
enum JSONValue: Codable, Equatable {
|
|
6
|
+
case string(String)
|
|
7
|
+
case number(Double)
|
|
8
|
+
case bool(Bool)
|
|
9
|
+
case null
|
|
10
|
+
case array([JSONValue])
|
|
11
|
+
case object([String: JSONValue])
|
|
12
|
+
|
|
13
|
+
/// Converts a Foundation value. Returns nil for values JSON can't represent;
|
|
14
|
+
/// such values are dropped from inside arrays and objects.
|
|
15
|
+
/// Nesting deeper than this is dropped (also stops a dictionary that contains itself).
|
|
16
|
+
static let maxDepth = 32
|
|
17
|
+
|
|
18
|
+
static func from(_ any: Any) -> JSONValue? { from(any, depth: 0) }
|
|
19
|
+
|
|
20
|
+
private static func from(_ any: Any, depth: Int) -> JSONValue? {
|
|
21
|
+
switch any {
|
|
22
|
+
case let v as JSONValue:
|
|
23
|
+
return v
|
|
24
|
+
case let s as String:
|
|
25
|
+
return .string(s)
|
|
26
|
+
case let n as NSNumber:
|
|
27
|
+
if CFGetTypeID(n) == CFBooleanGetTypeID() { return .bool(n.boolValue) }
|
|
28
|
+
let d = n.doubleValue
|
|
29
|
+
return d.isFinite ? .number(d) : nil
|
|
30
|
+
case is NSNull:
|
|
31
|
+
return .null
|
|
32
|
+
case let a as [Any]:
|
|
33
|
+
guard depth < maxDepth else { return nil }
|
|
34
|
+
return .array(a.compactMap { from($0, depth: depth + 1) })
|
|
35
|
+
case let o as [String: Any]:
|
|
36
|
+
guard depth < maxDepth else { return nil }
|
|
37
|
+
var out: [String: JSONValue] = [:]
|
|
38
|
+
for (k, v) in o { if let j = from(v, depth: depth + 1) { out[k] = j } }
|
|
39
|
+
return .object(out)
|
|
40
|
+
default:
|
|
41
|
+
// Optional.none boxed in Any
|
|
42
|
+
if case Optional<Any>.none = any { return .null }
|
|
43
|
+
return nil
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// Compact JSON with sorted keys.
|
|
48
|
+
func encoded() -> Data {
|
|
49
|
+
let encoder = JSONEncoder()
|
|
50
|
+
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
|
|
51
|
+
return (try? encoder.encode(self)) ?? Data("null".utf8)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
init(from decoder: Decoder) throws {
|
|
55
|
+
let c = try decoder.singleValueContainer()
|
|
56
|
+
if c.decodeNil() { self = .null }
|
|
57
|
+
else if let b = try? c.decode(Bool.self) { self = .bool(b) }
|
|
58
|
+
else if let d = try? c.decode(Double.self) { self = .number(d) }
|
|
59
|
+
else if let s = try? c.decode(String.self) { self = .string(s) }
|
|
60
|
+
else if let a = try? c.decode([JSONValue].self) { self = .array(a) }
|
|
61
|
+
else { self = .object(try c.decode([String: JSONValue].self)) }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
func encode(to encoder: Encoder) throws {
|
|
65
|
+
var c = encoder.singleValueContainer()
|
|
66
|
+
switch self {
|
|
67
|
+
case .string(let s): try c.encode(s)
|
|
68
|
+
case .number(let d):
|
|
69
|
+
if d.rounded() == d, abs(d) < 1e15 { try c.encode(Int64(d)) } else { try c.encode(d) }
|
|
70
|
+
case .bool(let b): try c.encode(b)
|
|
71
|
+
case .null: try c.encodeNil()
|
|
72
|
+
case .array(let a): try c.encode(a)
|
|
73
|
+
case .object(let o): try c.encode(o)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
var stringValue: String? { if case .string(let s) = self { return s }; return nil }
|
|
78
|
+
var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }
|
|
79
|
+
var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil }
|
|
80
|
+
subscript(key: String) -> JSONValue? { objectValue?[key] }
|
|
81
|
+
}
|