@app-swiss-knife/react-native-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/net/ExponentialBackoff.kt
|
|
2
|
+
//
|
|
3
|
+
// Round-C Android port of the iOS unified Net layer. Mirror of
|
|
4
|
+
// `Sources/SwissKnifeiOS/Net/ExponentialBackoff.swift` — same schedule,
|
|
5
|
+
// same jitter model, same Retry-After honouring. Reusable across
|
|
6
|
+
// IngestClient, BackendHttpClient, Attribution, Identity.
|
|
7
|
+
//
|
|
8
|
+
// Schedule (defaults):
|
|
9
|
+
// attempt 0 → 1s, attempt 1 → 2s, attempt 2 → 4s, attempt 3 → 8s,
|
|
10
|
+
// attempt 4 → 16s, capped at 30s. Each delay is multiplied by
|
|
11
|
+
// (1 + r * jitter) where r ∈ [-1.0, +1.0] from the random source.
|
|
12
|
+
//
|
|
13
|
+
// `429` honouring lives one level up: callers pass the parsed Retry-After
|
|
14
|
+
// value to [delay] and the policy never returns a value smaller than what
|
|
15
|
+
// the server asked for.
|
|
16
|
+
|
|
17
|
+
package com.appswissknife.net
|
|
18
|
+
|
|
19
|
+
import kotlin.math.max
|
|
20
|
+
import kotlin.math.min
|
|
21
|
+
import kotlin.math.pow
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Stateless reusable back-off policy. All parameters per-call; no shared
|
|
25
|
+
* mutable state. Safe to share across threads.
|
|
26
|
+
*
|
|
27
|
+
* @param initialMillis Initial delay. Default 1s → 1/2/4/8/16s pattern.
|
|
28
|
+
* @param multiplier Geometric multiplier. 2.0 is canonical.
|
|
29
|
+
* @param maxMillis Hard cap on the exponential.
|
|
30
|
+
* @param jitterFraction Symmetric jitter window. 0.25 → [0.75, 1.25].
|
|
31
|
+
* @param cap Max retries (initial attempt is NOT counted).
|
|
32
|
+
* @param randomSource Returns a value in [-1.0, 1.0]. Override in tests for
|
|
33
|
+
* deterministic delays.
|
|
34
|
+
*/
|
|
35
|
+
internal class ExponentialBackoff(
|
|
36
|
+
val initialMillis: Long = 1_000L,
|
|
37
|
+
val multiplier: Double = 2.0,
|
|
38
|
+
val maxMillis: Long = 30_000L,
|
|
39
|
+
val jitterFraction: Double = 0.25,
|
|
40
|
+
val cap: Int = 5,
|
|
41
|
+
private val randomSource: () -> Double = { kotlin.random.Random.nextDouble(-1.0, 1.0) },
|
|
42
|
+
) {
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Compute the delay (in milliseconds) for the given 0-indexed retry.
|
|
46
|
+
*
|
|
47
|
+
* `attempt = 0` is the FIRST retry after the original send failed. The
|
|
48
|
+
* effective multiplier is `[1 - jitterFraction, 1 + jitterFraction]`.
|
|
49
|
+
*/
|
|
50
|
+
fun delay(attempt: Int): Long {
|
|
51
|
+
val exponential = initialMillis.toDouble() * multiplier.pow(attempt.toDouble())
|
|
52
|
+
val capped = min(exponential, maxMillis.toDouble())
|
|
53
|
+
val r = randomSource()
|
|
54
|
+
val clamped = max(-1.0, min(1.0, r))
|
|
55
|
+
val factor = 1.0 + clamped * jitterFraction
|
|
56
|
+
return (capped * factor).toLong().coerceAtLeast(0L)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Compute the delay, but never return less than the server-advertised
|
|
61
|
+
* `retryAfterMillis`. The Retry-After value is honoured exactly (no
|
|
62
|
+
* jitter applied) so we never undershoot the server's explicit request.
|
|
63
|
+
*/
|
|
64
|
+
fun delay(attempt: Int, retryAfterMillis: Long?): Long {
|
|
65
|
+
val scheduled = delay(attempt)
|
|
66
|
+
if (retryAfterMillis == null || retryAfterMillis <= 0L) return scheduled
|
|
67
|
+
return max(scheduled, retryAfterMillis)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/net/IngestClient.kt
|
|
2
|
+
//
|
|
3
|
+
// Round-C Android port — unified ingest pipeline for the SDK's
|
|
4
|
+
// `POST /ingest` endpoint. Mirror of
|
|
5
|
+
// `Sources/SwissKnifeiOS/Net/IngestClient.swift`.
|
|
6
|
+
//
|
|
7
|
+
// Replaces per-feature transports (analytics events batch, error batch,
|
|
8
|
+
// performance transaction/session, paywall/funnel events) with one typed
|
|
9
|
+
// envelope.
|
|
10
|
+
//
|
|
11
|
+
// Contract — apps/swiss-ingest/src/routes/ingest.ts:
|
|
12
|
+
// POST /ingest
|
|
13
|
+
// Headers: X-API-Key
|
|
14
|
+
// Body (batched): { items: [{ type, data, context }, ...] } max 100
|
|
15
|
+
// Body (single): { type, data, context } auto-wrapped
|
|
16
|
+
// Returns: 202 with { queued: N, errors: [{ index, error }] }
|
|
17
|
+
//
|
|
18
|
+
// Architecture:
|
|
19
|
+
// - enqueue(IngestItem) → OfflineQueueStore on disk, fire-and-forget.
|
|
20
|
+
// - WorkManager-backed flush: enqueue a OneTimeWorkRequest<IngestFlushWorker>
|
|
21
|
+
// with ExistingWorkPolicy.KEEP so concurrent enqueues coalesce.
|
|
22
|
+
// - Worker invokes IngestClient.flushSync() which drains the queue in
|
|
23
|
+
// ≤100-item batches → POST /ingest via BackendHttpClient.
|
|
24
|
+
// - Identity / Session / DeviceContext / Clock are stamped at flush time
|
|
25
|
+
// (late-bind to mirror RevenueCat's identify semantics).
|
|
26
|
+
// - 4xx → dead-letter (validation reject is not retriable).
|
|
27
|
+
// 5xx / network → retry with shared ExponentialBackoff.
|
|
28
|
+
// After budget → dead-letter.
|
|
29
|
+
//
|
|
30
|
+
// Context primitives (DeviceContext / IDs / Session / Reachability / Clock)
|
|
31
|
+
// arrive in Commit 3. This commit ships placeholder providers that take
|
|
32
|
+
// snapshots from Identity + simple defaults; Commit 3 wires the real ones
|
|
33
|
+
// at the SwissKnife.configure call site without changing this file's
|
|
34
|
+
// public surface.
|
|
35
|
+
|
|
36
|
+
package com.appswissknife.net
|
|
37
|
+
|
|
38
|
+
import android.content.Context
|
|
39
|
+
import android.os.Build
|
|
40
|
+
import android.util.Log
|
|
41
|
+
import androidx.annotation.VisibleForTesting
|
|
42
|
+
import androidx.work.BackoffPolicy
|
|
43
|
+
import androidx.work.Constraints
|
|
44
|
+
import androidx.work.CoroutineWorker
|
|
45
|
+
import androidx.work.Data
|
|
46
|
+
import androidx.work.ExistingWorkPolicy
|
|
47
|
+
import androidx.work.NetworkType
|
|
48
|
+
import androidx.work.OneTimeWorkRequestBuilder
|
|
49
|
+
import androidx.work.WorkManager
|
|
50
|
+
import androidx.work.WorkerParameters
|
|
51
|
+
import com.appswissknife.context.IDs
|
|
52
|
+
import com.appswissknife.identity.Identity
|
|
53
|
+
import org.json.JSONArray
|
|
54
|
+
import org.json.JSONObject
|
|
55
|
+
import java.io.File
|
|
56
|
+
import java.io.IOException
|
|
57
|
+
import java.util.Locale
|
|
58
|
+
import java.util.TimeZone
|
|
59
|
+
import java.util.concurrent.TimeUnit
|
|
60
|
+
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
// IngestItemType — mirror of iOS IngestItemType (and swiss-ingest server enum).
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
internal enum class IngestItemType(val wire: String) {
|
|
66
|
+
Error("error"),
|
|
67
|
+
ErrorBatch("error_batch"),
|
|
68
|
+
Analytics("analytics"),
|
|
69
|
+
Transaction("transaction"),
|
|
70
|
+
Session("session"),
|
|
71
|
+
Feedback("feedback"),
|
|
72
|
+
Paywall("paywall"),
|
|
73
|
+
Funnel("funnel"),
|
|
74
|
+
;
|
|
75
|
+
|
|
76
|
+
companion object {
|
|
77
|
+
fun from(wire: String): IngestItemType? = values().firstOrNull { it.wire == wire }
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// IngestItem — queue + wire representation.
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Single queued item. `id` is the local idempotency key (stamped at
|
|
87
|
+
* enqueue time, embedded as `event_id` in the outgoing envelope).
|
|
88
|
+
*
|
|
89
|
+
* `data` is a `JSONObject` because each `type` has a distinct schema —
|
|
90
|
+
* statically modelling all 8 shapes would require 8 generic queues.
|
|
91
|
+
*/
|
|
92
|
+
internal data class IngestItem(
|
|
93
|
+
override val id: String,
|
|
94
|
+
val type: IngestItemType,
|
|
95
|
+
val data: JSONObject,
|
|
96
|
+
val enqueuedAtMs: Long,
|
|
97
|
+
) : OfflineQueueItem {
|
|
98
|
+
|
|
99
|
+
override fun toJson(): JSONObject = JSONObject().apply {
|
|
100
|
+
put("id", id)
|
|
101
|
+
put("type", type.wire)
|
|
102
|
+
put("data", data)
|
|
103
|
+
put("enqueuedAtMs", enqueuedAtMs)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
companion object {
|
|
107
|
+
fun create(type: IngestItemType, data: JSONObject, idGen: () -> String = { IDs.eventId() }): IngestItem {
|
|
108
|
+
return IngestItem(
|
|
109
|
+
id = idGen(),
|
|
110
|
+
type = type,
|
|
111
|
+
data = data,
|
|
112
|
+
enqueuedAtMs = System.currentTimeMillis(),
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
fun parse(obj: JSONObject): IngestItem {
|
|
117
|
+
val rawType = obj.getString("type")
|
|
118
|
+
val type = IngestItemType.from(rawType)
|
|
119
|
+
?: throw IOException("Unknown ingest type: $rawType")
|
|
120
|
+
return IngestItem(
|
|
121
|
+
id = obj.getString("id"),
|
|
122
|
+
type = type,
|
|
123
|
+
data = obj.optJSONObject("data") ?: JSONObject(),
|
|
124
|
+
enqueuedAtMs = obj.optLong("enqueuedAtMs", 0L),
|
|
125
|
+
)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ---------------------------------------------------------------------------
|
|
131
|
+
// ContextSnapshot + provider plumbing.
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Cross-cutting context stamped onto every IngestItem at flush time.
|
|
136
|
+
* Mirror of iOS `ContextSnapshot`. `eventId` is per-item (carries the
|
|
137
|
+
* persisted `IngestItem.id` so retries reuse the idempotency key); the
|
|
138
|
+
* rest are snapshotted at the moment the batch is flushed.
|
|
139
|
+
*/
|
|
140
|
+
internal data class ContextSnapshot(
|
|
141
|
+
val eventId: String,
|
|
142
|
+
val anonymousId: String,
|
|
143
|
+
val userId: String?,
|
|
144
|
+
val sessionId: String,
|
|
145
|
+
val sessionNumber: Int,
|
|
146
|
+
val timestampMs: Long,
|
|
147
|
+
val device: DeviceContextSnapshot,
|
|
148
|
+
val sdkVersion: String,
|
|
149
|
+
) {
|
|
150
|
+
fun toJson(): JSONObject = JSONObject().apply {
|
|
151
|
+
put("event_id", eventId)
|
|
152
|
+
put("anonymous_id", anonymousId)
|
|
153
|
+
if (userId != null) put("user_id", userId) else put("user_id", JSONObject.NULL)
|
|
154
|
+
put("session_id", sessionId)
|
|
155
|
+
put("session_number", sessionNumber)
|
|
156
|
+
put("timestamp", timestampMs)
|
|
157
|
+
put("device", device.toJson())
|
|
158
|
+
put("sdk_version", sdkVersion)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Wire-shaped device snapshot — passed by Commit 3's real DeviceContext
|
|
164
|
+
* primitive. Defined here so the Commit-2 IngestClient compiles in
|
|
165
|
+
* isolation; Commit 3 supersedes the placeholder provider with the
|
|
166
|
+
* memoized DeviceContextProvider.
|
|
167
|
+
*/
|
|
168
|
+
internal data class DeviceContextSnapshot(
|
|
169
|
+
val deviceModel: String,
|
|
170
|
+
val osName: String,
|
|
171
|
+
val osVersion: String,
|
|
172
|
+
val appVersion: String,
|
|
173
|
+
val appBuild: String,
|
|
174
|
+
val locale: String,
|
|
175
|
+
val timezone: String,
|
|
176
|
+
val sdkVersion: String,
|
|
177
|
+
val bundleIdentifier: String?,
|
|
178
|
+
) {
|
|
179
|
+
fun toJson(): JSONObject = JSONObject().apply {
|
|
180
|
+
put("device_model", deviceModel)
|
|
181
|
+
put("os_name", osName)
|
|
182
|
+
put("os_version", osVersion)
|
|
183
|
+
put("app_version", appVersion)
|
|
184
|
+
put("app_build", appBuild)
|
|
185
|
+
put("locale", locale)
|
|
186
|
+
put("timezone", timezone)
|
|
187
|
+
put("sdk_version", sdkVersion)
|
|
188
|
+
if (bundleIdentifier != null) put("bundle_identifier", bundleIdentifier)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Placeholder device provider — Commit 3 swaps in the memoized
|
|
194
|
+
* DeviceContextProvider that reads Build.MODEL, BuildConfig, etc. For now
|
|
195
|
+
* the IngestClient holds a function reference that any caller (including
|
|
196
|
+
* the future DeviceContextProvider) can supply.
|
|
197
|
+
*/
|
|
198
|
+
internal object IngestPlaceholderDevice {
|
|
199
|
+
@Volatile
|
|
200
|
+
var supplier: () -> DeviceContextSnapshot = { defaultSnapshot() }
|
|
201
|
+
|
|
202
|
+
private fun defaultSnapshot(): DeviceContextSnapshot {
|
|
203
|
+
return DeviceContextSnapshot(
|
|
204
|
+
deviceModel = Build.MODEL ?: "unknown",
|
|
205
|
+
osName = "Android",
|
|
206
|
+
osVersion = Build.VERSION.RELEASE ?: "unknown",
|
|
207
|
+
appVersion = "unknown",
|
|
208
|
+
appBuild = "unknown",
|
|
209
|
+
locale = Locale.getDefault().toString(),
|
|
210
|
+
timezone = TimeZone.getDefault().id,
|
|
211
|
+
sdkVersion = "0.1.0",
|
|
212
|
+
bundleIdentifier = null,
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Placeholder session provider — Commit 3 swaps in the real Session
|
|
219
|
+
* primitive that drives foreground/background restart rules.
|
|
220
|
+
*/
|
|
221
|
+
internal object IngestPlaceholderSession {
|
|
222
|
+
@Volatile
|
|
223
|
+
var supplier: () -> Pair<String, Int> = { Pair(IDs.sessionId(), 1) }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Placeholder clock provider — Commit 3 swaps in Clock.now() with
|
|
228
|
+
* server-skew correction.
|
|
229
|
+
*/
|
|
230
|
+
internal object IngestPlaceholderClock {
|
|
231
|
+
@Volatile
|
|
232
|
+
var supplier: () -> Long = { System.currentTimeMillis() }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ---------------------------------------------------------------------------
|
|
236
|
+
// IngestResult — mirror of the server's IngestResult.
|
|
237
|
+
// ---------------------------------------------------------------------------
|
|
238
|
+
|
|
239
|
+
internal data class IngestResult(
|
|
240
|
+
val queued: Int,
|
|
241
|
+
val errors: List<IngestErrorEntry>,
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
internal data class IngestErrorEntry(
|
|
245
|
+
val index: Int,
|
|
246
|
+
val error: String,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
// ---------------------------------------------------------------------------
|
|
250
|
+
// IngestClient
|
|
251
|
+
// ---------------------------------------------------------------------------
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Unified client for `POST /ingest`. Process-wide singleton wired by
|
|
255
|
+
* SwissKnife.configure (Commit 3); tests construct their own.
|
|
256
|
+
*/
|
|
257
|
+
internal class IngestClient(
|
|
258
|
+
private val queue: OfflineQueueStore<IngestItem>,
|
|
259
|
+
private val http: BackendHttpClient,
|
|
260
|
+
private val batchSize: Int = 100,
|
|
261
|
+
private val path: String = "/ingest",
|
|
262
|
+
private val identitySnapshot: () -> Identity.Snapshot = { Identity.current() },
|
|
263
|
+
private val deviceSnapshot: () -> DeviceContextSnapshot = { IngestPlaceholderDevice.supplier() },
|
|
264
|
+
private val sessionSnapshot: () -> Pair<String, Int> = { IngestPlaceholderSession.supplier() },
|
|
265
|
+
private val timestampProvider: () -> Long = { IngestPlaceholderClock.supplier() },
|
|
266
|
+
) {
|
|
267
|
+
|
|
268
|
+
companion object {
|
|
269
|
+
const val TAG = "SwissKnife.IngestClient"
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Process-wide instance — wired by SwissKnife.configure (Commit 3).
|
|
273
|
+
* Tests construct their own. Direct read access is internal-only;
|
|
274
|
+
* the singleton is exposed primarily so the WorkManager Worker can
|
|
275
|
+
* pull it without DI.
|
|
276
|
+
*/
|
|
277
|
+
@Volatile
|
|
278
|
+
private var _shared: IngestClient? = null
|
|
279
|
+
|
|
280
|
+
@JvmStatic
|
|
281
|
+
val shared: IngestClient?
|
|
282
|
+
get() = _shared
|
|
283
|
+
|
|
284
|
+
@JvmStatic
|
|
285
|
+
@VisibleForTesting
|
|
286
|
+
fun setSharedForTesting(client: IngestClient?) {
|
|
287
|
+
_shared = client
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Wire the process singleton. Called by SwissKnife.configure once
|
|
292
|
+
* the BackendHttpClient base URL / apiKey are known.
|
|
293
|
+
*/
|
|
294
|
+
fun install(client: IngestClient) {
|
|
295
|
+
_shared = client
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Build a production IngestClient backed by cacheDir/swissknife/ingest.
|
|
300
|
+
* Falls back to a tmpdir-rooted queue if cacheDir is unwritable —
|
|
301
|
+
* data loss is preferable to startup crash.
|
|
302
|
+
*/
|
|
303
|
+
fun build(context: Context, http: BackendHttpClient): IngestClient {
|
|
304
|
+
val ctx = context.applicationContext ?: context
|
|
305
|
+
val dir = File(File(ctx.cacheDir, "swissknife"), "ingest")
|
|
306
|
+
runCatching { dir.mkdirs() }
|
|
307
|
+
val queue = try {
|
|
308
|
+
OfflineQueueStore(dir, "ingest", IngestItem.Companion::parse)
|
|
309
|
+
} catch (_: IOException) {
|
|
310
|
+
val tmp = File(System.getProperty("java.io.tmpdir"), "swissknife-ingest-fb")
|
|
311
|
+
tmp.mkdirs()
|
|
312
|
+
OfflineQueueStore(tmp, "ingest-fb", IngestItem.Companion::parse)
|
|
313
|
+
}
|
|
314
|
+
return IngestClient(queue = queue, http = http)
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Network reachability — short-circuits flush when offline so we
|
|
320
|
+
* don't burn the retry budget against a known-broken connection.
|
|
321
|
+
* Commit 3 wires the real Reachability observer; default optimistic
|
|
322
|
+
* true keeps this commit self-contained.
|
|
323
|
+
*/
|
|
324
|
+
@Volatile
|
|
325
|
+
private var isReachable: Boolean = true
|
|
326
|
+
|
|
327
|
+
// -------- Public enqueue API --------
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Enqueue an IngestItem. Synchronous up to disk write — on return the
|
|
331
|
+
* item is on disk (fsync'd inside OfflineQueueStore). Crossing
|
|
332
|
+
* batchSize triggers a WorkManager flush.
|
|
333
|
+
*/
|
|
334
|
+
fun enqueue(item: IngestItem, context: Context) {
|
|
335
|
+
try {
|
|
336
|
+
queue.append(item)
|
|
337
|
+
} catch (e: IOException) {
|
|
338
|
+
Log.w(TAG, "enqueue failed", e)
|
|
339
|
+
return
|
|
340
|
+
}
|
|
341
|
+
val count = runCatching { queue.count() }.getOrNull() ?: return
|
|
342
|
+
if (count >= batchSize) {
|
|
343
|
+
scheduleFlush(context)
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Convenience — build an item from type + JSON data.
|
|
349
|
+
*/
|
|
350
|
+
fun enqueue(type: IngestItemType, data: JSONObject, context: Context) {
|
|
351
|
+
enqueue(IngestItem.create(type, data), context)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Schedule a flush via WorkManager. KEEP coalesces concurrent enqueues.
|
|
356
|
+
*/
|
|
357
|
+
fun scheduleFlush(context: Context) {
|
|
358
|
+
val ctx = context.applicationContext ?: context
|
|
359
|
+
val request = OneTimeWorkRequestBuilder<IngestFlushWorker>()
|
|
360
|
+
.setConstraints(
|
|
361
|
+
Constraints.Builder()
|
|
362
|
+
.setRequiredNetworkType(NetworkType.CONNECTED)
|
|
363
|
+
.build()
|
|
364
|
+
)
|
|
365
|
+
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.SECONDS)
|
|
366
|
+
.build()
|
|
367
|
+
runCatching {
|
|
368
|
+
WorkManager.getInstance(ctx).enqueueUniqueWork(
|
|
369
|
+
IngestFlushWorker.UNIQUE_WORK_NAME,
|
|
370
|
+
ExistingWorkPolicy.KEEP,
|
|
371
|
+
request,
|
|
372
|
+
)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// -------- Reachability / lifecycle hooks (Commit 3 wires the real observers) --------
|
|
377
|
+
|
|
378
|
+
/** Set by Reachability observer in Commit 3. */
|
|
379
|
+
fun setReachable(reachable: Boolean) {
|
|
380
|
+
isReachable = reachable
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
fun isReachableForTesting(): Boolean = isReachable
|
|
384
|
+
|
|
385
|
+
@VisibleForTesting
|
|
386
|
+
internal fun queueForTesting(): OfflineQueueStore<IngestItem> = queue
|
|
387
|
+
|
|
388
|
+
// -------- Synchronous flush (called by IngestFlushWorker) --------
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Drain the queue in ≤batchSize batches. Returns aggregate result.
|
|
392
|
+
* Items hit by `BackendRejected` (4xx) go to dead-letter. After the
|
|
393
|
+
* retry budget for `BackendUnavailable` exhausts, the batch is
|
|
394
|
+
* dead-lettered and removed.
|
|
395
|
+
*
|
|
396
|
+
* Reachability gating: if `isReachable` is false, returns
|
|
397
|
+
* (0, []) without touching the queue.
|
|
398
|
+
*/
|
|
399
|
+
@Throws(IOException::class)
|
|
400
|
+
fun flushSync(): IngestResult {
|
|
401
|
+
if (!isReachable) return IngestResult(queued = 0, errors = emptyList())
|
|
402
|
+
var totalQueued = 0
|
|
403
|
+
val aggregateErrors = mutableListOf<IngestErrorEntry>()
|
|
404
|
+
while (true) {
|
|
405
|
+
val items = queue.readAll()
|
|
406
|
+
if (items.isEmpty()) break
|
|
407
|
+
val batch = items.take(batchSize)
|
|
408
|
+
val envelope = buildEnvelope(batch)
|
|
409
|
+
val resp = try {
|
|
410
|
+
http.postRaw(path, envelope.toString())
|
|
411
|
+
} catch (e: BackendRejected) {
|
|
412
|
+
// Whole batch rejected → dead-letter all.
|
|
413
|
+
queue.deadLetter(batch)
|
|
414
|
+
queue.remove(batch.map { it.id }.toSet())
|
|
415
|
+
throw e
|
|
416
|
+
} catch (e: BackendUnavailable) {
|
|
417
|
+
// BackendUnavailable here means the bounded retry budget in
|
|
418
|
+
// BackendHttpClient.kt:358 has already been exhausted.
|
|
419
|
+
// Do NOT wrap in another retry — that would double-count
|
|
420
|
+
// attempts and silently extend the effective retry window.
|
|
421
|
+
// The batch is dead-lettered (not discarded) so it can be
|
|
422
|
+
// inspected offline; retrying at this layer would only delay
|
|
423
|
+
// the dead-letter and mask real backend degradation.
|
|
424
|
+
queue.deadLetter(batch)
|
|
425
|
+
queue.remove(batch.map { it.id }.toSet())
|
|
426
|
+
throw e
|
|
427
|
+
}
|
|
428
|
+
val parsed = parseResult(resp, batch.size)
|
|
429
|
+
totalQueued += parsed.queued
|
|
430
|
+
aggregateErrors.addAll(parsed.errors)
|
|
431
|
+
val errorIdxs = parsed.errors.map { it.index }.toSet()
|
|
432
|
+
val deadLetterItems = batch.withIndex()
|
|
433
|
+
.filter { it.index in errorIdxs }
|
|
434
|
+
.map { it.value }
|
|
435
|
+
if (deadLetterItems.isNotEmpty()) {
|
|
436
|
+
queue.deadLetter(deadLetterItems)
|
|
437
|
+
}
|
|
438
|
+
queue.remove(batch.map { it.id }.toSet())
|
|
439
|
+
if (batch.size < batchSize) break
|
|
440
|
+
}
|
|
441
|
+
return IngestResult(queued = totalQueued, errors = aggregateErrors)
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// -------- Envelope construction --------
|
|
445
|
+
|
|
446
|
+
@VisibleForTesting
|
|
447
|
+
internal fun buildEnvelope(batch: List<IngestItem>): JSONObject {
|
|
448
|
+
val items = JSONArray()
|
|
449
|
+
for (item in batch) {
|
|
450
|
+
val ctx = buildContext(item)
|
|
451
|
+
val obj = JSONObject().apply {
|
|
452
|
+
put("type", item.type.wire)
|
|
453
|
+
val data = enrichLegacy(item, ctx)
|
|
454
|
+
put("data", data)
|
|
455
|
+
put("context", ctx.toJson())
|
|
456
|
+
}
|
|
457
|
+
items.put(obj)
|
|
458
|
+
}
|
|
459
|
+
return JSONObject().put("items", items)
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
private fun buildContext(item: IngestItem): ContextSnapshot {
|
|
463
|
+
val identity = identitySnapshot()
|
|
464
|
+
val (sessionId, sessionNum) = sessionSnapshot()
|
|
465
|
+
val device = deviceSnapshot()
|
|
466
|
+
return ContextSnapshot(
|
|
467
|
+
eventId = item.id,
|
|
468
|
+
anonymousId = identity.anonymousId,
|
|
469
|
+
userId = identity.userId,
|
|
470
|
+
sessionId = sessionId,
|
|
471
|
+
sessionNumber = sessionNum,
|
|
472
|
+
timestampMs = timestampProvider(),
|
|
473
|
+
device = device,
|
|
474
|
+
sdkVersion = device.sdkVersion,
|
|
475
|
+
)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Legacy back-compat: analytics consumers downstream of /ingest still
|
|
480
|
+
* key off `anonymous_id`/`user_id` directly inside `data`. We inject
|
|
481
|
+
* them from the context unless already present. Matches iOS' shim.
|
|
482
|
+
* Drops in a later round when all consumers read from `context`.
|
|
483
|
+
*/
|
|
484
|
+
private fun enrichLegacy(item: IngestItem, ctx: ContextSnapshot): JSONObject {
|
|
485
|
+
val data = JSONObject(item.data.toString()) // shallow copy
|
|
486
|
+
when (item.type) {
|
|
487
|
+
IngestItemType.Analytics -> {
|
|
488
|
+
if (!data.has("anonymous_id")) data.put("anonymous_id", ctx.anonymousId)
|
|
489
|
+
if (!data.has("user_id") && ctx.userId != null) data.put("user_id", ctx.userId)
|
|
490
|
+
}
|
|
491
|
+
IngestItemType.Paywall, IngestItemType.Funnel -> {
|
|
492
|
+
if (!data.has("user_id")) {
|
|
493
|
+
data.put("user_id", ctx.userId ?: ctx.anonymousId)
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
else -> Unit
|
|
497
|
+
}
|
|
498
|
+
return data
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private fun parseResult(body: String, batchSize: Int): IngestResult {
|
|
502
|
+
if (body.isEmpty()) return IngestResult(queued = batchSize, errors = emptyList())
|
|
503
|
+
return runCatching {
|
|
504
|
+
val obj = JSONObject(body)
|
|
505
|
+
val queued = obj.optInt("queued", batchSize)
|
|
506
|
+
val errArr = obj.optJSONArray("errors")
|
|
507
|
+
val errs = mutableListOf<IngestErrorEntry>()
|
|
508
|
+
if (errArr != null) {
|
|
509
|
+
for (i in 0 until errArr.length()) {
|
|
510
|
+
val e = errArr.optJSONObject(i) ?: continue
|
|
511
|
+
errs.add(IngestErrorEntry(index = e.optInt("index"), error = e.optString("error")))
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
IngestResult(queued = queued, errors = errs)
|
|
515
|
+
}.getOrElse {
|
|
516
|
+
// 202 with empty / non-JSON body — assume everything queued.
|
|
517
|
+
IngestResult(queued = batchSize, errors = emptyList())
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// ---------------------------------------------------------------------------
|
|
523
|
+
// IngestFlushWorker — WorkManager backing for IngestClient flush.
|
|
524
|
+
// ---------------------------------------------------------------------------
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* WorkManager worker that drains the IngestClient queue. Structurally
|
|
528
|
+
* identical to the legacy FlushEventsWorker, but generic over IngestItem
|
|
529
|
+
* instead of analytics events.
|
|
530
|
+
*
|
|
531
|
+
* Why WorkManager (vs. coroutine on an internal pool)?
|
|
532
|
+
* - Survives process death — system reschedules after a kill.
|
|
533
|
+
* - Network constraint is system-managed — waits for connectivity.
|
|
534
|
+
* - Exponential backoff is system-managed — no in-app retry loop
|
|
535
|
+
* burning wakelocks.
|
|
536
|
+
* - Doze + App Standby aware out of the box.
|
|
537
|
+
*/
|
|
538
|
+
internal class IngestFlushWorker(
|
|
539
|
+
appContext: Context,
|
|
540
|
+
params: WorkerParameters,
|
|
541
|
+
) : CoroutineWorker(appContext, params) {
|
|
542
|
+
|
|
543
|
+
companion object {
|
|
544
|
+
const val TAG = "SwissKnife.IngestFlush"
|
|
545
|
+
const val UNIQUE_WORK_NAME = "swissknife.ingest_flush"
|
|
546
|
+
const val MAX_ATTEMPTS = 5
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
override suspend fun doWork(): Result {
|
|
550
|
+
val client = IngestClient.shared
|
|
551
|
+
if (client == null) {
|
|
552
|
+
Log.w(TAG, "no installed IngestClient; nothing to flush")
|
|
553
|
+
return Result.success()
|
|
554
|
+
}
|
|
555
|
+
return try {
|
|
556
|
+
client.flushSync()
|
|
557
|
+
Result.success()
|
|
558
|
+
} catch (e: BackendRejected) {
|
|
559
|
+
// 4xx → already dead-lettered by flushSync.
|
|
560
|
+
Log.w(TAG, "ingest 4xx rejected: ${e.code}", e)
|
|
561
|
+
Result.success()
|
|
562
|
+
} catch (e: BackendUnavailable) {
|
|
563
|
+
if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
|
|
564
|
+
Log.w(TAG, "ingest 5xx after $MAX_ATTEMPTS attempts; giving up", e)
|
|
565
|
+
Result.success(
|
|
566
|
+
Data.Builder().putBoolean("dead_lettered", true).build()
|
|
567
|
+
)
|
|
568
|
+
} else {
|
|
569
|
+
Log.w(TAG, "ingest 5xx attempt ${runAttemptCount + 1}; will retry", e)
|
|
570
|
+
Result.retry()
|
|
571
|
+
}
|
|
572
|
+
} catch (e: IOException) {
|
|
573
|
+
if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
|
|
574
|
+
Log.w(TAG, "ingest IO after $MAX_ATTEMPTS attempts; giving up", e)
|
|
575
|
+
Result.success()
|
|
576
|
+
} else {
|
|
577
|
+
Log.w(TAG, "ingest IO attempt ${runAttemptCount + 1}; will retry", e)
|
|
578
|
+
Result.retry()
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|