@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,320 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/net/OfflineQueueStore.kt
2
+ //
3
+ // Round-C Android port — generic append-only JSONL disk-backed queue.
4
+ // Mirror of `Sources/SwissKnifeiOS/Net/OfflineQueueStore.swift`. Replaces
5
+ // per-module ad-hoc on-disk queues; existing `analytics/EventQueueStore`
6
+ // stays as-is until SKAnalytics migrates to IngestClient.
7
+ //
8
+ // Storage strategy — `cacheDir/swissknife/<name>/`:
9
+ // - `cacheDir` because the OS may reclaim under storage pressure, which
10
+ // is acceptable for outgoing telemetry queues (dropping a batch is
11
+ // preferable to filling user disk; backend dedupes per-item via id).
12
+ // - Each queue gets its own subdirectory keyed by `name`.
13
+ //
14
+ // Encoding — append-only JSONL:
15
+ // - One self-describing JSON object per line. No outer array, no
16
+ // rewrite-the-world-on-append. A crash mid-write leaves at most one
17
+ // torn final line which `readAll` silently drops.
18
+ //
19
+ // Crash safety:
20
+ // - `append()` writes + fd.sync() and closes synchronously.
21
+ // - `remove()` writes the filtered copy to `items.jsonl.tmp` then
22
+ // atomic-renames over the original.
23
+ //
24
+ // Thread safety:
25
+ // - All public methods synchronize on a single object lock. Disk I/O is
26
+ // slow enough that a serial lock is the right tradeoff vs a reader/
27
+ // writer lock; we never need concurrent reads.
28
+
29
+ package com.appswissknife.net
30
+
31
+ import android.util.Log
32
+ import org.json.JSONObject
33
+ import java.io.BufferedReader
34
+ import java.io.File
35
+ import java.io.FileOutputStream
36
+ import java.io.IOException
37
+ import java.io.InputStreamReader
38
+
39
+ /**
40
+ * One queued item must serialize itself to JSON and expose a stable string
41
+ * `id`. The id drives idempotency (backend dedupes against it) and the
42
+ * `remove(ids:)` path after a successful flush.
43
+ */
44
+ internal interface OfflineQueueItem {
45
+ val id: String
46
+ fun toJson(): JSONObject
47
+ }
48
+
49
+ /**
50
+ * Defaults shared across all OfflineQueueStore instances. Matches the iOS
51
+ * defaults in `OfflineQueueStoreDefaults`.
52
+ */
53
+ internal object OfflineQueueStoreDefaults {
54
+ const val MAX_ITEMS: Int = 10_000
55
+ const val MAX_BYTES: Long = 10L * 1024L * 1024L
56
+ }
57
+
58
+ /**
59
+ * Generic disk-backed FIFO queue. `T` is any type implementing
60
+ * [OfflineQueueItem]; the caller supplies a `parser` lambda that turns a
61
+ * JSONObject back into a `T`.
62
+ *
63
+ * Parser-takes-JSONObject (rather than a Codable generic) keeps Kotlin
64
+ * call sites lean — Kotlin has no first-class JSON codec; downstream
65
+ * callers (IngestClient) already work in `org.json` for the wire envelope.
66
+ */
67
+ internal class OfflineQueueStore<T : OfflineQueueItem>(
68
+ private val directory: File,
69
+ private val name: String = "default",
70
+ private val parser: (JSONObject) -> T,
71
+ private val maxItems: Int = OfflineQueueStoreDefaults.MAX_ITEMS,
72
+ private val maxBytes: Long = OfflineQueueStoreDefaults.MAX_BYTES,
73
+ ) {
74
+ private val tag = "SwissKnife.Queue.$name"
75
+ private val lock = Any()
76
+
77
+ private val file: File
78
+ private val deadLetterFile: File
79
+
80
+ init {
81
+ ensureDirectory(directory)
82
+ file = File(directory, "items.jsonl")
83
+ deadLetterFile = File(directory, "dead-letter.jsonl")
84
+ if (!file.exists()) {
85
+ runCatching { file.createNewFile() }
86
+ }
87
+ }
88
+
89
+ // ----- Public API -----
90
+
91
+ /**
92
+ * Append one item. Synchronous — on return the item is on disk
93
+ * (fd.sync()'d). Throws on I/O failure; callers usually swallow
94
+ * because the enqueue contract is fire-and-forget.
95
+ */
96
+ @Throws(IOException::class)
97
+ fun append(item: T) {
98
+ synchronized(lock) {
99
+ appendLocked(item)
100
+ enforceLimitsLocked()
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Append a batch. Cheaper than N appends — limit-enforcement only fires
106
+ * at the end.
107
+ */
108
+ @Throws(IOException::class)
109
+ fun appendAll(items: List<T>) {
110
+ synchronized(lock) {
111
+ for (item in items) appendLocked(item)
112
+ enforceLimitsLocked()
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Read all currently-persisted items, oldest first. Silently skips
118
+ * malformed lines and rewrites the file to drop the bad lines — better
119
+ * to lose one item than wedge the queue.
120
+ */
121
+ fun readAll(): List<T> {
122
+ synchronized(lock) {
123
+ return readAllLocked().first
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Remove items whose ids are in [ids]. Atomic via .tmp + rename.
129
+ */
130
+ fun remove(ids: Set<String>) {
131
+ if (ids.isEmpty()) return
132
+ synchronized(lock) {
133
+ val (remaining, _) = readAllLocked()
134
+ writeAllLocked(remaining.filter { it.id !in ids })
135
+ }
136
+ }
137
+
138
+ /** Current number of items. Walks the file. */
139
+ fun count(): Int = synchronized(lock) { readAllLocked().first.size }
140
+
141
+ /** Bytes on disk for the items file. */
142
+ fun sizeBytes(): Long = synchronized(lock) {
143
+ if (file.exists()) file.length() else 0L
144
+ }
145
+
146
+ /**
147
+ * Move items into the dead-letter file. Best-effort — any I/O failure
148
+ * is logged and swallowed because the live queue must keep moving even
149
+ * if dead-letter persistence fails. Caller is still responsible for
150
+ * `remove(ids:)` on the live queue afterwards.
151
+ */
152
+ fun deadLetter(items: List<T>) {
153
+ if (items.isEmpty()) return
154
+ synchronized(lock) {
155
+ try {
156
+ appendToDeadLetterLocked(items)
157
+ } catch (e: IOException) {
158
+ Log.w(tag, "dead-letter write failed; dropping ${items.size}", e)
159
+ }
160
+ }
161
+ }
162
+
163
+ /** Read dead-lettered items. Used by tests + potential recovery flows. */
164
+ fun readDeadLetter(): List<T> {
165
+ synchronized(lock) {
166
+ if (!deadLetterFile.exists()) return emptyList()
167
+ val out = ArrayList<T>()
168
+ try {
169
+ BufferedReader(InputStreamReader(deadLetterFile.inputStream(), Charsets.UTF_8)).use { reader ->
170
+ while (true) {
171
+ val line = reader.readLine() ?: break
172
+ if (line.isEmpty()) continue
173
+ runCatching { parser(JSONObject(line)) }.onSuccess { out.add(it) }
174
+ }
175
+ }
176
+ } catch (e: IOException) {
177
+ Log.w(tag, "dead-letter read failed", e)
178
+ }
179
+ return out
180
+ }
181
+ }
182
+
183
+ // ----- Internals (must hold lock) -----
184
+
185
+ private fun appendLocked(item: T) {
186
+ file.parentFile?.takeIf { !it.exists() }?.mkdirs()
187
+ val line = item.toJson().toString() + "\n"
188
+ FileOutputStream(file, /* append = */ true).use { out ->
189
+ out.write(line.toByteArray(Charsets.UTF_8))
190
+ out.flush()
191
+ runCatching { out.fd.sync() }
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Read items + sawMalformed flag. If any line failed to parse we
197
+ * rewrite the file with only the well-formed entries so the bad lines
198
+ * don't haunt subsequent reads.
199
+ */
200
+ private fun readAllLocked(): Pair<List<T>, Boolean> {
201
+ if (!file.exists()) return Pair(emptyList(), false)
202
+ val out = ArrayList<T>()
203
+ var sawBad = false
204
+ try {
205
+ BufferedReader(InputStreamReader(file.inputStream(), Charsets.UTF_8)).use { reader ->
206
+ while (true) {
207
+ val line = reader.readLine() ?: break
208
+ if (line.isEmpty()) continue
209
+ val parsed = runCatching { parser(JSONObject(line)) }.getOrNull()
210
+ if (parsed == null) {
211
+ sawBad = true
212
+ } else {
213
+ out.add(parsed)
214
+ }
215
+ }
216
+ }
217
+ } catch (e: IOException) {
218
+ Log.w(tag, "readAll failed; returning ${out.size}", e)
219
+ }
220
+ if (sawBad) {
221
+ runCatching { writeAllLocked(out) }
222
+ }
223
+ return Pair(out, sawBad)
224
+ }
225
+
226
+ private fun writeAllLocked(items: List<T>) {
227
+ file.parentFile?.takeIf { !it.exists() }?.mkdirs()
228
+ val tmp = File(file.parentFile, "${file.name}.tmp")
229
+ try {
230
+ FileOutputStream(tmp, false).use { out ->
231
+ for (item in items) {
232
+ val line = item.toJson().toString() + "\n"
233
+ out.write(line.toByteArray(Charsets.UTF_8))
234
+ }
235
+ out.flush()
236
+ runCatching { out.fd.sync() }
237
+ }
238
+ if (!tmp.renameTo(file)) {
239
+ file.delete()
240
+ if (!tmp.renameTo(file)) {
241
+ Log.w(tag, "writeAll renameTo failed; queue may be inconsistent")
242
+ }
243
+ }
244
+ } catch (e: IOException) {
245
+ Log.w(tag, "writeAll failed", e)
246
+ tmp.delete()
247
+ }
248
+ }
249
+
250
+ private fun appendToDeadLetterLocked(items: List<T>) {
251
+ deadLetterFile.parentFile?.takeIf { !it.exists() }?.mkdirs()
252
+ if (!deadLetterFile.exists()) deadLetterFile.createNewFile()
253
+ FileOutputStream(deadLetterFile, true).use { out ->
254
+ for (item in items) {
255
+ val line = item.toJson().toString() + "\n"
256
+ out.write(line.toByteArray(Charsets.UTF_8))
257
+ }
258
+ out.flush()
259
+ runCatching { out.fd.sync() }
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Enforce (maxItems, maxBytes) by dropping oldest first. Common case
265
+ * (under cap) is a file.length() check + count() walk — cheap.
266
+ */
267
+ private fun enforceLimitsLocked() {
268
+ val sizeOk = file.length() <= maxBytes
269
+ if (sizeOk) {
270
+ val approx = approximateCountLocked()
271
+ if (approx <= maxItems) return
272
+ }
273
+ val (all, _) = readAllLocked()
274
+ if (all.size <= maxItems && file.length() <= maxBytes) return
275
+
276
+ var keep = all
277
+ if (keep.size > maxItems) {
278
+ val dropped = keep.size - maxItems
279
+ Log.w(tag, "queue exceeded $maxItems items; dropping oldest $dropped")
280
+ keep = keep.subList(dropped, keep.size).toList()
281
+ }
282
+ while (keep.isNotEmpty() && estimateBytesLocked(keep) > maxBytes) {
283
+ val dropCount = maxOf(1, keep.size / 10)
284
+ Log.w(tag, "queue exceeded $maxBytes bytes; dropping oldest $dropCount")
285
+ keep = keep.subList(dropCount, keep.size).toList()
286
+ }
287
+ writeAllLocked(keep)
288
+ }
289
+
290
+ private fun approximateCountLocked(): Int {
291
+ if (!file.exists()) return 0
292
+ var count = 0
293
+ try {
294
+ BufferedReader(InputStreamReader(file.inputStream(), Charsets.UTF_8)).use { reader ->
295
+ while (reader.readLine() != null) count++
296
+ }
297
+ } catch (_: IOException) {
298
+ return Int.MAX_VALUE
299
+ }
300
+ return count
301
+ }
302
+
303
+ private fun estimateBytesLocked(items: List<T>): Long {
304
+ var total = 0L
305
+ for (item in items) total += item.toJson().toString().length + 1
306
+ return total
307
+ }
308
+
309
+ private fun ensureDirectory(dir: File) {
310
+ if (dir.exists()) {
311
+ if (!dir.isDirectory) {
312
+ throw IOException("Path exists and is not a directory: ${dir.absolutePath}")
313
+ }
314
+ return
315
+ }
316
+ if (!dir.mkdirs() && !dir.exists()) {
317
+ throw IOException("Unable to create directory ${dir.absolutePath}")
318
+ }
319
+ }
320
+ }
@@ -0,0 +1,219 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/offerings/OfferingsRepository.kt
2
+ //
3
+ // Phase 6 commit 4 — fetch offerings from the backend and enrich with live
4
+ // Play Billing prices.
5
+ //
6
+ // Backend contract: we use the existing /api/sdk/paywalls/show endpoint
7
+ // (keyed by paywall_slug) as the source of truth for which products exist
8
+ // in the user's current paywall variant. Output shape:
9
+ // { paywall_id, slug, render_url, config, products_with_prices: [{
10
+ // id, product_id, name, platform, duration_days, price, position,
11
+ // badge_text, is_highlighted }], experiment_id, variant_id }
12
+ //
13
+ // Why paywalls/show and not a brand-new /api/sdk/offerings endpoint:
14
+ // - paywalls/show is the only endpoint today that returns the product set
15
+ // in a per-user, experiment-resolved shape. Building a separate
16
+ // /api/sdk/offerings would duplicate the variant-resolution logic that
17
+ // paywalls/show already owns.
18
+ // - The host app already knows the paywall slug it wants to render (paywall
19
+ // selection is a product decision, not an SDK auto-resolution).
20
+ // - Phase 5 (iOS) hasn't added a /api/sdk/offerings either as of branch
21
+ // creation, so contracts stay aligned across platforms.
22
+ //
23
+ // Price enrichment: paywalls/show returns the backend's last-known price
24
+ // (set in the dashboard). For Play purchases the live price comes from
25
+ // queryProductDetailsAsync at purchase time. We enrich each product with the
26
+ // Play Billing ProductDetails when available so the dashboard's price drift
27
+ // vs Play store is reflected in the UI.
28
+ //
29
+ // Cache: 1-hour in-memory cache. paywalls/show is keyed by user (assignment
30
+ // is sticky) so the cache key includes (paywallSlug, userId).
31
+
32
+ package com.appswissknife.offerings
33
+
34
+ import com.appswissknife.models.Offering
35
+ import com.appswissknife.models.Offerings
36
+ import com.appswissknife.models.Package
37
+ import com.appswissknife.models.PackageType
38
+ import com.appswissknife.models.Price
39
+ import com.appswissknife.models.StoreProduct
40
+ import com.appswissknife.models.StoreProductDiscount
41
+ import com.appswissknife.models.SubscriptionPeriod
42
+ import com.appswissknife.purchases.BillingHttpClient
43
+ import com.appswissknife.purchases.PriceEnrichmentProvider
44
+ import org.json.JSONObject
45
+ import java.io.IOException
46
+ import java.util.concurrent.ConcurrentHashMap
47
+
48
+ class OfferingsRepository(
49
+ private val httpClient: BillingHttpClient,
50
+ private val serverUrl: String,
51
+ private val apiKey: String,
52
+ // Backend `platform` rows belonging to the active store (case-insensitive),
53
+ // e.g. {"play","android"} or {"rustore"}.
54
+ private val platformTags: Set<String>,
55
+ // Live price enrichment for the active store; null = backend prices only.
56
+ private val priceProvider: PriceEnrichmentProvider?,
57
+ private val clock: () -> Long = System::currentTimeMillis,
58
+ ) {
59
+
60
+ private data class CacheEntry(val offerings: Offerings, val fetchedAt: Long)
61
+
62
+ private val cache = ConcurrentHashMap<String, CacheEntry>()
63
+
64
+ /**
65
+ * Fetch the offerings for [paywallSlug] for the given [userId]. Goes to
66
+ * /api/sdk/paywalls/show, optionally enriches each product with live
67
+ * Play Billing ProductDetails, returns within the 1h cache window if
68
+ * we've fetched recently.
69
+ */
70
+ @Throws(IOException::class)
71
+ fun current(paywallSlug: String, userId: String): Offerings {
72
+ val key = "$paywallSlug:$userId"
73
+ cache[key]?.takeIf { clock() - it.fetchedAt < CACHE_TTL_MILLIS }?.let { return it.offerings }
74
+ val raw = fetchPaywallsShow(paywallSlug, userId)
75
+ val parsed = parseAndEnrich(raw, paywallSlug)
76
+ cache[key] = CacheEntry(parsed, clock())
77
+ return parsed
78
+ }
79
+
80
+ /** Invalidate the cache - useful on logIn/logOut (user assignment changes). */
81
+ fun invalidate() {
82
+ cache.clear()
83
+ }
84
+
85
+ // --- Internals ---------------------------------------------------------
86
+
87
+ @Throws(IOException::class)
88
+ private fun fetchPaywallsShow(paywallSlug: String, userId: String): JSONObject {
89
+ // Round-D: routed through the unified BackendHttpClient transport.
90
+ // The pre-Round-D path issued the GET directly and (incorrectly) sent
91
+ // `Authorization: Bearer ...` — the backend `paywalls/show` route
92
+ // uses `withApiKeyAuth` (X-API-Key). simpleBackendGet stamps the
93
+ // right header.
94
+ val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
95
+ val (_, text) = client.simpleGet(
96
+ path = "/api/sdk/paywalls/show",
97
+ query = listOf(
98
+ "paywall_slug" to paywallSlug,
99
+ "user_id" to userId,
100
+ ),
101
+ )
102
+ return JSONObject(text)
103
+ }
104
+
105
+ private fun parseAndEnrich(raw: JSONObject, paywallSlug: String): Offerings {
106
+ val productsJson = raw.optJSONArray("products_with_prices") ?: org.json.JSONArray()
107
+ val backendProducts = mutableListOf<BackendProduct>()
108
+ for (i in 0 until productsJson.length()) {
109
+ val o = productsJson.optJSONObject(i) ?: continue
110
+ backendProducts.add(
111
+ BackendProduct(
112
+ productId = o.optString("product_id"),
113
+ name = o.optString("name"),
114
+ platform = o.optString("platform"),
115
+ durationDays = o.optInt("duration_days"),
116
+ backendPrice = o.optDouble("price", 0.0),
117
+ )
118
+ )
119
+ }
120
+ // Filter to the active store's products (Play: play/android; RuStore: rustore).
121
+ val tagsLower = platformTags.map { it.lowercase() }.toSet()
122
+ val storeProducts = backendProducts.filter { it.platform.lowercase() in tagsLower }
123
+ // Enrich with live store prices; ids the store can't resolve fall back to
124
+ // the backend-priced product.
125
+ val enriched = priceProvider?.enrich(storeProducts.associate { it.productId to it.name }) ?: emptyMap()
126
+ val packages = storeProducts.map { bp ->
127
+ val storeProduct = enriched[bp.productId] ?: StoreProductFromBackend(bp)
128
+ SimplePackage(
129
+ identifier = bp.productId,
130
+ packageType = bp.durationDays.toPackageType(),
131
+ product = storeProduct,
132
+ offeringIdentifier = paywallSlug,
133
+ )
134
+ }
135
+ val offering = SimpleOffering(
136
+ identifier = paywallSlug,
137
+ serverDescription = raw.optString("slug", paywallSlug),
138
+ metadata = mapOf(
139
+ "paywall_id" to raw.opt("paywall_id"),
140
+ "render_url" to raw.opt("render_url"),
141
+ "experiment_id" to raw.opt("experiment_id"),
142
+ "variant_id" to raw.opt("variant_id"),
143
+ ),
144
+ availablePackages = packages,
145
+ )
146
+ return SimpleOfferings(
147
+ all = mapOf(paywallSlug to offering),
148
+ current = offering,
149
+ )
150
+ }
151
+
152
+ private fun Int.toPackageType(): PackageType = when (this) {
153
+ in 0..0 -> PackageType.LIFETIME
154
+ in 1..7 -> PackageType.WEEKLY
155
+ in 8..31 -> PackageType.MONTHLY
156
+ in 32..90 -> PackageType.THREE_MONTH
157
+ in 91..180 -> PackageType.SIX_MONTH
158
+ in 181..365 -> PackageType.ANNUAL
159
+ else -> PackageType.UNKNOWN
160
+ }
161
+
162
+ companion object {
163
+ private const val CACHE_TTL_MILLIS: Long = 60L * 60 * 1000 // 1h
164
+ }
165
+ }
166
+
167
+ // --- Backend DTO -----------------------------------------------------------
168
+
169
+ private data class BackendProduct(
170
+ val productId: String,
171
+ val name: String,
172
+ val platform: String,
173
+ val durationDays: Int,
174
+ val backendPrice: Double,
175
+ )
176
+
177
+ // --- Public model impls ----------------------------------------------------
178
+
179
+ data class SimpleOfferings(
180
+ override val all: Map<String, Offering>,
181
+ override val current: Offering?,
182
+ ) : Offerings
183
+
184
+ data class SimpleOffering(
185
+ override val identifier: String,
186
+ override val serverDescription: String,
187
+ override val metadata: Map<String, Any?>,
188
+ override val availablePackages: List<Package>,
189
+ ) : Offering
190
+
191
+ data class SimplePackage(
192
+ override val identifier: String,
193
+ override val packageType: PackageType,
194
+ override val product: StoreProduct,
195
+ override val offeringIdentifier: String,
196
+ ) : Package
197
+
198
+ /** StoreProduct sourced from a backend BackendProduct - used when
199
+ * queryProductDetailsAsync hasn't returned anything for this id (offline /
200
+ * not yet uploaded to Play). */
201
+ private class StoreProductFromBackend(private val bp: BackendProduct) : StoreProduct {
202
+ override val id: String = bp.productId
203
+ override val localizedTitle: String = bp.name
204
+ override val localizedDescription: String = bp.name
205
+ override val price: Price = SimplePrice(
206
+ formatted = "$${"%.2f".format(bp.backendPrice)}",
207
+ currencyCode = "USD",
208
+ amountMicros = (bp.backendPrice * 1_000_000).toLong(),
209
+ )
210
+ override val subscriptionPeriod: SubscriptionPeriod? = null
211
+ override val introductoryDiscount: StoreProductDiscount? = null
212
+ override val discounts: List<StoreProductDiscount> = emptyList()
213
+ }
214
+
215
+ data class SimplePrice(
216
+ override val formatted: String,
217
+ override val currencyCode: String,
218
+ override val amountMicros: Long,
219
+ ) : Price
@@ -0,0 +1,94 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/performance/SKFrameTracker.kt
2
+ //
3
+ // Tracks slow and frozen frames via Choreographer for performance transactions.
4
+ // Slow frame: > 16ms (missed 60fps deadline)
5
+ // Frozen frame: > 700ms (perceived freeze)
6
+
7
+ package com.appswissknife.performance
8
+
9
+ import android.view.Choreographer
10
+
11
+ object SKFrameTracker : Choreographer.FrameCallback {
12
+
13
+ private var lastFrameNanos = 0L
14
+ private var tracking = false
15
+
16
+ /** Frames that took > 16ms but <= 700ms to render. */
17
+ @Volatile
18
+ var slowFrameCount = 0
19
+ private set
20
+
21
+ /** Frames that took > 700ms to render. */
22
+ @Volatile
23
+ var frozenFrameCount = 0
24
+ private set
25
+
26
+ /** Total frames observed since tracking started. */
27
+ @Volatile
28
+ var totalFrameCount = 0
29
+ private set
30
+
31
+ // MARK: - Start / Stop
32
+
33
+ fun start() {
34
+ if (tracking) return
35
+ tracking = true
36
+ lastFrameNanos = 0
37
+ try {
38
+ Choreographer.getInstance().postFrameCallback(this)
39
+ } catch (_: Exception) {
40
+ // Choreographer not available (e.g. in tests without a Looper)
41
+ tracking = false
42
+ }
43
+ }
44
+
45
+ fun stop() {
46
+ tracking = false
47
+ try {
48
+ Choreographer.getInstance().removeFrameCallback(this)
49
+ } catch (_: Exception) {
50
+ // ignore
51
+ }
52
+ }
53
+
54
+ fun reset() {
55
+ slowFrameCount = 0
56
+ frozenFrameCount = 0
57
+ totalFrameCount = 0
58
+ lastFrameNanos = 0
59
+ }
60
+
61
+ // MARK: - FrameCallback
62
+
63
+ override fun doFrame(frameTimeNanos: Long) {
64
+ if (!tracking) return
65
+
66
+ if (lastFrameNanos > 0) {
67
+ val durationMs = (frameTimeNanos - lastFrameNanos) / 1_000_000
68
+ totalFrameCount++
69
+ when {
70
+ durationMs > 700 -> frozenFrameCount++
71
+ durationMs > 16 -> slowFrameCount++
72
+ }
73
+ }
74
+ lastFrameNanos = frameTimeNanos
75
+
76
+ // Re-register for the next frame
77
+ if (tracking) {
78
+ try {
79
+ Choreographer.getInstance().postFrameCallback(this)
80
+ } catch (_: Exception) {
81
+ tracking = false
82
+ }
83
+ }
84
+ }
85
+
86
+ // MARK: - Attach to Transaction
87
+
88
+ /** Attach current frame counts to a transaction as data fields. */
89
+ fun attachToTransaction(tx: SKTransaction) {
90
+ tx.setData("frames_total", totalFrameCount.toString())
91
+ tx.setData("frames_slow", slowFrameCount.toString())
92
+ tx.setData("frames_frozen", frozenFrameCount.toString())
93
+ }
94
+ }