@metarouter/react-native-sdk 1.5.1 → 1.7.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 +28 -6
- package/android/build.gradle +41 -0
- package/android/src/main/AndroidManifest.xml +4 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterNetworkMonitorModule.kt +119 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +23 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterQueueStorageModule.kt +124 -0
- package/ios/MetaRouterNetworkMonitor.m +76 -0
- package/ios/MetaRouterQueueStorage.m +127 -0
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts +23 -4
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
- package/lib/analytics/MetaRouterAnalyticsClient.js +178 -89
- package/lib/analytics/dispatcher.d.ts +57 -1
- package/lib/analytics/dispatcher.d.ts.map +1 -1
- package/lib/analytics/dispatcher.js +231 -32
- package/lib/analytics/init.d.ts +1 -1
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +3 -2
- package/lib/analytics/persistence/NativeQueueStorage.d.ts +5 -0
- package/lib/analytics/persistence/NativeQueueStorage.d.ts.map +1 -0
- package/lib/analytics/persistence/NativeQueueStorage.js +59 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts +96 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts.map +1 -0
- package/lib/analytics/persistence/PersistentEventQueue.js +401 -0
- package/lib/analytics/persistence/types.d.ts +20 -0
- package/lib/analytics/persistence/types.d.ts.map +1 -0
- package/lib/analytics/persistence/types.js +10 -0
- package/lib/analytics/proxy/proxyClient.d.ts +1 -1
- package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
- package/lib/analytics/proxy/proxyClient.js +21 -19
- package/lib/analytics/types.d.ts +12 -4
- package/lib/analytics/types.d.ts.map +1 -1
- package/lib/analytics/utils/circuitBreaker.d.ts +4 -1
- package/lib/analytics/utils/circuitBreaker.d.ts.map +1 -1
- package/lib/analytics/utils/circuitBreaker.js +23 -14
- package/lib/analytics/utils/contextInfo.d.ts +1 -1
- package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
- package/lib/analytics/utils/contextInfo.js +28 -24
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts +25 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.js +68 -0
- package/lib/analytics/utils/networkMonitor.d.ts +30 -0
- package/lib/analytics/utils/networkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/networkMonitor.js +90 -0
- package/lib/analytics/utils/responseCategory.d.ts +14 -0
- package/lib/analytics/utils/responseCategory.d.ts.map +1 -0
- package/lib/analytics/utils/responseCategory.js +26 -0
- package/metarouter-react-native-sdk.podspec +19 -0
- package/package.json +6 -3
- package/react-native.config.js +15 -0
package/README.md
CHANGED
|
@@ -14,6 +14,7 @@ A lightweight React Native analytics SDK that transmits events to your MetaRoute
|
|
|
14
14
|
- [Direct Usage](#direct-usage)
|
|
15
15
|
- [API Reference](#api-reference)
|
|
16
16
|
- [Features](#features)
|
|
17
|
+
- [Disk-Backed Queue Persistence](#disk-backed-queue-persistence)
|
|
17
18
|
- [Compatibility](#-compatibility)
|
|
18
19
|
- [Debugging](#debugging)
|
|
19
20
|
- [Identity Persistence](#identity-persistence)
|
|
@@ -27,6 +28,8 @@ A lightweight React Native analytics SDK that transmits events to your MetaRoute
|
|
|
27
28
|
npm install @metarouter/react-native-sdk @react-native-async-storage/async-storage react-native-device-info
|
|
28
29
|
```
|
|
29
30
|
|
|
31
|
+
After installing or upgrading, run `cd ios && pod install` and rebuild the native app. This release includes native iOS and Android modules for queue persistence, so a JavaScript-only reload is not sufficient.
|
|
32
|
+
|
|
30
33
|
## Usage
|
|
31
34
|
|
|
32
35
|
### Basic Setup
|
|
@@ -190,7 +193,7 @@ Calls to `track`, `identify`, etc. are **buffered in-memory** by the proxy and r
|
|
|
190
193
|
- `ingestionHost` (string, required): Your MetaRouter ingestor host
|
|
191
194
|
- `debug` (boolean, optional): Enable debug mode
|
|
192
195
|
- `flushIntervalSeconds` (number, optional): Interval in seconds to flush events
|
|
193
|
-
- `
|
|
196
|
+
- `maxQueueBytes` (number, optional): max bytes (UTF-8) held in memory queue (default: 5MB)
|
|
194
197
|
|
|
195
198
|
**Proxy behavior (quick notes):**
|
|
196
199
|
|
|
@@ -211,6 +214,7 @@ The analytics client provides the following methods:
|
|
|
211
214
|
- `alias(newUserId: string)`: Connect anonymous users to known user IDs. See [Using the alias() Method](#using-the-alias-method) for details
|
|
212
215
|
- `setAdvertisingId(advertisingId: string)`: Set the advertising identifier (IDFA on iOS, GAID on Android) for ad tracking. See [Advertising ID](#advertising-id-idfagaid) section for usage and compliance requirements
|
|
213
216
|
- `clearAdvertisingId()`: Clear the advertising identifier from storage and context. Useful for GDPR/CCPA compliance when users opt out of ad tracking
|
|
217
|
+
- `getAnonymousId(): Promise<string>`: Returns the current anonymous ID. Async, never returns null — guaranteed to resolve a string after `init()`
|
|
214
218
|
- `setTracing(enabled: boolean)`: Enable or disable tracing headers on API requests. When enabled, includes a `Trace: true` header for debugging request flows
|
|
215
219
|
- `flush()`: Flush events immediately
|
|
216
220
|
- `reset()`: Reset analytics state and clear all stored data (includes clearing advertising ID)
|
|
@@ -232,18 +236,29 @@ The analytics client provides the following methods:
|
|
|
232
236
|
- 🎣 **React Hooks**: Easy integration with React components
|
|
233
237
|
- 🔧 **TypeScript Support**: Full TypeScript support included
|
|
234
238
|
- 🚀 **Lightweight**: Minimal overhead and dependencies
|
|
239
|
+
- 💾 **Best-Effort Queue Persistence**: Can persist queued events to native disk storage and rehydrate them on next launch
|
|
235
240
|
- 🔄 **Reset Capability**: Easily reset analytics state for testing or logout scenarios
|
|
236
241
|
- 🐛 **Debug Support**: Built-in debugging tools for troubleshooting
|
|
237
242
|
|
|
243
|
+
## Disk-Backed Queue Persistence
|
|
244
|
+
|
|
245
|
+
This release adds native iOS and Android storage for best-effort queue durability.
|
|
246
|
+
|
|
247
|
+
- If queued events remain buffered when the app backgrounds, the SDK may persist the remaining queue to disk.
|
|
248
|
+
- If the in-memory queue grows past internal persistence thresholds, the SDK may snapshot the queue to disk as a fallback.
|
|
249
|
+
- Persisted events are rehydrated during the next `init()`.
|
|
250
|
+
- This is a durability baseline, not a full offline mode. The SDK still primarily uses in-memory batching and normal network delivery, and it does not guarantee zero-loss across every crash or termination window.
|
|
251
|
+
|
|
238
252
|
## ✅ Compatibility
|
|
239
253
|
|
|
240
254
|
| Component | Supported Versions |
|
|
241
255
|
| -------------------------- | ------------------ |
|
|
242
|
-
| React Native | >= 0.
|
|
256
|
+
| React Native | >= 0.73 |
|
|
243
257
|
| React | >= 16.8 |
|
|
244
258
|
| iOS Deployment Target | >= iOS 13 |
|
|
245
|
-
| Android Min SDK | >= API
|
|
246
|
-
|
|
|
259
|
+
| Android Min SDK | >= API 23 |
|
|
260
|
+
| Android Build JDK | >= 17 |
|
|
261
|
+
| Node.js | >= 18 |
|
|
247
262
|
|
|
248
263
|
## Debugging
|
|
249
264
|
|
|
@@ -287,7 +302,7 @@ await analytics.flush();
|
|
|
287
302
|
|
|
288
303
|
### Delivery & Backoff (How events flow under failures)
|
|
289
304
|
|
|
290
|
-
Queue capacity: The SDK
|
|
305
|
+
Queue capacity: The SDK caps the in-memory queue at 5MB by default. When the cap is reached, the oldest events are dropped first (drop-oldest). You can change this via maxQueueBytes in createAnalyticsClient(options)
|
|
291
306
|
|
|
292
307
|
This SDK uses a circuit breaker around network I/O. It keeps ordering stable, avoids tight retry loops, and backs off cleanly when your cluster is unhealthy or throttling.
|
|
293
308
|
|
|
@@ -299,7 +314,7 @@ Half-open probe: After cooldown, one probe is allowed.
|
|
|
299
314
|
Success → breaker CLOSED (keep flushing).
|
|
300
315
|
Failure → breaker OPEN again with longer cooldown.
|
|
301
316
|
|
|
302
|
-
sentAt semantics: sentAt is stamped when
|
|
317
|
+
sentAt semantics: sentAt is stamped when a batch is prepared for transmission. If the client is backing off, the actual transmit may be later; if you need the original occurrence time, include your own event `timestamp`.
|
|
303
318
|
|
|
304
319
|
| Status / Failure | Action | Breaker | Queue effect |
|
|
305
320
|
| ----------------------------------- | -------------------------------------------------------------------- | ------- | ------------------------------ |
|
|
@@ -379,6 +394,13 @@ The `anonymousId` is a unique identifier automatically generated for each device
|
|
|
379
394
|
- Remains stable across app sessions until `reset()` is called
|
|
380
395
|
- Cleared on `reset()` and a **new** UUID is generated on next `init()`
|
|
381
396
|
|
|
397
|
+
**Accessing the anonymous ID:**
|
|
398
|
+
|
|
399
|
+
```js
|
|
400
|
+
const anonymousId = await analytics.getAnonymousId();
|
|
401
|
+
console.log(anonymousId); // e.g. "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
|
402
|
+
```
|
|
403
|
+
|
|
382
404
|
**Use case:**
|
|
383
405
|
Track user behavior before they log in or create an account, then connect pre-login and post-login activity using the `alias()` method.
|
|
384
406
|
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
buildscript {
|
|
2
|
+
repositories {
|
|
3
|
+
google()
|
|
4
|
+
mavenCentral()
|
|
5
|
+
}
|
|
6
|
+
dependencies {
|
|
7
|
+
classpath 'com.android.tools.build:gradle:8.1.0'
|
|
8
|
+
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.10"
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
apply plugin: 'com.android.library'
|
|
13
|
+
apply plugin: 'kotlin-android'
|
|
14
|
+
|
|
15
|
+
android {
|
|
16
|
+
namespace "com.metarouter.reactnative"
|
|
17
|
+
compileSdkVersion 34
|
|
18
|
+
|
|
19
|
+
defaultConfig {
|
|
20
|
+
minSdkVersion 23
|
|
21
|
+
targetSdkVersion 34
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
compileOptions {
|
|
25
|
+
sourceCompatibility JavaVersion.VERSION_17
|
|
26
|
+
targetCompatibility JavaVersion.VERSION_17
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
kotlinOptions {
|
|
30
|
+
jvmTarget = "17"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
repositories {
|
|
35
|
+
google()
|
|
36
|
+
mavenCentral()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
dependencies {
|
|
40
|
+
implementation "com.facebook.react:react-android:+"
|
|
41
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
package com.metarouter.reactnative
|
|
2
|
+
|
|
3
|
+
import android.net.ConnectivityManager
|
|
4
|
+
import android.net.Network
|
|
5
|
+
import android.net.NetworkCapabilities
|
|
6
|
+
import android.net.NetworkRequest
|
|
7
|
+
import android.content.Context
|
|
8
|
+
import com.facebook.react.bridge.ReactApplicationContext
|
|
9
|
+
import com.facebook.react.bridge.ReactContextBaseJavaModule
|
|
10
|
+
import com.facebook.react.bridge.ReactMethod
|
|
11
|
+
import com.facebook.react.bridge.Promise
|
|
12
|
+
import com.facebook.react.bridge.Arguments
|
|
13
|
+
import com.facebook.react.modules.core.DeviceEventManagerModule
|
|
14
|
+
|
|
15
|
+
class MetaRouterNetworkMonitorModule(
|
|
16
|
+
private val reactContext: ReactApplicationContext
|
|
17
|
+
) : ReactContextBaseJavaModule(reactContext) {
|
|
18
|
+
|
|
19
|
+
override fun getName(): String = "MetaRouterNetworkMonitor"
|
|
20
|
+
|
|
21
|
+
@Volatile
|
|
22
|
+
private var isConnected: Boolean = true
|
|
23
|
+
|
|
24
|
+
private var connectivityManager: ConnectivityManager? = null
|
|
25
|
+
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
|
26
|
+
|
|
27
|
+
init {
|
|
28
|
+
connectivityManager = try {
|
|
29
|
+
reactContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
|
30
|
+
} catch (_: Exception) {
|
|
31
|
+
null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Snapshot initial state
|
|
35
|
+
connectivityManager?.let { cm ->
|
|
36
|
+
isConnected = try {
|
|
37
|
+
val network = cm.activeNetwork
|
|
38
|
+
val caps = network?.let { cm.getNetworkCapabilities(it) }
|
|
39
|
+
caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
|
|
40
|
+
} catch (_: Exception) {
|
|
41
|
+
true // fallback
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Register callback for changes
|
|
46
|
+
connectivityManager?.let { cm ->
|
|
47
|
+
val request = NetworkRequest.Builder()
|
|
48
|
+
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
49
|
+
.build()
|
|
50
|
+
|
|
51
|
+
val cb = object : ConnectivityManager.NetworkCallback() {
|
|
52
|
+
override fun onAvailable(network: Network) {
|
|
53
|
+
if (!isConnected) {
|
|
54
|
+
isConnected = true
|
|
55
|
+
sendEvent(true)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
override fun onLost(network: Network) {
|
|
60
|
+
val activeNet = cm.activeNetwork
|
|
61
|
+
val caps = activeNet?.let { cm.getNetworkCapabilities(it) }
|
|
62
|
+
val hasInternet = caps?.hasCapability(
|
|
63
|
+
NetworkCapabilities.NET_CAPABILITY_INTERNET
|
|
64
|
+
) == true
|
|
65
|
+
if (!hasInternet && isConnected) {
|
|
66
|
+
isConnected = false
|
|
67
|
+
sendEvent(false)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
cm.registerNetworkCallback(request, cb)
|
|
74
|
+
networkCallback = cb
|
|
75
|
+
} catch (_: SecurityException) {
|
|
76
|
+
// Missing ACCESS_NETWORK_STATE — fallback to always connected
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private fun sendEvent(connected: Boolean) {
|
|
82
|
+
val params = Arguments.createMap().apply {
|
|
83
|
+
putBoolean("isConnected", connected)
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
reactContext
|
|
87
|
+
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
|
88
|
+
.emit("onConnectivityChange", params)
|
|
89
|
+
} catch (_: Exception) {
|
|
90
|
+
// JS runtime not ready yet — ignore
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
@ReactMethod
|
|
95
|
+
fun getCurrentStatus(promise: Promise) {
|
|
96
|
+
promise.resolve(isConnected)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
@ReactMethod
|
|
100
|
+
fun addListener(@Suppress("UNUSED_PARAMETER") eventName: String) {
|
|
101
|
+
// Required for RN event emitter
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
@ReactMethod
|
|
105
|
+
fun removeListeners(@Suppress("UNUSED_PARAMETER") count: Int) {
|
|
106
|
+
// Required for RN event emitter
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
override fun invalidate() {
|
|
110
|
+
networkCallback?.let { cb ->
|
|
111
|
+
try {
|
|
112
|
+
connectivityManager?.unregisterNetworkCallback(cb)
|
|
113
|
+
} catch (_: Exception) {
|
|
114
|
+
// ignore
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
networkCallback = null
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
package com.metarouter.reactnative
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.ReactPackage
|
|
4
|
+
import com.facebook.react.bridge.NativeModule
|
|
5
|
+
import com.facebook.react.bridge.ReactApplicationContext
|
|
6
|
+
import com.facebook.react.uimanager.ViewManager
|
|
7
|
+
|
|
8
|
+
class MetaRouterPackage : ReactPackage {
|
|
9
|
+
override fun createNativeModules(
|
|
10
|
+
reactContext: ReactApplicationContext
|
|
11
|
+
): List<NativeModule> {
|
|
12
|
+
return listOf(
|
|
13
|
+
MetaRouterQueueStorageModule(reactContext),
|
|
14
|
+
MetaRouterNetworkMonitorModule(reactContext)
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
override fun createViewManagers(
|
|
19
|
+
reactContext: ReactApplicationContext
|
|
20
|
+
): List<ViewManager<*, *>> {
|
|
21
|
+
return emptyList()
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
package com.metarouter.reactnative
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.bridge.ReactApplicationContext
|
|
4
|
+
import com.facebook.react.bridge.ReactContextBaseJavaModule
|
|
5
|
+
import com.facebook.react.bridge.ReactMethod
|
|
6
|
+
import com.facebook.react.bridge.Promise
|
|
7
|
+
import java.io.File
|
|
8
|
+
|
|
9
|
+
class MetaRouterQueueStorageModule(
|
|
10
|
+
private val reactContext: ReactApplicationContext
|
|
11
|
+
) : ReactContextBaseJavaModule(reactContext) {
|
|
12
|
+
|
|
13
|
+
override fun getName(): String = "MetaRouterQueueStorage"
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Returns the path to the queue snapshot file.
|
|
17
|
+
* Location: Context.noBackupFilesDir/metarouter/disk-queue/queue.v1.json
|
|
18
|
+
*/
|
|
19
|
+
private fun snapshotFile(): File {
|
|
20
|
+
val noBackupDir = reactContext.noBackupFilesDir
|
|
21
|
+
return File(noBackupDir, "metarouter/disk-queue/queue.v1.json")
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
private fun ensureParentDirectory(file: File) {
|
|
25
|
+
val parent = file.parentFile
|
|
26
|
+
?: throw IllegalStateException("Snapshot file has no parent directory")
|
|
27
|
+
|
|
28
|
+
if (!parent.exists() && !parent.mkdirs()) {
|
|
29
|
+
throw IllegalStateException("Failed to create snapshot directory")
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (!parent.isDirectory) {
|
|
33
|
+
throw IllegalStateException("Snapshot parent path is not a directory")
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private fun deleteIfExists(file: File, errorMessage: String) {
|
|
38
|
+
if (file.exists() && !file.delete()) {
|
|
39
|
+
throw IllegalStateException(errorMessage)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Cheap existence check — does not read the file contents.
|
|
45
|
+
* Used on boot so a large snapshot doesn't get fully parsed just to
|
|
46
|
+
* discover whether there's anything to drain.
|
|
47
|
+
*/
|
|
48
|
+
@ReactMethod
|
|
49
|
+
fun exists(promise: Promise) {
|
|
50
|
+
try {
|
|
51
|
+
promise.resolve(snapshotFile().exists())
|
|
52
|
+
} catch (e: Exception) {
|
|
53
|
+
promise.reject("EXISTS_ERROR", "Failed to check snapshot existence", e)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
@ReactMethod
|
|
58
|
+
fun readSnapshot(promise: Promise) {
|
|
59
|
+
try {
|
|
60
|
+
val file = snapshotFile()
|
|
61
|
+
if (!file.exists()) {
|
|
62
|
+
promise.resolve(null)
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
val contents = file.readText(Charsets.UTF_8)
|
|
66
|
+
promise.resolve(contents)
|
|
67
|
+
} catch (e: Exception) {
|
|
68
|
+
promise.reject("READ_ERROR", "Failed to read queue snapshot", e)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
@ReactMethod
|
|
73
|
+
fun writeSnapshot(data: String, promise: Promise) {
|
|
74
|
+
try {
|
|
75
|
+
val file = snapshotFile()
|
|
76
|
+
ensureParentDirectory(file)
|
|
77
|
+
|
|
78
|
+
val parent = file.parentFile
|
|
79
|
+
?: throw IllegalStateException("Snapshot file has no parent directory")
|
|
80
|
+
val tempFile = File(parent, "${file.name}.tmp")
|
|
81
|
+
val backupFile = File(parent, "${file.name}.bak")
|
|
82
|
+
|
|
83
|
+
deleteIfExists(tempFile, "Failed to clear stale temp snapshot")
|
|
84
|
+
tempFile.writeText(data, Charsets.UTF_8)
|
|
85
|
+
|
|
86
|
+
val hadExistingSnapshot = file.exists()
|
|
87
|
+
if (hadExistingSnapshot) {
|
|
88
|
+
deleteIfExists(backupFile, "Failed to clear stale backup snapshot")
|
|
89
|
+
if (!file.renameTo(backupFile)) {
|
|
90
|
+
deleteIfExists(tempFile, "Failed to clean up temp snapshot")
|
|
91
|
+
throw IllegalStateException("Failed to back up existing snapshot")
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (!tempFile.renameTo(file)) {
|
|
96
|
+
deleteIfExists(tempFile, "Failed to clean up temp snapshot")
|
|
97
|
+
|
|
98
|
+
if (hadExistingSnapshot && backupFile.exists() && !backupFile.renameTo(file)) {
|
|
99
|
+
throw IllegalStateException(
|
|
100
|
+
"Failed to write queue snapshot and restore previous snapshot"
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
throw IllegalStateException("Failed to move temp snapshot into place")
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
deleteIfExists(backupFile, "Failed to delete snapshot backup")
|
|
108
|
+
promise.resolve(null)
|
|
109
|
+
} catch (e: Exception) {
|
|
110
|
+
promise.reject("WRITE_ERROR", "Failed to write queue snapshot", e)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@ReactMethod
|
|
115
|
+
fun deleteSnapshot(promise: Promise) {
|
|
116
|
+
try {
|
|
117
|
+
val file = snapshotFile()
|
|
118
|
+
deleteIfExists(file, "Failed to delete queue snapshot")
|
|
119
|
+
promise.resolve(null)
|
|
120
|
+
} catch (e: Exception) {
|
|
121
|
+
promise.reject("DELETE_ERROR", "Failed to delete queue snapshot", e)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
#import <React/RCTBridgeModule.h>
|
|
2
|
+
#import <React/RCTEventEmitter.h>
|
|
3
|
+
#import <Network/Network.h>
|
|
4
|
+
|
|
5
|
+
@interface MetaRouterNetworkMonitor : RCTEventEmitter <RCTBridgeModule>
|
|
6
|
+
@end
|
|
7
|
+
|
|
8
|
+
@implementation MetaRouterNetworkMonitor {
|
|
9
|
+
nw_path_monitor_t _monitor;
|
|
10
|
+
dispatch_queue_t _monitorQueue;
|
|
11
|
+
BOOL _isConnected;
|
|
12
|
+
BOOL _hasListeners;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
RCT_EXPORT_MODULE()
|
|
16
|
+
|
|
17
|
+
+ (BOOL)requiresMainQueueSetup {
|
|
18
|
+
return NO;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
- (instancetype)init {
|
|
22
|
+
self = [super init];
|
|
23
|
+
if (self) {
|
|
24
|
+
_isConnected = YES; // optimistic default
|
|
25
|
+
_hasListeners = NO;
|
|
26
|
+
_monitorQueue = dispatch_queue_create("com.metarouter.network.monitor", DISPATCH_QUEUE_SERIAL);
|
|
27
|
+
_monitor = nw_path_monitor_create();
|
|
28
|
+
|
|
29
|
+
__weak typeof(self) weakSelf = self;
|
|
30
|
+
nw_path_monitor_set_update_handler(_monitor, ^(nw_path_t path) {
|
|
31
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
32
|
+
if (!strongSelf) return;
|
|
33
|
+
|
|
34
|
+
BOOL connected = (nw_path_get_status(path) == nw_path_status_satisfied);
|
|
35
|
+
BOOL changed = (connected != strongSelf->_isConnected);
|
|
36
|
+
strongSelf->_isConnected = connected;
|
|
37
|
+
|
|
38
|
+
if (changed && strongSelf->_hasListeners) {
|
|
39
|
+
[strongSelf sendEventWithName:@"onConnectivityChange"
|
|
40
|
+
body:@{@"isConnected": @(connected)}];
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
nw_path_monitor_set_queue(_monitor, _monitorQueue);
|
|
45
|
+
nw_path_monitor_start(_monitor);
|
|
46
|
+
}
|
|
47
|
+
return self;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
- (NSArray<NSString *> *)supportedEvents {
|
|
51
|
+
return @[@"onConnectivityChange"];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
- (void)startObserving {
|
|
55
|
+
_hasListeners = YES;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
- (void)stopObserving {
|
|
59
|
+
_hasListeners = NO;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
RCT_EXPORT_METHOD(getCurrentStatus:(RCTPromiseResolveBlock)resolve
|
|
63
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
64
|
+
{
|
|
65
|
+
dispatch_async(_monitorQueue, ^{
|
|
66
|
+
resolve(@(self->_isConnected));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
- (void)dealloc {
|
|
71
|
+
if (_monitor) {
|
|
72
|
+
nw_path_monitor_cancel(_monitor);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
@end
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#import <React/RCTBridgeModule.h>
|
|
2
|
+
#import <React/RCTLog.h>
|
|
3
|
+
|
|
4
|
+
@interface MetaRouterQueueStorage : NSObject <RCTBridgeModule>
|
|
5
|
+
@end
|
|
6
|
+
|
|
7
|
+
@implementation MetaRouterQueueStorage
|
|
8
|
+
|
|
9
|
+
RCT_EXPORT_MODULE()
|
|
10
|
+
|
|
11
|
+
+ (BOOL)requiresMainQueueSetup {
|
|
12
|
+
return NO;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Returns the path to the queue snapshot file.
|
|
17
|
+
* Location: Application Support/metarouter/disk-queue/queue.v1.json
|
|
18
|
+
* The directory is created on first write and marked as excluded from backup.
|
|
19
|
+
*/
|
|
20
|
+
- (NSString *)snapshotPath {
|
|
21
|
+
NSArray *paths = NSSearchPathForDirectoriesInDomains(
|
|
22
|
+
NSApplicationSupportDirectory, NSUserDomainMask, YES
|
|
23
|
+
);
|
|
24
|
+
NSString *appSupport = paths.firstObject;
|
|
25
|
+
return [appSupport stringByAppendingPathComponent:@"metarouter/disk-queue/queue.v1.json"];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Ensures the queue directory exists and is excluded from backup.
|
|
30
|
+
*/
|
|
31
|
+
- (BOOL)ensureDirectoryExists:(NSError **)error {
|
|
32
|
+
NSString *dir = [[self snapshotPath] stringByDeletingLastPathComponent];
|
|
33
|
+
NSFileManager *fm = [NSFileManager defaultManager];
|
|
34
|
+
|
|
35
|
+
if (![fm fileExistsAtPath:dir]) {
|
|
36
|
+
if (![fm createDirectoryAtPath:dir
|
|
37
|
+
withIntermediateDirectories:YES
|
|
38
|
+
attributes:nil
|
|
39
|
+
error:error]) {
|
|
40
|
+
return NO;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Mark directory as excluded from backup
|
|
45
|
+
NSURL *dirURL = [NSURL fileURLWithPath:dir];
|
|
46
|
+
return [dirURL setResourceValue:@YES
|
|
47
|
+
forKey:NSURLIsExcludedFromBackupKey
|
|
48
|
+
error:error];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Cheap existence check — does not read the file contents.
|
|
53
|
+
* Used on boot so a large snapshot doesn't get fully parsed just to
|
|
54
|
+
* discover whether there's anything to drain.
|
|
55
|
+
*/
|
|
56
|
+
RCT_EXPORT_METHOD(exists:(RCTPromiseResolveBlock)resolve
|
|
57
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
58
|
+
{
|
|
59
|
+
NSString *path = [self snapshotPath];
|
|
60
|
+
NSFileManager *fm = [NSFileManager defaultManager];
|
|
61
|
+
resolve(@([fm fileExistsAtPath:path]));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
RCT_EXPORT_METHOD(readSnapshot:(RCTPromiseResolveBlock)resolve
|
|
65
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
66
|
+
{
|
|
67
|
+
NSString *path = [self snapshotPath];
|
|
68
|
+
NSFileManager *fm = [NSFileManager defaultManager];
|
|
69
|
+
|
|
70
|
+
if (![fm fileExistsAtPath:path]) {
|
|
71
|
+
resolve([NSNull null]);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
NSError *error = nil;
|
|
76
|
+
NSString *contents = [NSString stringWithContentsOfFile:path
|
|
77
|
+
encoding:NSUTF8StringEncoding
|
|
78
|
+
error:&error];
|
|
79
|
+
if (error) {
|
|
80
|
+
reject(@"READ_ERROR", @"Failed to read queue snapshot", error);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
resolve(contents);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
RCT_EXPORT_METHOD(writeSnapshot:(NSString *)data
|
|
88
|
+
resolver:(RCTPromiseResolveBlock)resolve
|
|
89
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
90
|
+
{
|
|
91
|
+
NSError *error = nil;
|
|
92
|
+
|
|
93
|
+
if (![self ensureDirectoryExists:&error]) {
|
|
94
|
+
reject(@"DIR_ERROR", @"Failed to create queue directory", error);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
NSString *path = [self snapshotPath];
|
|
99
|
+
if (![data writeToFile:path
|
|
100
|
+
atomically:YES
|
|
101
|
+
encoding:NSUTF8StringEncoding
|
|
102
|
+
error:&error]) {
|
|
103
|
+
reject(@"WRITE_ERROR", @"Failed to write queue snapshot", error);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
resolve([NSNull null]);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
RCT_EXPORT_METHOD(deleteSnapshot:(RCTPromiseResolveBlock)resolve
|
|
111
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
112
|
+
{
|
|
113
|
+
NSString *path = [self snapshotPath];
|
|
114
|
+
NSFileManager *fm = [NSFileManager defaultManager];
|
|
115
|
+
|
|
116
|
+
if ([fm fileExistsAtPath:path]) {
|
|
117
|
+
NSError *error = nil;
|
|
118
|
+
if (![fm removeItemAtPath:path error:&error]) {
|
|
119
|
+
reject(@"DELETE_ERROR", @"Failed to delete queue snapshot", error);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
resolve([NSNull null]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
@end
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { InitOptions, Lifecycle } from
|
|
1
|
+
import { InitOptions, Lifecycle } from './types';
|
|
2
|
+
import { type NetworkReachability, type NetworkStatus } from './utils/networkMonitor';
|
|
2
3
|
/**
|
|
3
4
|
* Analytics client for MetaRouter.
|
|
4
5
|
* - Handles event queueing, batching, and delivery with retries.
|
|
@@ -17,15 +18,24 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
17
18
|
private appState;
|
|
18
19
|
private appStateSubscription;
|
|
19
20
|
private identityManager;
|
|
20
|
-
private static readonly
|
|
21
|
-
private
|
|
21
|
+
private static readonly AUTO_FLUSH_THRESHOLD;
|
|
22
|
+
private static readonly DEFAULT_MAX_QUEUE_EVENTS;
|
|
23
|
+
private static readonly DEFAULT_MAX_DISK_EVENTS;
|
|
24
|
+
private static readonly MAX_QUEUE_BYTES;
|
|
25
|
+
private maxDiskEvents;
|
|
22
26
|
private dispatcher;
|
|
27
|
+
private persistentQueue;
|
|
23
28
|
private tracingEnabled;
|
|
29
|
+
private networkMonitor;
|
|
30
|
+
private networkStatus;
|
|
31
|
+
private unsubscribeNetwork;
|
|
24
32
|
/**
|
|
25
33
|
* Initializes the analytics client with the provided options.
|
|
26
34
|
* @param options - The initialization options.
|
|
27
35
|
*/
|
|
28
|
-
constructor(options: InitOptions
|
|
36
|
+
constructor(options: InitOptions, deps?: {
|
|
37
|
+
networkMonitor?: NetworkReachability;
|
|
38
|
+
});
|
|
29
39
|
/**
|
|
30
40
|
* Initializes the analytics client.
|
|
31
41
|
* @returns A promise that resolves when the client is initialized.
|
|
@@ -139,6 +149,12 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
139
149
|
* Enable debug logging for troubleshooting
|
|
140
150
|
*/
|
|
141
151
|
enableDebugLogging(): void;
|
|
152
|
+
/**
|
|
153
|
+
* Returns the current anonymous ID managed by the JS identity layer.
|
|
154
|
+
* Awaits init() if it is still in-flight. Throws only if the client was
|
|
155
|
+
* never initialized or a reset() races with this call.
|
|
156
|
+
*/
|
|
157
|
+
getAnonymousId(): Promise<string>;
|
|
142
158
|
/**
|
|
143
159
|
* Get current state for debugging
|
|
144
160
|
*/
|
|
@@ -156,7 +172,10 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
156
172
|
circuitState: import("./utils/circuitBreaker").CircuitState;
|
|
157
173
|
circuitRemainingMs: number;
|
|
158
174
|
maxQueueEvents: number;
|
|
175
|
+
maxDiskEvents: number;
|
|
159
176
|
tracingEnabled: boolean;
|
|
177
|
+
hasDiskData: boolean;
|
|
178
|
+
networkStatus: NetworkStatus;
|
|
160
179
|
}>;
|
|
161
180
|
/**
|
|
162
181
|
* Flushes the event queue to the ingestion endpoint in chunks.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,WAAW,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,WAAW,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAe7E,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,aAAa,EACnB,MAAM,wBAAwB,C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