@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +385 -2
- package/LICENSE +21 -0
- package/README.md +229 -42
- package/SwissKnifePurchases.podspec +1 -1
- package/android/build.gradle +24 -2
- package/android/consumer-rules.pro +12 -0
- package/android/src/main/AndroidManifest.xml +15 -1
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
- package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
- package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
- package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
- package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
- package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
- package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
- package/android/vendor-rustore/AndroidManifest.xml +59 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
- package/app.plugin.js +287 -0
- package/ios/SwissKnifePurchases.m +20 -0
- package/ios/SwissKnifePurchases.swift +97 -3
- package/ios/SwissKnifePushBootstrap.m +34 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
- package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
- package/lib/commonjs/attribution.js +4 -3
- package/lib/commonjs/attribution.js.map +1 -1
- package/lib/commonjs/identity.js +12 -11
- package/lib/commonjs/identity.js.map +1 -1
- package/lib/commonjs/index.js +16 -5
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/config.js +105 -8
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/internal/telemetry-context.js +70 -0
- package/lib/commonjs/internal/telemetry-context.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +18 -25
- package/lib/commonjs/modules/analytics.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +27 -6
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/commonjs/modules/log.js +1 -1
- package/lib/commonjs/modules/notifications.js +500 -0
- package/lib/commonjs/modules/notifications.js.map +1 -0
- package/lib/commonjs/modules/performance.js +57 -8
- package/lib/commonjs/modules/performance.js.map +1 -1
- package/lib/commonjs/native/module.js +6 -0
- package/lib/commonjs/native/module.js.map +1 -1
- package/lib/commonjs/native/spec.js +12 -5
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/purchases.js +4 -4
- package/lib/commonjs/types.js +12 -15
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/attribution.js +4 -3
- package/lib/module/attribution.js.map +1 -1
- package/lib/module/identity.js +12 -11
- package/lib/module/identity.js.map +1 -1
- package/lib/module/index.js +8 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/config.js +103 -8
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/internal/telemetry-context.js +63 -0
- package/lib/module/internal/telemetry-context.js.map +1 -0
- package/lib/module/modules/analytics.js +18 -25
- package/lib/module/modules/analytics.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +27 -6
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/log.js +1 -1
- package/lib/module/modules/notifications.js +491 -0
- package/lib/module/modules/notifications.js.map +1 -0
- package/lib/module/modules/performance.js +57 -8
- package/lib/module/modules/performance.js.map +1 -1
- package/lib/module/native/module.js +6 -1
- package/lib/module/native/module.js.map +1 -1
- package/lib/module/native/spec.js +11 -4
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/purchases.js +4 -4
- package/lib/module/types.js +12 -15
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/attribution.d.ts +3 -2
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
- package/lib/typescript/commonjs/identity.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +2 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts +16 -2
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
- package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/module.d.ts +2 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +33 -4
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/purchases.d.ts +4 -4
- package/lib/typescript/commonjs/types.d.ts +4 -5
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/attribution.d.ts +3 -2
- package/lib/typescript/module/attribution.d.ts.map +1 -1
- package/lib/typescript/module/identity.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +2 -0
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts +16 -2
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +8 -11
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/notifications.d.ts +110 -0
- package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +13 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -1
- package/lib/typescript/module/native/module.d.ts +2 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +33 -4
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/purchases.d.ts +4 -4
- package/lib/typescript/module/types.d.ts +4 -5
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +12 -4
- package/src/attribution.ts +4 -3
- package/src/identity.ts +12 -11
- package/src/index.ts +16 -4
- package/src/internal/config.ts +113 -8
- package/src/internal/telemetry-context.ts +76 -0
- package/src/modules/analytics.ts +24 -33
- package/src/modules/crash-reporting.ts +50 -9
- package/src/modules/log.ts +1 -1
- package/src/modules/notifications.ts +557 -0
- package/src/modules/performance.ts +94 -14
- package/src/native/module.ts +6 -0
- package/src/native/spec.ts +45 -10
- package/src/purchases.ts +4 -4
- package/src/types.ts +12 -15
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
|
@@ -33,6 +33,31 @@
|
|
|
33
33
|
// - All public methods dispatch onto a serial queue. Disk I/O is slow
|
|
34
34
|
// enough that a serial queue is the right tradeoff over a
|
|
35
35
|
// reader/writer lock; we never need concurrent reads on these queues.
|
|
36
|
+
//
|
|
37
|
+
// COST PER APPEND:
|
|
38
|
+
// - `append()` runs on the CALLER's thread (often main), so it must not
|
|
39
|
+
// grow with the queue. The item count and byte size are cached after
|
|
40
|
+
// ONE read of the file, at first access, and kept current by every
|
|
41
|
+
// mutation (append, appendAll, remove, the limit trims, self-repair).
|
|
42
|
+
// `count()` and the limit check read the cache, so an append is one
|
|
43
|
+
// write + fsync no matter how many items are queued. It used to decode
|
|
44
|
+
// the whole JSONL twice per append once the file passed ~20 KB.
|
|
45
|
+
// - Only exceeding a cap still costs a full read + rewrite, and the trim
|
|
46
|
+
// goes down to a low watermark (90% of the item cap), so
|
|
47
|
+
// a queue that stays full pays it once per `maxItems / 10` appends
|
|
48
|
+
// instead of on every one.
|
|
49
|
+
//
|
|
50
|
+
// DEAD LETTER:
|
|
51
|
+
// - `dead-letter.jsonl` is capped by bytes (`maxDeadLetterBytes`). When
|
|
52
|
+
// an append pushes it over, the OLDEST lines are dropped until the file
|
|
53
|
+
// is back under three quarters of the cap, reading only the tail that
|
|
54
|
+
// is kept. It used to grow without bound in Caches.
|
|
55
|
+
//
|
|
56
|
+
// SIDECARS:
|
|
57
|
+
// - `readSidecar(named:)` / `writeSidecar(named:_:)` keep a small state file
|
|
58
|
+
// of the queue's owner in the same directory (IngestClient keeps
|
|
59
|
+
// `set-aside.json` there), replaced atomically. An in-memory store keeps
|
|
60
|
+
// them in memory, so they live exactly as long as its items do.
|
|
36
61
|
|
|
37
62
|
import Foundation
|
|
38
63
|
import os.log
|
|
@@ -46,6 +71,13 @@ internal enum OfflineQueueStoreDefaults {
|
|
|
46
71
|
static let maxItems: Int = 10_000
|
|
47
72
|
/// Default hard ceiling on bytes on disk. Overflow drops oldest.
|
|
48
73
|
static let maxBytes: Int64 = 10 * 1024 * 1024 // 10 MB
|
|
74
|
+
/// Default ceiling on `dead-letter.jsonl`. Overflow drops the oldest
|
|
75
|
+
/// lines. Dead letters are diagnostics, not a delivery path, so a
|
|
76
|
+
/// bounded tail of the most recent rejects is all that is worth keeping.
|
|
77
|
+
static let maxDeadLetterBytes: Int64 = 1024 * 1024 // 1 MB
|
|
78
|
+
/// In-memory analogue of `maxDeadLetterBytes` for the last-ditch
|
|
79
|
+
/// `inMemory` store, which has no byte measure.
|
|
80
|
+
static let maxDeadLetterItemsInMemory: Int = 1_000
|
|
49
81
|
}
|
|
50
82
|
|
|
51
83
|
/// Generic disk-backed FIFO queue of `Codable` items. Used by IngestClient
|
|
@@ -62,10 +94,22 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
62
94
|
private let deadLetterURL: URL
|
|
63
95
|
private let maxItems: Int
|
|
64
96
|
private let maxBytes: Int64
|
|
97
|
+
private let maxDeadLetterBytes: Int64
|
|
65
98
|
private let log: OSLog
|
|
66
99
|
private let encoder: JSONEncoder
|
|
67
100
|
private let decoder: JSONDecoder
|
|
68
101
|
|
|
102
|
+
/// Item count and byte size of `items.jsonl`, or `nil` until the first
|
|
103
|
+
/// access loads them with one full read. Guarded by `queue`. Every
|
|
104
|
+
/// mutation keeps them current, and every use checks the cached size
|
|
105
|
+
/// against the file's (one `stat`), so a file changed behind our back is
|
|
106
|
+
/// re-read rather than miscounted.
|
|
107
|
+
private var cachedCount: Int?
|
|
108
|
+
private var cachedBytes: Int64?
|
|
109
|
+
|
|
110
|
+
/// Number of full reads of `items.jsonl` (test seam). Guarded by `queue`.
|
|
111
|
+
private var fullReads: Int = 0
|
|
112
|
+
|
|
69
113
|
/// When `true` the store never touches disk — all items live in
|
|
70
114
|
/// `memoryItems` for the process lifetime and are lost on termination.
|
|
71
115
|
/// This is the last-ditch fallback used when no writable directory can
|
|
@@ -77,6 +121,10 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
77
121
|
/// else, so plain mutation under `queue.sync` is safe.
|
|
78
122
|
private var memoryItems: [T] = []
|
|
79
123
|
private var memoryDeadLetter: [T] = []
|
|
124
|
+
private var memorySidecars: [String: Data] = [:]
|
|
125
|
+
|
|
126
|
+
/// The directory holding `items.jsonl`, where sidecars live too.
|
|
127
|
+
private var directoryURL: URL { fileURL.deletingLastPathComponent() }
|
|
80
128
|
|
|
81
129
|
/// Production initializer — `cachesDirectory/SwissKnife/<name>/items.jsonl`.
|
|
82
130
|
convenience init(name: String) throws {
|
|
@@ -106,6 +154,7 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
106
154
|
self.deadLetterURL = placeholder.appendingPathComponent("dead-letter.jsonl", isDirectory: false)
|
|
107
155
|
self.maxItems = OfflineQueueStoreDefaults.maxItems
|
|
108
156
|
self.maxBytes = OfflineQueueStoreDefaults.maxBytes
|
|
157
|
+
self.maxDeadLetterBytes = OfflineQueueStoreDefaults.maxDeadLetterBytes
|
|
109
158
|
self.queue = DispatchQueue(label: "com.swissknife.queue.\(name)", qos: .utility)
|
|
110
159
|
self.log = OSLog(subsystem: "com.swissknife.net", category: "OfflineQueueStore.\(name).inmem")
|
|
111
160
|
self.encoder = JSONEncoder()
|
|
@@ -118,6 +167,7 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
118
167
|
name: String = "default",
|
|
119
168
|
maxItems: Int = OfflineQueueStoreDefaults.maxItems,
|
|
120
169
|
maxBytes: Int64 = OfflineQueueStoreDefaults.maxBytes,
|
|
170
|
+
maxDeadLetterBytes: Int64 = OfflineQueueStoreDefaults.maxDeadLetterBytes,
|
|
121
171
|
encoder: JSONEncoder = JSONEncoder(),
|
|
122
172
|
decoder: JSONDecoder = JSONDecoder()
|
|
123
173
|
) throws {
|
|
@@ -127,12 +177,17 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
127
177
|
self.deadLetterURL = directory.appendingPathComponent("dead-letter.jsonl", isDirectory: false)
|
|
128
178
|
self.maxItems = maxItems
|
|
129
179
|
self.maxBytes = maxBytes
|
|
180
|
+
self.maxDeadLetterBytes = maxDeadLetterBytes
|
|
130
181
|
self.queue = DispatchQueue(label: "com.swissknife.queue.\(name)", qos: .utility)
|
|
131
182
|
self.log = OSLog(subsystem: "com.swissknife.net", category: "OfflineQueueStore.\(name)")
|
|
132
183
|
self.encoder = encoder
|
|
133
184
|
self.decoder = decoder
|
|
134
185
|
if !FileManager.default.fileExists(atPath: fileURL.path) {
|
|
135
|
-
FileManager.default.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
|
|
186
|
+
if FileManager.default.createFile(atPath: fileURL.path, contents: nil, attributes: nil) {
|
|
187
|
+
// A file we just created is empty: nothing to read.
|
|
188
|
+
cachedCount = 0
|
|
189
|
+
cachedBytes = 0
|
|
190
|
+
}
|
|
136
191
|
}
|
|
137
192
|
}
|
|
138
193
|
|
|
@@ -189,11 +244,12 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
189
244
|
}
|
|
190
245
|
}
|
|
191
246
|
|
|
192
|
-
/// Number of items currently persisted.
|
|
247
|
+
/// Number of items currently persisted. O(1) after the first access:
|
|
248
|
+
/// it reads the cached count, which every mutation keeps current.
|
|
193
249
|
func count() throws -> Int {
|
|
194
250
|
try queue.sync {
|
|
195
251
|
if inMemory { return memoryItems.count }
|
|
196
|
-
return try
|
|
252
|
+
return try cachedStatsLocked().count
|
|
197
253
|
}
|
|
198
254
|
}
|
|
199
255
|
|
|
@@ -213,6 +269,8 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
213
269
|
queue.sync {
|
|
214
270
|
if inMemory {
|
|
215
271
|
memoryDeadLetter.append(contentsOf: items)
|
|
272
|
+
let excess = memoryDeadLetter.count - OfflineQueueStoreDefaults.maxDeadLetterItemsInMemory
|
|
273
|
+
if excess > 0 { memoryDeadLetter.removeFirst(excess) }
|
|
216
274
|
return
|
|
217
275
|
}
|
|
218
276
|
do {
|
|
@@ -241,39 +299,127 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
241
299
|
}
|
|
242
300
|
}
|
|
243
301
|
|
|
302
|
+
/// A small file the queue's owner keeps beside the queue (`name` is a
|
|
303
|
+
/// plain file name in the queue's directory), or `nil` when there is none
|
|
304
|
+
/// or it cannot be read. An in-memory store keeps sidecars in memory.
|
|
305
|
+
func readSidecar(named name: String) -> Data? {
|
|
306
|
+
queue.sync {
|
|
307
|
+
if inMemory { return memorySidecars[name] }
|
|
308
|
+
return try? Data(contentsOf: directoryURL.appendingPathComponent(name, isDirectory: false))
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/// Replace a sidecar atomically (write a temporary file, then rename), or
|
|
313
|
+
/// delete it when `data` is `nil`. Best-effort like the dead-letter file:
|
|
314
|
+
/// a failure is logged and swallowed, because the live queue must keep
|
|
315
|
+
/// moving without it.
|
|
316
|
+
func writeSidecar(named name: String, _ data: Data?) {
|
|
317
|
+
queue.sync {
|
|
318
|
+
if inMemory {
|
|
319
|
+
memorySidecars[name] = data
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
let url = directoryURL.appendingPathComponent(name, isDirectory: false)
|
|
323
|
+
do {
|
|
324
|
+
if let data {
|
|
325
|
+
try data.write(to: url, options: .atomic)
|
|
326
|
+
} else if FileManager.default.fileExists(atPath: url.path) {
|
|
327
|
+
try FileManager.default.removeItem(at: url)
|
|
328
|
+
}
|
|
329
|
+
} catch {
|
|
330
|
+
os_log(
|
|
331
|
+
"Failed to write sidecar %{public}@: %{public}@",
|
|
332
|
+
log: log,
|
|
333
|
+
type: .error,
|
|
334
|
+
name,
|
|
335
|
+
String(describing: error)
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/// Test seam — how many times `items.jsonl` has been read in full.
|
|
342
|
+
internal func _fullReadCountForTesting() -> Int {
|
|
343
|
+
queue.sync { fullReads }
|
|
344
|
+
}
|
|
345
|
+
|
|
244
346
|
// MARK: - Locked helpers (must hold `queue`)
|
|
245
347
|
|
|
348
|
+
/// The cached `(count, bytes)`, loaded by one full read on first use.
|
|
349
|
+
///
|
|
350
|
+
/// The cache is checked against the file's size (one `stat`) on every
|
|
351
|
+
/// use: if anything else wrote the file (a second store instance over
|
|
352
|
+
/// the same directory, a torn write), the sizes disagree and the next
|
|
353
|
+
/// use re-reads it instead of trusting a stale count.
|
|
354
|
+
private func cachedStatsLocked() throws -> (count: Int, bytes: Int64) {
|
|
355
|
+
if let count = cachedCount, let bytes = cachedBytes, try fileSizeLocked() == bytes {
|
|
356
|
+
return (count, bytes)
|
|
357
|
+
}
|
|
358
|
+
_ = try readAllLocked() // fills both
|
|
359
|
+
return (cachedCount ?? 0, cachedBytes ?? 0)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private func invalidateCacheLocked() {
|
|
363
|
+
cachedCount = nil
|
|
364
|
+
cachedBytes = nil
|
|
365
|
+
}
|
|
366
|
+
|
|
246
367
|
private func appendLocked(_ item: T) throws {
|
|
247
368
|
let json = try encoder.encode(item)
|
|
248
369
|
var line = Data()
|
|
249
370
|
line.append(json)
|
|
250
371
|
line.append(0x0A) // newline
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
372
|
+
do {
|
|
373
|
+
let handle = try FileHandle(forWritingTo: fileURL)
|
|
374
|
+
defer { try? handle.close() }
|
|
375
|
+
try handle.seekToEnd()
|
|
376
|
+
try handle.write(contentsOf: line)
|
|
377
|
+
try handle.synchronize()
|
|
378
|
+
} catch {
|
|
379
|
+
// We no longer know what is on disk; the next access re-reads.
|
|
380
|
+
invalidateCacheLocked()
|
|
381
|
+
throw error
|
|
382
|
+
}
|
|
383
|
+
if let count = cachedCount, let bytes = cachedBytes {
|
|
384
|
+
cachedCount = count + 1
|
|
385
|
+
cachedBytes = bytes + Int64(line.count)
|
|
386
|
+
}
|
|
256
387
|
}
|
|
257
388
|
|
|
258
389
|
private func readAllLocked() throws -> [T] {
|
|
259
|
-
guard FileManager.default.fileExists(atPath: fileURL.path) else {
|
|
390
|
+
guard FileManager.default.fileExists(atPath: fileURL.path) else {
|
|
391
|
+
cachedCount = 0
|
|
392
|
+
cachedBytes = 0
|
|
393
|
+
return []
|
|
394
|
+
}
|
|
260
395
|
let data = try Data(contentsOf: fileURL)
|
|
261
|
-
|
|
396
|
+
fullReads += 1
|
|
397
|
+
guard !data.isEmpty else {
|
|
398
|
+
cachedCount = 0
|
|
399
|
+
cachedBytes = 0
|
|
400
|
+
return []
|
|
401
|
+
}
|
|
262
402
|
let (items, sawMalformed) = parseJSONLTolerant(data)
|
|
263
403
|
if sawMalformed {
|
|
264
|
-
// Rewrite to drop the bad line(s) permanently.
|
|
404
|
+
// Rewrite to drop the bad line(s) permanently. Sets the cache.
|
|
265
405
|
try writeAllLocked(items)
|
|
406
|
+
} else {
|
|
407
|
+
cachedCount = items.count
|
|
408
|
+
cachedBytes = Int64(data.count)
|
|
266
409
|
}
|
|
267
410
|
return items
|
|
268
411
|
}
|
|
269
412
|
|
|
270
413
|
private func writeAllLocked(_ items: [T]) throws {
|
|
414
|
+
// Unknown until the rewrite has landed; set again below on success.
|
|
415
|
+
invalidateCacheLocked()
|
|
271
416
|
let tmp = fileURL.appendingPathExtension("tmp")
|
|
272
417
|
if FileManager.default.fileExists(atPath: tmp.path) {
|
|
273
418
|
try FileManager.default.removeItem(at: tmp)
|
|
274
419
|
}
|
|
275
420
|
FileManager.default.createFile(atPath: tmp.path, contents: nil, attributes: nil)
|
|
276
421
|
let handle = try FileHandle(forWritingTo: tmp)
|
|
422
|
+
var written: Int64 = 0
|
|
277
423
|
for item in items {
|
|
278
424
|
let json = try encoder.encode(item)
|
|
279
425
|
// Use the throwing `write(contentsOf:)`, NOT the deprecated
|
|
@@ -282,10 +428,13 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
282
428
|
// host app. This path runs on every flush (remove/limit/self-repair).
|
|
283
429
|
try handle.write(contentsOf: json)
|
|
284
430
|
try handle.write(contentsOf: Data([0x0A]))
|
|
431
|
+
written += Int64(json.count + 1)
|
|
285
432
|
}
|
|
286
433
|
try handle.synchronize()
|
|
287
434
|
try handle.close()
|
|
288
435
|
_ = try FileManager.default.replaceItemAt(fileURL, withItemAt: tmp)
|
|
436
|
+
cachedCount = items.count
|
|
437
|
+
cachedBytes = written
|
|
289
438
|
}
|
|
290
439
|
|
|
291
440
|
private func fileSizeLocked() throws -> Int64 {
|
|
@@ -295,13 +444,18 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
295
444
|
}
|
|
296
445
|
|
|
297
446
|
private func enforceLimitsLocked() throws {
|
|
298
|
-
|
|
299
|
-
//
|
|
300
|
-
|
|
447
|
+
// Cheap path: the cached count and size, no file read. Only a queue
|
|
448
|
+
// that is actually over a cap pays for the read + rewrite below.
|
|
449
|
+
let (count, size) = try cachedStatsLocked()
|
|
450
|
+
if count <= maxItems, size <= maxBytes { return }
|
|
301
451
|
var all = try readAllLocked()
|
|
302
452
|
if all.count <= maxItems, try fileSizeLocked() <= maxBytes { return }
|
|
303
453
|
if all.count > maxItems {
|
|
304
|
-
|
|
454
|
+
// Down to a low watermark, not to exactly `maxItems`: trimmed to
|
|
455
|
+
// the cap, a full queue (a refused key keeps it full) would pay
|
|
456
|
+
// this read + rewrite on EVERY append, one dropped item at a time.
|
|
457
|
+
// Dropping the oldest tenth buys `maxItems / 10` cheap appends.
|
|
458
|
+
let drop = all.count - (maxItems - maxItems / 10)
|
|
305
459
|
os_log(
|
|
306
460
|
"Queue exceeded %d items; dropping %d oldest",
|
|
307
461
|
log: log,
|
|
@@ -346,15 +500,69 @@ internal final class OfflineQueueStore<T: Codable & Identifiable> where T.ID ==
|
|
|
346
500
|
if !FileManager.default.fileExists(atPath: deadLetterURL.path) {
|
|
347
501
|
FileManager.default.createFile(atPath: deadLetterURL.path, contents: nil, attributes: nil)
|
|
348
502
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
503
|
+
do {
|
|
504
|
+
let handle = try FileHandle(forWritingTo: deadLetterURL)
|
|
505
|
+
defer { try? handle.close() }
|
|
506
|
+
try handle.seekToEnd()
|
|
507
|
+
for item in items {
|
|
508
|
+
let json = try encoder.encode(item)
|
|
509
|
+
try handle.write(contentsOf: json)
|
|
510
|
+
try handle.write(contentsOf: Data([0x0A]))
|
|
511
|
+
}
|
|
512
|
+
try handle.synchronize()
|
|
356
513
|
}
|
|
357
|
-
|
|
514
|
+
// The items are written; a failed trim only leaves the file long.
|
|
515
|
+
do {
|
|
516
|
+
try trimDeadLetterLocked()
|
|
517
|
+
} catch {
|
|
518
|
+
os_log(
|
|
519
|
+
"Dead-letter trim failed: %{public}@",
|
|
520
|
+
log: log,
|
|
521
|
+
type: .error,
|
|
522
|
+
String(describing: error)
|
|
523
|
+
)
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/// Keep `dead-letter.jsonl` under `maxDeadLetterBytes` by dropping its
|
|
528
|
+
/// OLDEST lines. Trims to three quarters of the cap so a steady trickle
|
|
529
|
+
/// of rejects does not rewrite the file on every append.
|
|
530
|
+
///
|
|
531
|
+
/// Reads only the tail that can survive, never the whole file: one
|
|
532
|
+
/// written before the cap existed may be tens of MB, and loading it
|
|
533
|
+
/// would put all of it in memory on the flush path.
|
|
534
|
+
private func trimDeadLetterLocked() throws {
|
|
535
|
+
guard maxDeadLetterBytes > 0 else { return }
|
|
536
|
+
let attrs = try FileManager.default.attributesOfItem(atPath: deadLetterURL.path)
|
|
537
|
+
let size = (attrs[.size] as? NSNumber)?.int64Value ?? 0
|
|
538
|
+
guard size > maxDeadLetterBytes else { return }
|
|
539
|
+
let budget = maxDeadLetterBytes * 3 / 4
|
|
540
|
+
let tail = try Self.readWholeLinesTail(of: deadLetterURL, size: size, budget: budget)
|
|
541
|
+
try tail.write(to: deadLetterURL, options: .atomic)
|
|
542
|
+
os_log(
|
|
543
|
+
"Dead-letter file exceeded %lld bytes; kept the newest %d line(s)",
|
|
544
|
+
log: log,
|
|
545
|
+
type: .info,
|
|
546
|
+
maxDeadLetterBytes,
|
|
547
|
+
tail.reduce(0) { $1 == 0x0A ? $0 + 1 : $0 }
|
|
548
|
+
)
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/// The longest run of whole lines at the end of the file that fits in
|
|
552
|
+
/// `budget` bytes. Reads `budget + 1` bytes at most: the extra byte, just
|
|
553
|
+
/// before the window, says whether the window starts on a line boundary.
|
|
554
|
+
private static func readWholeLinesTail(of url: URL, size: Int64, budget: Int64) throws -> Data {
|
|
555
|
+
let from = max(0, size - budget)
|
|
556
|
+
let readFrom = max(0, from - 1)
|
|
557
|
+
let handle = try FileHandle(forReadingFrom: url)
|
|
558
|
+
defer { try? handle.close() }
|
|
559
|
+
try handle.seek(toOffset: UInt64(readFrom))
|
|
560
|
+
let window = try handle.read(upToCount: Int(size - readFrom)) ?? Data()
|
|
561
|
+
guard from > 0 else { return window }
|
|
562
|
+
// `window` starts one byte before `from`; keep from the first line
|
|
563
|
+
// that starts at or after it.
|
|
564
|
+
guard let newline = window.firstIndex(of: 0x0A) else { return Data() }
|
|
565
|
+
return Data(window[window.index(after: newline)...])
|
|
358
566
|
}
|
|
359
567
|
|
|
360
568
|
// MARK: - JSONL parsing
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Notifications/PushPayload.swift
|
|
2
|
+
//
|
|
3
|
+
// Wire-format helpers for swiss-push (see the shared push contract).
|
|
4
|
+
// APNs payloads carry a reserved `sk` dictionary next to `aps`:
|
|
5
|
+
// "sk": { "m": <message_id>, "d": <delivery_id>, "link": <deep link>, "img": <image url> }
|
|
6
|
+
|
|
7
|
+
import Foundation
|
|
8
|
+
|
|
9
|
+
public extension SwissKnife {
|
|
10
|
+
enum Notifications {
|
|
11
|
+
|
|
12
|
+
/// Permission state as understood by the backend (`permission_status`).
|
|
13
|
+
public enum PermissionStatus: String, Sendable, Equatable {
|
|
14
|
+
case authorized
|
|
15
|
+
case provisional
|
|
16
|
+
case denied
|
|
17
|
+
case notDetermined = "not_determined"
|
|
18
|
+
case ephemeral
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// Swiss Knife metadata parsed out of a notification's `userInfo`.
|
|
22
|
+
public struct Payload: Sendable, Equatable {
|
|
23
|
+
public let messageId: String
|
|
24
|
+
public let deliveryId: String
|
|
25
|
+
public let link: URL?
|
|
26
|
+
public let imageURL: URL?
|
|
27
|
+
|
|
28
|
+
/// Parse the reserved `sk` dictionary. Returns nil when the
|
|
29
|
+
/// notification was not sent by Swiss Knife (no `sk`, or no
|
|
30
|
+
/// message/delivery id).
|
|
31
|
+
public static func parse(userInfo: [AnyHashable: Any]) -> Payload? {
|
|
32
|
+
guard let sk = userInfo["sk"] as? [String: Any],
|
|
33
|
+
let m = sk["m"] as? String, !m.isEmpty,
|
|
34
|
+
let d = sk["d"] as? String, !d.isEmpty
|
|
35
|
+
else { return nil }
|
|
36
|
+
let link = (sk["link"] as? String).flatMap { $0.isEmpty ? nil : URL(string: $0) }
|
|
37
|
+
let img = (sk["img"] as? String).flatMap { $0.isEmpty ? nil : URL(string: $0) }
|
|
38
|
+
return Payload(messageId: m, deliveryId: d, link: link, imageURL: img)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// MARK: - Device token
|
|
45
|
+
|
|
46
|
+
internal enum PushTokenFormat {
|
|
47
|
+
/// APNs device token bytes -> lowercase hex string.
|
|
48
|
+
static func hex(_ data: Data) -> String {
|
|
49
|
+
data.map { String(format: "%02x", $0) }.joined()
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// MARK: - Environment detection
|
|
54
|
+
|
|
55
|
+
internal enum PushEnvironment {
|
|
56
|
+
/// Derive the APNs environment from the raw bytes of
|
|
57
|
+
/// `embedded.mobileprovision` (a CMS-signed blob wrapping an XML plist).
|
|
58
|
+
/// `aps-environment == "development"` -> sandbox; anything else
|
|
59
|
+
/// (including a missing profile, i.e. App Store / TestFlight) -> production.
|
|
60
|
+
static func detect(provisioningProfile data: Data?) -> String {
|
|
61
|
+
guard let data,
|
|
62
|
+
let start = data.range(of: Data("<?xml".utf8)),
|
|
63
|
+
let end = data.range(of: Data("</plist>".utf8), in: start.lowerBound..<data.endIndex)
|
|
64
|
+
else { return "production" }
|
|
65
|
+
let plistData = data.subdata(in: start.lowerBound..<end.upperBound)
|
|
66
|
+
guard let plist = try? PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as? [String: Any],
|
|
67
|
+
let entitlements = plist["Entitlements"] as? [String: Any],
|
|
68
|
+
let aps = entitlements["aps-environment"] as? String
|
|
69
|
+
else { return "production" }
|
|
70
|
+
return aps == "development" ? "sandbox" : "production"
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#if targetEnvironment(simulator)
|
|
74
|
+
static let runningOnSimulator = true
|
|
75
|
+
#else
|
|
76
|
+
static let runningOnSimulator = false
|
|
77
|
+
#endif
|
|
78
|
+
|
|
79
|
+
/// The simulator has no provisioning profile, and its tokens only work
|
|
80
|
+
/// against the APNs sandbox (`simctl push` / development builds), so a
|
|
81
|
+
/// missing profile must not be read as "App Store -> production" there.
|
|
82
|
+
static func detectFromBundle(_ bundle: Bundle = .main, isSimulator: Bool = PushEnvironment.runningOnSimulator) -> String {
|
|
83
|
+
if isSimulator { return "sandbox" }
|
|
84
|
+
let url = bundle.bundleURL.appendingPathComponent("embedded.mobileprovision")
|
|
85
|
+
return detect(provisioningProfile: try? Data(contentsOf: url))
|
|
86
|
+
}
|
|
87
|
+
}
|