@metarouter/react-native-sdk 1.5.0 → 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 +59 -10
- 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 +61 -4
- package/lib/analytics/dispatcher.d.ts.map +1 -1
- package/lib/analytics/dispatcher.js +248 -45
- package/lib/analytics/init.d.ts +1 -1
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +12 -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 +23 -29
- 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 +27 -10
- 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
|
|
@@ -147,6 +150,33 @@ analytics.flush();
|
|
|
147
150
|
await analytics.reset();
|
|
148
151
|
```
|
|
149
152
|
|
|
153
|
+
### Reconfiguring the Analytics Client
|
|
154
|
+
|
|
155
|
+
⚠️ **Important**: If you need to change the analytics configuration (e.g., different `writeKey` or `ingestionHost`), you must call `reset()` first:
|
|
156
|
+
|
|
157
|
+
```js
|
|
158
|
+
// Initial configuration
|
|
159
|
+
const analytics = await createAnalyticsClient({
|
|
160
|
+
writeKey: "key-1",
|
|
161
|
+
ingestionHost: "https://endpoint-1.com",
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// Later, if you need to change configuration:
|
|
165
|
+
await analytics.reset(); // Must reset first!
|
|
166
|
+
|
|
167
|
+
// Now reconfigure with new options
|
|
168
|
+
const analytics = await createAnalyticsClient({
|
|
169
|
+
writeKey: "key-2",
|
|
170
|
+
ingestionHost: "https://endpoint-2.com",
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
If you call `createAnalyticsClient()` with different options without resetting first, you'll see this warning:
|
|
175
|
+
|
|
176
|
+
```
|
|
177
|
+
[MetaRouter] Config changed but client not reset. Call await client.reset() before reinitializing with new options.
|
|
178
|
+
```
|
|
179
|
+
|
|
150
180
|
## API Reference
|
|
151
181
|
|
|
152
182
|
### createAnalyticsClient(options)
|
|
@@ -163,7 +193,7 @@ Calls to `track`, `identify`, etc. are **buffered in-memory** by the proxy and r
|
|
|
163
193
|
- `ingestionHost` (string, required): Your MetaRouter ingestor host
|
|
164
194
|
- `debug` (boolean, optional): Enable debug mode
|
|
165
195
|
- `flushIntervalSeconds` (number, optional): Interval in seconds to flush events
|
|
166
|
-
- `
|
|
196
|
+
- `maxQueueBytes` (number, optional): max bytes (UTF-8) held in memory queue (default: 5MB)
|
|
167
197
|
|
|
168
198
|
**Proxy behavior (quick notes):**
|
|
169
199
|
|
|
@@ -184,6 +214,7 @@ The analytics client provides the following methods:
|
|
|
184
214
|
- `alias(newUserId: string)`: Connect anonymous users to known user IDs. See [Using the alias() Method](#using-the-alias-method) for details
|
|
185
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
|
|
186
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()`
|
|
187
218
|
- `setTracing(enabled: boolean)`: Enable or disable tracing headers on API requests. When enabled, includes a `Trace: true` header for debugging request flows
|
|
188
219
|
- `flush()`: Flush events immediately
|
|
189
220
|
- `reset()`: Reset analytics state and clear all stored data (includes clearing advertising ID)
|
|
@@ -205,18 +236,29 @@ The analytics client provides the following methods:
|
|
|
205
236
|
- 🎣 **React Hooks**: Easy integration with React components
|
|
206
237
|
- 🔧 **TypeScript Support**: Full TypeScript support included
|
|
207
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
|
|
208
240
|
- 🔄 **Reset Capability**: Easily reset analytics state for testing or logout scenarios
|
|
209
241
|
- 🐛 **Debug Support**: Built-in debugging tools for troubleshooting
|
|
210
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
|
+
|
|
211
252
|
## ✅ Compatibility
|
|
212
253
|
|
|
213
|
-
| Component
|
|
214
|
-
|
|
|
215
|
-
| React Native
|
|
216
|
-
| React
|
|
217
|
-
| iOS Deployment Target
|
|
218
|
-
| Android Min SDK
|
|
219
|
-
|
|
|
254
|
+
| Component | Supported Versions |
|
|
255
|
+
| -------------------------- | ------------------ |
|
|
256
|
+
| React Native | >= 0.73 |
|
|
257
|
+
| React | >= 16.8 |
|
|
258
|
+
| iOS Deployment Target | >= iOS 13 |
|
|
259
|
+
| Android Min SDK | >= API 23 |
|
|
260
|
+
| Android Build JDK | >= 17 |
|
|
261
|
+
| Node.js | >= 18 |
|
|
220
262
|
|
|
221
263
|
## Debugging
|
|
222
264
|
|
|
@@ -260,7 +302,7 @@ await analytics.flush();
|
|
|
260
302
|
|
|
261
303
|
### Delivery & Backoff (How events flow under failures)
|
|
262
304
|
|
|
263
|
-
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)
|
|
264
306
|
|
|
265
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.
|
|
266
308
|
|
|
@@ -272,7 +314,7 @@ Half-open probe: After cooldown, one probe is allowed.
|
|
|
272
314
|
Success → breaker CLOSED (keep flushing).
|
|
273
315
|
Failure → breaker OPEN again with longer cooldown.
|
|
274
316
|
|
|
275
|
-
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`.
|
|
276
318
|
|
|
277
319
|
| Status / Failure | Action | Breaker | Queue effect |
|
|
278
320
|
| ----------------------------------- | -------------------------------------------------------------------- | ------- | ------------------------------ |
|
|
@@ -352,6 +394,13 @@ The `anonymousId` is a unique identifier automatically generated for each device
|
|
|
352
394
|
- Remains stable across app sessions until `reset()` is called
|
|
353
395
|
- Cleared on `reset()` and a **new** UUID is generated on next `init()`
|
|
354
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
|
+
|
|
355
404
|
**Use case:**
|
|
356
405
|
Track user behavior before they log in or create an account, then connect pre-login and post-login activity using the `alias()` method.
|
|
357
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
|