@app-swiss-knife/react-native-sdk 0.1.0
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/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Net/IngestClient.swift
|
|
2
|
+
//
|
|
3
|
+
// Wave 3 unified ingest pipeline — single client for every write path the
|
|
4
|
+
// SDK sends to swiss-ingest's `POST /ingest` endpoint. Replaces the
|
|
5
|
+
// per-feature endpoints (`/events/batch`, `/errors/event/batch`,
|
|
6
|
+
// `/subscriptions/validate`, paywall events, funnel events, performance
|
|
7
|
+
// transactions) with one typed envelope.
|
|
8
|
+
//
|
|
9
|
+
// Contract — `apps/swiss-ingest/src/routes/ingest.ts`:
|
|
10
|
+
// POST /ingest
|
|
11
|
+
// Headers: X-API-Key
|
|
12
|
+
// Body (batched): { items: [{ type, data }, ...] } max 100
|
|
13
|
+
// Body (single): { type, data } auto-wrapped
|
|
14
|
+
// Returns: 202 with { queued: N, errors: [{index, error}] }
|
|
15
|
+
//
|
|
16
|
+
// `type` is one of:
|
|
17
|
+
// "error" | "error_batch" | "analytics" | "transaction" | "session"
|
|
18
|
+
// | "feedback" | "paywall" | "funnel"
|
|
19
|
+
// (`store_notification` is server-side only — webhooks land there.)
|
|
20
|
+
//
|
|
21
|
+
// Architecture:
|
|
22
|
+
// - `enqueue(_ item: IngestItem)` writes to `OfflineQueueStore<IngestItem>`
|
|
23
|
+
// synchronously and returns immediately. The item carries an
|
|
24
|
+
// `event_id` (UUIDv4) stamped at enqueue time — this is the
|
|
25
|
+
// idempotency key the backend dedupes on.
|
|
26
|
+
// - Flush is size-threshold + lifecycle-driven only — there is no
|
|
27
|
+
// periodic timer. A flush is triggered when the queue crosses
|
|
28
|
+
// `batchSize` (default 100), when reachability returns, or when the
|
|
29
|
+
// app enters background. A `Task`-driven flush coordinator
|
|
30
|
+
// short-circuits redundant schedules so concurrent enqueues coalesce
|
|
31
|
+
// into a single drain.
|
|
32
|
+
// - On flush, the client reads `SwissKnife.Identity.current` and stamps
|
|
33
|
+
// `anonymous_id` + `user_id` into each item's outgoing envelope.
|
|
34
|
+
// Items enqueued before an identity change get the CURRENT identity at
|
|
35
|
+
// flush time (matches RC's late-binding behaviour).
|
|
36
|
+
// - Retries go through `BackendHttpClient` — 4xx dead-letters
|
|
37
|
+
// immediately, 5xx / network errors retry with the shared
|
|
38
|
+
// `ExponentialBackoff`. After the bounded retry budget the items go
|
|
39
|
+
// to the dead-letter file and are removed from the live queue.
|
|
40
|
+
|
|
41
|
+
import Foundation
|
|
42
|
+
import os.log
|
|
43
|
+
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
// MARK: - Type enum
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
/// All ingest item types accepted by `POST /ingest`. Mirror of
|
|
49
|
+
/// `apps/swiss-ingest/src/core/ingest.ts` `IngestItem.type`. The
|
|
50
|
+
/// `errorBatch` case wraps an array of `error` payloads — used by the
|
|
51
|
+
/// crash reporter when it has multiple buffered crashes to send.
|
|
52
|
+
///
|
|
53
|
+
/// `storeNotification` is intentionally absent: it's an Apple/Google
|
|
54
|
+
/// webhook path the server handles directly, never originated by the SDK.
|
|
55
|
+
internal enum IngestItemType: String, Codable, Sendable {
|
|
56
|
+
case error
|
|
57
|
+
case errorBatch = "error_batch"
|
|
58
|
+
case analytics
|
|
59
|
+
case transaction
|
|
60
|
+
case session
|
|
61
|
+
case feedback
|
|
62
|
+
case paywall
|
|
63
|
+
case funnel
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// MARK: - IngestItem (wire + queue representation)
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
/// Single queued item. `id` is the local idempotency key — stamped at
|
|
71
|
+
/// `enqueue()` time, used by `OfflineQueueStore.remove(ids:)` after the
|
|
72
|
+
/// server accepts the batch, and embedded in the outgoing payload via
|
|
73
|
+
/// `event_id` so the backend dedupes on it too.
|
|
74
|
+
///
|
|
75
|
+
/// `data` is type-erased JSON because each `type` has a different schema
|
|
76
|
+
/// (validated on the server). We can't statically enforce all 8 shapes
|
|
77
|
+
/// without splitting into 8 generic queues — not worth the type ceremony.
|
|
78
|
+
internal struct IngestItem: Codable, Identifiable, Sendable {
|
|
79
|
+
let id: String
|
|
80
|
+
let type: IngestItemType
|
|
81
|
+
let data: AnyEncodable
|
|
82
|
+
let enqueuedAtMs: Int64
|
|
83
|
+
|
|
84
|
+
init(type: IngestItemType, data: AnyEncodable, id: String = IDs.eventId()) {
|
|
85
|
+
self.id = id
|
|
86
|
+
self.type = type
|
|
87
|
+
self.data = data
|
|
88
|
+
self.enqueuedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Custom decoding — JSON envelope keys are camelCase locally, but
|
|
92
|
+
// when decoded back from disk we want the same shape.
|
|
93
|
+
private enum CodingKeys: String, CodingKey {
|
|
94
|
+
case id, type, data, enqueuedAtMs
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// MARK: - AnyEncodable / AnyCodable type-erasure
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
/// Holder for arbitrary JSON-encodable values. We use a thin shim around
|
|
103
|
+
/// `JSONSerialization` for two reasons:
|
|
104
|
+
/// 1. The data shapes vary per `IngestItemType` and we want each
|
|
105
|
+
/// producer (Analytics, Crash, ...) to be free to choose dictionary
|
|
106
|
+
/// or struct without us mandating one.
|
|
107
|
+
/// 2. The persisted queue round-trips through JSONL — we re-encode on
|
|
108
|
+
/// read, so storing as a normalized JSON value is cheaper than
|
|
109
|
+
/// carrying through a generic `T: Codable`.
|
|
110
|
+
internal struct AnyEncodable: Codable, Sendable {
|
|
111
|
+
/// Lossless JSON representation as raw `Data`. Always valid JSON.
|
|
112
|
+
private let jsonData: Data
|
|
113
|
+
|
|
114
|
+
/// Wrap an already-`Encodable` value (struct, dict-as-Encodable).
|
|
115
|
+
init<T: Encodable>(_ value: T) throws {
|
|
116
|
+
let encoder = JSONEncoder()
|
|
117
|
+
self.jsonData = try encoder.encode(value)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/// Wrap a JSON-foundation value (`[String: Any]` / `[Any]` / scalar).
|
|
121
|
+
/// Used by the legacy `[String: Any]` event dictionaries that
|
|
122
|
+
/// `SKAnalytics.track` builds.
|
|
123
|
+
init(jsonObject: Any) throws {
|
|
124
|
+
// `[String: Any]` containing `NSNull` is valid JSON; check first
|
|
125
|
+
// so JSONSerialization doesn't reject scalars at the top level.
|
|
126
|
+
if JSONSerialization.isValidJSONObject(jsonObject) {
|
|
127
|
+
self.jsonData = try JSONSerialization.data(withJSONObject: jsonObject)
|
|
128
|
+
} else {
|
|
129
|
+
// Top-level scalar — wrap so JSONSerialization accepts it.
|
|
130
|
+
self.jsonData = try JSONSerialization.data(withJSONObject: [jsonObject])
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// Raw bytes — used internally when assembling the outgoing envelope.
|
|
135
|
+
var rawJSON: Data { jsonData }
|
|
136
|
+
|
|
137
|
+
/// JSON-decode back to a foundation object (used in tests).
|
|
138
|
+
func asJSONObject() throws -> Any {
|
|
139
|
+
try JSONSerialization.jsonObject(with: jsonData)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Codable — pass-through. Encoder writes the raw bytes as-is; decoder
|
|
143
|
+
// reads a JSON value and re-encodes it to normalize.
|
|
144
|
+
init(from decoder: Decoder) throws {
|
|
145
|
+
let container = try decoder.singleValueContainer()
|
|
146
|
+
// Try value-as-Any first via JSONSerialization fall-through.
|
|
147
|
+
// Decoding sub-values without knowing the schema is awkward in
|
|
148
|
+
// Codable — easiest is to grab the raw bytes from the data
|
|
149
|
+
// representation if the decoder is a JSONDecoder, else
|
|
150
|
+
// reconstitute via Any.
|
|
151
|
+
if let v = try? container.decode([String: AnyDecodableLeaf].self) {
|
|
152
|
+
self = try AnyEncodable(jsonObject: v.mapValues { $0.value })
|
|
153
|
+
return
|
|
154
|
+
}
|
|
155
|
+
if let v = try? container.decode([AnyDecodableLeaf].self) {
|
|
156
|
+
self = try AnyEncodable(jsonObject: v.map { $0.value })
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
if let v = try? container.decode(String.self) {
|
|
160
|
+
self = try AnyEncodable(jsonObject: v)
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
if let v = try? container.decode(Double.self) {
|
|
164
|
+
self = try AnyEncodable(jsonObject: v)
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
if let v = try? container.decode(Bool.self) {
|
|
168
|
+
self = try AnyEncodable(jsonObject: v)
|
|
169
|
+
return
|
|
170
|
+
}
|
|
171
|
+
// Default — empty object.
|
|
172
|
+
self = try AnyEncodable(jsonObject: [String: Any]())
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
func encode(to encoder: Encoder) throws {
|
|
176
|
+
// Write the raw JSON bytes back into whatever encoder we're given.
|
|
177
|
+
let json = try JSONSerialization.jsonObject(with: jsonData, options: [.fragmentsAllowed])
|
|
178
|
+
var container = encoder.singleValueContainer()
|
|
179
|
+
try container.encode(AnyDecodableLeaf(value: json))
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// Internal helper — Codable leaf that round-trips any JSON scalar /
|
|
184
|
+
/// container. Used only by `AnyEncodable`'s `init(from:)` / `encode(to:)`.
|
|
185
|
+
/// `@unchecked Sendable` because `value: Any` is always a JSON-derived
|
|
186
|
+
/// immutable value (Bool/Int/Double/String/NSNull/Array/Dictionary of the
|
|
187
|
+
/// same). Swift can't prove this through `Any`, so we assert it manually.
|
|
188
|
+
private struct AnyDecodableLeaf: Codable, @unchecked Sendable {
|
|
189
|
+
let value: Any
|
|
190
|
+
|
|
191
|
+
init(value: Any) { self.value = value }
|
|
192
|
+
|
|
193
|
+
init(from decoder: Decoder) throws {
|
|
194
|
+
let container = try decoder.singleValueContainer()
|
|
195
|
+
if container.decodeNil() {
|
|
196
|
+
self.value = NSNull()
|
|
197
|
+
} else if let v = try? container.decode(Bool.self) {
|
|
198
|
+
self.value = v
|
|
199
|
+
} else if let v = try? container.decode(Int.self) {
|
|
200
|
+
self.value = v
|
|
201
|
+
} else if let v = try? container.decode(Double.self) {
|
|
202
|
+
self.value = v
|
|
203
|
+
} else if let v = try? container.decode(String.self) {
|
|
204
|
+
self.value = v
|
|
205
|
+
} else if let arr = try? container.decode([AnyDecodableLeaf].self) {
|
|
206
|
+
self.value = arr.map { $0.value }
|
|
207
|
+
} else if let dict = try? container.decode([String: AnyDecodableLeaf].self) {
|
|
208
|
+
self.value = dict.mapValues { $0.value }
|
|
209
|
+
} else {
|
|
210
|
+
self.value = NSNull()
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
func encode(to encoder: Encoder) throws {
|
|
215
|
+
var container = encoder.singleValueContainer()
|
|
216
|
+
switch value {
|
|
217
|
+
case is NSNull:
|
|
218
|
+
try container.encodeNil()
|
|
219
|
+
case let v as Bool:
|
|
220
|
+
try container.encode(v)
|
|
221
|
+
case let v as Int:
|
|
222
|
+
try container.encode(v)
|
|
223
|
+
case let v as Int64:
|
|
224
|
+
try container.encode(v)
|
|
225
|
+
case let v as Double:
|
|
226
|
+
try container.encode(v)
|
|
227
|
+
case let v as String:
|
|
228
|
+
try container.encode(v)
|
|
229
|
+
case let v as [Any]:
|
|
230
|
+
try container.encode(v.map { AnyDecodableLeaf(value: $0) })
|
|
231
|
+
case let v as [String: Any]:
|
|
232
|
+
try container.encode(v.mapValues { AnyDecodableLeaf(value: $0) })
|
|
233
|
+
default:
|
|
234
|
+
try container.encodeNil()
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ---------------------------------------------------------------------------
|
|
240
|
+
// MARK: - Result types
|
|
241
|
+
// ---------------------------------------------------------------------------
|
|
242
|
+
|
|
243
|
+
/// Mirror of the server's `IngestResult`.
|
|
244
|
+
internal struct IngestResult: Codable, Sendable {
|
|
245
|
+
let queued: Int
|
|
246
|
+
let errors: [IngestErrorEntry]
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
internal struct IngestErrorEntry: Codable, Sendable {
|
|
250
|
+
let index: Int
|
|
251
|
+
let error: String
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ---------------------------------------------------------------------------
|
|
255
|
+
// MARK: - ContextSnapshot
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
|
|
258
|
+
/// The cross-cutting context stamped onto every IngestItem at flush time.
|
|
259
|
+
/// Materialises the Round-A primitives (Identity + Session + DeviceContext +
|
|
260
|
+
/// Clock + IDs) into one wire-shaped struct.
|
|
261
|
+
///
|
|
262
|
+
/// Each field is captured from the SDK's CURRENT state at flush time except
|
|
263
|
+
/// `eventId`, which is re-minted per item so retries reuse the persisted
|
|
264
|
+
/// `IngestItem.id` and the backend dedupes correctly.
|
|
265
|
+
internal struct ContextSnapshot: Codable, Sendable, Equatable {
|
|
266
|
+
/// Per-item idempotency key. The backend dedupes against
|
|
267
|
+
/// `(app_project_id, event_id)` so retries MUST reuse this id —
|
|
268
|
+
/// derived from `IngestItem.id` (not freshly minted at flush time).
|
|
269
|
+
let eventId: String
|
|
270
|
+
let anonymousId: String
|
|
271
|
+
let userId: String?
|
|
272
|
+
let sessionId: String
|
|
273
|
+
let sessionNumber: Int
|
|
274
|
+
let timestamp: Date
|
|
275
|
+
let device: DeviceContext
|
|
276
|
+
/// Duplicated from `device.sdkVersion` for top-level visibility — some
|
|
277
|
+
/// downstream consumers (alerting, dashboards) key off this without
|
|
278
|
+
/// drilling into the nested device block.
|
|
279
|
+
let sdkVersion: String
|
|
280
|
+
|
|
281
|
+
enum CodingKeys: String, CodingKey {
|
|
282
|
+
case eventId = "event_id"
|
|
283
|
+
case anonymousId = "anonymous_id"
|
|
284
|
+
case userId = "user_id"
|
|
285
|
+
case sessionId = "session_id"
|
|
286
|
+
case sessionNumber = "session_number"
|
|
287
|
+
case timestamp
|
|
288
|
+
case device
|
|
289
|
+
case sdkVersion = "sdk_version"
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ---------------------------------------------------------------------------
|
|
294
|
+
// MARK: - IngestClient
|
|
295
|
+
// ---------------------------------------------------------------------------
|
|
296
|
+
|
|
297
|
+
/// Unified client for the `/ingest` endpoint. Single shared instance.
|
|
298
|
+
internal final class IngestClient: @unchecked Sendable {
|
|
299
|
+
|
|
300
|
+
/// Shared production instance — wired to the live BackendHttpClient.
|
|
301
|
+
static let shared: IngestClient = {
|
|
302
|
+
// This runs lazily the first time the SDK touches the ingest
|
|
303
|
+
// pipeline — typically during `SwissKnife.configure`. It MUST NOT
|
|
304
|
+
// throw or crash: a startup SIGABRT here takes the whole host app
|
|
305
|
+
// down. Data loss is preferable to a startup crash (see the
|
|
306
|
+
// OfflineQueueStore header), so every fallback below is non-fatal.
|
|
307
|
+
//
|
|
308
|
+
// 1. Preferred: the durable `cachesDirectory` JSONL queue.
|
|
309
|
+
if let queue = try? OfflineQueueStore<IngestItem>(name: "ingest") {
|
|
310
|
+
return IngestClient(queue: queue)
|
|
311
|
+
}
|
|
312
|
+
// 2. Fallback: a tmpdir-backed durable queue (caches dir may be
|
|
313
|
+
// unavailable under sandboxing / disk pressure).
|
|
314
|
+
let tmp = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
|
|
315
|
+
.appendingPathComponent("SwissKnife-ingest-fallback-\(IDs.requestId())")
|
|
316
|
+
if let queue = try? OfflineQueueStore<IngestItem>(directory: tmp, name: "ingest-fb") {
|
|
317
|
+
return IngestClient(queue: queue)
|
|
318
|
+
}
|
|
319
|
+
// 3. Last-ditch: a purely in-memory queue. Cannot throw, cannot
|
|
320
|
+
// crash. Items are lost on process termination, but the SDK —
|
|
321
|
+
// and the host app — stay alive.
|
|
322
|
+
let memoryQueue = OfflineQueueStore<IngestItem>(inMemoryName: "ingest-mem")
|
|
323
|
+
return IngestClient(queue: memoryQueue)
|
|
324
|
+
}()
|
|
325
|
+
|
|
326
|
+
/// Max items per HTTP request. Mirrors the server's 100-item cap on
|
|
327
|
+
/// the envelope's `items` array.
|
|
328
|
+
let batchSize: Int
|
|
329
|
+
let path: String
|
|
330
|
+
|
|
331
|
+
private let queue: OfflineQueueStore<IngestItem>
|
|
332
|
+
private let http: BackendHttpClient
|
|
333
|
+
private let identitySnapshot: @Sendable () -> SwissKnife.Identity.Snapshot
|
|
334
|
+
private let sessionSnapshot: @Sendable () -> SessionSnapshot
|
|
335
|
+
private let deviceSnapshot: @Sendable () -> DeviceContext
|
|
336
|
+
private let timestampProvider: @Sendable () -> Date
|
|
337
|
+
private let log = OSLog(subsystem: "com.swissknife.net", category: "IngestClient")
|
|
338
|
+
|
|
339
|
+
// Flush coordination — `flushTask` keeps the latest in-flight task
|
|
340
|
+
// (`nil` between flushes). `isFlushing` short-circuits redundant
|
|
341
|
+
// schedule calls. Both are guarded by `flushQueue` which is a
|
|
342
|
+
// serial DispatchQueue (sync-safe from async contexts, unlike
|
|
343
|
+
// NSLock which Swift 6 will reject).
|
|
344
|
+
private let flushQueue = DispatchQueue(label: "com.swissknife.ingest.flush")
|
|
345
|
+
private var flushTask: Task<Void, Never>?
|
|
346
|
+
private var isFlushing: Bool = false
|
|
347
|
+
|
|
348
|
+
/// Whether the network is reachable. Updated by the Reachability
|
|
349
|
+
/// observer; flush short-circuits to no-op when false.
|
|
350
|
+
private var isReachable: Bool = true
|
|
351
|
+
private var reachabilityToken: UUID?
|
|
352
|
+
private var lifecycleToken: UUID?
|
|
353
|
+
|
|
354
|
+
init(
|
|
355
|
+
queue: OfflineQueueStore<IngestItem>,
|
|
356
|
+
http: BackendHttpClient = BackendHttpClient.shared,
|
|
357
|
+
batchSize: Int = 100,
|
|
358
|
+
// Kept as an ignored init parameter only for source compatibility
|
|
359
|
+
// with the small number of test sites that still pass it. Flush is
|
|
360
|
+
// size-threshold + lifecycle-driven; there is no periodic timer to
|
|
361
|
+
// configure. Will be removed after callers migrate.
|
|
362
|
+
flushIntervalSec: TimeInterval = 0,
|
|
363
|
+
path: String = "/ingest",
|
|
364
|
+
identitySnapshot: @escaping @Sendable () -> SwissKnife.Identity.Snapshot
|
|
365
|
+
= { SwissKnife.Identity.current },
|
|
366
|
+
sessionSnapshot: @escaping @Sendable () -> SessionSnapshot
|
|
367
|
+
= { Session.shared.current },
|
|
368
|
+
deviceSnapshot: @escaping @Sendable () -> DeviceContext
|
|
369
|
+
= { DeviceContextProvider.current() },
|
|
370
|
+
timestampProvider: @escaping @Sendable () -> Date = { Clock.now() }
|
|
371
|
+
) {
|
|
372
|
+
_ = flushIntervalSec // intentionally unused — see param doc.
|
|
373
|
+
self.queue = queue
|
|
374
|
+
self.http = http
|
|
375
|
+
self.batchSize = batchSize
|
|
376
|
+
self.path = path
|
|
377
|
+
self.identitySnapshot = identitySnapshot
|
|
378
|
+
self.sessionSnapshot = sessionSnapshot
|
|
379
|
+
self.deviceSnapshot = deviceSnapshot
|
|
380
|
+
self.timestampProvider = timestampProvider
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// MARK: - Public enqueue API
|
|
384
|
+
|
|
385
|
+
/// Enqueue an `IngestItem` synchronously. Returns immediately;
|
|
386
|
+
/// the item is on disk by the time this returns. If the queue
|
|
387
|
+
/// crosses `batchSize` items, schedules an immediate flush.
|
|
388
|
+
func enqueue(_ item: IngestItem) {
|
|
389
|
+
do {
|
|
390
|
+
try queue.append(item)
|
|
391
|
+
// Check size and trigger an immediate flush if we crossed
|
|
392
|
+
// the threshold. The size() call is cheap — file-stat only.
|
|
393
|
+
if let count = try? queue.count(), count >= batchSize {
|
|
394
|
+
scheduleImmediateFlush()
|
|
395
|
+
}
|
|
396
|
+
} catch {
|
|
397
|
+
os_log(
|
|
398
|
+
"IngestClient.enqueue failed: %{public}@",
|
|
399
|
+
log: log,
|
|
400
|
+
type: .error,
|
|
401
|
+
String(describing: error)
|
|
402
|
+
)
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/// Convenience — build an item from a typed `Encodable` body.
|
|
407
|
+
func enqueue(type: IngestItemType, data: some Encodable) {
|
|
408
|
+
do {
|
|
409
|
+
let item = IngestItem(type: type, data: try AnyEncodable(data))
|
|
410
|
+
enqueue(item)
|
|
411
|
+
} catch {
|
|
412
|
+
os_log(
|
|
413
|
+
"IngestClient.enqueue<Encodable> failed: %{public}@",
|
|
414
|
+
log: log,
|
|
415
|
+
type: .error,
|
|
416
|
+
String(describing: error)
|
|
417
|
+
)
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/// Convenience — enqueue from a `[String: Any]` dictionary (legacy
|
|
422
|
+
/// analytics path). The dictionary must be JSON-serializable.
|
|
423
|
+
func enqueue(type: IngestItemType, jsonObject: [String: Any]) {
|
|
424
|
+
do {
|
|
425
|
+
let item = IngestItem(type: type, data: try AnyEncodable(jsonObject: jsonObject))
|
|
426
|
+
enqueue(item)
|
|
427
|
+
} catch {
|
|
428
|
+
os_log(
|
|
429
|
+
"IngestClient.enqueue<JSON> failed: %{public}@",
|
|
430
|
+
log: log,
|
|
431
|
+
type: .error,
|
|
432
|
+
String(describing: error)
|
|
433
|
+
)
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// MARK: - Flush
|
|
438
|
+
|
|
439
|
+
/// Drain the queue in batches of up to `batchSize`. Returns the
|
|
440
|
+
/// aggregated `IngestResult` across all batches. Items that hit a
|
|
441
|
+
/// terminal `backendRejected` error are dead-lettered.
|
|
442
|
+
///
|
|
443
|
+
/// If the network is unreachable (per the Reachability observer), the
|
|
444
|
+
/// flush short-circuits to an empty result — items stay queued and
|
|
445
|
+
/// will be re-attempted when reachability returns. This prevents the
|
|
446
|
+
/// retry budget from being burned on calls we know will fail at the
|
|
447
|
+
/// DNS / TCP layer.
|
|
448
|
+
@discardableResult
|
|
449
|
+
func flush() async throws -> IngestResult {
|
|
450
|
+
let reachable = flushQueue.sync { isReachable }
|
|
451
|
+
if !reachable {
|
|
452
|
+
return IngestResult(queued: 0, errors: [])
|
|
453
|
+
}
|
|
454
|
+
var aggregateQueued = 0
|
|
455
|
+
var aggregateErrors: [IngestErrorEntry] = []
|
|
456
|
+
|
|
457
|
+
while true {
|
|
458
|
+
let items = try queue.readAll()
|
|
459
|
+
if items.isEmpty { break }
|
|
460
|
+
let batch = Array(items.prefix(batchSize))
|
|
461
|
+
let result = try await sendBatch(batch)
|
|
462
|
+
aggregateQueued += result.queued
|
|
463
|
+
aggregateErrors.append(contentsOf: result.errors)
|
|
464
|
+
// Remove ALL items the server reported on (queued + errors).
|
|
465
|
+
// The errors array references items by index in this batch —
|
|
466
|
+
// they're validation rejects, not retriable, so they go to
|
|
467
|
+
// dead-letter.
|
|
468
|
+
let errorIdxs = Set(result.errors.map { $0.index })
|
|
469
|
+
let deadLetterItems = batch.enumerated().compactMap { (i, item) in
|
|
470
|
+
errorIdxs.contains(i) ? item : nil
|
|
471
|
+
}
|
|
472
|
+
if !deadLetterItems.isEmpty {
|
|
473
|
+
queue.deadLetter(deadLetterItems)
|
|
474
|
+
}
|
|
475
|
+
try queue.remove(ids: Set(batch.map { $0.id }))
|
|
476
|
+
// If the batch was the full size, there might be more — loop.
|
|
477
|
+
if batch.count < batchSize { break }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
return IngestResult(queued: aggregateQueued, errors: aggregateErrors)
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/// Drain the queue, ignoring all errors. Used by the background
|
|
484
|
+
/// timer-driven flush where there's no caller to await an outcome.
|
|
485
|
+
func flushBestEffort() async {
|
|
486
|
+
do { _ = try await flush() } catch {
|
|
487
|
+
os_log(
|
|
488
|
+
"IngestClient flush failed: %{public}@",
|
|
489
|
+
log: log,
|
|
490
|
+
type: .error,
|
|
491
|
+
String(describing: error)
|
|
492
|
+
)
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/// Send one batch through `BackendHttpClient.postRaw`. ContextSnapshot
|
|
497
|
+
/// stamping happens HERE — we read Identity / Session / Device / Clock
|
|
498
|
+
/// at flush time and embed a per-item `context` block alongside each
|
|
499
|
+
/// payload. This is the "late binding" semantic: items enqueued under
|
|
500
|
+
/// a previous identity get the current one at send time, mirroring
|
|
501
|
+
/// RevenueCat's identify flow.
|
|
502
|
+
private func sendBatch(_ batch: [IngestItem]) async throws -> IngestResult {
|
|
503
|
+
let envelope = try buildEnvelope(batch: batch)
|
|
504
|
+
let responseData = try await http.postRaw(path: path, body: envelope)
|
|
505
|
+
let decoded: IngestResult
|
|
506
|
+
do {
|
|
507
|
+
decoded = try JSONDecoder().decode(IngestResult.self, from: responseData)
|
|
508
|
+
} catch {
|
|
509
|
+
// 202 with empty body is acceptable.
|
|
510
|
+
decoded = IngestResult(queued: batch.count, errors: [])
|
|
511
|
+
}
|
|
512
|
+
return decoded
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/// Build a `ContextSnapshot` for a given item. Per-item because
|
|
516
|
+
/// `event_id` is unique to each item; everything else is shared by
|
|
517
|
+
/// snapshot-at-flush-time.
|
|
518
|
+
private func buildContext(for item: IngestItem) -> ContextSnapshot {
|
|
519
|
+
let identity = identitySnapshot()
|
|
520
|
+
let session = sessionSnapshot()
|
|
521
|
+
let device = deviceSnapshot()
|
|
522
|
+
return ContextSnapshot(
|
|
523
|
+
eventId: item.id,
|
|
524
|
+
anonymousId: identity.anonymousId,
|
|
525
|
+
userId: identity.userId,
|
|
526
|
+
sessionId: session.id,
|
|
527
|
+
sessionNumber: session.sessionNumber,
|
|
528
|
+
timestamp: timestampProvider(),
|
|
529
|
+
device: device,
|
|
530
|
+
sdkVersion: device.sdkVersion
|
|
531
|
+
)
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/// Assemble the outgoing envelope JSON.
|
|
535
|
+
///
|
|
536
|
+
/// Wire shape: `{ items: [ {type, data, context}, ... ] }`.
|
|
537
|
+
/// `context` is the full ContextSnapshot serialized as a flat block —
|
|
538
|
+
/// downstream consumers of swiss-ingest read it as extras alongside the
|
|
539
|
+
/// schema-validated `data`. The server's ingest schema accepts
|
|
540
|
+
/// `data: unknown` so the per-type payload shapes are passed through
|
|
541
|
+
/// untouched.
|
|
542
|
+
///
|
|
543
|
+
/// Legacy back-compat: for `analytics` items we ALSO inject
|
|
544
|
+
/// `anonymous_id` + `user_id` directly into `data` since the downstream
|
|
545
|
+
/// `/api/sdk/events/batch` consumer reads them from there. Future
|
|
546
|
+
/// rounds will drop this once all consumers read from the `context`
|
|
547
|
+
/// block.
|
|
548
|
+
private func buildEnvelope(batch: [IngestItem]) throws -> Data {
|
|
549
|
+
var items: [[String: Any]] = []
|
|
550
|
+
let encoder = JSONEncoder()
|
|
551
|
+
for item in batch {
|
|
552
|
+
var data = (try? item.data.asJSONObject() as? [String: Any]) ?? [:]
|
|
553
|
+
let context = buildContext(for: item)
|
|
554
|
+
|
|
555
|
+
// Legacy: keep direct `anonymous_id`/`user_id` on analytics
|
|
556
|
+
// data block for backward compat. Drop in a later round.
|
|
557
|
+
switch item.type {
|
|
558
|
+
case .analytics:
|
|
559
|
+
if data["anonymous_id"] == nil {
|
|
560
|
+
data["anonymous_id"] = context.anonymousId
|
|
561
|
+
}
|
|
562
|
+
if data["user_id"] == nil, let userId = context.userId {
|
|
563
|
+
data["user_id"] = userId
|
|
564
|
+
}
|
|
565
|
+
case .paywall, .funnel:
|
|
566
|
+
if data["user_id"] == nil {
|
|
567
|
+
data["user_id"] = context.userId ?? context.anonymousId
|
|
568
|
+
}
|
|
569
|
+
default:
|
|
570
|
+
break
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
let contextData = try encoder.encode(context)
|
|
574
|
+
guard let contextDict = try JSONSerialization.jsonObject(with: contextData) as? [String: Any] else {
|
|
575
|
+
continue
|
|
576
|
+
}
|
|
577
|
+
items.append([
|
|
578
|
+
"type": item.type.rawValue,
|
|
579
|
+
"data": data,
|
|
580
|
+
"context": contextDict,
|
|
581
|
+
])
|
|
582
|
+
}
|
|
583
|
+
let envelope: [String: Any] = ["items": items]
|
|
584
|
+
return try JSONSerialization.data(withJSONObject: envelope)
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// MARK: - Background scheduling
|
|
588
|
+
|
|
589
|
+
/// Coalescing flush trigger — used by the size threshold, reachability
|
|
590
|
+
/// regain, `didEnterBackground`, and the crash reporter's launch-time
|
|
591
|
+
/// recovery (a crash recovered from a previous run must not sit in the
|
|
592
|
+
/// disk queue until the next lifecycle event). Safe to call from any
|
|
593
|
+
/// thread; a no-op when a flush is already in flight.
|
|
594
|
+
func scheduleImmediateFlush() {
|
|
595
|
+
let shouldStart = flushQueue.sync { () -> Bool in
|
|
596
|
+
if isFlushing { return false }
|
|
597
|
+
isFlushing = true
|
|
598
|
+
return true
|
|
599
|
+
}
|
|
600
|
+
guard shouldStart else { return }
|
|
601
|
+
let task = Task { [weak self] in
|
|
602
|
+
await self?.flushBestEffort()
|
|
603
|
+
self?.flushQueue.sync {
|
|
604
|
+
self?.isFlushing = false
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
flushQueue.sync { self.flushTask = task }
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// MARK: - Reachability / Lifecycle wiring
|
|
611
|
+
|
|
612
|
+
/// Subscribe to network reachability and app-lifecycle events.
|
|
613
|
+
/// - Reachability transitions to offline → pause flush (handled via
|
|
614
|
+
/// `isReachable` checked at flush() entry).
|
|
615
|
+
/// - Reachability transitions to online → trigger an immediate flush
|
|
616
|
+
/// to drain whatever piled up during the offline window.
|
|
617
|
+
/// - `didEnterBackground` → trigger an opportunistic flush so events
|
|
618
|
+
/// land server-side before the host process may be suspended.
|
|
619
|
+
///
|
|
620
|
+
/// Idempotent — calling twice re-subscribes (after dropping the
|
|
621
|
+
/// previous tokens) so we don't end up double-firing on background.
|
|
622
|
+
@MainActor
|
|
623
|
+
func startObservingContext(
|
|
624
|
+
reachability: Reachability = .shared
|
|
625
|
+
) {
|
|
626
|
+
// Reachability — note the initial state and then track changes.
|
|
627
|
+
let initial = reachability.isReachable
|
|
628
|
+
flushQueue.sync { isReachable = initial }
|
|
629
|
+
if let token = reachabilityToken {
|
|
630
|
+
reachability.removeObserver(token)
|
|
631
|
+
}
|
|
632
|
+
reachabilityToken = reachability.addObserver { [weak self] reachable in
|
|
633
|
+
guard let self = self else { return }
|
|
634
|
+
self.flushQueue.sync { self.isReachable = reachable }
|
|
635
|
+
if reachable {
|
|
636
|
+
// Came back online — drain whatever queued during offline.
|
|
637
|
+
self.scheduleImmediateFlush()
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// Lifecycle — flush on background.
|
|
642
|
+
if let token = lifecycleToken {
|
|
643
|
+
AppLifecycle.unsubscribe(token)
|
|
644
|
+
}
|
|
645
|
+
lifecycleToken = AppLifecycle.subscribe { [weak self] event in
|
|
646
|
+
guard let self = self else { return }
|
|
647
|
+
if case .didEnterBackground = event {
|
|
648
|
+
self.scheduleImmediateFlush()
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// MARK: - Test seams
|
|
654
|
+
|
|
655
|
+
/// Synthetically drive the reachable bit so tests can assert pause /
|
|
656
|
+
/// resume without an NWPathMonitor.
|
|
657
|
+
func _setReachableForTesting(_ reachable: Bool) {
|
|
658
|
+
flushQueue.sync { isReachable = reachable }
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/// Read access to the underlying queue — tests need to assert on
|
|
662
|
+
/// queue depth without going through flush().
|
|
663
|
+
internal var queueForTesting: OfflineQueueStore<IngestItem> { queue }
|
|
664
|
+
|
|
665
|
+
/// Drop in a different identity snapshot — tests inject a fixed
|
|
666
|
+
/// `Snapshot` so they don't have to drive the full Identity state
|
|
667
|
+
/// machine.
|
|
668
|
+
func _setIdentitySnapshotForTesting(_ snap: @escaping @Sendable () -> SwissKnife.Identity.Snapshot) {
|
|
669
|
+
// Re-assignment of a let — used by tests only via a helper.
|
|
670
|
+
// No-op stub here so the symbol exists; the production path is
|
|
671
|
+
// immutable via `init`. Tests should construct a fresh
|
|
672
|
+
// `IngestClient` with their own snapshot closure.
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/// Synchronously wait for any in-flight background flush to settle.
|
|
676
|
+
/// Tests call this before asserting on queue state.
|
|
677
|
+
func _awaitFlushSettleForTesting() async {
|
|
678
|
+
let task = flushQueue.sync { flushTask }
|
|
679
|
+
if let task = task { await task.value }
|
|
680
|
+
}
|
|
681
|
+
}
|