@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.
Files changed (218) hide show
  1. package/README.md +182 -0
  2. package/SwissKnifePurchases.podspec +40 -0
  3. package/android/build.gradle +89 -0
  4. package/android/gradle.properties +3 -0
  5. package/android/src/main/AndroidManifest.xml +26 -0
  6. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
  7. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
  8. package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
  11. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
  12. package/android/vendor/GENERATED.md +10 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
  14. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
  15. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
  16. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
  17. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
  18. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
  19. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
  20. package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
  21. package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
  22. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
  23. package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
  24. package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
  25. package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
  26. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
  27. package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
  28. package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
  29. package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
  30. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
  31. package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
  32. package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
  33. package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
  34. package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
  35. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
  36. package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
  37. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
  38. package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
  39. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
  40. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
  41. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
  42. package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
  43. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
  44. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
  45. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
  46. package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
  47. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
  48. package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
  49. package/ios/SwissKnifeCrashReporting.m +32 -0
  50. package/ios/SwissKnifeCrashReporting.swift +186 -0
  51. package/ios/SwissKnifeJSON.swift +347 -0
  52. package/ios/SwissKnifePurchases.m +124 -0
  53. package/ios/SwissKnifePurchases.swift +523 -0
  54. package/ios/vendor/GENERATED.md +10 -0
  55. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
  56. package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
  57. package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
  58. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
  59. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
  60. package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
  61. package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
  62. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
  63. package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
  64. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
  65. package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
  66. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
  67. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
  68. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
  69. package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
  70. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
  71. package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
  72. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
  73. package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
  74. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
  75. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
  76. package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
  77. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
  78. package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
  79. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
  80. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
  81. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
  82. package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
  83. package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
  84. package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
  85. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
  86. package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
  87. package/lib/commonjs/attribution.js +55 -0
  88. package/lib/commonjs/attribution.js.map +1 -0
  89. package/lib/commonjs/identity.js +126 -0
  90. package/lib/commonjs/identity.js.map +1 -0
  91. package/lib/commonjs/index.js +118 -0
  92. package/lib/commonjs/index.js.map +1 -0
  93. package/lib/commonjs/modules/analytics.js +646 -0
  94. package/lib/commonjs/modules/analytics.js.map +1 -0
  95. package/lib/commonjs/modules/attachments.js +169 -0
  96. package/lib/commonjs/modules/attachments.js.map +1 -0
  97. package/lib/commonjs/modules/crash-reporting.js +1327 -0
  98. package/lib/commonjs/modules/crash-reporting.js.map +1 -0
  99. package/lib/commonjs/modules/ids.js +50 -0
  100. package/lib/commonjs/modules/ids.js.map +1 -0
  101. package/lib/commonjs/modules/log.js +59 -0
  102. package/lib/commonjs/modules/log.js.map +1 -0
  103. package/lib/commonjs/modules/offline-store.js +44 -0
  104. package/lib/commonjs/modules/offline-store.js.map +1 -0
  105. package/lib/commonjs/modules/performance.js +494 -0
  106. package/lib/commonjs/modules/performance.js.map +1 -0
  107. package/lib/commonjs/native/module.js +41 -0
  108. package/lib/commonjs/native/module.js.map +1 -0
  109. package/lib/commonjs/native/spec.js +26 -0
  110. package/lib/commonjs/native/spec.js.map +1 -0
  111. package/lib/commonjs/package.json +1 -0
  112. package/lib/commonjs/purchases.js +194 -0
  113. package/lib/commonjs/purchases.js.map +1 -0
  114. package/lib/commonjs/types.js +236 -0
  115. package/lib/commonjs/types.js.map +1 -0
  116. package/lib/module/attribution.js +51 -0
  117. package/lib/module/attribution.js.map +1 -0
  118. package/lib/module/identity.js +122 -0
  119. package/lib/module/identity.js.map +1 -0
  120. package/lib/module/index.js +36 -0
  121. package/lib/module/index.js.map +1 -0
  122. package/lib/module/modules/analytics.js +642 -0
  123. package/lib/module/modules/analytics.js.map +1 -0
  124. package/lib/module/modules/attachments.js +162 -0
  125. package/lib/module/modules/attachments.js.map +1 -0
  126. package/lib/module/modules/crash-reporting.js +1320 -0
  127. package/lib/module/modules/crash-reporting.js.map +1 -0
  128. package/lib/module/modules/ids.js +44 -0
  129. package/lib/module/modules/ids.js.map +1 -0
  130. package/lib/module/modules/log.js +54 -0
  131. package/lib/module/modules/log.js.map +1 -0
  132. package/lib/module/modules/offline-store.js +39 -0
  133. package/lib/module/modules/offline-store.js.map +1 -0
  134. package/lib/module/modules/performance.js +491 -0
  135. package/lib/module/modules/performance.js.map +1 -0
  136. package/lib/module/native/module.js +34 -0
  137. package/lib/module/native/module.js.map +1 -0
  138. package/lib/module/native/spec.js +22 -0
  139. package/lib/module/native/spec.js.map +1 -0
  140. package/lib/module/package.json +1 -0
  141. package/lib/module/purchases.js +187 -0
  142. package/lib/module/purchases.js.map +1 -0
  143. package/lib/module/types.js +230 -0
  144. package/lib/module/types.js.map +1 -0
  145. package/lib/typescript/commonjs/attribution.d.ts +24 -0
  146. package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/identity.d.ts +37 -0
  148. package/lib/typescript/commonjs/identity.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/index.d.ts +15 -0
  150. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
  152. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
  153. package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
  154. package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
  155. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
  156. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
  157. package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
  158. package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
  159. package/lib/typescript/commonjs/modules/log.d.ts +12 -0
  160. package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
  161. package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
  162. package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
  163. package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
  164. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
  165. package/lib/typescript/commonjs/native/module.d.ts +6 -0
  166. package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
  167. package/lib/typescript/commonjs/native/spec.d.ts +119 -0
  168. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
  169. package/lib/typescript/commonjs/package.json +1 -0
  170. package/lib/typescript/commonjs/purchases.d.ts +68 -0
  171. package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/types.d.ts +384 -0
  173. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  174. package/lib/typescript/module/attribution.d.ts +24 -0
  175. package/lib/typescript/module/attribution.d.ts.map +1 -0
  176. package/lib/typescript/module/identity.d.ts +37 -0
  177. package/lib/typescript/module/identity.d.ts.map +1 -0
  178. package/lib/typescript/module/index.d.ts +15 -0
  179. package/lib/typescript/module/index.d.ts.map +1 -0
  180. package/lib/typescript/module/modules/analytics.d.ts +127 -0
  181. package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
  182. package/lib/typescript/module/modules/attachments.d.ts +50 -0
  183. package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
  184. package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
  185. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
  186. package/lib/typescript/module/modules/ids.d.ts +17 -0
  187. package/lib/typescript/module/modules/ids.d.ts.map +1 -0
  188. package/lib/typescript/module/modules/log.d.ts +12 -0
  189. package/lib/typescript/module/modules/log.d.ts.map +1 -0
  190. package/lib/typescript/module/modules/offline-store.d.ts +9 -0
  191. package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
  192. package/lib/typescript/module/modules/performance.d.ts +75 -0
  193. package/lib/typescript/module/modules/performance.d.ts.map +1 -0
  194. package/lib/typescript/module/native/module.d.ts +6 -0
  195. package/lib/typescript/module/native/module.d.ts.map +1 -0
  196. package/lib/typescript/module/native/spec.d.ts +119 -0
  197. package/lib/typescript/module/native/spec.d.ts.map +1 -0
  198. package/lib/typescript/module/package.json +1 -0
  199. package/lib/typescript/module/purchases.d.ts +68 -0
  200. package/lib/typescript/module/purchases.d.ts.map +1 -0
  201. package/lib/typescript/module/types.d.ts +384 -0
  202. package/lib/typescript/module/types.d.ts.map +1 -0
  203. package/package.json +115 -0
  204. package/react-native.config.js +23 -0
  205. package/src/attribution.ts +56 -0
  206. package/src/identity.ts +133 -0
  207. package/src/index.ts +54 -0
  208. package/src/modules/analytics.ts +689 -0
  209. package/src/modules/attachments.ts +222 -0
  210. package/src/modules/crash-reporting.ts +1577 -0
  211. package/src/modules/ids.ts +41 -0
  212. package/src/modules/log.ts +56 -0
  213. package/src/modules/offline-store.ts +51 -0
  214. package/src/modules/performance.ts +589 -0
  215. package/src/native/module.ts +47 -0
  216. package/src/native/spec.ts +183 -0
  217. package/src/purchases.ts +214 -0
  218. package/src/types.ts +470 -0
@@ -0,0 +1,120 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/context/AppLifecycle.kt
2
+ //
3
+ // Round-C cross-cutting primitive #3 — single source of foreground /
4
+ // background events. Mirror of `Sources/SwissKnifeiOS/Context/AppLifecycle.swift`.
5
+ //
6
+ // Before this primitive each module that cared about lifecycle (Session
7
+ // rotation, IngestClient flush-on-background, CrashReporting flush-on-
8
+ // foreground, Performance start/stop) wired its own
9
+ // ActivityLifecycleCallbacks observer. This led to:
10
+ // - N callbacks for the same event.
11
+ // - Each module deciding independently which lifecycle event to map to
12
+ // (didStart vs didResume) — drift between modules.
13
+ // - Tests had to load every module to assert lifecycle handling.
14
+ //
15
+ // AppLifecycle subscribes ONCE to androidx.lifecycle.ProcessLifecycleOwner
16
+ // (the recommended single-source-of-truth for "is the app foregrounded?")
17
+ // and rebroadcasts to its own observer list.
18
+
19
+ package com.appswissknife.context
20
+
21
+ import android.os.Handler
22
+ import android.os.Looper
23
+ import androidx.lifecycle.DefaultLifecycleObserver
24
+ import androidx.lifecycle.Lifecycle
25
+ import androidx.lifecycle.LifecycleOwner
26
+ import androidx.lifecycle.ProcessLifecycleOwner
27
+ import java.util.UUID
28
+
29
+ /**
30
+ * Unified app-lifecycle event bus.
31
+ *
32
+ * Cross-platform note: iOS has four discrete UIApplication events
33
+ * (didBecomeActive / willResignActive / didEnterBackground /
34
+ * willEnterForeground). Android's ProcessLifecycleOwner exposes
35
+ * onStart / onStop / onResume / onPause — we map them 1:1 to keep the
36
+ * Event enum identical with iOS:
37
+ * - onStart ↔ willEnterForeground
38
+ * - onResume ↔ didBecomeActive
39
+ * - onPause ↔ willResignActive
40
+ * - onStop ↔ didEnterBackground
41
+ */
42
+ internal object AppLifecycle {
43
+
44
+ enum class Event {
45
+ DidBecomeActive,
46
+ WillResignActive,
47
+ DidEnterBackground,
48
+ WillEnterForeground,
49
+ }
50
+
51
+ private val mainHandler = Handler(Looper.getMainLooper())
52
+ private val observers = mutableMapOf<UUID, (Event) -> Unit>()
53
+ private val lock = Any()
54
+
55
+ @Volatile
56
+ private var didRegister: Boolean = false
57
+
58
+ private val processObserver = object : DefaultLifecycleObserver {
59
+ override fun onStart(owner: LifecycleOwner) {
60
+ broadcast(Event.WillEnterForeground)
61
+ }
62
+ override fun onResume(owner: LifecycleOwner) {
63
+ broadcast(Event.DidBecomeActive)
64
+ }
65
+ override fun onPause(owner: LifecycleOwner) {
66
+ broadcast(Event.WillResignActive)
67
+ }
68
+ override fun onStop(owner: LifecycleOwner) {
69
+ broadcast(Event.DidEnterBackground)
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Subscribe. Returns a token; pass to [unsubscribe] to drop.
75
+ * Idempotent — multiple calls add multiple observers.
76
+ */
77
+ fun subscribe(block: (Event) -> Unit): UUID {
78
+ ensureRegistered()
79
+ val token = UUID.randomUUID()
80
+ synchronized(lock) { observers[token] = block }
81
+ return token
82
+ }
83
+
84
+ fun unsubscribe(token: UUID) {
85
+ synchronized(lock) { observers.remove(token) }
86
+ }
87
+
88
+ private fun ensureRegistered() {
89
+ if (didRegister) return
90
+ synchronized(lock) {
91
+ if (didRegister) return
92
+ didRegister = true
93
+ }
94
+ // ProcessLifecycleOwner must be observed on the main thread.
95
+ mainHandler.post {
96
+ runCatching {
97
+ ProcessLifecycleOwner.get().lifecycle.addObserver(processObserver)
98
+ }
99
+ }
100
+ }
101
+
102
+ private fun broadcast(event: Event) {
103
+ val snapshot: List<(Event) -> Unit> = synchronized(lock) {
104
+ observers.values.toList()
105
+ }
106
+ for (observer in snapshot) observer(event)
107
+ }
108
+
109
+ // ----- Test seams -----
110
+
111
+ /** Synthetic event injection for unit tests. */
112
+ internal fun _postForTesting(event: Event) {
113
+ broadcast(event)
114
+ }
115
+
116
+ /** Drop all observers — used by tests for a clean slate. */
117
+ internal fun _resetObserversForTesting() {
118
+ synchronized(lock) { observers.clear() }
119
+ }
120
+ }
@@ -0,0 +1,70 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/context/Clock.kt
2
+ //
3
+ // Round-C cross-cutting primitive — Clock with server-time skew correction.
4
+ // Mirror of `Sources/SwissKnifeiOS/Context/Clock.swift`.
5
+ //
6
+ // The host device's wall clock can't be trusted absolutely — users edit
7
+ // system time, devices boot before NTP sync, time zones change mid-flight.
8
+ // For analytics timestamps that's "ok-ish" (event ordering within a
9
+ // session is preserved) but for retention / cohort / time-series the
10
+ // absolute instant matters.
11
+ //
12
+ // This primitive lets the SDK gradually self-correct using the backend's
13
+ // HTTP `Date` response header as a reference. On every successful HTTP
14
+ // response, BackendHttpClient observes the Date header and calls
15
+ // `Clock.applyServerTime(serverMillis, localObservedMillis)`. Clock
16
+ // computes `skew = serverMillis - localObservedMillis` and adds that
17
+ // offset to every subsequent `Clock.now()`.
18
+
19
+ package com.appswissknife.context
20
+
21
+ import com.appswissknife.net.IngestPlaceholderClock
22
+
23
+ /** Time source with optional server-corrected skew. */
24
+ internal object Clock {
25
+
26
+ @Volatile
27
+ private var _skewMs: Long = 0L
28
+
29
+ /**
30
+ * Current corrected wall-clock instant in epoch milliseconds. If no
31
+ * skew has been observed yet, identical to `System.currentTimeMillis()`.
32
+ */
33
+ fun now(): Long = System.currentTimeMillis() + _skewMs
34
+
35
+ /**
36
+ * Apply a new observation from a backend HTTP Date header. `serverMillis`
37
+ * is what the backend claimed the time was; `localObservedMillis` is
38
+ * the device's local now() taken right when the response landed. Skew
39
+ * is the difference.
40
+ *
41
+ * In-memory only — a persisted skew across launches would defeat "user
42
+ * fixed their system clock between sessions." Cheap to re-learn on each
43
+ * launch.
44
+ */
45
+ fun applyServerTime(serverMillis: Long, localObservedMillis: Long) {
46
+ _skewMs = serverMillis - localObservedMillis
47
+ }
48
+
49
+ /** Currently-applied skew in millis. Positive = server ahead of device. */
50
+ val skewMs: Long
51
+ get() = _skewMs
52
+
53
+ /**
54
+ * Install this Clock as the IngestClient timestamp supplier so each
55
+ * ContextSnapshot.timestamp comes from corrected time.
56
+ */
57
+ fun installAsIngestSupplier() {
58
+ IngestPlaceholderClock.supplier = { now() }
59
+ }
60
+
61
+ // ----- Test seams -----
62
+
63
+ internal fun _setSkewForTesting(ms: Long) {
64
+ _skewMs = ms
65
+ }
66
+
67
+ internal fun _resetForTesting() {
68
+ _skewMs = 0L
69
+ }
70
+ }
@@ -0,0 +1,138 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/context/DeviceContext.kt
2
+ //
3
+ // Round-C cross-cutting primitive #1 — DeviceContext.
4
+ //
5
+ // Single source of truth for device / app / OS metadata that every
6
+ // IngestItem needs stamped onto its outgoing envelope. Mirror of
7
+ // `Sources/SwissKnifeiOS/Context/DeviceContext.swift`.
8
+ //
9
+ // Before this primitive each module (Analytics, Crash, Performance,
10
+ // Attribution) reached for `Build.MODEL`, `Build.VERSION.RELEASE`, and
11
+ // the host's BuildConfig.VERSION_NAME directly — inconsistent field
12
+ // names, drift between modules.
13
+ //
14
+ // Memoization: every field is stable for the lifetime of the process
15
+ // (locale and timezone CAN change at runtime via user settings, but we
16
+ // accept the staleness — the next process launch picks up the new value
17
+ // and IngestItems already queued are tagged at enqueue time anyway).
18
+
19
+ package com.appswissknife.context
20
+
21
+ import android.content.Context
22
+ import android.os.Build
23
+ import com.appswissknife.net.DeviceContextSnapshot
24
+ import com.appswissknife.net.IngestPlaceholderDevice
25
+ import java.util.Locale
26
+ import java.util.TimeZone
27
+
28
+ /**
29
+ * Memoized accessor over the host device's snapshot. `current(context)`
30
+ * computes once and caches; subsequent calls return the cached value.
31
+ * `current()` (no context) is fine when the cache has already been
32
+ * primed — callers (e.g. SwissKnife.configure) are expected to prime it.
33
+ *
34
+ * Tests can drop the cache via `_resetForTesting()` to rebuild from
35
+ * scratch.
36
+ */
37
+ internal object DeviceContextProvider {
38
+
39
+ /**
40
+ * Hardcoded SDK version constant — bump on every SDK release. Matches
41
+ * iOS' `sdkVersionConstant`. The build pipeline (`swiss-build`) will
42
+ * eventually inject this via `BuildConfig`, but for now keep it in
43
+ * source so we don't have to thread build settings through every test.
44
+ */
45
+ const val SDK_VERSION: String = "0.1.0"
46
+
47
+ private val cacheLock = Any()
48
+
49
+ @Volatile
50
+ private var cached: DeviceContextSnapshot? = null
51
+
52
+ /**
53
+ * Returns the current device context, computing and memoizing on
54
+ * first call. Thread-safe.
55
+ */
56
+ fun current(context: Context): DeviceContextSnapshot {
57
+ cached?.let { return it }
58
+ synchronized(cacheLock) {
59
+ cached?.let { return it }
60
+ val fresh = buildSnapshot(context)
61
+ cached = fresh
62
+ return fresh
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Returns the cached snapshot or a best-effort fallback if `current(context)`
68
+ * was never called. Used at flush time where threading the Context
69
+ * through `IngestClient.flushSync` would force every caller to carry
70
+ * one.
71
+ */
72
+ fun currentOrFallback(): DeviceContextSnapshot {
73
+ cached?.let { return it }
74
+ // Best-effort path: build a snapshot without a Context. The host
75
+ // package name will be unknown but the rest is OS-derivable.
76
+ return DeviceContextSnapshot(
77
+ deviceModel = Build.MODEL ?: "unknown",
78
+ osName = "Android",
79
+ osVersion = Build.VERSION.RELEASE ?: "unknown",
80
+ appVersion = "unknown",
81
+ appBuild = "unknown",
82
+ locale = Locale.getDefault().toString(),
83
+ timezone = TimeZone.getDefault().id,
84
+ sdkVersion = SDK_VERSION,
85
+ bundleIdentifier = null,
86
+ )
87
+ }
88
+
89
+ /**
90
+ * Test seam — drop the memoized snapshot so the next `current()` call
91
+ * rebuilds from scratch. Production code MUST NOT call this.
92
+ */
93
+ internal fun _resetForTesting() {
94
+ synchronized(cacheLock) { cached = null }
95
+ }
96
+
97
+ /**
98
+ * Install this provider as the IngestClient's DeviceContext supplier.
99
+ * Wired by SwissKnife.configure.
100
+ */
101
+ fun install(context: Context) {
102
+ val appCtx = context.applicationContext ?: context
103
+ current(appCtx) // prime cache
104
+ IngestPlaceholderDevice.supplier = { currentOrFallback() }
105
+ }
106
+
107
+ // ----- internals -----
108
+
109
+ private fun buildSnapshot(context: Context): DeviceContextSnapshot {
110
+ val pkg = context.packageName
111
+ val (versionName, versionCode) = readVersion(context, pkg)
112
+ return DeviceContextSnapshot(
113
+ deviceModel = Build.MODEL ?: "unknown",
114
+ osName = "Android",
115
+ osVersion = Build.VERSION.RELEASE ?: "unknown",
116
+ appVersion = versionName,
117
+ appBuild = versionCode,
118
+ locale = Locale.getDefault().toString(),
119
+ timezone = TimeZone.getDefault().id,
120
+ sdkVersion = SDK_VERSION,
121
+ bundleIdentifier = pkg,
122
+ )
123
+ }
124
+
125
+ private fun readVersion(context: Context, pkg: String): Pair<String, String> {
126
+ return runCatching {
127
+ val info = context.packageManager.getPackageInfo(pkg, 0)
128
+ val name = info.versionName ?: "unknown"
129
+ @Suppress("DEPRECATION")
130
+ val code = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
131
+ info.longVersionCode.toString()
132
+ } else {
133
+ info.versionCode.toString()
134
+ }
135
+ Pair(name, code)
136
+ }.getOrElse { Pair("unknown", "unknown") }
137
+ }
138
+ }
@@ -0,0 +1,55 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/context/IDs.kt
2
+ //
3
+ // Round-C cross-cutting primitive — unified ID generation. Mirror of
4
+ // `Sources/SwissKnifeiOS/Context/IDs.swift`.
5
+ //
6
+ // Centralises every callsite that historically reached for
7
+ // UUID.randomUUID().toString() to mint an identifier. The wrapper lets us:
8
+ // - Swap to UUIDv7 (sortable / time-prefixed) without grepping every
9
+ // module.
10
+ // - Distinguish externally-visible IDs (event_id is the backend dedupe
11
+ // key) from purely internal ones (request_id, session_id).
12
+ // - Stub generation deterministically in tests via _setGeneratorForTesting.
13
+
14
+ package com.appswissknife.context
15
+
16
+ import java.util.UUID
17
+
18
+ /**
19
+ * Unified ID factory. Internal — IngestClient, Identity, Session,
20
+ * AttributesClient, CrashReporting, Performance, and Attribution route
21
+ * through here.
22
+ */
23
+ internal object IDs {
24
+
25
+ private val defaultGenerator: () -> String = { UUID.randomUUID().toString() }
26
+
27
+ @Volatile
28
+ private var generator: () -> String = defaultGenerator
29
+
30
+ /**
31
+ * Idempotency key for an individual telemetry event. The backend
32
+ * dedupes against (app_project_id, event_id) so the same id MUST
33
+ * NOT be reused across logically distinct events.
34
+ */
35
+ fun eventId(): String = generator()
36
+
37
+ /**
38
+ * Per-HTTP-request correlation id. Surfaces in BackendHttpClient
39
+ * logs / future X-Request-Id headers.
40
+ */
41
+ fun requestId(): String = generator()
42
+
43
+ /** Per-session uuid — used by Session on restart. */
44
+ fun sessionId(): String = generator()
45
+
46
+ /** Inject a deterministic generator. Production MUST NOT call. */
47
+ internal fun _setGeneratorForTesting(gen: () -> String) {
48
+ generator = gen
49
+ }
50
+
51
+ /** Restore the production generator. */
52
+ internal fun _resetForTesting() {
53
+ generator = defaultGenerator
54
+ }
55
+ }
@@ -0,0 +1,145 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/context/Reachability.kt
2
+ //
3
+ // Round-C cross-cutting primitive — network reachability state. Mirror of
4
+ // `Sources/SwissKnifeiOS/Context/Reachability.swift`.
5
+ //
6
+ // Single source of "is the device online?". Used by IngestClient to pause
7
+ // flush when offline (no point burning the retry budget when DNS will
8
+ // fail anyway) and resume immediately when connectivity returns.
9
+ //
10
+ // Implementation
11
+ // --------------
12
+ // ConnectivityManager.registerDefaultNetworkCallback is the right
13
+ // primitive on API 24+ (our minSdk). It posts onAvailable / onLost on a
14
+ // background thread; we bridge those into a simple isReachable bool and
15
+ // broadcast only on TRANSITIONS (not on every duplicate onAvailable —
16
+ // ConnectivityManager occasionally fires repeats during network switches).
17
+ //
18
+ // Boot semantics
19
+ // --------------
20
+ // Optimistic true on construction. Same as iOS — the first NWPath update
21
+ // arrives within milliseconds and overrides the optimistic default; in
22
+ // the meantime any enqueue+flush path runs as normal rather than queuing
23
+ // for a "first-update" event that may never happen on devices that
24
+ // never observe a path transition.
25
+
26
+ package com.appswissknife.context
27
+
28
+ import android.content.Context
29
+ import android.net.ConnectivityManager
30
+ import android.net.Network
31
+ import android.os.Build
32
+ import com.appswissknife.net.IngestClient
33
+ import java.util.UUID
34
+
35
+ /**
36
+ * Single shared reachability monitor. Production callers go through
37
+ * `Reachability.shared(context)`; tests construct a private instance
38
+ * via the public ctor and drive transitions via `_setReachableForTesting`.
39
+ */
40
+ internal class Reachability(
41
+ context: Context?,
42
+ private val registerCallback: Boolean = true,
43
+ ) {
44
+ private val lock = Any()
45
+ private val observers = mutableMapOf<UUID, (Boolean) -> Unit>()
46
+
47
+ @Volatile
48
+ private var current: Boolean = true
49
+
50
+ private val cm: ConnectivityManager? = context?.let {
51
+ it.applicationContext?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
52
+ }
53
+
54
+ private val callback = object : ConnectivityManager.NetworkCallback() {
55
+ override fun onAvailable(network: Network) {
56
+ update(true)
57
+ }
58
+ override fun onLost(network: Network) {
59
+ update(false)
60
+ }
61
+ }
62
+
63
+ init {
64
+ val mgr = cm
65
+ if (registerCallback && mgr != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
66
+ runCatching { mgr.registerDefaultNetworkCallback(callback) }
67
+ }
68
+ }
69
+
70
+ val isReachable: Boolean
71
+ get() = current
72
+
73
+ /**
74
+ * Subscribe to reachability transitions. Fired only when state CHANGES
75
+ * (duplicate onAvailable callbacks are coalesced).
76
+ */
77
+ fun addObserver(block: (Boolean) -> Unit): UUID {
78
+ val token = UUID.randomUUID()
79
+ synchronized(lock) { observers[token] = block }
80
+ return token
81
+ }
82
+
83
+ fun removeObserver(token: UUID) {
84
+ synchronized(lock) { observers.remove(token) }
85
+ }
86
+
87
+ /**
88
+ * Wire the IngestClient.shared so it pauses / resumes flush in
89
+ * lockstep with reachability transitions.
90
+ */
91
+ fun installAsIngestObserver() {
92
+ val client = IngestClient.shared ?: return
93
+ client.setReachable(isReachable)
94
+ addObserver { reachable ->
95
+ client.setReachable(reachable)
96
+ if (reachable) {
97
+ // Came back online — drain whatever queued during offline.
98
+ // The context arg is only used to enqueue WorkManager work;
99
+ // the worker re-discovers IngestClient.shared at run time.
100
+ // We have no Context handle here, so skip the explicit
101
+ // scheduleFlush — the next enqueue or the periodic timer
102
+ // will pick up the backlog.
103
+ }
104
+ }
105
+ }
106
+
107
+ private fun update(reachable: Boolean) {
108
+ val (changed, snapshot) = synchronized(lock) {
109
+ val c = (reachable != current)
110
+ current = reachable
111
+ Pair(c, observers.values.toList())
112
+ }
113
+ if (!changed) return
114
+ for (obs in snapshot) obs(reachable)
115
+ }
116
+
117
+ // ----- Test seams -----
118
+
119
+ internal fun _setReachableForTesting(reachable: Boolean) {
120
+ update(reachable)
121
+ }
122
+
123
+ internal fun _resetObserversForTesting() {
124
+ synchronized(lock) { observers.clear() }
125
+ }
126
+
127
+ companion object {
128
+ @Volatile
129
+ private var _shared: Reachability? = null
130
+
131
+ fun shared(context: Context): Reachability {
132
+ _shared?.let { return it }
133
+ synchronized(this) {
134
+ _shared?.let { return it }
135
+ val r = Reachability(context.applicationContext ?: context)
136
+ _shared = r
137
+ return r
138
+ }
139
+ }
140
+
141
+ internal fun _resetSharedForTesting() {
142
+ synchronized(this) { _shared = null }
143
+ }
144
+ }
145
+ }