@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.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 (177) hide show
  1. package/CHANGELOG.md +385 -2
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +27 -6
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +27 -6
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +2 -0
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +2 -0
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +12 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +16 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +50 -9
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -1,326 +0,0 @@
1
- // packages/swiss-knife-android/src/main/java/com/appswissknife/analytics/EventQueueStore.kt
2
- //
3
- // Disk-persistent append-only JSONL queue for analytics events.
4
- //
5
- // Why this exists:
6
- // Phase 2.2 replaces the in-memory CopyOnWriteArrayList queue in SKAnalytics
7
- // with a disk-backed log so events survive process death (background kill,
8
- // OOM, force-stop, ANR-driven termination). Combined with FlushEventsWorker
9
- // (WorkManager-driven retry), tracked events are durable from track() return
10
- // through successful HTTP ack — matching the same posture DeviceID got in
11
- // Phase 1.2.
12
- //
13
- // Storage format:
14
- // - One JSON object per line (JSONL / NDJSON).
15
- // - File at cacheDir/swissknife/events.jsonl. We use cacheDir intentionally
16
- // (vs filesDir) because the system MAY reclaim cacheDir under storage
17
- // pressure — events are recoverable user-action data, not user-content
18
- // data that must be preserved. A retried flush after cache-eviction is
19
- // fine; an idempotent backend handles the dedupe.
20
- // - Append is sync'd (FileOutputStream.fd.sync()) so an OOM or kernel kill
21
- // immediately after track() returns still preserves the event on disk.
22
- //
23
- // Limits:
24
- // - Hard cap at 10,000 events OR ~10MB on disk. On overflow we drop OLDEST
25
- // events first (FIFO eviction) and emit a Log.w warning. Drop-oldest keeps
26
- // the live-ish tail; drop-newest would silently shadow current activity.
27
- //
28
- // Crash safety:
29
- // - append: write then fd.sync(). If process dies mid-write, the file may
30
- // contain a partial last line — readAll() silently skips unparseable
31
- // lines so a torn write loses at most that one event.
32
- // - remove: write all surviving lines to a temp file, then atomic
33
- // renameTo(). On crash mid-rename, either the old file or the new file
34
- // exists in full — never a half-applied delete.
35
- //
36
- // Threading:
37
- // - Single object lock guards all file IO. Callers can hit this from any
38
- // thread; readers and writers serialize through @Synchronized. The
39
- // contention is low — track() does one short write per call.
40
-
41
- package com.appswissknife.analytics
42
-
43
- import android.content.Context
44
- import android.util.Log
45
- import androidx.annotation.VisibleForTesting
46
- import org.json.JSONException
47
- import org.json.JSONObject
48
- import java.io.BufferedReader
49
- import java.io.File
50
- import java.io.FileOutputStream
51
- import java.io.IOException
52
- import java.io.InputStreamReader
53
- import com.appswissknife.context.IDs
54
-
55
- /**
56
- * A single queued event as stored on disk and read back for flushing.
57
- *
58
- * @property id The event_id field from the body — the per-event idempotency
59
- * key. Matches Phase 0.1 backend dedupe semantics.
60
- * @property body The full JSON payload as written by SKAnalytics.track().
61
- * @property enqueueTime The wall-clock millis when this record was appended to
62
- * the store. Used for diagnostics + ordering only (not sent
63
- * on the wire — the body already carries "time").
64
- */
65
- internal data class QueuedEvent(
66
- val id: String,
67
- val body: JSONObject,
68
- val enqueueTime: Long,
69
- )
70
-
71
- internal class EventQueueStore(
72
- context: Context,
73
- private val maxEvents: Int = DEFAULT_MAX_EVENTS,
74
- private val maxBytes: Long = DEFAULT_MAX_BYTES,
75
- ) {
76
-
77
- companion object {
78
- private const val TAG = "SwissKnife.EventQueue"
79
-
80
- @VisibleForTesting
81
- internal const val DIR_NAME = "swissknife"
82
-
83
- @VisibleForTesting
84
- internal const val FILE_NAME = "events.jsonl"
85
-
86
- // Sized to bound disk usage at ~10MB and bound the number of events to
87
- // 10k. The smaller of (count cap, size cap) wins on each append.
88
- const val DEFAULT_MAX_EVENTS = 10_000
89
- const val DEFAULT_MAX_BYTES = 10L * 1024 * 1024
90
-
91
- // Field name used in the persisted JSON body to look up the idempotency
92
- // key. Matches SKAnalytics.track() output.
93
- private const val EVENT_ID_FIELD = "event_id"
94
- // Side-channel timestamp field — added by EventQueueStore.append to
95
- // record when the line was written. Not part of the wire payload.
96
- private const val ENQUEUE_TIME_FIELD = "_sk_enqueue_time"
97
- }
98
-
99
- private val appContext: Context = context.applicationContext ?: context
100
-
101
- @VisibleForTesting
102
- internal val file: File = run {
103
- val dir = File(appContext.cacheDir, DIR_NAME)
104
- if (!dir.exists()) dir.mkdirs()
105
- File(dir, FILE_NAME)
106
- }
107
-
108
- private val lock = Any()
109
-
110
- /**
111
- * Synchronously append [event] to the on-disk queue. Forces an fsync so
112
- * the event survives an immediate process kill. Enforces the size/count
113
- * caps by dropping oldest events on overflow.
114
- */
115
- fun append(event: JSONObject) {
116
- synchronized(lock) {
117
- // Tag the on-disk copy with its enqueue timestamp. The original
118
- // event JSON is not mutated — we add the metadata field to a
119
- // shallow copy before serializing.
120
- val withMeta = copyJson(event).apply {
121
- put(ENQUEUE_TIME_FIELD, System.currentTimeMillis())
122
- }
123
- val line = withMeta.toString() + "\n"
124
-
125
- try {
126
- // cacheDir contents may be reclaimed by the OS under storage
127
- // pressure (we use cacheDir deliberately — events are not
128
- // user content). Re-create the parent dir on every append so
129
- // the next track() after eviction still lands.
130
- file.parentFile?.takeIf { !it.exists() }?.mkdirs()
131
- FileOutputStream(file, /* append = */ true).use { out ->
132
- out.write(line.toByteArray(Charsets.UTF_8))
133
- out.flush()
134
- // Force-sync the inode + data to disk so an immediate
135
- // process kill cannot lose this event. fd.sync() is the
136
- // crash-safety primitive — flush() alone leaves the data
137
- // in the OS page cache.
138
- runCatching { out.fd.sync() }
139
- }
140
- } catch (e: IOException) {
141
- Log.w(TAG, "append failed; event dropped", e)
142
- return
143
- }
144
-
145
- enforceCapsLocked()
146
- }
147
- }
148
-
149
- /**
150
- * Read all queued events back from disk, in insertion order (oldest first).
151
- * Unparseable lines (e.g. torn final write from a process kill) are
152
- * silently skipped.
153
- */
154
- fun readAll(): List<QueuedEvent> {
155
- synchronized(lock) {
156
- return readAllLocked()
157
- }
158
- }
159
-
160
- /**
161
- * Drop the events whose `event_id` is in [ids]. Atomic via temp-file +
162
- * rename, so a crash mid-remove leaves either the pre-remove state or
163
- * the post-remove state — never a partial delete.
164
- */
165
- fun remove(ids: Set<String>) {
166
- if (ids.isEmpty()) return
167
- synchronized(lock) {
168
- val surviving = readAllLocked().filterNot { it.id in ids }
169
- writeAllLocked(surviving)
170
- }
171
- }
172
-
173
- fun count(): Int = synchronized(lock) { readAllLocked().size }
174
-
175
- fun sizeBytes(): Long = synchronized(lock) {
176
- if (file.exists()) file.length() else 0L
177
- }
178
-
179
- /**
180
- * Test-only: nuke the queue file. Production callers go through [remove].
181
- */
182
- @VisibleForTesting
183
- internal fun clearForTesting() {
184
- synchronized(lock) {
185
- if (file.exists()) file.delete()
186
- }
187
- }
188
-
189
- // ---- Internals (all callers must hold `lock`) ----
190
-
191
- private fun readAllLocked(): List<QueuedEvent> {
192
- if (!file.exists()) return emptyList()
193
- val out = ArrayList<QueuedEvent>()
194
- try {
195
- BufferedReader(InputStreamReader(file.inputStream(), Charsets.UTF_8)).use { reader ->
196
- while (true) {
197
- val line = reader.readLine() ?: break
198
- if (line.isEmpty()) continue
199
- val parsed = parseLine(line) ?: continue
200
- out.add(parsed)
201
- }
202
- }
203
- } catch (e: IOException) {
204
- Log.w(TAG, "readAll failed; returning ${out.size} parsed events", e)
205
- }
206
- return out
207
- }
208
-
209
- private fun parseLine(line: String): QueuedEvent? {
210
- return try {
211
- val obj = JSONObject(line)
212
- val id = obj.optString(EVENT_ID_FIELD).ifEmpty {
213
- // Defensive: if event_id is missing (e.g. legacy data), mint
214
- // a stable id so callers still have something to dedupe on.
215
- IDs.eventId().also { obj.put(EVENT_ID_FIELD, it) }
216
- }
217
- val enqueueTime = obj.optLong(ENQUEUE_TIME_FIELD, 0L)
218
- // Strip the side-channel field so the wire body matches what
219
- // SKAnalytics.track() originally produced.
220
- obj.remove(ENQUEUE_TIME_FIELD)
221
- QueuedEvent(id = id, body = obj, enqueueTime = enqueueTime)
222
- } catch (_: JSONException) {
223
- // Torn last line from a crashed write — skip silently.
224
- null
225
- }
226
- }
227
-
228
- private fun writeAllLocked(events: List<QueuedEvent>) {
229
- file.parentFile?.takeIf { !it.exists() }?.mkdirs()
230
- val tmp = File(file.parentFile, "${file.name}.tmp")
231
- try {
232
- FileOutputStream(tmp, /* append = */ false).use { out ->
233
- for (ev in events) {
234
- val withMeta = copyJson(ev.body).apply {
235
- put(ENQUEUE_TIME_FIELD, ev.enqueueTime)
236
- }
237
- out.write((withMeta.toString() + "\n").toByteArray(Charsets.UTF_8))
238
- }
239
- out.flush()
240
- runCatching { out.fd.sync() }
241
- }
242
- if (!tmp.renameTo(file)) {
243
- // renameTo may fail on some FS (esp. cross-device or when
244
- // destination exists on older Android). Try delete + rename.
245
- file.delete()
246
- if (!tmp.renameTo(file)) {
247
- Log.w(TAG, "writeAll renameTo failed; queue state may be inconsistent")
248
- }
249
- }
250
- } catch (e: IOException) {
251
- Log.w(TAG, "writeAll failed", e)
252
- tmp.delete()
253
- }
254
- }
255
-
256
- /**
257
- * Enforce the (maxEvents, maxBytes) caps by dropping oldest events.
258
- * Called after every successful append. The common case (under cap) is a
259
- * file.length() + count() check — cheap.
260
- */
261
- private fun enforceCapsLocked() {
262
- val sizeOk = file.length() <= maxBytes
263
- // count() walks the file; only do it if size says we might be over,
264
- // OR if size is materially over so we can pick how many to drop.
265
- if (sizeOk) {
266
- // Quick path: bound count separately. Most overflow happens at
267
- // size cap (event payloads can be a few KB) — but a flood of
268
- // tiny events could also blow the count cap.
269
- val approxCount = approximateCountLocked()
270
- if (approxCount <= maxEvents) return
271
- }
272
-
273
- val all = readAllLocked()
274
- if (all.size <= maxEvents && file.length() <= maxBytes) return
275
-
276
- // Drop oldest until both caps are satisfied. We start by dropping the
277
- // count-cap excess, then iteratively drop more until the bytes cap is
278
- // also satisfied.
279
- var keep = all
280
- if (keep.size > maxEvents) {
281
- val dropped = keep.size - maxEvents
282
- Log.w(TAG, "queue exceeded $maxEvents events; dropping oldest $dropped")
283
- keep = keep.subList(dropped, keep.size).toList()
284
- }
285
- // Iteratively trim from the head until the serialized form is under
286
- // the byte cap. Each iteration drops ~10% of the head — bounded log
287
- // iterations even for pathological payload sizes.
288
- while (keep.isNotEmpty() && estimateBytes(keep) > maxBytes) {
289
- val dropCount = maxOf(1, keep.size / 10)
290
- Log.w(TAG, "queue exceeded $maxBytes bytes; dropping oldest $dropCount")
291
- keep = keep.subList(dropCount, keep.size).toList()
292
- }
293
- writeAllLocked(keep)
294
- }
295
-
296
- private fun approximateCountLocked(): Int {
297
- if (!file.exists()) return 0
298
- var count = 0
299
- try {
300
- BufferedReader(InputStreamReader(file.inputStream(), Charsets.UTF_8)).use { reader ->
301
- while (reader.readLine() != null) count++
302
- }
303
- } catch (_: IOException) {
304
- return Int.MAX_VALUE
305
- }
306
- return count
307
- }
308
-
309
- private fun estimateBytes(events: List<QueuedEvent>): Long {
310
- // Cheap projection — sum the JSON string lengths. Avoids materializing
311
- // a temp file just to ask "would this fit?".
312
- var total = 0L
313
- for (ev in events) {
314
- total += ev.body.toString().length + 64 // +64 for newline + meta field
315
- }
316
- return total
317
- }
318
-
319
- private fun copyJson(src: JSONObject): JSONObject {
320
- // Shallow copy via the string round-trip. JSONObject has no clone API
321
- // and a key-by-key copy still aliases nested JSONObjects, which the
322
- // caller could then mutate. The round-trip is the safe, cheap option
323
- // for the size of event payloads we deal with (single-digit KB).
324
- return JSONObject(src.toString())
325
- }
326
- }
@@ -1,296 +0,0 @@
1
- // packages/swiss-knife-android/src/main/java/com/appswissknife/analytics/FlushEventsWorker.kt
2
- //
3
- // WorkManager-driven flush of the persistent event queue.
4
- //
5
- // Why WorkManager (vs. ExecutorService + bespoke retry)?
6
- // - Survives process death: the OS schedules the work after a kill/restart
7
- // without app participation. Raw ExecutorService dies with the process.
8
- // - Network constraint is system-managed: WorkManager waits for the device
9
- // to be online before invoking us, so we never burn battery thrashing on
10
- // a doomed flush.
11
- // - Backoff is system-managed: ExponentialBackoff with floor+ceiling, with
12
- // no risk of an in-app loop holding wakelocks.
13
- // - Doze + App Standby aware out of the box.
14
- // The alternative — raw ExecutorService + AlarmManager + custom retry — has
15
- // to reimplement all of the above to be production-grade. The cost of
16
- // pulling in androidx.work is well worth not maintaining that.
17
- //
18
- // Retry cap mechanism:
19
- // We rely on the system-provided `runAttemptCount` (incremented by WM on
20
- // each retry) and cap retries at 5. We DO NOT keep a custom per-event
21
- // attempt counter because:
22
- // - The queue is a single coalesced batch — every retry tries to flush
23
- // whatever is on disk at that moment, not a specific event. Per-event
24
- // counters would need cross-attempt persistence anyway.
25
- // - runAttemptCount is already monotonic and survives process death — the
26
- // exact guarantee a custom counter would need.
27
- // - One source of truth is simpler than two.
28
- // On the 5th failed attempt we dead-letter (drop the current batch from
29
- // disk + Log.w warning) and return Result.success so WM stops retrying.
30
- //
31
- // Error-class handling (matches the Phase 0.1 backend semantics):
32
- // - 2xx → success, remove batch from disk.
33
- // - 4xx (not 429) → server rejected, retry can't help; DLQ
34
- // immediately and return success.
35
- // - 429 → retry; if Retry-After is present, stash
36
- // it in output for diagnostics.
37
- // - 5xx / IOException / timeout → retry until cap, then DLQ.
38
- //
39
- // Dead-letter policy:
40
- // "DLQ" here is "drop from disk + Log.w warning with first event_id +
41
- // count". We do NOT persist a separate dead-letter file — the events are
42
- // either delivered or lost-with-warning. Reasoning: a separate DLQ file is
43
- // storage we'd have to evict ourselves, the events are not user-content,
44
- // and observability via Logcat is sufficient for the rare-failure case.
45
-
46
- package com.appswissknife.analytics
47
-
48
- import android.content.Context
49
- import android.util.Log
50
- import androidx.annotation.VisibleForTesting
51
- import androidx.work.CoroutineWorker
52
- import androidx.work.Data
53
- import androidx.work.WorkerParameters
54
- import org.json.JSONArray
55
- import org.json.JSONObject
56
- import java.io.IOException
57
- import java.net.URL
58
-
59
- /**
60
- * Reads queued events from [EventQueueStore], POSTs them as a single batch
61
- * to the backend, and on success removes the delivered IDs from disk.
62
- *
63
- * Designed for [androidx.work.WorkManager] — scheduled via [SKAnalytics.flush]
64
- * with a unique work name so concurrent enqueues coalesce instead of stacking.
65
- */
66
- internal class FlushEventsWorker(
67
- appContext: Context,
68
- params: WorkerParameters,
69
- ) : CoroutineWorker(appContext, params) {
70
-
71
- companion object {
72
- const val TAG = "SwissKnife.FlushWorker"
73
-
74
- /** Unique work name for [androidx.work.WorkManager] enqueue. */
75
- const val UNIQUE_WORK_NAME = "swissknife.flush_events"
76
-
77
- /**
78
- * After this many attempts (including the original), give up and DLQ.
79
- * Counts against [androidx.work.ListenableWorker.getRunAttemptCount],
80
- * which is 0-indexed (first run = 0, first retry = 1, ...).
81
- */
82
- const val MAX_ATTEMPTS = 5
83
-
84
- // ---- Data keys ----
85
- const val KEY_API_KEY = "api_key"
86
- const val KEY_SERVER_URL = "server_url"
87
-
88
- // ---- Output keys (diagnostics; not consumed by the worker on retry) ----
89
- const val OUTPUT_HTTP_STATUS = "http_status"
90
- const val OUTPUT_RETRY_AFTER_SECONDS = "retry_after_seconds"
91
- const val OUTPUT_DEAD_LETTERED = "dead_lettered"
92
-
93
- // Default endpoint — matches SKAnalytics.flushSync() in the pre-Phase-2.2
94
- // codebase. Override via server_url Data input.
95
- private const val DEFAULT_BASE_URL = "https://api.swiss-knife.dev"
96
- private const val ENDPOINT_PATH = "/api/sdk/events/batch"
97
-
98
- /**
99
- * Build the input [Data] block this worker expects. Centralized here so
100
- * SKAnalytics + tests stay aligned on the keys.
101
- */
102
- fun buildInput(apiKey: String, serverURL: String): Data =
103
- Data.Builder()
104
- .putString(KEY_API_KEY, apiKey)
105
- .putString(KEY_SERVER_URL, serverURL)
106
- .build()
107
- }
108
-
109
- /**
110
- * Pluggable HTTP transport. Production wires the URL-connection
111
- * implementation below; tests inject a fake. Function-typed seam keeps
112
- * the worker free of DI infrastructure.
113
- */
114
- @VisibleForTesting
115
- internal var httpClient: HttpClient = UrlConnectionHttpClient()
116
-
117
- /**
118
- * Pluggable store factory. Defaults to the production store rooted at
119
- * cacheDir; tests can swap in a store backed by a temp dir.
120
- */
121
- @VisibleForTesting
122
- internal var storeFactory: (Context) -> EventQueueStore =
123
- { ctx -> EventQueueStore(ctx) }
124
-
125
- override suspend fun doWork(): Result {
126
- // CoroutineWorker is already invoked on its own executor (configured
127
- // via WorkManager.Configuration; defaults to a background executor).
128
- // We deliberately do NOT wrap in withContext(Dispatchers.IO) — under
129
- // Robolectric + SynchronousExecutor, dispatcher hopping can leave
130
- // the test thread with unexecuted Main-looper continuations and the
131
- // worker stuck in RUNNING. Staying on the WM-provided thread keeps
132
- // execution deterministic.
133
- val apiKey = inputData.getString(KEY_API_KEY).orEmpty()
134
- val serverURL = inputData.getString(KEY_SERVER_URL).orEmpty()
135
- if (apiKey.isEmpty()) {
136
- // No API key → nothing useful we can do. Don't retry.
137
- Log.w(TAG, "missing api_key input; skipping flush")
138
- return Result.success()
139
- }
140
-
141
- val store = storeFactory(applicationContext)
142
- val pending = store.readAll()
143
- if (pending.isEmpty()) return Result.success()
144
-
145
- val baseURL = serverURL.ifEmpty { DEFAULT_BASE_URL }
146
- val endpoint = URL(baseURL.trimEnd('/') + ENDPOINT_PATH)
147
-
148
- val payload = JSONObject().apply {
149
- val arr = JSONArray()
150
- for (ev in pending) arr.put(ev.body)
151
- put("events", arr)
152
- put("api_key", apiKey)
153
- }
154
-
155
- val response = try {
156
- httpClient.post(endpoint, apiKey, payload.toString())
157
- } catch (e: IOException) {
158
- return retryOrDeadLetter(
159
- store = store,
160
- pending = pending,
161
- reason = "network error: ${e.message}",
162
- httpStatus = null,
163
- retryAfterSeconds = null,
164
- )
165
- }
166
-
167
- return handleResponse(store, pending, response)
168
- }
169
-
170
- private fun handleResponse(
171
- store: EventQueueStore,
172
- pending: List<QueuedEvent>,
173
- response: HttpResponse,
174
- ): Result {
175
- val code = response.code
176
- return when {
177
- code in 200..299 -> {
178
- store.remove(pending.map { it.id }.toSet())
179
- Result.success(
180
- Data.Builder().putInt(OUTPUT_HTTP_STATUS, code).build()
181
- )
182
- }
183
- code == 429 -> {
184
- // Server is rate-limiting us. Honour Retry-After if present
185
- // (WorkManager won't actually consume it — the backoff comes
186
- // from BackoffPolicy.EXPONENTIAL on the request — but we
187
- // surface it via output for diagnostics).
188
- val retryAfter = response.retryAfterSeconds
189
- if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
190
- deadLetter(store, pending, "429 after $MAX_ATTEMPTS attempts")
191
- Result.success(
192
- Data.Builder()
193
- .putInt(OUTPUT_HTTP_STATUS, code)
194
- .putBoolean(OUTPUT_DEAD_LETTERED, true)
195
- .apply { if (retryAfter != null) putLong(OUTPUT_RETRY_AFTER_SECONDS, retryAfter) }
196
- .build()
197
- )
198
- } else {
199
- Result.retry()
200
- }
201
- }
202
- code in 400..499 -> {
203
- // 4xx (not 429) → server rejected the payload shape or auth.
204
- // Retrying with the same bytes will keep failing; DLQ now.
205
- deadLetter(store, pending, "client error $code")
206
- Result.success(
207
- Data.Builder()
208
- .putInt(OUTPUT_HTTP_STATUS, code)
209
- .putBoolean(OUTPUT_DEAD_LETTERED, true)
210
- .build()
211
- )
212
- }
213
- else -> {
214
- // 5xx or unexpected status.
215
- retryOrDeadLetter(
216
- store = store,
217
- pending = pending,
218
- reason = "server error $code",
219
- httpStatus = code,
220
- retryAfterSeconds = response.retryAfterSeconds,
221
- )
222
- }
223
- }
224
- }
225
-
226
- private fun retryOrDeadLetter(
227
- store: EventQueueStore,
228
- pending: List<QueuedEvent>,
229
- reason: String,
230
- httpStatus: Int?,
231
- retryAfterSeconds: Long?,
232
- ): Result {
233
- return if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
234
- deadLetter(store, pending, "$reason after $MAX_ATTEMPTS attempts")
235
- Result.success(
236
- Data.Builder()
237
- .apply {
238
- if (httpStatus != null) putInt(OUTPUT_HTTP_STATUS, httpStatus)
239
- if (retryAfterSeconds != null) putLong(OUTPUT_RETRY_AFTER_SECONDS, retryAfterSeconds)
240
- putBoolean(OUTPUT_DEAD_LETTERED, true)
241
- }
242
- .build()
243
- )
244
- } else {
245
- Log.w(TAG, "flush attempt ${runAttemptCount + 1}/$MAX_ATTEMPTS failed ($reason); retrying")
246
- Result.retry()
247
- }
248
- }
249
-
250
- private fun deadLetter(
251
- store: EventQueueStore,
252
- pending: List<QueuedEvent>,
253
- reason: String,
254
- ) {
255
- val firstId = pending.firstOrNull()?.id ?: "?"
256
- Log.w(
257
- TAG,
258
- "dead-lettering ${pending.size} event(s); first event_id=$firstId; reason=$reason",
259
- )
260
- store.remove(pending.map { it.id }.toSet())
261
- }
262
-
263
- /**
264
- * Minimal abstraction over the HTTP layer so tests don't need to spin a
265
- * MockWebServer just to exercise the retry/DLQ branches.
266
- */
267
- @VisibleForTesting
268
- internal interface HttpClient {
269
- fun post(url: URL, apiKey: String, body: String): HttpResponse
270
- }
271
-
272
- @VisibleForTesting
273
- internal data class HttpResponse(
274
- val code: Int,
275
- val retryAfterSeconds: Long? = null,
276
- )
277
-
278
- /**
279
- * Round-D default — delegates to the unified [com.appswissknife.net.BackendHttpClient]
280
- * transport. The worker owns the retry policy; transport at zero retries.
281
- */
282
- private class UrlConnectionHttpClient : HttpClient {
283
- override fun post(url: URL, apiKey: String, body: String): HttpResponse {
284
- // Decompose the prebuilt URL into base + path so we can route
285
- // through the unified BackendHttpClient transport — same
286
- // X-API-Key stamping, Clock-skew feed, error types. The worker
287
- // owns the retry policy; create() is a one-shot client with no
288
- // configResolver dependency.
289
- val baseUrl = "${url.protocol}://${url.authority}"
290
- val path = url.path + (url.query?.let { "?$it" } ?: "")
291
- val client = com.appswissknife.net.BackendHttpClient.create(apiKey, baseUrl)
292
- val r = client.simplePost(path = path, body = body)
293
- return HttpResponse(code = r.code, retryAfterSeconds = r.retryAfterSeconds)
294
- }
295
- }
296
- }