@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,329 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Net/BackendHttpClient.swift
|
|
2
|
+
//
|
|
3
|
+
// Wave 3 unified Net layer — single iOS HTTP primitive for every backend
|
|
4
|
+
// call the SDK makes. Replaces the per-feature transports (each now a
|
|
5
|
+
// thin `BackendHttpClient*` shim that delegates here):
|
|
6
|
+
// - EventTransport (Analytics) — supplanted by IngestClient
|
|
7
|
+
// which itself sits on top of this client
|
|
8
|
+
// - IdentityNetwork — `post` to /api/sdk/users/identify
|
|
9
|
+
// - AttributesTransport — `post` to /api/sdk/users/attributes
|
|
10
|
+
// - EntitlementsTransport — `get` /api/sdk/entitlements/list
|
|
11
|
+
// - OfferingsTransport — `get` /api/sdk/offerings
|
|
12
|
+
// - AttributionNetwork — `post` /api/sdk/attribution/install
|
|
13
|
+
//
|
|
14
|
+
// Design decisions:
|
|
15
|
+
// - Adds `X-API-Key` automatically using `SwissKnife.identityConfigSnapshot()`.
|
|
16
|
+
// Callers never thread the API key through their own argument list.
|
|
17
|
+
// - Resolves base URL from the configured serverURL (proxyURL on
|
|
18
|
+
// `SwissKnife.configure(...)`), falling back to the production host.
|
|
19
|
+
// - One retry policy via `ExponentialBackoff` — same schedule everywhere.
|
|
20
|
+
// The number of retries is per-call (`maxRetries` argument) so identify
|
|
21
|
+
// can keep its tight 3-retry budget while the ingest pipeline uses a
|
|
22
|
+
// looser 5-retry budget.
|
|
23
|
+
// - Distinguishes 4xx (terminal, `backendRejected`) from 5xx /
|
|
24
|
+
// network-level errors (retriable, `backendUnavailable`). 429 is
|
|
25
|
+
// retried with respect for the `Retry-After` header.
|
|
26
|
+
// - Decoding is done by the caller via generics so each feature owns its
|
|
27
|
+
// own response shape — no monolithic response wrapper.
|
|
28
|
+
|
|
29
|
+
import Foundation
|
|
30
|
+
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// MARK: - Transport seam
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
/// Outcome of one HTTP attempt. `.success` covers any well-formed HTTP
|
|
36
|
+
/// response (2xx and non-2xx). `.failure` is reserved for transport-level
|
|
37
|
+
/// errors (DNS, TLS, timeout, etc).
|
|
38
|
+
internal struct BackendHttpResponse {
|
|
39
|
+
let statusCode: Int
|
|
40
|
+
let body: Data
|
|
41
|
+
let retryAfterSeconds: TimeInterval?
|
|
42
|
+
/// Parsed value of the response's `Date` HTTP header, if present.
|
|
43
|
+
/// `BackendHttpClient` feeds this into `Clock.applyServerTime(...)` on
|
|
44
|
+
/// every successful response so subsequent `Clock.now()` calls converge
|
|
45
|
+
/// on server wall-clock instead of trusting the device's clock.
|
|
46
|
+
let serverDate: Date?
|
|
47
|
+
|
|
48
|
+
init(
|
|
49
|
+
statusCode: Int,
|
|
50
|
+
body: Data,
|
|
51
|
+
retryAfterSeconds: TimeInterval?,
|
|
52
|
+
serverDate: Date? = nil
|
|
53
|
+
) {
|
|
54
|
+
self.statusCode = statusCode
|
|
55
|
+
self.body = body
|
|
56
|
+
self.retryAfterSeconds = retryAfterSeconds
|
|
57
|
+
self.serverDate = serverDate
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Thin protocol so tests can inject a `FakeBackendTransport` that scripts
|
|
62
|
+
/// a sequence of responses without touching the network. Production
|
|
63
|
+
/// implementation is `URLSessionBackendTransport`.
|
|
64
|
+
internal protocol BackendTransport: Sendable {
|
|
65
|
+
func perform(request: URLRequest) async throws -> BackendHttpResponse
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
internal final class URLSessionBackendTransport: BackendTransport, @unchecked Sendable {
|
|
69
|
+
private let session: URLSession
|
|
70
|
+
|
|
71
|
+
init(session: URLSession = .shared) {
|
|
72
|
+
self.session = session
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
func perform(request: URLRequest) async throws -> BackendHttpResponse {
|
|
76
|
+
let (data, response) = try await session.data(for: request)
|
|
77
|
+
guard let http = response as? HTTPURLResponse else {
|
|
78
|
+
throw PurchasesError.networkError(underlying: "Non-HTTP response")
|
|
79
|
+
}
|
|
80
|
+
let retryAfter = Self.parseRetryAfter(http.value(forHTTPHeaderField: "Retry-After"))
|
|
81
|
+
// Parse the `Date` header so BackendHttpClient can feed it into
|
|
82
|
+
// `Clock.applyServerTime` for skew correction.
|
|
83
|
+
let serverDate = Clock.parseHTTPDate(http.value(forHTTPHeaderField: "Date"))
|
|
84
|
+
return BackendHttpResponse(
|
|
85
|
+
statusCode: http.statusCode,
|
|
86
|
+
body: data,
|
|
87
|
+
retryAfterSeconds: retryAfter,
|
|
88
|
+
serverDate: serverDate
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/// Parse the HTTP `Retry-After` header per RFC 7231 (integer-seconds
|
|
93
|
+
/// form). HTTP-date form is uncommon for 429 and would require
|
|
94
|
+
/// `DateFormatter` setup we'd rather not carry for one edge case.
|
|
95
|
+
private static func parseRetryAfter(_ raw: String?) -> TimeInterval? {
|
|
96
|
+
guard let raw = raw?.trimmingCharacters(in: .whitespaces), !raw.isEmpty else {
|
|
97
|
+
return nil
|
|
98
|
+
}
|
|
99
|
+
if let secs = TimeInterval(raw), secs >= 0 { return secs }
|
|
100
|
+
return nil
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
// MARK: - BackendHttpClient
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
/// Single HTTP primitive for every backend call. Internal — only the
|
|
109
|
+
/// per-feature clients (`IngestClient`, `IdentityNetwork`, ...) should
|
|
110
|
+
/// reach for this directly.
|
|
111
|
+
internal final class BackendHttpClient: @unchecked Sendable {
|
|
112
|
+
|
|
113
|
+
/// Shared, lazily-configured production instance. Tests should
|
|
114
|
+
/// construct their own with an injected `BackendTransport` rather than
|
|
115
|
+
/// mutating this one.
|
|
116
|
+
static let shared = BackendHttpClient()
|
|
117
|
+
|
|
118
|
+
private let transport: BackendTransport
|
|
119
|
+
private let backoff: ExponentialBackoff
|
|
120
|
+
private let configResolver: @Sendable () -> (apiKey: String, baseURL: String?)
|
|
121
|
+
private let encoder: JSONEncoder
|
|
122
|
+
private let decoder: JSONDecoder
|
|
123
|
+
|
|
124
|
+
init(
|
|
125
|
+
transport: BackendTransport = URLSessionBackendTransport(),
|
|
126
|
+
backoff: ExponentialBackoff = ExponentialBackoff(),
|
|
127
|
+
configResolver: @escaping @Sendable () -> (apiKey: String, baseURL: String?)
|
|
128
|
+
= { SwissKnife.identityConfigSnapshot() },
|
|
129
|
+
encoder: JSONEncoder = JSONEncoder(),
|
|
130
|
+
decoder: JSONDecoder = JSONDecoder()
|
|
131
|
+
) {
|
|
132
|
+
self.transport = transport
|
|
133
|
+
self.backoff = backoff
|
|
134
|
+
self.configResolver = configResolver
|
|
135
|
+
self.encoder = encoder
|
|
136
|
+
self.decoder = decoder
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// MARK: - Public API
|
|
140
|
+
|
|
141
|
+
/// GET `path` with optional query parameters, decode the response body
|
|
142
|
+
/// as `R`. `path` is the route (no leading host) — e.g.
|
|
143
|
+
/// `"/api/sdk/entitlements/list"`.
|
|
144
|
+
func get<R: Decodable>(
|
|
145
|
+
path: String,
|
|
146
|
+
query: [(String, String)] = [],
|
|
147
|
+
maxRetries: Int = 3
|
|
148
|
+
) async throws -> R {
|
|
149
|
+
let data = try await getRaw(path: path, query: query, maxRetries: maxRetries)
|
|
150
|
+
return try decoder.decode(R.self, from: data)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/// GET returning the raw response body. Used by callers that need to
|
|
154
|
+
/// do custom decoding (e.g. partial-parse or shape-detection).
|
|
155
|
+
func getRaw(
|
|
156
|
+
path: String,
|
|
157
|
+
query: [(String, String)] = [],
|
|
158
|
+
maxRetries: Int = 3
|
|
159
|
+
) async throws -> Data {
|
|
160
|
+
let request = try makeRequest(method: "GET", path: path, query: query, body: nil)
|
|
161
|
+
let response = try await performWithRetries(request: request, maxRetries: maxRetries)
|
|
162
|
+
return response.body
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/// POST a `Codable` body and decode the response as `R`.
|
|
166
|
+
func post<R: Decodable, B: Encodable>(
|
|
167
|
+
path: String,
|
|
168
|
+
body: B,
|
|
169
|
+
maxRetries: Int = 3
|
|
170
|
+
) async throws -> R {
|
|
171
|
+
let bodyData = try encoder.encode(body)
|
|
172
|
+
let data = try await postRaw(path: path, body: bodyData, maxRetries: maxRetries)
|
|
173
|
+
return try decoder.decode(R.self, from: data)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/// POST a `Codable` body and discard the response body. Returns the
|
|
177
|
+
/// HTTP status code so callers can branch on 201-created vs 200-ok.
|
|
178
|
+
@discardableResult
|
|
179
|
+
func postIgnoringResponse<B: Encodable>(
|
|
180
|
+
path: String,
|
|
181
|
+
body: B,
|
|
182
|
+
maxRetries: Int = 3
|
|
183
|
+
) async throws -> Int {
|
|
184
|
+
let bodyData = try encoder.encode(body)
|
|
185
|
+
let request = try makeRequest(method: "POST", path: path, query: [], body: bodyData)
|
|
186
|
+
let response = try await performWithRetries(request: request, maxRetries: maxRetries)
|
|
187
|
+
return response.statusCode
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/// POST raw `Data` (already serialized) and return raw response body.
|
|
191
|
+
/// Used by `IngestClient` which builds the envelope itself.
|
|
192
|
+
func postRaw(
|
|
193
|
+
path: String,
|
|
194
|
+
body: Data,
|
|
195
|
+
maxRetries: Int = 3
|
|
196
|
+
) async throws -> Data {
|
|
197
|
+
let request = try makeRequest(method: "POST", path: path, query: [], body: body)
|
|
198
|
+
let response = try await performWithRetries(request: request, maxRetries: maxRetries)
|
|
199
|
+
return response.body
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// MARK: - Request construction
|
|
203
|
+
|
|
204
|
+
/// Build a `URLRequest` against the configured base URL. Adds the
|
|
205
|
+
/// `X-API-Key` header. Throws `PurchasesError.notConfigured` if the
|
|
206
|
+
/// SDK hasn't been configured yet.
|
|
207
|
+
func makeRequest(
|
|
208
|
+
method: String,
|
|
209
|
+
path: String,
|
|
210
|
+
query: [(String, String)],
|
|
211
|
+
body: Data?
|
|
212
|
+
) throws -> URLRequest {
|
|
213
|
+
let config = configResolver()
|
|
214
|
+
guard !config.apiKey.isEmpty else { throw PurchasesError.notConfigured }
|
|
215
|
+
|
|
216
|
+
let url = try Self.buildURL(baseURL: config.baseURL, path: path, query: query)
|
|
217
|
+
var request = URLRequest(url: url)
|
|
218
|
+
request.httpMethod = method
|
|
219
|
+
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
220
|
+
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
|
221
|
+
request.setValue(config.apiKey, forHTTPHeaderField: "X-API-Key")
|
|
222
|
+
if let body = body {
|
|
223
|
+
request.httpBody = body
|
|
224
|
+
}
|
|
225
|
+
return request
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// MARK: - Retry loop
|
|
229
|
+
|
|
230
|
+
/// Drive the bounded retry loop. Returns on 2xx, throws `backendRejected`
|
|
231
|
+
/// on 4xx (no retries — 4xx is terminal), throws `backendUnavailable`
|
|
232
|
+
/// after exhausting the retry budget for 5xx / network errors. 429 is
|
|
233
|
+
/// retried up to `maxRetries` with respect for the `Retry-After` header.
|
|
234
|
+
private func performWithRetries(
|
|
235
|
+
request: URLRequest,
|
|
236
|
+
maxRetries: Int
|
|
237
|
+
) async throws -> BackendHttpResponse {
|
|
238
|
+
var attempt = 0
|
|
239
|
+
var lastError: Error?
|
|
240
|
+
while true {
|
|
241
|
+
do {
|
|
242
|
+
let response = try await transport.perform(request: request)
|
|
243
|
+
if (200...299).contains(response.statusCode) {
|
|
244
|
+
// Feed any observed server Date into Clock so subsequent
|
|
245
|
+
// `Clock.now()` calls converge on server wall-clock.
|
|
246
|
+
if let serverDate = response.serverDate {
|
|
247
|
+
Clock.applyServerTime(serverDate, localObservedAt: Date())
|
|
248
|
+
}
|
|
249
|
+
return response
|
|
250
|
+
}
|
|
251
|
+
if response.statusCode == 429 || response.statusCode >= 500 {
|
|
252
|
+
if attempt < maxRetries {
|
|
253
|
+
try await sleep(forAttempt: attempt, honoring: response.retryAfterSeconds)
|
|
254
|
+
attempt += 1
|
|
255
|
+
continue
|
|
256
|
+
}
|
|
257
|
+
let msg = Self.extractMessage(from: response.body)
|
|
258
|
+
throw PurchasesError.backendUnavailable(
|
|
259
|
+
statusCode: response.statusCode,
|
|
260
|
+
message: msg
|
|
261
|
+
)
|
|
262
|
+
}
|
|
263
|
+
// 4xx (other than 429) — terminal.
|
|
264
|
+
let msg = Self.extractMessage(from: response.body)
|
|
265
|
+
throw PurchasesError.backendRejected(
|
|
266
|
+
statusCode: response.statusCode,
|
|
267
|
+
message: msg
|
|
268
|
+
)
|
|
269
|
+
} catch let error as PurchasesError {
|
|
270
|
+
throw error
|
|
271
|
+
} catch {
|
|
272
|
+
// Network-level error (DNS, TLS, timeout) — retry.
|
|
273
|
+
if attempt < maxRetries {
|
|
274
|
+
try await sleep(forAttempt: attempt, honoring: nil)
|
|
275
|
+
attempt += 1
|
|
276
|
+
lastError = error
|
|
277
|
+
continue
|
|
278
|
+
}
|
|
279
|
+
throw PurchasesError.networkError(
|
|
280
|
+
underlying: (lastError ?? error).localizedDescription
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private func sleep(forAttempt attempt: Int, honoring retryAfter: TimeInterval?) async throws {
|
|
287
|
+
let delay = backoff.delay(forAttempt: attempt, honoring: retryAfter)
|
|
288
|
+
let nanos = UInt64(max(0, delay) * 1_000_000_000)
|
|
289
|
+
try await Task.sleep(nanoseconds: nanos)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// MARK: - Static helpers
|
|
293
|
+
|
|
294
|
+
/// Build a full URL by joining the (possibly nil/trimmed) baseURL with
|
|
295
|
+
/// the path and appending query parameters. The default production
|
|
296
|
+
/// host is `https://api.swiss-knife.dev`.
|
|
297
|
+
static func buildURL(
|
|
298
|
+
baseURL: String?,
|
|
299
|
+
path: String,
|
|
300
|
+
query: [(String, String)]
|
|
301
|
+
) throws -> URL {
|
|
302
|
+
let base = (baseURL?.isEmpty == false ? baseURL! : "https://api.swiss-knife.dev")
|
|
303
|
+
var trimmedBase = base
|
|
304
|
+
while trimmedBase.hasSuffix("/") { trimmedBase.removeLast() }
|
|
305
|
+
let leadingPath = path.hasPrefix("/") ? path : "/\(path)"
|
|
306
|
+
let raw = "\(trimmedBase)\(leadingPath)"
|
|
307
|
+
guard var components = URLComponents(string: raw) else {
|
|
308
|
+
throw PurchasesError.unknown(message: "Invalid URL: \(raw)")
|
|
309
|
+
}
|
|
310
|
+
if !query.isEmpty {
|
|
311
|
+
components.queryItems = query.map { URLQueryItem(name: $0.0, value: $0.1) }
|
|
312
|
+
}
|
|
313
|
+
guard let url = components.url else {
|
|
314
|
+
throw PurchasesError.unknown(message: "Invalid URL components for: \(raw)")
|
|
315
|
+
}
|
|
316
|
+
return url
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/// Pull an `error` field out of a JSON error body if present. Best-effort
|
|
320
|
+
/// — non-JSON bodies (e.g. an HTML error page from a misconfigured
|
|
321
|
+
/// reverse proxy) yield `nil` and the caller falls back to the HTTP
|
|
322
|
+
/// status code as the only signal.
|
|
323
|
+
private static func extractMessage(from body: Data) -> String? {
|
|
324
|
+
guard
|
|
325
|
+
let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any]
|
|
326
|
+
else { return nil }
|
|
327
|
+
return json["error"] as? String
|
|
328
|
+
}
|
|
329
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Net/ExponentialBackoff.swift
|
|
2
|
+
//
|
|
3
|
+
// Wave 3 unified Net layer — exponential back-off with bounded jitter,
|
|
4
|
+
// reusable across IngestClient, BackendHttpClient, Identity, and
|
|
5
|
+
// Attribution. Replaces the per-module `BackoffPolicy` that used to live
|
|
6
|
+
// under `Analytics/`. The Analytics-flavoured `BackoffPolicy` is kept as a
|
|
7
|
+
// thin wrapper around this type for back-compat with existing tests.
|
|
8
|
+
//
|
|
9
|
+
// Schedule, per spec (defaults below):
|
|
10
|
+
// attempt 0 → 1s, attempt 1 → 2s, attempt 2 → 4s, attempt 3 → 8s,
|
|
11
|
+
// attempt 4 → 16s, capped at 30s. Each delay is multiplied by
|
|
12
|
+
// `(1 + r * jitter)` where `r ∈ [-1.0, +1.0]` from the random source.
|
|
13
|
+
//
|
|
14
|
+
// `429` handling lives one level up: when the server returns a `Retry-After`
|
|
15
|
+
// header callers use `delayHonoring(retryAfter:)` so the client never
|
|
16
|
+
// retries sooner than the server explicitly requested.
|
|
17
|
+
|
|
18
|
+
import Foundation
|
|
19
|
+
|
|
20
|
+
/// Stateless policy object — all parameters passed per-call. A struct keeps
|
|
21
|
+
/// testing trivial (no shared mutable state) and the type is `Sendable` so
|
|
22
|
+
/// it can be passed across actor boundaries from the IngestClient flush
|
|
23
|
+
/// task.
|
|
24
|
+
internal struct ExponentialBackoff: Sendable {
|
|
25
|
+
|
|
26
|
+
/// Default initial delay (1s) → 1/2/4/8/16s schedule with multiplier 2.
|
|
27
|
+
let initialSeconds: TimeInterval
|
|
28
|
+
|
|
29
|
+
/// Geometric multiplier. 2 gives the canonical 1/2/4/8/16 pattern.
|
|
30
|
+
let multiplier: Double
|
|
31
|
+
|
|
32
|
+
/// Hard cap before jitter — beyond this the exponential is clamped.
|
|
33
|
+
let maxSeconds: TimeInterval
|
|
34
|
+
|
|
35
|
+
/// Symmetric jitter fraction. 0.25 means each delay is multiplied by
|
|
36
|
+
/// a uniform random in [0.75, 1.25].
|
|
37
|
+
let jitterFraction: Double
|
|
38
|
+
|
|
39
|
+
/// Maximum number of retries before the caller should dead-letter or
|
|
40
|
+
/// surface failure. The initial attempt is NOT counted as a retry.
|
|
41
|
+
let cap: Int
|
|
42
|
+
|
|
43
|
+
/// Random source — overrideable for deterministic tests. Returns a
|
|
44
|
+
/// value in `[-1.0, 1.0]`.
|
|
45
|
+
let randomSource: @Sendable () -> Double
|
|
46
|
+
|
|
47
|
+
init(
|
|
48
|
+
initialSeconds: TimeInterval = 1.0,
|
|
49
|
+
multiplier: Double = 2.0,
|
|
50
|
+
maxSeconds: TimeInterval = 30.0,
|
|
51
|
+
jitterFraction: Double = 0.25,
|
|
52
|
+
cap: Int = 5,
|
|
53
|
+
randomSource: @escaping @Sendable () -> Double = { Double.random(in: -1.0...1.0) }
|
|
54
|
+
) {
|
|
55
|
+
self.initialSeconds = initialSeconds
|
|
56
|
+
self.multiplier = multiplier
|
|
57
|
+
self.maxSeconds = maxSeconds
|
|
58
|
+
self.jitterFraction = jitterFraction
|
|
59
|
+
self.cap = cap
|
|
60
|
+
self.randomSource = randomSource
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// Compute the delay for the given 0-indexed retry attempt.
|
|
64
|
+
///
|
|
65
|
+
/// `attempt = 0` is the FIRST retry (after the original send failed).
|
|
66
|
+
/// The jitter is `randomSource()` (clamped to `[-1, 1]`) multiplied by
|
|
67
|
+
/// `jitterFraction` and added to 1, so the effective multiplier is
|
|
68
|
+
/// `[1 - jitterFraction, 1 + jitterFraction]`.
|
|
69
|
+
func delay(forAttempt attempt: Int) -> TimeInterval {
|
|
70
|
+
let exponential = initialSeconds * pow(multiplier, Double(attempt))
|
|
71
|
+
let capped = min(exponential, maxSeconds)
|
|
72
|
+
let r = randomSource()
|
|
73
|
+
let clamped = max(-1.0, min(1.0, r))
|
|
74
|
+
let factor = 1.0 + clamped * jitterFraction
|
|
75
|
+
return capped * factor
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// Compute the delay for the given attempt, but never return less than
|
|
79
|
+
/// the server-advertised `retryAfter`. The Retry-After value is honored
|
|
80
|
+
/// exactly (no jitter) so the client doesn't undershoot the server's
|
|
81
|
+
/// explicit request.
|
|
82
|
+
func delay(forAttempt attempt: Int, honoring retryAfter: TimeInterval?) -> TimeInterval {
|
|
83
|
+
let scheduled = delay(forAttempt: attempt)
|
|
84
|
+
guard let retryAfter = retryAfter, retryAfter > 0 else { return scheduled }
|
|
85
|
+
return max(scheduled, retryAfter)
|
|
86
|
+
}
|
|
87
|
+
}
|