@app-swiss-knife/react-native-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,646 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/EntitlementsService.swift
|
|
2
|
+
//
|
|
3
|
+
// Phase 5 step 2 — own entitlements service: disk-backed `CustomerInfo`
|
|
4
|
+
// cache with a 24-hour offline grace window plus a backend refresh path that
|
|
5
|
+
// fetches the user's full entitlement set from
|
|
6
|
+
// `GET /api/sdk/entitlements/list`. Replaces the RevenueCat caching layer
|
|
7
|
+
// that the rest of the SDK currently depends on.
|
|
8
|
+
//
|
|
9
|
+
// Why we own this (vs. delegating to RC)
|
|
10
|
+
// --------------------------------------
|
|
11
|
+
// - Offline policy is OURS to set (locked decision: 24h grace from the last
|
|
12
|
+
// successful online refresh, with a silent-push invalidate hook). RC's
|
|
13
|
+
// cache policy is process-internal and not under our control.
|
|
14
|
+
// - Backend is the source of truth for entitlements; the SDK's job is to
|
|
15
|
+
// surface what the backend says, fall back to the most recent cache when
|
|
16
|
+
// offline, and reconcile on the next online opportunity.
|
|
17
|
+
//
|
|
18
|
+
// Disk layout
|
|
19
|
+
// -----------
|
|
20
|
+
// Cache lives at `Caches/SwissKnife/customerInfo.json`. Mirrors the
|
|
21
|
+
// `EventQueueStore` placement rationale — `cachesDirectory` is documented
|
|
22
|
+
// for "data that can be recreated", excluded from backups by default, and
|
|
23
|
+
// won't surface in Files.app. The file is a single JSON object with shape
|
|
24
|
+
// `{ "fetchedAt": <epoch-ms>, "customerInfo": <CustomerInfo JSON> }`. We
|
|
25
|
+
// write atomically (write to `.tmp` → rename) so a crash mid-write either
|
|
26
|
+
// leaves the old file intact or the new one fully written — never partial.
|
|
27
|
+
//
|
|
28
|
+
// Endpoint contract (added alongside Phase 5 commit 4)
|
|
29
|
+
// ----------------------------------------------------
|
|
30
|
+
// `GET /api/sdk/entitlements/list?user_id=<id>` returns the same shape we
|
|
31
|
+
// already model in `CustomerInfo` — entitlements (all+active), purchase
|
|
32
|
+
// dates, original purchase metadata. Until that endpoint lands, refresh()
|
|
33
|
+
// falls back to building an empty/stable CustomerInfo from the cached
|
|
34
|
+
// originalAppUserId so the public API never hard-fails.
|
|
35
|
+
//
|
|
36
|
+
// Push-invalidate
|
|
37
|
+
// ---------------
|
|
38
|
+
// `handleSilentPush(_:)` is a stub for the host app to call from its
|
|
39
|
+
// `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`
|
|
40
|
+
// when a silent-push entitlements update arrives. Today it invalidates the
|
|
41
|
+
// cache and triggers an immediate refresh; the APNs cert / backend
|
|
42
|
+
// push-send service are follow-up work (see PR description).
|
|
43
|
+
//
|
|
44
|
+
// Thread safety
|
|
45
|
+
// -------------
|
|
46
|
+
// All access goes through a private serial DispatchQueue. The `current()`
|
|
47
|
+
// fast path is cheap (no network); `refresh()` enqueues a single in-flight
|
|
48
|
+
// network request and coalesces concurrent callers onto the same Task.
|
|
49
|
+
|
|
50
|
+
import Foundation
|
|
51
|
+
import os.log
|
|
52
|
+
|
|
53
|
+
/// Process-wide owner of `CustomerInfo` caching + backend refresh.
|
|
54
|
+
public final class EntitlementsService {
|
|
55
|
+
|
|
56
|
+
/// Shared singleton — same pattern as `AttributesClient`. Configured by
|
|
57
|
+
/// `SwissKnife.configure(...)`.
|
|
58
|
+
public static let shared = EntitlementsService()
|
|
59
|
+
|
|
60
|
+
// MARK: Tunables
|
|
61
|
+
|
|
62
|
+
/// Locked decision: 24-hour offline grace from the last successful
|
|
63
|
+
/// online refresh. Older caches are treated as expired and force a
|
|
64
|
+
/// network call on the next `current()` request.
|
|
65
|
+
public static let cacheTTL: TimeInterval = 24 * 60 * 60
|
|
66
|
+
|
|
67
|
+
private let log = OSLog(subsystem: "com.swissknife", category: "entitlements")
|
|
68
|
+
private let queue = DispatchQueue(label: "com.swissknife.entitlements")
|
|
69
|
+
|
|
70
|
+
// MARK: Configuration (set by SwissKnife.configure)
|
|
71
|
+
|
|
72
|
+
private var serverURL: String?
|
|
73
|
+
private var apiKey: String?
|
|
74
|
+
/// Tracks the current logical user the cache belongs to. When the user
|
|
75
|
+
/// identifies/logs out, the cache must be invalidated to avoid showing
|
|
76
|
+
/// userA's entitlements to userB.
|
|
77
|
+
private var currentUserId: String?
|
|
78
|
+
|
|
79
|
+
// MARK: In-memory + disk cache
|
|
80
|
+
|
|
81
|
+
/// In-memory snapshot of the most recent cache for the fast-path
|
|
82
|
+
/// `current()` read. Backed by the on-disk file; we load it once on
|
|
83
|
+
/// first access and keep both in sync afterwards.
|
|
84
|
+
private var cachedSnapshot: CachedCustomerInfo?
|
|
85
|
+
private var cacheLoaded = false
|
|
86
|
+
private let cacheFileURL: URL
|
|
87
|
+
|
|
88
|
+
// MARK: Network seam
|
|
89
|
+
|
|
90
|
+
/// Dependency seam — production wires `BackendHttpClientEntitlementsTransport`;
|
|
91
|
+
/// tests inject a fake.
|
|
92
|
+
internal var transport: EntitlementsTransport = BackendHttpClientEntitlementsTransport()
|
|
93
|
+
|
|
94
|
+
/// Clock injection seam. Tests inject a stub clock to assert TTL
|
|
95
|
+
/// behavior without sleeping; production calls `Date()`.
|
|
96
|
+
internal var now: () -> Date = { Date() }
|
|
97
|
+
|
|
98
|
+
// MARK: Refresh coalescing
|
|
99
|
+
|
|
100
|
+
/// At most one in-flight refresh at a time. Concurrent callers await
|
|
101
|
+
/// the same task rather than racing the backend.
|
|
102
|
+
private var inflightRefresh: Task<CustomerInfo, Error>?
|
|
103
|
+
|
|
104
|
+
/// AsyncStream continuations fed by every successful refresh (replaces
|
|
105
|
+
/// RC's PurchasesDelegate→customerInfoStream path in commits 5/6).
|
|
106
|
+
private var streamContinuations: [UUID: AsyncStream<CustomerInfo>.Continuation] = [:]
|
|
107
|
+
|
|
108
|
+
// MARK: Init
|
|
109
|
+
|
|
110
|
+
private init() {
|
|
111
|
+
// Production path: `cachesDirectory/SwissKnife/customerInfo.json`.
|
|
112
|
+
// Failures here are extremely rare (we'd need an unwritable Caches);
|
|
113
|
+
// we fall back to a temp directory path so subsequent disk writes
|
|
114
|
+
// also fail silently and the SDK degrades to "no cache" mode rather
|
|
115
|
+
// than crashing on init.
|
|
116
|
+
let url: URL
|
|
117
|
+
do {
|
|
118
|
+
let caches = try FileManager.default.url(
|
|
119
|
+
for: .cachesDirectory,
|
|
120
|
+
in: .userDomainMask,
|
|
121
|
+
appropriateFor: nil,
|
|
122
|
+
create: true
|
|
123
|
+
)
|
|
124
|
+
let dir = caches.appendingPathComponent("SwissKnife", isDirectory: true)
|
|
125
|
+
try Self.ensureDirectory(dir)
|
|
126
|
+
url = dir.appendingPathComponent("customerInfo.json", isDirectory: false)
|
|
127
|
+
} catch {
|
|
128
|
+
os_log(
|
|
129
|
+
"EntitlementsService: failed to resolve cachesDirectory (%{public}@); cache disabled",
|
|
130
|
+
log: OSLog(subsystem: "com.swissknife", category: "entitlements"),
|
|
131
|
+
type: .error,
|
|
132
|
+
String(describing: error)
|
|
133
|
+
)
|
|
134
|
+
url = URL(fileURLWithPath: NSTemporaryDirectory())
|
|
135
|
+
.appendingPathComponent("swisskife-customerInfo-disabled.json")
|
|
136
|
+
}
|
|
137
|
+
self.cacheFileURL = url
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// MARK: Configure
|
|
141
|
+
|
|
142
|
+
/// Wire up the service after `SwissKnife.configure(...)` resolves the
|
|
143
|
+
/// proxy URL + API key. Idempotent — re-configuring just overwrites
|
|
144
|
+
/// the cached values.
|
|
145
|
+
internal func configure(serverURL: String?, apiKey: String, userId: String?) {
|
|
146
|
+
queue.sync {
|
|
147
|
+
self.serverURL = (serverURL?.isEmpty == true) ? nil : serverURL
|
|
148
|
+
self.apiKey = apiKey
|
|
149
|
+
// If the userId on the cache differs from the configured one,
|
|
150
|
+
// the cache is stale relative to the new identity — drop it.
|
|
151
|
+
// This handles the cross-launch case where the host app
|
|
152
|
+
// re-configures with a different appUserID.
|
|
153
|
+
if let cached = loadFromDiskIfNeededLocked(),
|
|
154
|
+
let configuredId = userId,
|
|
155
|
+
cached.customerInfo.originalAppUserId != configuredId {
|
|
156
|
+
clearDiskLocked()
|
|
157
|
+
cachedSnapshot = nil
|
|
158
|
+
}
|
|
159
|
+
self.currentUserId = userId
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/// Update the user the cache should be keyed against (login / logout).
|
|
164
|
+
/// Invalidates any cached state belonging to the previous identity so
|
|
165
|
+
/// userA's entitlements are never shown to userB.
|
|
166
|
+
internal func setCurrentUser(_ userId: String?) {
|
|
167
|
+
queue.sync {
|
|
168
|
+
if currentUserId != userId {
|
|
169
|
+
clearDiskLocked()
|
|
170
|
+
cachedSnapshot = nil
|
|
171
|
+
currentUserId = userId
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// MARK: Public read API
|
|
177
|
+
|
|
178
|
+
/// Return the cached `CustomerInfo` IFF it's still inside the 24h grace
|
|
179
|
+
/// window. Returns `nil` when the cache is missing or expired so the
|
|
180
|
+
/// caller knows to issue a refresh. Synchronous and cheap — used by
|
|
181
|
+
/// `SwissKnife.getCustomerInfo()` as the fast path.
|
|
182
|
+
public func current() -> CustomerInfo? {
|
|
183
|
+
queue.sync {
|
|
184
|
+
let snapshot = loadFromDiskIfNeededLocked()
|
|
185
|
+
guard let snapshot else { return nil }
|
|
186
|
+
let age = now().timeIntervalSince(snapshot.fetchedAt)
|
|
187
|
+
if age > Self.cacheTTL {
|
|
188
|
+
return nil
|
|
189
|
+
}
|
|
190
|
+
return snapshot.customerInfo
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/// Force a refresh from the backend. Coalesces concurrent callers onto
|
|
195
|
+
/// a single network request — the first caller in a quiescent state
|
|
196
|
+
/// kicks it off; subsequent callers await the same task. Throws on
|
|
197
|
+
/// network/HTTP failure; the cache is left untouched on failure so the
|
|
198
|
+
/// next `current()` can still serve a stale-but-valid response.
|
|
199
|
+
@discardableResult
|
|
200
|
+
public func refresh() async throws -> CustomerInfo {
|
|
201
|
+
// Capture the in-flight task under the queue lock so we coalesce
|
|
202
|
+
// racing callers without holding the lock across the network call.
|
|
203
|
+
// `Task` is a value type so we can't compare identity directly;
|
|
204
|
+
// instead the performRefresh closure clears `inflightRefresh` itself
|
|
205
|
+
// at the very end, before the awaiter returns.
|
|
206
|
+
let task: Task<CustomerInfo, Error> = queue.sync {
|
|
207
|
+
if let existing = inflightRefresh {
|
|
208
|
+
return existing
|
|
209
|
+
}
|
|
210
|
+
let newTask = Task { [weak self] () throws -> CustomerInfo in
|
|
211
|
+
guard let self else { throw PurchasesError.notConfigured }
|
|
212
|
+
do {
|
|
213
|
+
let info = try await self.performRefresh()
|
|
214
|
+
self.queue.async { self.inflightRefresh = nil }
|
|
215
|
+
return info
|
|
216
|
+
} catch {
|
|
217
|
+
self.queue.async { self.inflightRefresh = nil }
|
|
218
|
+
throw error
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
inflightRefresh = newTask
|
|
222
|
+
return newTask
|
|
223
|
+
}
|
|
224
|
+
return try await task.value
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/// Invalidate the cache: drop the in-memory snapshot AND remove the
|
|
228
|
+
/// on-disk file. Subsequent `current()` returns nil; the next
|
|
229
|
+
/// `refresh()` will re-fetch from the backend.
|
|
230
|
+
public func invalidate() {
|
|
231
|
+
queue.sync {
|
|
232
|
+
clearDiskLocked()
|
|
233
|
+
cachedSnapshot = nil
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/// Subscribe to CustomerInfo updates. The stream fires every time
|
|
238
|
+
/// `refresh()` completes successfully. Mirrors the old
|
|
239
|
+
/// `SwissKnife.customerInfoStream` semantics but is now owned by the
|
|
240
|
+
/// service rather than by RC's PurchasesDelegate.
|
|
241
|
+
public var customerInfoStream: AsyncStream<CustomerInfo> {
|
|
242
|
+
AsyncStream { continuation in
|
|
243
|
+
let id = UUID()
|
|
244
|
+
self.queue.sync {
|
|
245
|
+
self.streamContinuations[id] = continuation
|
|
246
|
+
}
|
|
247
|
+
continuation.onTermination = { _ in
|
|
248
|
+
self.queue.sync {
|
|
249
|
+
self.streamContinuations[id] = nil
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/// Silent-push handler for entitlement invalidations sent from the
|
|
256
|
+
/// backend. Host apps wire this into
|
|
257
|
+
/// `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`.
|
|
258
|
+
/// Today it invalidates the cache and triggers an immediate refresh; the
|
|
259
|
+
/// APNs cert / backend push-send service are follow-up work tracked in
|
|
260
|
+
/// the Phase 5 PR description.
|
|
261
|
+
public func handleSilentPush(_ userInfo: [AnyHashable: Any]) {
|
|
262
|
+
// We don't currently inspect `userInfo` — the policy is "any push
|
|
263
|
+
// means our cache is stale; refresh from the source of truth."
|
|
264
|
+
// Future work: read a `version` token from the push payload to
|
|
265
|
+
// skip refresh when it's not newer than what we already have.
|
|
266
|
+
_ = userInfo
|
|
267
|
+
invalidate()
|
|
268
|
+
Task {
|
|
269
|
+
do { _ = try await refresh() }
|
|
270
|
+
catch {
|
|
271
|
+
os_log(
|
|
272
|
+
"EntitlementsService: silent-push refresh failed: %{public}@",
|
|
273
|
+
log: log,
|
|
274
|
+
type: .info,
|
|
275
|
+
String(describing: error)
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// MARK: Test seams
|
|
282
|
+
|
|
283
|
+
/// Test seam — reset all in-memory + on-disk state and the configured
|
|
284
|
+
/// hooks. Used by `EntitlementsCacheTest` between cases.
|
|
285
|
+
internal func _resetForTesting() {
|
|
286
|
+
queue.sync {
|
|
287
|
+
clearDiskLocked()
|
|
288
|
+
cachedSnapshot = nil
|
|
289
|
+
cacheLoaded = false
|
|
290
|
+
inflightRefresh = nil
|
|
291
|
+
streamContinuations.removeAll()
|
|
292
|
+
serverURL = nil
|
|
293
|
+
apiKey = nil
|
|
294
|
+
currentUserId = nil
|
|
295
|
+
transport = BackendHttpClientEntitlementsTransport()
|
|
296
|
+
now = { Date() }
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/// Test seam — write a known cache entry to disk so tests can exercise
|
|
301
|
+
/// the read path without going through `refresh()`.
|
|
302
|
+
internal func _seedCacheForTesting(_ info: CustomerInfo, fetchedAt: Date) {
|
|
303
|
+
queue.sync {
|
|
304
|
+
let cached = CachedCustomerInfo(customerInfo: info, fetchedAt: fetchedAt)
|
|
305
|
+
cachedSnapshot = cached
|
|
306
|
+
cacheLoaded = true
|
|
307
|
+
try? writeToDiskLocked(cached)
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// MARK: Internals — refresh implementation
|
|
312
|
+
|
|
313
|
+
private func performRefresh() async throws -> CustomerInfo {
|
|
314
|
+
let (urlOpt, apiKey, userId) = queue.sync {
|
|
315
|
+
(self.serverURL, self.apiKey, self.currentUserId)
|
|
316
|
+
}
|
|
317
|
+
guard let apiKey, !apiKey.isEmpty else {
|
|
318
|
+
throw PurchasesError.notConfigured
|
|
319
|
+
}
|
|
320
|
+
let base = (urlOpt?.isEmpty == false ? urlOpt! : "https://api.swiss-knife.dev")
|
|
321
|
+
.trimmingTrailingSlash()
|
|
322
|
+
// Effective user id: the configured one, else the SDK's anonymous id.
|
|
323
|
+
// We fall back to the keychain-backed device id so first-launch
|
|
324
|
+
// refresh still has *something* to identify the user with.
|
|
325
|
+
let effectiveUserId = (userId?.isEmpty == false) ? userId! : DeviceID.get()
|
|
326
|
+
let urlString = "\(base)/api/sdk/entitlements/list?user_id=\(effectiveUserId)"
|
|
327
|
+
guard let url = URL(string: urlString) else {
|
|
328
|
+
throw PurchasesError.unknown(message: "Invalid entitlements URL: \(urlString)")
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
let response = try await transport.fetch(url: url, apiKey: apiKey)
|
|
332
|
+
|
|
333
|
+
guard (200...299).contains(response.statusCode) else {
|
|
334
|
+
// 401/403/404 are non-retriable signals; 5xx is retriable. We
|
|
335
|
+
// surface both as typed errors and let the caller decide.
|
|
336
|
+
if response.statusCode >= 500 {
|
|
337
|
+
throw PurchasesError.backendUnavailable(
|
|
338
|
+
statusCode: response.statusCode,
|
|
339
|
+
message: response.errorMessage
|
|
340
|
+
)
|
|
341
|
+
} else {
|
|
342
|
+
throw PurchasesError.backendRejected(
|
|
343
|
+
statusCode: response.statusCode,
|
|
344
|
+
message: response.errorMessage
|
|
345
|
+
)
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
let info: CustomerInfo
|
|
349
|
+
do {
|
|
350
|
+
info = try parseCustomerInfo(
|
|
351
|
+
data: response.body,
|
|
352
|
+
originalAppUserId: effectiveUserId
|
|
353
|
+
)
|
|
354
|
+
} catch {
|
|
355
|
+
throw PurchasesError.unknown(message: "Failed to decode entitlements response: \(error)")
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Update cache atomically + fan out to subscribers.
|
|
359
|
+
queue.sync {
|
|
360
|
+
let cached = CachedCustomerInfo(customerInfo: info, fetchedAt: now())
|
|
361
|
+
cachedSnapshot = cached
|
|
362
|
+
cacheLoaded = true
|
|
363
|
+
do { try writeToDiskLocked(cached) }
|
|
364
|
+
catch {
|
|
365
|
+
os_log(
|
|
366
|
+
"EntitlementsService: failed to write cache to disk: %{public}@",
|
|
367
|
+
log: log,
|
|
368
|
+
type: .error,
|
|
369
|
+
String(describing: error)
|
|
370
|
+
)
|
|
371
|
+
}
|
|
372
|
+
for c in streamContinuations.values { c.yield(info) }
|
|
373
|
+
}
|
|
374
|
+
return info
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/// Parse the backend's `/api/sdk/entitlements/list` JSON response into
|
|
378
|
+
/// a `CustomerInfo`. The endpoint mirrors RC's
|
|
379
|
+
/// `getOrCreateSubscriber` shape — top-level
|
|
380
|
+
/// `{ entitlements: {<key>: {...}}, original_purchase_date, ... }`. If
|
|
381
|
+
/// fields are missing we fall back to safe defaults so a partial
|
|
382
|
+
/// backend response still surfaces *something* useful to the SDK
|
|
383
|
+
/// consumer.
|
|
384
|
+
private func parseCustomerInfo(
|
|
385
|
+
data: Data,
|
|
386
|
+
originalAppUserId: String
|
|
387
|
+
) throws -> CustomerInfo {
|
|
388
|
+
// Empty body → empty CustomerInfo. Treat as "user has no
|
|
389
|
+
// entitlements" rather than throwing — keeps the offline grace path
|
|
390
|
+
// benign.
|
|
391
|
+
guard !data.isEmpty,
|
|
392
|
+
let json = try? JSONSerialization.jsonObject(with: data, options: []),
|
|
393
|
+
let dict = json as? [String: Any] else {
|
|
394
|
+
return CustomerInfo.empty(originalAppUserId: originalAppUserId)
|
|
395
|
+
}
|
|
396
|
+
let entitlementsJSON = (dict["entitlements"] as? [String: Any]) ?? [:]
|
|
397
|
+
var all: [String: EntitlementInfo] = [:]
|
|
398
|
+
for (key, raw) in entitlementsJSON {
|
|
399
|
+
guard let entDict = raw as? [String: Any] else { continue }
|
|
400
|
+
let info = decodeEntitlementInfo(key: key, dict: entDict)
|
|
401
|
+
all[key] = info
|
|
402
|
+
}
|
|
403
|
+
let firstSeen = decodeDate(dict["first_seen"]) ?? Date()
|
|
404
|
+
let originalPurchaseDate = decodeDate(dict["original_purchase_date"])
|
|
405
|
+
let latestExpirationDate = decodeDate(dict["latest_expiration_date"])
|
|
406
|
+
var allPurchaseDates: [String: Date] = [:]
|
|
407
|
+
if let purchaseDates = dict["all_purchase_dates"] as? [String: Any] {
|
|
408
|
+
for (productId, raw) in purchaseDates {
|
|
409
|
+
if let d = decodeDate(raw) { allPurchaseDates[productId] = d }
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
let activeSubs: [String] = (dict["active_subscriptions"] as? [String]) ?? []
|
|
413
|
+
let mgmtURL = (dict["management_url"] as? String).flatMap(URL.init(string:))
|
|
414
|
+
return CustomerInfo(
|
|
415
|
+
entitlements: EntitlementInfos(all: all),
|
|
416
|
+
originalAppUserId: (dict["original_app_user_id"] as? String) ?? originalAppUserId,
|
|
417
|
+
firstSeen: firstSeen,
|
|
418
|
+
originalPurchaseDate: originalPurchaseDate,
|
|
419
|
+
latestExpirationDate: latestExpirationDate,
|
|
420
|
+
allPurchaseDates: allPurchaseDates,
|
|
421
|
+
activeSubscriptions: activeSubs,
|
|
422
|
+
managementURL: mgmtURL
|
|
423
|
+
)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private func decodeEntitlementInfo(key: String, dict: [String: Any]) -> EntitlementInfo {
|
|
427
|
+
let store: Store
|
|
428
|
+
switch (dict["store"] as? String)?.lowercased() {
|
|
429
|
+
case "app_store", "appstore": store = .appStore
|
|
430
|
+
case "play_store", "playstore": store = .playStore
|
|
431
|
+
default: store = .unknownStore
|
|
432
|
+
}
|
|
433
|
+
let periodType: PeriodType
|
|
434
|
+
switch (dict["period_type"] as? String)?.lowercased() {
|
|
435
|
+
case "trial": periodType = .trial
|
|
436
|
+
case "intro": periodType = .intro
|
|
437
|
+
default: periodType = .normal
|
|
438
|
+
}
|
|
439
|
+
let ownership: OwnershipType
|
|
440
|
+
switch (dict["ownership_type"] as? String)?.lowercased() {
|
|
441
|
+
case "family_shared", "familyshared": ownership = .familyShared
|
|
442
|
+
default: ownership = .purchased
|
|
443
|
+
}
|
|
444
|
+
return EntitlementInfo(
|
|
445
|
+
identifier: key,
|
|
446
|
+
isActive: (dict["is_active"] as? Bool) ?? false,
|
|
447
|
+
willRenew: (dict["will_renew"] as? Bool) ?? false,
|
|
448
|
+
latestPurchaseDate: decodeDate(dict["latest_purchase_date"]) ?? Date(),
|
|
449
|
+
expirationDate: decodeDate(dict["expiration_date"]),
|
|
450
|
+
productIdentifier: (dict["product_identifier"] as? String) ?? "",
|
|
451
|
+
productPlanIdentifier: dict["product_plan_identifier"] as? String,
|
|
452
|
+
isSandbox: (dict["is_sandbox"] as? Bool) ?? false,
|
|
453
|
+
unsubscribeDetectedAt: decodeDate(dict["unsubscribe_detected_at"]),
|
|
454
|
+
billingIssueDetectedAt: decodeDate(dict["billing_issue_detected_at"]),
|
|
455
|
+
periodType: periodType,
|
|
456
|
+
store: store,
|
|
457
|
+
ownershipType: ownership
|
|
458
|
+
)
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
private func decodeDate(_ raw: Any?) -> Date? {
|
|
462
|
+
if let iso = raw as? String, !iso.isEmpty {
|
|
463
|
+
let formatter = ISO8601DateFormatter()
|
|
464
|
+
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
465
|
+
if let d = formatter.date(from: iso) { return d }
|
|
466
|
+
formatter.formatOptions = [.withInternetDateTime]
|
|
467
|
+
return formatter.date(from: iso)
|
|
468
|
+
}
|
|
469
|
+
if let epochMs = raw as? Double {
|
|
470
|
+
return Date(timeIntervalSince1970: epochMs / 1000.0)
|
|
471
|
+
}
|
|
472
|
+
if let epochInt = raw as? Int {
|
|
473
|
+
return Date(timeIntervalSince1970: TimeInterval(epochInt) / 1000.0)
|
|
474
|
+
}
|
|
475
|
+
return nil
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// MARK: Internals — disk I/O (called from `queue`)
|
|
479
|
+
|
|
480
|
+
private func loadFromDiskIfNeededLocked() -> CachedCustomerInfo? {
|
|
481
|
+
if cacheLoaded { return cachedSnapshot }
|
|
482
|
+
cacheLoaded = true
|
|
483
|
+
guard FileManager.default.fileExists(atPath: cacheFileURL.path) else {
|
|
484
|
+
return nil
|
|
485
|
+
}
|
|
486
|
+
do {
|
|
487
|
+
let data = try Data(contentsOf: cacheFileURL)
|
|
488
|
+
guard !data.isEmpty else { return nil }
|
|
489
|
+
let cached = try Self.decodeCacheFile(data: data)
|
|
490
|
+
cachedSnapshot = cached
|
|
491
|
+
return cached
|
|
492
|
+
} catch {
|
|
493
|
+
os_log(
|
|
494
|
+
"EntitlementsService: failed to read cache file (%{public}@); deleting and starting fresh",
|
|
495
|
+
log: log,
|
|
496
|
+
type: .error,
|
|
497
|
+
String(describing: error)
|
|
498
|
+
)
|
|
499
|
+
try? FileManager.default.removeItem(at: cacheFileURL)
|
|
500
|
+
return nil
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
private func writeToDiskLocked(_ cached: CachedCustomerInfo) throws {
|
|
505
|
+
let data = try Self.encodeCacheFile(cached)
|
|
506
|
+
let tmp = cacheFileURL.appendingPathExtension("tmp")
|
|
507
|
+
if FileManager.default.fileExists(atPath: tmp.path) {
|
|
508
|
+
try FileManager.default.removeItem(at: tmp)
|
|
509
|
+
}
|
|
510
|
+
try data.write(to: tmp, options: .atomic)
|
|
511
|
+
if FileManager.default.fileExists(atPath: cacheFileURL.path) {
|
|
512
|
+
_ = try FileManager.default.replaceItemAt(cacheFileURL, withItemAt: tmp)
|
|
513
|
+
} else {
|
|
514
|
+
try FileManager.default.moveItem(at: tmp, to: cacheFileURL)
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
private func clearDiskLocked() {
|
|
519
|
+
if FileManager.default.fileExists(atPath: cacheFileURL.path) {
|
|
520
|
+
try? FileManager.default.removeItem(at: cacheFileURL)
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// MARK: Static helpers
|
|
525
|
+
|
|
526
|
+
private static func ensureDirectory(_ url: URL) throws {
|
|
527
|
+
var isDir: ObjCBool = false
|
|
528
|
+
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) {
|
|
529
|
+
if isDir.boolValue { return }
|
|
530
|
+
throw NSError(
|
|
531
|
+
domain: "com.swissknife.entitlements",
|
|
532
|
+
code: 1,
|
|
533
|
+
userInfo: [NSLocalizedDescriptionKey: "Path exists and is not a directory: \(url.path)"]
|
|
534
|
+
)
|
|
535
|
+
}
|
|
536
|
+
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private static func encodeCacheFile(_ cached: CachedCustomerInfo) throws -> Data {
|
|
540
|
+
let encoder = JSONEncoder()
|
|
541
|
+
encoder.dateEncodingStrategy = .iso8601
|
|
542
|
+
let infoData = try encoder.encode(cached.customerInfo)
|
|
543
|
+
let infoObj = try JSONSerialization.jsonObject(with: infoData, options: [])
|
|
544
|
+
let wrapper: [String: Any] = [
|
|
545
|
+
"fetchedAt": cached.fetchedAt.timeIntervalSince1970 * 1000,
|
|
546
|
+
"customerInfo": infoObj,
|
|
547
|
+
]
|
|
548
|
+
return try JSONSerialization.data(withJSONObject: wrapper, options: [])
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
private static func decodeCacheFile(data: Data) throws -> CachedCustomerInfo {
|
|
552
|
+
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
|
|
553
|
+
let fetchedAtMs = json["fetchedAt"] as? Double,
|
|
554
|
+
let infoObj = json["customerInfo"] else {
|
|
555
|
+
throw NSError(
|
|
556
|
+
domain: "com.swissknife.entitlements",
|
|
557
|
+
code: 2,
|
|
558
|
+
userInfo: [NSLocalizedDescriptionKey: "Malformed cache file structure"]
|
|
559
|
+
)
|
|
560
|
+
}
|
|
561
|
+
let infoData = try JSONSerialization.data(withJSONObject: infoObj, options: [])
|
|
562
|
+
let decoder = JSONDecoder()
|
|
563
|
+
decoder.dateDecodingStrategy = .iso8601
|
|
564
|
+
let info = try decoder.decode(CustomerInfo.self, from: infoData)
|
|
565
|
+
return CachedCustomerInfo(
|
|
566
|
+
customerInfo: info,
|
|
567
|
+
fetchedAt: Date(timeIntervalSince1970: fetchedAtMs / 1000.0)
|
|
568
|
+
)
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// MARK: - Cached wrapper
|
|
573
|
+
|
|
574
|
+
internal struct CachedCustomerInfo {
|
|
575
|
+
let customerInfo: CustomerInfo
|
|
576
|
+
let fetchedAt: Date
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// MARK: - Transport seam
|
|
580
|
+
|
|
581
|
+
internal struct EntitlementsTransportResponse {
|
|
582
|
+
let statusCode: Int
|
|
583
|
+
let body: Data
|
|
584
|
+
let errorMessage: String?
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
internal protocol EntitlementsTransport {
|
|
588
|
+
func fetch(url: URL, apiKey: String) async throws -> EntitlementsTransportResponse
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/// Production transport — delegates to `BackendHttpClient`. Splits the
|
|
592
|
+
/// inbound `(url, apiKey)` argument back into path + query and lets the
|
|
593
|
+
/// shared client re-assemble against its configured base URL. The shared
|
|
594
|
+
/// client also handles retry / Clock sync / X-API-Key injection so this
|
|
595
|
+
/// shim is intentionally thin.
|
|
596
|
+
internal final class BackendHttpClientEntitlementsTransport: EntitlementsTransport {
|
|
597
|
+
private let http: BackendHttpClient
|
|
598
|
+
|
|
599
|
+
init(http: BackendHttpClient = .shared) {
|
|
600
|
+
self.http = http
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
func fetch(url: URL, apiKey: String) async throws -> EntitlementsTransportResponse {
|
|
604
|
+
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
|
|
605
|
+
let path = components?.path ?? url.path
|
|
606
|
+
let query: [(String, String)] = (components?.queryItems ?? []).compactMap { item in
|
|
607
|
+
guard let value = item.value else { return nil }
|
|
608
|
+
return (item.name, value)
|
|
609
|
+
}
|
|
610
|
+
do {
|
|
611
|
+
let data = try await http.getRaw(path: path, query: query)
|
|
612
|
+
return EntitlementsTransportResponse(
|
|
613
|
+
statusCode: 200,
|
|
614
|
+
body: data,
|
|
615
|
+
errorMessage: nil
|
|
616
|
+
)
|
|
617
|
+
} catch let error as PurchasesError {
|
|
618
|
+
switch error {
|
|
619
|
+
case .backendRejected(let code, let msg):
|
|
620
|
+
return EntitlementsTransportResponse(
|
|
621
|
+
statusCode: code,
|
|
622
|
+
body: Data(),
|
|
623
|
+
errorMessage: msg
|
|
624
|
+
)
|
|
625
|
+
case .backendUnavailable(let code, let msg):
|
|
626
|
+
return EntitlementsTransportResponse(
|
|
627
|
+
statusCode: code ?? 503,
|
|
628
|
+
body: Data(),
|
|
629
|
+
errorMessage: msg
|
|
630
|
+
)
|
|
631
|
+
default:
|
|
632
|
+
throw error
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// MARK: - String helper (mirrors AttributesClient's)
|
|
639
|
+
|
|
640
|
+
private extension String {
|
|
641
|
+
func trimmingTrailingSlash() -> String {
|
|
642
|
+
var s = self
|
|
643
|
+
while s.hasSuffix("/") { s.removeLast() }
|
|
644
|
+
return s
|
|
645
|
+
}
|
|
646
|
+
}
|