@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,428 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/performance/SKPerformance.kt
2
+ //
3
+ // Sentry-compatible performance monitoring SDK for swiss-knife (Android).
4
+ // Provides Transaction/Span tracking with automatic app-start and activity-load
5
+ // instrumentation.
6
+
7
+ package com.appswissknife.performance
8
+
9
+ import android.app.Activity
10
+ import android.app.Application
11
+ import android.content.Context
12
+ import android.os.Bundle
13
+ import android.os.SystemClock
14
+ import org.json.JSONArray
15
+ import org.json.JSONObject
16
+ import java.text.SimpleDateFormat
17
+ import java.util.*
18
+ import java.util.concurrent.CopyOnWriteArrayList
19
+ import java.util.concurrent.Executors
20
+
21
+ // MARK: - Span Status
22
+
23
+ enum class SKSpanStatus(val value: String) {
24
+ OK("ok"),
25
+ CANCELLED("cancelled"),
26
+ UNKNOWN("unknown"),
27
+ INVALID_ARGUMENT("invalid_argument"),
28
+ DEADLINE_EXCEEDED("deadline_exceeded"),
29
+ NOT_FOUND("not_found"),
30
+ PERMISSION_DENIED("permission_denied"),
31
+ RESOURCE_EXHAUSTED("resource_exhausted"),
32
+ UNIMPLEMENTED("unimplemented"),
33
+ UNAVAILABLE("unavailable"),
34
+ INTERNAL_ERROR("internal_error"),
35
+ ABORTED("aborted"),
36
+ }
37
+
38
+ // MARK: - Span
39
+
40
+ class SKSpan(
41
+ val spanId: String,
42
+ val parentSpanId: String,
43
+ val op: String,
44
+ val description: String? = null
45
+ ) {
46
+ // Use the canonical SDK clock so server-skew correction (applied by
47
+ // BackendHttpClient via the response Date header) lands on the same
48
+ // timeline as ingest envelopes. Mirrors the iOS Performance fix.
49
+ private val startTime = Date(com.appswissknife.context.Clock.now())
50
+ private var endTime: Date? = null
51
+ private var status: SKSpanStatus = SKSpanStatus.OK
52
+ private val tags = mutableMapOf<String, String>()
53
+ private val data = mutableMapOf<String, String>()
54
+ private val children = CopyOnWriteArrayList<SKSpan>()
55
+
56
+ fun startChild(op: String, description: String? = null): SKSpan {
57
+ val child = SKSpan(
58
+ spanId = SKPerformance.generateSpanId(),
59
+ parentSpanId = spanId,
60
+ op = op,
61
+ description = description
62
+ )
63
+ children.add(child)
64
+ return child
65
+ }
66
+
67
+ fun finish(status: SKSpanStatus = SKSpanStatus.OK) {
68
+ if (endTime != null) return // already finished
69
+ this.endTime = Date(com.appswissknife.context.Clock.now())
70
+ this.status = status
71
+ }
72
+
73
+ fun setTag(key: String, value: String) {
74
+ tags[key] = value
75
+ }
76
+
77
+ fun setData(key: String, value: String) {
78
+ data[key] = value
79
+ }
80
+
81
+ internal fun toJSON(): JSONObject = JSONObject().apply {
82
+ put("spanId", spanId)
83
+ put("parentSpanId", parentSpanId)
84
+ put("op", op)
85
+ description?.let { put("description", it) }
86
+ put("startTimestamp", ISO_DATE.format(startTime))
87
+ put("endTimestamp", ISO_DATE.format(endTime ?: Date(com.appswissknife.context.Clock.now())))
88
+ put("status", status.value)
89
+ if (tags.isNotEmpty()) put("tags", JSONObject(tags as Map<*, *>))
90
+ if (data.isNotEmpty()) put("data", JSONObject(data as Map<*, *>))
91
+ }
92
+
93
+ internal fun allSpans(): List<SKSpan> {
94
+ val result = mutableListOf(this)
95
+ for (child in children) {
96
+ result.addAll(child.allSpans())
97
+ }
98
+ return result
99
+ }
100
+
101
+ companion object {
102
+ private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
103
+ timeZone = TimeZone.getTimeZone("UTC")
104
+ }
105
+ }
106
+ }
107
+
108
+ // MARK: - Transaction
109
+
110
+ class SKTransaction(
111
+ val traceId: String,
112
+ val name: String,
113
+ val op: String,
114
+ private val performance: SKPerformance,
115
+ val sampled: Boolean = true
116
+ ) {
117
+ val spanId: String = SKPerformance.generateSpanId()
118
+ private val startTime = Date(com.appswissknife.context.Clock.now())
119
+ private var endTime: Date? = null
120
+ private var status: SKSpanStatus = SKSpanStatus.OK
121
+ private val tags = mutableMapOf<String, String>()
122
+ private val data = mutableMapOf<String, String>()
123
+ private val spans = CopyOnWriteArrayList<SKSpan>()
124
+
125
+ fun startChild(op: String, description: String? = null): SKSpan {
126
+ val span = SKSpan(
127
+ spanId = SKPerformance.generateSpanId(),
128
+ parentSpanId = spanId,
129
+ op = op,
130
+ description = description
131
+ )
132
+ spans.add(span)
133
+ return span
134
+ }
135
+
136
+ fun finish(status: SKSpanStatus = SKSpanStatus.OK) {
137
+ if (endTime != null) return // already finished
138
+ this.endTime = Date(com.appswissknife.context.Clock.now())
139
+ this.status = status
140
+ // Clear active transaction reference
141
+ if (performance.currentTransaction === this) {
142
+ performance.currentTransaction = null
143
+ }
144
+ if (!sampled) return
145
+ for (span in allChildSpans()) {
146
+ span.finish(status = SKSpanStatus.OK)
147
+ }
148
+ performance.sendTransaction(this)
149
+ }
150
+
151
+ fun setTag(key: String, value: String) {
152
+ tags[key] = value
153
+ }
154
+
155
+ fun setData(key: String, value: String) {
156
+ data[key] = value
157
+ }
158
+
159
+ internal fun toJSON(): JSONObject = JSONObject().apply {
160
+ put("traceId", traceId)
161
+ put("name", name)
162
+ put("op", op)
163
+ put("startTimestamp", ISO_DATE.format(startTime))
164
+ put("endTimestamp", ISO_DATE.format(endTime ?: Date(com.appswissknife.context.Clock.now())))
165
+ put("status", status.value)
166
+ put("spans", JSONArray(allChildSpans().map { it.toJSON() }))
167
+ if (tags.isNotEmpty()) put("tags", JSONObject(tags as Map<*, *>))
168
+
169
+ // Sentry-compatible wire shape, but sourced from the canonical
170
+ // DeviceContext primitive instead of inline `Build.*` reads. Field
171
+ // names stay the same so the backend's Sentry parser is unaffected;
172
+ // values are now in lockstep with envelope ContextSnapshot.device.
173
+ val device = com.appswissknife.context.DeviceContextProvider.currentOrFallback()
174
+ val contexts = JSONObject().apply {
175
+ put("os", JSONObject().apply {
176
+ put("name", device.osName)
177
+ put("version", device.osVersion)
178
+ })
179
+ put("device", JSONObject().apply {
180
+ put("model", device.deviceModel)
181
+ })
182
+ }
183
+ put("contexts", contexts)
184
+ }
185
+
186
+ private fun allChildSpans(): List<SKSpan> {
187
+ val result = mutableListOf<SKSpan>()
188
+ for (span in spans) {
189
+ result.addAll(span.allSpans())
190
+ }
191
+ return result
192
+ }
193
+
194
+ companion object {
195
+ private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
196
+ timeZone = TimeZone.getTimeZone("UTC")
197
+ }
198
+ }
199
+ }
200
+
201
+ // MARK: - OkHttp Interceptor
202
+
203
+ /**
204
+ * OkHttp Interceptor for automatic HTTP span tracking.
205
+ * Add to OkHttpClient.Builder: `.addInterceptor(SKPerformanceInterceptor())`
206
+ *
207
+ * Requires okhttp3 on the classpath (compileOnly dependency — consumers bring their own).
208
+ */
209
+ class SKPerformanceInterceptor : okhttp3.Interceptor {
210
+ override fun intercept(chain: okhttp3.Interceptor.Chain): okhttp3.Response {
211
+ val request = chain.request()
212
+ val activeTransaction = SKPerformance.currentTransaction
213
+
214
+ // If there's an active transaction, create a child span; otherwise create a standalone transaction.
215
+ val span: SKSpan?
216
+ val standaloneTransaction: SKTransaction?
217
+
218
+ if (activeTransaction != null) {
219
+ span = activeTransaction.startChild("http.client", "${request.method} ${request.url}")
220
+ standaloneTransaction = null
221
+ } else {
222
+ standaloneTransaction = SKPerformance.startTransaction(
223
+ "${request.method} ${request.url.encodedPath}",
224
+ "http.client"
225
+ )
226
+ span = standaloneTransaction.startChild("http.request", "${request.method} ${request.url}")
227
+ }
228
+
229
+ span.setData("url", request.url.toString())
230
+ span.setData("method", request.method)
231
+
232
+ // Inject trace headers for distributed tracing
233
+ val traceId = activeTransaction?.traceId ?: standaloneTransaction?.traceId ?: ""
234
+ val spanId = span.spanId
235
+ val tracedRequest = request.newBuilder()
236
+ .header("sk-trace-id", traceId)
237
+ .header("sk-parent-span-id", spanId)
238
+ .build()
239
+
240
+ try {
241
+ val response = chain.proceed(tracedRequest)
242
+ span.setData("http.status_code", response.code.toString())
243
+ val status = if (response.isSuccessful) SKSpanStatus.OK else SKSpanStatus.INTERNAL_ERROR
244
+ span.finish(status)
245
+ standaloneTransaction?.finish(status)
246
+ return response
247
+ } catch (e: Exception) {
248
+ span.finish(SKSpanStatus.INTERNAL_ERROR)
249
+ standaloneTransaction?.finish(SKSpanStatus.INTERNAL_ERROR)
250
+ throw e
251
+ }
252
+ }
253
+ }
254
+
255
+ // MARK: - Performance Manager
256
+
257
+ object SKPerformance {
258
+
259
+ data class Configuration(
260
+ val apiKey: String,
261
+ val serverURL: String = "",
262
+ val environment: String = "production",
263
+ val release: String? = null,
264
+ val enableAutoAppStart: Boolean = true,
265
+ val enableAutoActivityLoad: Boolean = true,
266
+ val tracesSampleRate: Double = 1.0,
267
+ )
268
+
269
+ private var config: Configuration? = null
270
+ private var appContext: Context? = null
271
+ private val executor = Executors.newSingleThreadExecutor()
272
+
273
+ // App start tracking
274
+ private var appStartTransaction: SKTransaction? = null
275
+ private var firstActivityResumed = false
276
+
277
+ /// The most recently started (and not yet finished) transaction.
278
+ /// Used by `traceHeaders()` to propagate distributed tracing context.
279
+ @Volatile
280
+ var currentTransaction: SKTransaction? = null
281
+ internal set
282
+
283
+ // Activity load tracking
284
+ private val activityCreatedTimes = mutableMapOf<String, Long>()
285
+
286
+ // MARK: - Init
287
+
288
+ fun init(context: Context, config: Configuration) {
289
+ val appCtx = context.applicationContext ?: context
290
+ this.config = config
291
+ this.appContext = appCtx
292
+
293
+ if (config.enableAutoAppStart) {
294
+ startAppStartTransaction()
295
+ }
296
+
297
+ if (config.enableAutoActivityLoad) {
298
+ registerActivityLoadTracking(appCtx)
299
+ }
300
+ }
301
+
302
+ // MARK: - Public API
303
+
304
+ fun startTransaction(name: String, op: String): SKTransaction {
305
+ val rate = config?.tracesSampleRate ?: 1.0
306
+ val sampled = rate >= 1.0 || Math.random() <= rate
307
+ val tx = SKTransaction(
308
+ traceId = generateTraceId(),
309
+ name = name,
310
+ op = op,
311
+ performance = this,
312
+ sampled = sampled
313
+ )
314
+ currentTransaction = tx
315
+ return tx
316
+ }
317
+
318
+ // MARK: - Auto-Instrumentation: App Start
319
+
320
+ private fun startAppStartTransaction() {
321
+ appStartTransaction = startTransaction("App Start", "app.start")
322
+ firstActivityResumed = false
323
+ }
324
+
325
+ private fun registerActivityLoadTracking(context: Context) {
326
+ val app = context as? Application ?: return
327
+ app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
328
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
329
+ activityCreatedTimes[activity.javaClass.simpleName] = SystemClock.elapsedRealtime()
330
+ }
331
+
332
+ override fun onActivityResumed(activity: Activity) {
333
+ // Finish app start transaction on first resume
334
+ if (!firstActivityResumed && appStartTransaction != null) {
335
+ firstActivityResumed = true
336
+ appStartTransaction?.finish(status = SKSpanStatus.OK)
337
+ appStartTransaction = null
338
+ }
339
+
340
+ // Track activity load time
341
+ val name = activity.javaClass.simpleName
342
+ val createdAt = activityCreatedTimes.remove(name)
343
+ if (createdAt != null) {
344
+ val loadTimeMs = SystemClock.elapsedRealtime() - createdAt
345
+ val tx = startTransaction(name, "ui.load")
346
+ tx.setData("load_time_ms", loadTimeMs.toString())
347
+ tx.finish(status = SKSpanStatus.OK)
348
+ }
349
+ }
350
+
351
+ override fun onActivityPaused(activity: Activity) {}
352
+ override fun onActivityStarted(activity: Activity) {}
353
+ override fun onActivityStopped(activity: Activity) {}
354
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
355
+ override fun onActivityDestroyed(activity: Activity) {}
356
+ })
357
+ }
358
+
359
+ // MARK: - Send Transaction
360
+
361
+ internal fun sendTransaction(transaction: SKTransaction) {
362
+ executor.execute { sendTransactionPayload(transaction) }
363
+ }
364
+
365
+ private fun sendTransactionPayload(transaction: SKTransaction) {
366
+ val cfg = config ?: return
367
+ val payload = transaction.toJSON()
368
+ cfg.release?.let { payload.put("release", it) }
369
+ payload.put("environment", cfg.environment)
370
+
371
+ // Round-C: prefer IngestClient when wired.
372
+ val ingest = com.appswissknife.net.IngestClient.shared
373
+ val ctx = appContext
374
+ if (ingest != null && ctx != null) {
375
+ ingest.enqueue(com.appswissknife.net.IngestItemType.Transaction, payload, ctx)
376
+ return
377
+ }
378
+
379
+ // Round-D: legacy fallback (only reached when IngestClient is not
380
+ // wired — primarily host-app-only init via SKPerformance.initialize
381
+ // without going through SwissKnife.configure). Routes through the
382
+ // unified BackendHttpClient transport.
383
+ try {
384
+ com.appswissknife.net.BackendHttpClient
385
+ .create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
386
+ .simplePost(
387
+ path = "/api/sdk/errors/transaction",
388
+ body = payload.toString(),
389
+ )
390
+ } catch (e: Exception) {
391
+ println("[SwissKnife Performance] send error: ${e.message}")
392
+ }
393
+ }
394
+
395
+ // MARK: - ID Generation
396
+
397
+ internal fun generateTraceId(): String {
398
+ return UUID.randomUUID().toString().replace("-", "").lowercase()
399
+ }
400
+
401
+ internal fun generateSpanId(): String {
402
+ return UUID.randomUUID().toString().replace("-", "").lowercase().take(16)
403
+ }
404
+
405
+ // MARK: - Test Hooks
406
+
407
+ internal fun _resetForTesting() {
408
+ config = null
409
+ appContext = null
410
+ appStartTransaction = null
411
+ firstActivityResumed = false
412
+ activityCreatedTimes.clear()
413
+ currentTransaction = null
414
+ }
415
+ }
416
+
417
+ // MARK: - SKCrashReporting Extension
418
+
419
+ /**
420
+ * Extension function on SKCrashReporting companion for convenient transaction creation.
421
+ * Usage: `SKCrashReporting.startTransaction("name", "op")`
422
+ */
423
+ fun com.appswissknife.crashreporting.SKCrashReporting.startTransaction(
424
+ name: String,
425
+ op: String
426
+ ): SKTransaction {
427
+ return SKPerformance.startTransaction(name, op)
428
+ }