@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.1

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.
Files changed (185) hide show
  1. package/CHANGELOG.md +473 -2
  2. package/LICENSE +21 -0
  3. package/README.md +279 -47
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +20 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/GENERATED.md +1 -0
  14. package/android/vendor/java/com/appswissknife/SwissKnife.kt +111 -38
  15. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  16. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  17. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  18. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  19. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  20. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  21. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  22. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  23. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  24. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  25. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  26. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  27. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  32. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  34. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  35. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +312 -65
  36. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  37. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +705 -96
  38. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  39. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +29 -0
  40. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +24 -0
  41. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  44. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  45. package/app.plugin.js +343 -0
  46. package/ios/SwissKnifeJSON.swift +24 -2
  47. package/ios/SwissKnifePurchases.m +20 -0
  48. package/ios/SwissKnifePurchases.swift +97 -3
  49. package/ios/SwissKnifePushBootstrap.m +34 -0
  50. package/ios/vendor/GENERATED.md +1 -0
  51. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  52. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  53. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  54. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  55. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  56. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  57. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  58. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  59. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  60. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  61. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  62. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
  63. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  64. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  65. package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
  66. package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
  67. package/ios-notification-service/vendor/GENERATED.md +11 -0
  68. package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
  69. package/lib/commonjs/attribution.js +4 -3
  70. package/lib/commonjs/attribution.js.map +1 -1
  71. package/lib/commonjs/identity.js +12 -11
  72. package/lib/commonjs/identity.js.map +1 -1
  73. package/lib/commonjs/index.js +16 -5
  74. package/lib/commonjs/index.js.map +1 -1
  75. package/lib/commonjs/internal/config.js +105 -8
  76. package/lib/commonjs/internal/config.js.map +1 -1
  77. package/lib/commonjs/internal/telemetry-context.js +70 -0
  78. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  79. package/lib/commonjs/modules/analytics.js +18 -25
  80. package/lib/commonjs/modules/analytics.js.map +1 -1
  81. package/lib/commonjs/modules/crash-reporting.js +27 -6
  82. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  83. package/lib/commonjs/modules/log.js +1 -1
  84. package/lib/commonjs/modules/notifications.js +500 -0
  85. package/lib/commonjs/modules/notifications.js.map +1 -0
  86. package/lib/commonjs/modules/performance.js +57 -8
  87. package/lib/commonjs/modules/performance.js.map +1 -1
  88. package/lib/commonjs/native/module.js +6 -0
  89. package/lib/commonjs/native/module.js.map +1 -1
  90. package/lib/commonjs/native/spec.js +12 -5
  91. package/lib/commonjs/native/spec.js.map +1 -1
  92. package/lib/commonjs/purchases.js +4 -4
  93. package/lib/commonjs/types.js +12 -15
  94. package/lib/commonjs/types.js.map +1 -1
  95. package/lib/module/attribution.js +4 -3
  96. package/lib/module/attribution.js.map +1 -1
  97. package/lib/module/identity.js +12 -11
  98. package/lib/module/identity.js.map +1 -1
  99. package/lib/module/index.js +8 -4
  100. package/lib/module/index.js.map +1 -1
  101. package/lib/module/internal/config.js +103 -8
  102. package/lib/module/internal/config.js.map +1 -1
  103. package/lib/module/internal/telemetry-context.js +63 -0
  104. package/lib/module/internal/telemetry-context.js.map +1 -0
  105. package/lib/module/modules/analytics.js +18 -25
  106. package/lib/module/modules/analytics.js.map +1 -1
  107. package/lib/module/modules/crash-reporting.js +27 -6
  108. package/lib/module/modules/crash-reporting.js.map +1 -1
  109. package/lib/module/modules/log.js +1 -1
  110. package/lib/module/modules/notifications.js +491 -0
  111. package/lib/module/modules/notifications.js.map +1 -0
  112. package/lib/module/modules/performance.js +57 -8
  113. package/lib/module/modules/performance.js.map +1 -1
  114. package/lib/module/native/module.js +6 -1
  115. package/lib/module/native/module.js.map +1 -1
  116. package/lib/module/native/spec.js +11 -4
  117. package/lib/module/native/spec.js.map +1 -1
  118. package/lib/module/purchases.js +4 -4
  119. package/lib/module/types.js +12 -15
  120. package/lib/module/types.js.map +1 -1
  121. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  122. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  123. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/index.d.ts +2 -0
  125. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  127. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  128. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  129. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  130. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  131. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  133. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  135. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  136. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  137. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  138. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  139. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  140. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  141. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  142. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  143. package/lib/typescript/commonjs/types.d.ts +4 -5
  144. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  145. package/lib/typescript/module/attribution.d.ts +3 -2
  146. package/lib/typescript/module/attribution.d.ts.map +1 -1
  147. package/lib/typescript/module/identity.d.ts.map +1 -1
  148. package/lib/typescript/module/index.d.ts +2 -0
  149. package/lib/typescript/module/index.d.ts.map +1 -1
  150. package/lib/typescript/module/internal/config.d.ts +16 -2
  151. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  152. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  153. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  154. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  155. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  156. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  157. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  158. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  159. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  160. package/lib/typescript/module/modules/performance.d.ts +13 -0
  161. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  162. package/lib/typescript/module/native/module.d.ts +2 -0
  163. package/lib/typescript/module/native/module.d.ts.map +1 -1
  164. package/lib/typescript/module/native/spec.d.ts +33 -4
  165. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  166. package/lib/typescript/module/purchases.d.ts +4 -4
  167. package/lib/typescript/module/types.d.ts +4 -5
  168. package/lib/typescript/module/types.d.ts.map +1 -1
  169. package/package.json +13 -4
  170. package/src/attribution.ts +4 -3
  171. package/src/identity.ts +12 -11
  172. package/src/index.ts +16 -4
  173. package/src/internal/config.ts +113 -8
  174. package/src/internal/telemetry-context.ts +76 -0
  175. package/src/modules/analytics.ts +24 -33
  176. package/src/modules/crash-reporting.ts +50 -9
  177. package/src/modules/log.ts +1 -1
  178. package/src/modules/notifications.ts +557 -0
  179. package/src/modules/performance.ts +94 -14
  180. package/src/native/module.ts +6 -0
  181. package/src/native/spec.ts +45 -10
  182. package/src/purchases.ts +4 -4
  183. package/src/types.ts +12 -15
  184. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  185. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -6,23 +6,57 @@
6
6
  // Architecture:
7
7
  // - Owns a single BillingClient connected via startConnection. Connection
8
8
  // errors trigger exponential backoff reconnect (1s/2s/4s/8s/16s, cap 5).
9
+ // A purchase or restore that finds the client not ready resets that budget,
10
+ // reconnects, and runs once the client is connected.
11
+ // - Every OK setup (the first one comes from configure) reconciles: it
12
+ // queries SUBS and INAPP purchases and validates + acknowledges (or
13
+ // consumes, see below) each PURCHASED one that is still unacknowledged,
14
+ // and each consumable an earlier SDK left unconsumed, under the user id
15
+ // stamped on it at launch when there is one. Google auto-refunds an
16
+ // unacknowledged purchase after three days, and nothing server-side
17
+ // acknowledges on our behalf, so an ack lost to a network error or a
18
+ // process kill must be picked up here.
19
+ // - Only purchaseState == PURCHASED is validated or acknowledged. A PENDING
20
+ // purchase (cash, deferred payment) is reported to the in-flight call as
21
+ // PaymentPending; Play re-delivers it when the payment clears.
9
22
  // - All Play Billing callbacks are invoked on Play's executor (not main);
10
23
  // we surface them as-is - the gateway interface contract is "callbacks
11
24
  // may fire on any thread."
12
25
  // - Every successful purchase round-trips through our backend at
13
26
  // /api/sdk/subscriptions/validate before being surfaced as success. The
14
27
  // backend is authoritative for entitlement state per the locked decision.
15
- // - CustomerInfo reads delegate to EntitlementsRepository (24h cache).
28
+ // - CustomerInfo reads delegate to EntitlementsRepository (24h cache). Every
29
+ // validation the backend accepts (a purchase, a reconcile, a pending
30
+ // purchase that cleared, a restore) re-reads the entitlements into that
31
+ // cache, which tells the CustomerInfo listeners.
32
+ // - Subscriptions (SUBS) and one-time products (INAPP) alike: Play takes a
33
+ // product type on every query, so purchases and restores ask for both.
16
34
  //
17
35
  // What's intentionally NOT here:
18
36
  // - logIn/logOut don't actually exist in Play Billing - the SDK identity
19
37
  // model is ours, kept in [EntitlementsRepository.invalidate()] + a
20
38
  // userId mutable. We honor RC parity by exposing them on the gateway.
21
- // - Offerings/products fetching - that's OfferingsRepository (commit 4).
22
- // This gateway only queries ProductDetails on-demand for purchase.
23
- // - Acknowledge details: we acknowledge() non-consumed subscription /
24
- // non-consumable purchases. Consumables are NOT exposed today (RC parity:
25
- // RC didn't expose consume() either - those are managed by RC's backend).
39
+ // - Offerings/products fetching - that's OfferingsRepository, which
40
+ // SwissKnife.getOfferings() reads. This gateway only queries
41
+ // ProductDetails on-demand for purchase.
42
+ // - Acknowledge or consume: a purchase is consumed (consumeAsync, which also
43
+ // acknowledges it) only when the backend's validate answer for each of its
44
+ // products says `product_type: "consumable"`. That answer comes after the
45
+ // backend recorded the purchase in its ledger, so a crash or a failed
46
+ // consume never loses the credit, and the ledger is keyed on the purchase
47
+ // token, so validating it again never grants it twice. Anything else (a
48
+ // non-consumable, a subscription, an answer that names no type, a failed
49
+ // validate) keeps the acknowledge-only path: consuming a non-consumable
50
+ // would take a lifetime unlock away from the user.
51
+ // A consumable an earlier SDK only acknowledged is still owned on Play, so
52
+ // it cannot be bought again. The reconcile consumes it once the server's
53
+ // catalogue ([onServerProductTypes]) or an earlier validate answer says the
54
+ // product is a consumable, after validating it again; a restore consumes it
55
+ // too. Acknowledged purchases of any other product are never re-validated
56
+ // by the reconcile.
57
+ // acknowledge() and consume() check the BillingResult and retry a non-OK
58
+ // answer a bounded number of times; what is still unsettled after that is
59
+ // left to the next reconcile, and never fails the purchase call.
26
60
 
27
61
  package com.appswissknife.purchases
28
62
 
@@ -37,6 +71,7 @@ import com.android.billingclient.api.BillingClient
37
71
  import com.android.billingclient.api.BillingClientStateListener
38
72
  import com.android.billingclient.api.BillingFlowParams
39
73
  import com.android.billingclient.api.BillingResult
74
+ import com.android.billingclient.api.ConsumeParams
40
75
  import com.android.billingclient.api.PendingPurchasesParams
41
76
  import com.android.billingclient.api.ProductDetails
42
77
  import com.android.billingclient.api.Purchase
@@ -62,10 +97,13 @@ import java.io.IOException
62
97
  import java.util.Collections
63
98
  import java.util.Date
64
99
  import java.util.UUID
100
+ import java.util.concurrent.CountDownLatch
65
101
  import java.util.concurrent.ExecutorService
66
102
  import java.util.concurrent.Executors
103
+ import java.util.concurrent.TimeUnit
67
104
  import java.util.concurrent.atomic.AtomicBoolean
68
105
  import java.util.concurrent.atomic.AtomicInteger
106
+ import java.util.concurrent.atomic.AtomicReference
69
107
 
70
108
  /**
71
109
  * Production [PurchasesGateway] using Google Play Billing v8 directly. No
@@ -103,12 +141,51 @@ class BillingClientGateway(
103
141
  * dies. That is precisely why it must not be the normal path; see
104
142
  * [getAppUserID].
105
143
  */
106
- @Volatile private var fallbackAnonymousAppUserId: String =
107
- "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
144
+ @Volatile private var fallbackAnonymousAppUserId: String = newFallbackAnonymousId()
108
145
 
109
146
  private val configured = AtomicBoolean(false)
110
147
  private val reconnectAttempt = AtomicInteger(0)
111
148
 
149
+ /**
150
+ * Calls waiting for the client to connect: a purchase or restore that found
151
+ * it not ready. Drained by the next setup result, or failed by a timeout.
152
+ */
153
+ private val readyWaiters = mutableListOf<ReadyWaiter>()
154
+
155
+ /** One reconcile at a time; setups that land while one runs are covered by it. */
156
+ private val reconcileInFlight = AtomicBoolean(false)
157
+
158
+ /**
159
+ * Purchase tokens whose acknowledgement is in flight or succeeded in this
160
+ * process. Purchase objects are snapshots, so `isAcknowledged` can be stale
161
+ * when the purchase listener and a reconcile see the same purchase; this
162
+ * keeps them from acknowledging (and re-validating) it twice.
163
+ */
164
+ private val ackClaimed: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
165
+
166
+ /** Purchase tokens whose consume is in flight or succeeded in this process (see [ackClaimed]). */
167
+ private val consumeClaimed: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
168
+
169
+ /**
170
+ * The backend's product type (`auto_renewable`, `non_renewing`, `consumable`,
171
+ * `non_consumable`) of each product id it has described in this process: from
172
+ * the offerings it served ([onServerProductTypes]) and from validate answers.
173
+ * Only picks the acknowledged purchases a reconcile validates again; whether
174
+ * a purchase is consumed is decided by the validate answer itself.
175
+ */
176
+ private val serverProductTypes = java.util.concurrent.ConcurrentHashMap<String, String>()
177
+
178
+ /**
179
+ * Product ids a validate answer has typed in this process. The catalogue
180
+ * never overrides those: the validate answer is what decides a consume, and
181
+ * a catalogue row that disagrees with it would otherwise re-validate the
182
+ * purchase on every offerings read.
183
+ */
184
+ private val typedByValidate: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()
185
+
186
+ /** A reconcile was asked for while one was running; run another when it ends. */
187
+ private val reconcileAgain = AtomicBoolean(false)
188
+
112
189
  private val executor: ExecutorService =
113
190
  Executors.newSingleThreadExecutor { r -> Thread(r, "swissknife-billing").apply { isDaemon = true } }
114
191
 
@@ -153,30 +230,69 @@ class BillingClientGateway(
153
230
  userIdProvider = { getAppUserID() },
154
231
  )
155
232
  this.entitlementsRepo = repo
233
+ // A listener added before configure was only kept here; the repository is
234
+ // what announces each refresh, so hand it over.
235
+ synchronized(customerInfoListeners) { customerInfoListeners.toList() }.forEach(repo::addListener)
156
236
 
157
- val client = BillingClient.newBuilder(appContext)
158
- .setListener(this)
159
- .enablePendingPurchases(
160
- PendingPurchasesParams.newBuilder()
161
- .enableOneTimeProducts()
162
- .enablePrepaidPlans()
163
- .build()
164
- )
165
- .build()
166
- this.billingClient = client
237
+ this.billingClient = billingClientFactory(appContext, this)
238
+ // The first OK setup reconciles purchases left unacknowledged by an
239
+ // earlier process (see [reconcilePurchases]).
167
240
  connect()
168
241
  }
169
242
 
170
- /** Internal accessor for [PlayPriceEnrichmentProvider] - so it can issue
171
- * queryProductDetailsAsync calls via the same BillingClient this gateway
172
- * owns. */
243
+ /**
244
+ * Test seam: builds the [BillingClient]. Production builds Play's client;
245
+ * JVM tests hand back a fake so connection, reconcile and acknowledge paths
246
+ * run without Play.
247
+ */
248
+ @VisibleForTesting
249
+ internal var billingClientFactory: (Context, PurchasesUpdatedListener) -> BillingClient =
250
+ { context, listener ->
251
+ BillingClient.newBuilder(context)
252
+ .setListener(listener)
253
+ .enablePendingPurchases(
254
+ PendingPurchasesParams.newBuilder()
255
+ .enableOneTimeProducts()
256
+ .enablePrepaidPlans()
257
+ .build()
258
+ )
259
+ .build()
260
+ }
261
+
262
+ /** The BillingClient this gateway owns, connected or not (tests observe it). */
173
263
  @VisibleForTesting
174
264
  internal fun billingClientOrNull(): BillingClient? = billingClient
175
265
 
176
266
  /** Play Billing price enrichment for OfferingsRepository (Play types stay in
177
- * [PlayPriceEnrichmentProvider]). */
267
+ * [PlayPriceEnrichmentProvider]). It waits, bounded, for a connection in
268
+ * progress: an app that calls getOfferings() right after configure would
269
+ * otherwise find Play not connected yet and get no Play prices. */
178
270
  override fun priceEnrichmentProvider(): PriceEnrichmentProvider =
179
- PlayPriceEnrichmentProvider { billingClientOrNull() }
271
+ PlayPriceEnrichmentProvider { readyClientOrNull(PRICE_CONNECT_WAIT_MS) }
272
+
273
+ /**
274
+ * The connected client, waiting up to [timeoutMs] for it to connect (and
275
+ * connecting it if it is not, as a purchase does). Null when there is no
276
+ * client, the setup fails, or it does not finish in time. Blocks: call it
277
+ * off the main thread, as the offerings fetch does.
278
+ */
279
+ @VisibleForTesting
280
+ internal fun readyClientOrNull(timeoutMs: Long): BillingClient? {
281
+ val client = billingClient ?: return null
282
+ if (client.isReady) return client
283
+ val ready = AtomicReference<BillingClient?>(null)
284
+ val done = CountDownLatch(1)
285
+ withReadyClient(
286
+ onReady = { ready.set(it); done.countDown() },
287
+ onUnavailable = { done.countDown() },
288
+ )
289
+ try {
290
+ done.await(timeoutMs, TimeUnit.MILLISECONDS)
291
+ } catch (_: InterruptedException) {
292
+ Thread.currentThread().interrupt()
293
+ }
294
+ return ready.get()
295
+ }
180
296
 
181
297
  override fun isConfigured(): Boolean = configured.get()
182
298
 
@@ -239,11 +355,12 @@ class BillingClientGateway(
239
355
  onSuccess: (Offerings) -> Unit,
240
356
  onError: (PurchasesError) -> Unit,
241
357
  ) {
242
- // Offerings fetching lives in OfferingsRepository (commit 4). This
243
- // gateway intentionally returns an empty offerings set; SwissKnife will
244
- // be rewired in commit 5 to consult the OfferingsRepository directly.
245
- onError(PurchasesError.Unknown(
246
- "BillingClientGateway does not own offerings; use OfferingsRepository"
358
+ // SwissKnife.getOfferings() reads offerings through the OfferingsRepository
359
+ // that configurePurchases wires for this gateway, so this is reached only
360
+ // when nothing is configured yet.
361
+ onError(PurchasesError(
362
+ PurchasesErrorCode.ConfigurationError,
363
+ "Offerings are available once SwissKnife.configure has run",
247
364
  ))
248
365
  }
249
366
 
@@ -262,38 +379,25 @@ class BillingClientGateway(
262
379
  onSuccess: (StoreTransactionResult) -> Unit,
263
380
  onError: (PurchasesError, userCancelled: Boolean) -> Unit,
264
381
  ) {
265
- val client = billingClient
266
- if (client == null || !client.isReady) {
267
- onError(PurchasesError.StoreProblem("Billing client not ready"), false); return
268
- }
382
+ withReadyClient(
383
+ onReady = { client -> launchPurchase(client, activity, product, onSuccess, onError) },
384
+ onUnavailable = { onError(it, false) },
385
+ )
386
+ }
387
+
388
+ private fun launchPurchase(
389
+ client: BillingClient,
390
+ activity: Activity,
391
+ product: StoreProduct,
392
+ onSuccess: (StoreTransactionResult) -> Unit,
393
+ onError: (PurchasesError, userCancelled: Boolean) -> Unit,
394
+ ) {
269
395
  // Translate product into a Play Billing ProductDetails by re-querying.
270
396
  // We pay a roundtrip cost per purchase but the alternative (caching
271
397
  // ProductDetails graphs across the gateway boundary) leaks Play types.
272
- val productType = BillingClient.ProductType.SUBS // assume subscription;
273
- // for non-subs (one-time), the caller routes through purchaseStoreProduct
274
- // with a StoreProduct whose subscriptionPeriod is null - we'd ideally
275
- // branch here on `product.subscriptionPeriod`, but for Phase 6 SUBS is
276
- // the only path exercised; INAPP is left for follow-up.
277
- val params = QueryProductDetailsParams.newBuilder()
278
- .setProductList(
279
- listOf(
280
- QueryProductDetailsParams.Product.newBuilder()
281
- .setProductId(product.id)
282
- .setProductType(productType)
283
- .build()
284
- )
285
- )
286
- .build()
287
- client.queryProductDetailsAsync(params) { result, productDetailsResult ->
288
- if (result.responseCode != BillingClient.BillingResponseCode.OK) {
289
- onError(toPurchasesError(result), result.isUserCancelled()); return@queryProductDetailsAsync
290
- }
291
- val productDetailsList = productDetailsResult.productDetailsList
292
- val pd = productDetailsList.firstOrNull()
293
- if (pd == null) {
294
- onError(PurchasesError.ProductNotAvailable("No ProductDetails for ${product.id}"), false)
295
- return@queryProductDetailsAsync
296
- }
398
+ findProductDetails(client, product.id, productTypesFor(product), onError) { pd ->
399
+ // A subscription is bought through one of its offers. A one-time product
400
+ // needs no token: Play then sells its default purchase option.
297
401
  val offerToken = pd.subscriptionOfferDetails?.firstOrNull()?.offerToken
298
402
  val flowParamsBuilder = BillingFlowParams.ProductDetailsParams.newBuilder()
299
403
  .setProductDetails(pd)
@@ -306,36 +410,111 @@ class BillingClientGateway(
306
410
  val launchResult = client.launchBillingFlow(activity, flowParams)
307
411
  if (launchResult.responseCode != BillingClient.BillingResponseCode.OK) {
308
412
  pendingPurchase = null
413
+ if (launchResult.responseCode == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) reconcileSoon()
309
414
  onError(toPurchasesError(launchResult), launchResult.isUserCancelled())
310
415
  }
311
416
  }
312
417
  }
313
418
 
419
+ /**
420
+ * Find [productId]'s ProductDetails, asking Play for it as each of [types]
421
+ * in turn. Play answers a query for the wrong product type with no details,
422
+ * not an error, so the next type is asked only then; a Play error ends the
423
+ * search.
424
+ */
425
+ private fun findProductDetails(
426
+ client: BillingClient,
427
+ productId: String,
428
+ types: List<String>,
429
+ onError: (PurchasesError, userCancelled: Boolean) -> Unit,
430
+ onFound: (ProductDetails) -> Unit,
431
+ ) {
432
+ val params = QueryProductDetailsParams.newBuilder()
433
+ .setProductList(
434
+ listOf(
435
+ QueryProductDetailsParams.Product.newBuilder()
436
+ .setProductId(productId)
437
+ .setProductType(types.first())
438
+ .build()
439
+ )
440
+ )
441
+ .build()
442
+ client.queryProductDetailsAsync(params) { result, productDetailsResult ->
443
+ if (result.responseCode != BillingClient.BillingResponseCode.OK) {
444
+ onError(toPurchasesError(result), result.isUserCancelled()); return@queryProductDetailsAsync
445
+ }
446
+ val pd = productDetailsResult.productDetailsList.firstOrNull { it.productId == productId }
447
+ when {
448
+ pd != null -> onFound(pd)
449
+ types.size > 1 -> findProductDetails(client, productId, types.drop(1), onError, onFound)
450
+ else -> onError(PurchasesError.ProductNotAvailable("No ProductDetails for $productId"), false)
451
+ }
452
+ }
453
+ }
454
+
455
+ /**
456
+ * The Play product types to ask for [product] as, the likelier first. A
457
+ * product the SDK priced knows whether it is one-time ([ProductKindHint]);
458
+ * any other (a host's own, or one the React Native bridge built from an id)
459
+ * is asked for as a subscription first, as before one-time products were
460
+ * supported, so a subscription costs no extra query.
461
+ */
462
+ private fun productTypesFor(product: StoreProduct): List<String> =
463
+ if ((product as? ProductKindHint)?.isOneTime == true) {
464
+ listOf(BillingClient.ProductType.INAPP, BillingClient.ProductType.SUBS)
465
+ } else {
466
+ PRODUCT_TYPES
467
+ }
468
+
469
+ /**
470
+ * The backend's catalogue named these product types. A consumable learned
471
+ * here may be one an earlier SDK acknowledged and never consumed, which Play
472
+ * then refuses to sell again (ITEM_ALREADY_OWNED), so learning one runs a
473
+ * reconcile, which validates such a purchase again and consumes it if the
474
+ * backend confirms it is a consumable.
475
+ */
476
+ override fun onServerProductTypes(types: Map<String, String>) {
477
+ var learnedConsumable = false
478
+ for ((productId, type) in types) {
479
+ if (productId.isEmpty() || type.isEmpty() || productId in typedByValidate) continue
480
+ val previous = serverProductTypes.put(productId, type)
481
+ if (type == CONSUMABLE && previous != CONSUMABLE) learnedConsumable = true
482
+ }
483
+ if (learnedConsumable) reconcileSoon()
484
+ }
485
+
314
486
  override fun restorePurchases(
315
487
  onSuccess: (CustomerInfo) -> Unit,
316
488
  onError: (PurchasesError) -> Unit,
317
489
  ) {
318
- val client = billingClient
319
- if (client == null || !client.isReady) {
320
- onError(PurchasesError.StoreProblem("Billing client not ready")); return
321
- }
322
- val params = QueryPurchasesParams.newBuilder()
323
- .setProductType(BillingClient.ProductType.SUBS)
324
- .build()
325
- client.queryPurchasesAsync(params) { result, purchases ->
326
- if (result.responseCode != BillingClient.BillingResponseCode.OK) {
327
- onError(toPurchasesError(result)); return@queryPurchasesAsync
490
+ withReadyClient(
491
+ onReady = { client -> runRestore(client, onSuccess, onError) },
492
+ onUnavailable = onError,
493
+ )
494
+ }
495
+
496
+ private fun runRestore(
497
+ client: BillingClient,
498
+ onSuccess: (CustomerInfo) -> Unit,
499
+ onError: (PurchasesError) -> Unit,
500
+ ) {
501
+ // Subscriptions and one-time products (lifetime unlocks, and consumables
502
+ // nothing has consumed). A Play error on either query fails the restore
503
+ // rather than reporting a partial one as complete.
504
+ queryOwnedPurchases(client, PRODUCT_TYPES, mutableListOf()) { purchases, failure ->
505
+ if (failure != null) {
506
+ onError(toPurchasesError(failure)); return@queryOwnedPurchases
328
507
  }
329
508
  executor.execute {
330
509
  // Validate each purchase against the backend; the backend reconciles
331
510
  // entitlement state. Then refresh CustomerInfo from the repo.
332
511
  val errors = mutableListOf<Throwable>()
333
512
  for (p in purchases) {
334
- runCatching {
335
- for (productId in p.products) {
336
- validatePurchaseWithBackend(productId, p.purchaseToken)
337
- }
338
- }.onFailure { errors.add(it) }
513
+ // A pending payment is not a purchase yet: never validate or ack it.
514
+ if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
515
+ // Acknowledged consumables included: one the backend confirms as a
516
+ // consumable is consumed, so the user can buy it again.
517
+ runCatching { validateAndSettle(p) }.onFailure { errors.add(it) }
339
518
  }
340
519
  val repo = entitlementsRepo
341
520
  val info = try {
@@ -344,7 +523,7 @@ class BillingClientGateway(
344
523
  repo?.current() ?: emptyCustomerInfo()
345
524
  }
346
525
  if (errors.isNotEmpty() && purchases.isNotEmpty()) {
347
- onError(PurchasesError.NetworkError("restore: ${errors.size}/${purchases.size} validate calls failed"))
526
+ onError(toPurchasesError(errors.first()))
348
527
  } else {
349
528
  onSuccess(info)
350
529
  }
@@ -365,9 +544,11 @@ class BillingClientGateway(
365
544
  val repo = entitlementsRepo
366
545
  repo?.invalidate()
367
546
  executor.execute {
368
- runCatching { repo?.refresh(emptySet()) ?: emptyCustomerInfo() }
369
- .onSuccess { onSuccess(it, false) }
370
- .onFailure { onError(toPurchasesError(it)) }
547
+ // The new user's entitlements. A read that fails does not fail the
548
+ // logIn (the identify call already went through): it answers with no
549
+ // entitlements, as it always did, and the next getCustomerInfo() reads
550
+ // them again.
551
+ onSuccess(refreshEntitlements() ?: emptyCustomerInfo(), false)
371
552
  }
372
553
  }
373
554
 
@@ -385,13 +566,36 @@ class BillingClientGateway(
385
566
  // analytics stay continuous for the same physical install — same as iOS,
386
567
  // where logOut also returns to the stable device anonymous id rather than
387
568
  // inventing a new one.
388
- fallbackAnonymousAppUserId =
389
- "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
569
+ fallbackAnonymousAppUserId = newFallbackAnonymousId()
390
570
  val repo = entitlementsRepo
391
571
  repo?.invalidate()
392
572
  onSuccess(emptyCustomerInfo())
393
573
  }
394
574
 
575
+ /**
576
+ * Back to the anonymous user after `Identity.reset()` / `Identity.wipe()`
577
+ * (see [PurchasesGateway.resetToAnonymous]). Unlike [logOut] it answers no
578
+ * call and has no "already anonymous" error: Identity has already moved on,
579
+ * and this makes the gateway agree. Play is not contacted.
580
+ */
581
+ override fun resetToAnonymous() {
582
+ val droppedUser = explicitAppUserId
583
+ explicitAppUserId = null
584
+ fallbackAnonymousAppUserId = newFallbackAnonymousId()
585
+ entitlementsRepo?.invalidate()
586
+ if (droppedUser == null) return
587
+ // Taken now, while the subject is the anonymous id. Announced on the
588
+ // executor, after any entitlement read already running there, so the
589
+ // listeners hear the reset after that read's answer, never before it.
590
+ val anonymous = emptyCustomerInfo()
591
+ executor.execute { notifyCustomerInfoListeners(anonymous) }
592
+ }
593
+
594
+ private fun notifyCustomerInfoListeners(info: CustomerInfo) {
595
+ synchronized(customerInfoListeners) { customerInfoListeners.toList() }
596
+ .forEach { runCatching { it(info) } }
597
+ }
598
+
395
599
  override fun setLogLevel(level: LogLevel) {
396
600
  // Play Billing doesn't expose a log-level knob (it logs to logcat
397
601
  // unconditionally). We retain the call for parity but do nothing.
@@ -417,6 +621,10 @@ class BillingClientGateway(
417
621
  pending?.onError?.invoke(PurchasesError.PurchaseCancelled(), true); return
418
622
  }
419
623
  if (code != BillingClient.BillingResponseCode.OK) {
624
+ // Play still holds a purchase of the product. When it is a consumable an
625
+ // earlier SDK only acknowledged, the reconcile consumes it, so the next
626
+ // attempt goes through; the call still fails as before.
627
+ if (code == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) reconcileSoon()
420
628
  pending?.onError?.invoke(toPurchasesError(result), false); return
421
629
  }
422
630
  if (purchases.isNullOrEmpty()) {
@@ -446,12 +654,20 @@ class BillingClientGateway(
446
654
  // out-of-band ones would be its own bug. What must never happen is
447
655
  // attributing one of them to a request that did not produce it.
448
656
  var matchedFailure: Exception? = null
657
+ var validatedAny = false
449
658
  for (p in purchases) {
659
+ // PENDING (cash, deferred payment) means the user has not paid yet and
660
+ // may never pay. Validating it would record a purchase that does not
661
+ // exist, and Play refuses to acknowledge it. Play delivers it again
662
+ // through this listener once it clears, and the reconcile on the next
663
+ // connect finds it otherwise.
664
+ if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
450
665
  try {
451
- for (productId in p.products) {
452
- validatePurchaseWithBackend(productId, p.purchaseToken)
453
- }
454
- if (!p.isAcknowledged) acknowledge(p)
666
+ // Consumed or acknowledged after the backend recorded it. A consume
667
+ // or acknowledge that fails is retried and left to the reconcile; it
668
+ // never fails this call.
669
+ validateAndSettle(p)
670
+ validatedAny = true
455
671
  } catch (e: Exception) {
456
672
  if (p === matched) {
457
673
  matchedFailure = e
@@ -464,6 +680,14 @@ class BillingClientGateway(
464
680
  }
465
681
  }
466
682
 
683
+ // The backend now holds every purchase validated above, including the
684
+ // ones no call is waiting for: a pending payment that cleared, a promo
685
+ // code, a purchase made in the Play Store app. Re-read the entitlements
686
+ // once, so the cache and every CustomerInfo listener see what they
687
+ // unlocked, as iOS does after a Transaction.updates delivery. The call in
688
+ // flight, if any, is answered with the same read.
689
+ val refreshed = if (validatedAny) refreshEntitlements() else null
690
+
467
691
  if (pending == null) return@execute
468
692
 
469
693
  if (matched == null) {
@@ -478,15 +702,18 @@ class BillingClientGateway(
478
702
  )
479
703
  return@execute
480
704
  }
705
+ if (matched.purchaseState != Purchase.PurchaseState.PURCHASED) {
706
+ // iOS parity (`.pending` -> paymentPending): the flow finished but the
707
+ // money has not moved. Not a success, not a cancellation.
708
+ pending.onError(PurchasesError.PaymentPending(), false)
709
+ return@execute
710
+ }
481
711
  if (matchedFailure != null) {
482
712
  pending.onError(toPurchasesError(matchedFailure), false)
483
713
  return@execute
484
714
  }
485
715
 
486
- val repo = entitlementsRepo
487
- val info = runCatching { repo?.refresh(emptySet()) }.getOrNull()
488
- ?: repo?.current()
489
- ?: emptyCustomerInfo()
716
+ val info = refreshed ?: entitlementsRepo?.current() ?: emptyCustomerInfo()
490
717
  pending.onSuccess(
491
718
  StoreTransactionResult(
492
719
  transaction = matched.toStoreTransaction(),
@@ -501,11 +728,18 @@ class BillingClientGateway(
501
728
  @VisibleForTesting
502
729
  internal fun connect() {
503
730
  val client = billingClient ?: return
731
+ // A second startConnection while one is in flight is answered with
732
+ // DEVELOPER_ERROR, which would fail the waiters and burn a reconnect.
733
+ // The in-flight setup drains them anyway.
734
+ if (client.connectionState == BillingClient.ConnectionState.CONNECTING) return
504
735
  client.startConnection(object : BillingClientStateListener {
505
736
  override fun onBillingSetupFinished(result: BillingResult) {
506
737
  if (result.responseCode == BillingClient.BillingResponseCode.OK) {
507
738
  reconnectAttempt.set(0)
739
+ drainReadyWaiters(client)
740
+ reconcilePurchases(client)
508
741
  } else {
742
+ failReadyWaiters(toPurchasesError(result))
509
743
  scheduleReconnect()
510
744
  }
511
745
  }
@@ -516,6 +750,217 @@ class BillingClientGateway(
516
750
  })
517
751
  }
518
752
 
753
+ /**
754
+ * Run [onReady] with a connected client. When the client is not ready —
755
+ * mid-reconnect, or dead after [MAX_RECONNECT_ATTEMPTS] failed attempts —
756
+ * this resets the reconnect budget, connects, and runs [onReady] on the
757
+ * next OK setup. A failed setup, or no answer within
758
+ * [CONNECT_WAIT_TIMEOUT_MS], ends the call through [onUnavailable] instead.
759
+ *
760
+ * Before this the call simply failed "Billing client not ready", and after
761
+ * the fifth failed connect nothing ever connected again, so every purchase
762
+ * failed until the app was restarted.
763
+ */
764
+ private fun withReadyClient(
765
+ onReady: (BillingClient) -> Unit,
766
+ onUnavailable: (PurchasesError) -> Unit,
767
+ ) {
768
+ val client = billingClient
769
+ if (client == null) {
770
+ onUnavailable(PurchasesError.StoreProblem("Billing client not ready")); return
771
+ }
772
+ if (client.isReady) {
773
+ onReady(client); return
774
+ }
775
+ val waiter = ReadyWaiter(onReady, onUnavailable)
776
+ synchronized(readyWaiters) { readyWaiters.add(waiter) }
777
+ // The setup may have finished between the isReady check and the add.
778
+ if (client.isReady) {
779
+ drainReadyWaiters(client); return
780
+ }
781
+ reconnectScheduler.schedule(CONNECT_WAIT_TIMEOUT_MS) {
782
+ synchronized(readyWaiters) { readyWaiters.remove(waiter) }
783
+ waiter.fail(PurchasesError.StoreProblem("Billing client not ready"))
784
+ }
785
+ reconnectAttempt.set(0)
786
+ connect()
787
+ }
788
+
789
+ private fun takeReadyWaiters(): List<ReadyWaiter> = synchronized(readyWaiters) {
790
+ readyWaiters.toList().also { readyWaiters.clear() }
791
+ }
792
+
793
+ private fun drainReadyWaiters(client: BillingClient) {
794
+ for (w in takeReadyWaiters()) w.ready(client)
795
+ }
796
+
797
+ private fun failReadyWaiters(error: PurchasesError) {
798
+ for (w in takeReadyWaiters()) w.fail(error)
799
+ }
800
+
801
+ /** Completes exactly once: ready, failed setup, or timeout, whichever is first. */
802
+ private class ReadyWaiter(
803
+ private val onReady: (BillingClient) -> Unit,
804
+ private val onUnavailable: (PurchasesError) -> Unit,
805
+ ) {
806
+ private val done = AtomicBoolean(false)
807
+ fun ready(client: BillingClient) { if (done.compareAndSet(false, true)) onReady(client) }
808
+ fun fail(error: PurchasesError) { if (done.compareAndSet(false, true)) onUnavailable(error) }
809
+ }
810
+
811
+ /**
812
+ * Validate and acknowledge every PURCHASED purchase Play still holds
813
+ * unacknowledged, SUBS and INAPP. Runs on every OK setup, so on configure
814
+ * and after each reconnect.
815
+ *
816
+ * This is the only retry an acknowledgement gets beyond [acknowledge]'s own
817
+ * bounded one: a process killed between validate and acknowledge, an ack
818
+ * that failed on a bad connection, or a pending purchase that cleared while
819
+ * the app was not running all land here. There is no server-side
820
+ * acknowledge (that would be a store write from the backend).
821
+ *
822
+ * It also consumes the consumables an earlier SDK acknowledged and never
823
+ * consumed: an acknowledged purchase whose every product the backend has
824
+ * described as a consumable ([serverProductTypes]) is validated again (the
825
+ * backend's ledger is keyed on the token, so this grants nothing twice) and
826
+ * consumed when the answer confirms it. No other acknowledged purchase is
827
+ * validated again.
828
+ *
829
+ * When it validated anything, it then re-reads the entitlements, so the app
830
+ * sees what those purchases unlocked without a restore.
831
+ *
832
+ * [rerunIfBusy]: a reconcile asked for while one runs is dropped (the running
833
+ * one covers a new setup), unless the caller learned something the running
834
+ * one may have missed; then another runs when it ends.
835
+ */
836
+ private fun reconcilePurchases(client: BillingClient, rerunIfBusy: Boolean = false) {
837
+ if (!reconcileInFlight.compareAndSet(false, true)) {
838
+ if (rerunIfBusy) reconcileAgain.set(true)
839
+ return
840
+ }
841
+ try {
842
+ queryOwnedPurchases(client, PRODUCT_TYPES, mutableListOf()) { owned, _ ->
843
+ executor.execute {
844
+ var validatedAny = false
845
+ try {
846
+ for (p in owned) {
847
+ if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
848
+ val token = p.purchaseToken
849
+ if (token in ackClaimed || token in consumeClaimed) continue
850
+ if (p.isAcknowledged && !isKnownConsumable(p)) continue
851
+ try {
852
+ validateAndSettle(p, reconcileSubject(p))
853
+ validatedAny = true
854
+ } catch (e: Exception) {
855
+ // Not settled, so the next connect tries again.
856
+ Log.w(TAG, "reconcile: validate failed for a purchase left to settle", e)
857
+ }
858
+ }
859
+ } finally {
860
+ reconcileInFlight.set(false)
861
+ }
862
+ if (validatedAny) refreshEntitlements()
863
+ if (reconcileAgain.getAndSet(false)) reconcileSoon()
864
+ }
865
+ }
866
+ } catch (e: RuntimeException) {
867
+ reconcileInFlight.set(false)
868
+ Log.w(TAG, "reconcile: queryPurchasesAsync failed", e)
869
+ }
870
+ }
871
+
872
+ /** Reconcile now if Play is connected; otherwise the next OK setup reconciles anyway. */
873
+ private fun reconcileSoon() {
874
+ val client = billingClient?.takeIf { it.isReady } ?: return
875
+ reconcilePurchases(client, rerunIfBusy = true)
876
+ }
877
+
878
+ /** Every product of [p] is one the backend has described as a consumable. */
879
+ private fun isKnownConsumable(p: Purchase): Boolean =
880
+ p.products.isNotEmpty() && p.products.all { serverProductTypes[it] == CONSUMABLE }
881
+
882
+ /**
883
+ * Validate [p] with the backend under [subject], then settle it with Play:
884
+ * consume it when the backend answered that every one of its products is a
885
+ * consumable (it has recorded the purchase by then), otherwise acknowledge it
886
+ * if Play still holds it unacknowledged. Throws what a validate threw, and
887
+ * settles nothing then.
888
+ */
889
+ @Throws(IOException::class)
890
+ private fun validateAndSettle(p: Purchase, subject: String = getAppUserID()) {
891
+ // Every product is validated before anything is settled.
892
+ val types = p.products.map { productId ->
893
+ validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken, subject)
894
+ }
895
+ if (types.isNotEmpty() && types.all { it == CONSUMABLE }) {
896
+ consume(p)
897
+ } else if (!p.isAcknowledged) {
898
+ acknowledge(p)
899
+ }
900
+ }
901
+
902
+ /**
903
+ * The subject a reconciled purchase is validated under.
904
+ *
905
+ * [launchPurchase] stamps [getAppUserID] on every purchase as its
906
+ * obfuscatedAccountId. A reconcile mostly runs at configure, before the host
907
+ * has called logIn again ([Identity] keeps the user id in memory only), so
908
+ * the current subject there is the device's anonymous id. Posting that for a
909
+ * purchase a signed-in user made would let the backend move the purchase onto
910
+ * the anonymous id, or refuse it and leave it to be refunded. A purchase
911
+ * stamped with a user id is therefore validated under that user.
912
+ *
913
+ * An anonymous stamp, or none (promo codes, the Play Store app), uses the
914
+ * current subject, as before: older SDKs stamped a per-process anonymous id
915
+ * (`${'$'}SKAnonymousID:` or, before that, `${'$'}RCAnonymousID:`) that
916
+ * nothing reads back, and the current one is this device's.
917
+ */
918
+ private fun reconcileSubject(p: Purchase): String =
919
+ p.accountIdentifiers?.obfuscatedAccountId
920
+ ?.takeIf { stamp -> stamp.isNotEmpty() && ANONYMOUS_ID_PREFIXES.none { stamp.startsWith(it) } }
921
+ ?: getAppUserID()
922
+
923
+ /**
924
+ * The purchases Play holds of each of [productTypes], asked one type after
925
+ * the other. [done] gets them all, and the first non-OK answer if a query
926
+ * failed (its type's purchases are then missing).
927
+ */
928
+ private fun queryOwnedPurchases(
929
+ client: BillingClient,
930
+ productTypes: List<String>,
931
+ found: MutableList<Purchase>,
932
+ failure: BillingResult? = null,
933
+ done: (List<Purchase>, failure: BillingResult?) -> Unit,
934
+ ) {
935
+ val type = productTypes.firstOrNull() ?: run { done(found, failure); return }
936
+ val params = QueryPurchasesParams.newBuilder().setProductType(type).build()
937
+ client.queryPurchasesAsync(params) { result, purchases ->
938
+ var firstFailure = failure
939
+ if (result.responseCode == BillingClient.BillingResponseCode.OK) {
940
+ found.addAll(purchases)
941
+ } else {
942
+ Log.w(TAG, "queryPurchasesAsync($type) returned ${result.responseCode}")
943
+ if (firstFailure == null) firstFailure = result
944
+ }
945
+ queryOwnedPurchases(client, productTypes.drop(1), found, firstFailure, done)
946
+ }
947
+ }
948
+
949
+ /**
950
+ * Re-read the user's entitlements from the backend into the cache, which
951
+ * tells every CustomerInfo listener. Null when the backend cannot be read;
952
+ * the cache then keeps what it had, and the next read tries again.
953
+ */
954
+ private fun refreshEntitlements(): CustomerInfo? {
955
+ val repo = entitlementsRepo ?: return null
956
+ return try {
957
+ repo.refresh(emptySet())
958
+ } catch (e: Exception) {
959
+ Log.w(TAG, "entitlements refresh failed; keeping the cached entitlements", e)
960
+ null
961
+ }
962
+ }
963
+
519
964
  private fun scheduleReconnect() {
520
965
  val n = reconnectAttempt.getAndIncrement()
521
966
  if (n >= MAX_RECONNECT_ATTEMPTS) {
@@ -533,21 +978,29 @@ class BillingClientGateway(
533
978
  * validates against Google's Real-Time Developer Notifications channel
534
979
  * and the Play Developer API. Returns when the backend ack'd; throws on
535
980
  * non-2xx.
981
+ *
982
+ * Returns the backend's `product_type` for [productId] from its answer, or
983
+ * null when the answer names none (or names another product). The backend
984
+ * answers only after it has recorded the purchase.
536
985
  */
537
986
  @Throws(IOException::class)
538
- private fun validatePurchaseWithBackend(productId: String, purchaseToken: String) {
987
+ private fun validatePurchaseWithBackend(
988
+ packageName: String,
989
+ productId: String,
990
+ purchaseToken: String,
991
+ userId: String = getAppUserID(),
992
+ ): String? {
539
993
  val body = JSONObject().apply {
540
- put("user_id", getAppUserID())
541
- put("product_id", productId)
542
- put("purchase_token", purchaseToken)
543
- put("store", "play")
994
+ put("user_id", userId)
995
+ put("platform", "android")
996
+ put("receipt_data", "$packageName:$productId:$purchaseToken")
544
997
  }.toString()
545
998
  // Round-D auth audit: the backend `/api/sdk/subscriptions/validate`
546
999
  // route uses `withApiKeyAuth` (X-API-Key header). Pre-Round-D we
547
1000
  // sent `Authorization: Bearer ...` which the route ignored — every
548
1001
  // validate POST was returning 401 in production. Aligning with the
549
1002
  // backend contract here.
550
- httpClient.post(
1003
+ val answer = httpClient.post(
551
1004
  url = "$serverUrl/api/sdk/subscriptions/validate",
552
1005
  body = body,
553
1006
  headers = mapOf(
@@ -555,6 +1008,21 @@ class BillingClientGateway(
555
1008
  "Content-Type" to "application/json",
556
1009
  ),
557
1010
  )
1011
+ val type = productTypeIn(answer, productId) ?: return null
1012
+ typedByValidate.add(productId)
1013
+ serverProductTypes[productId] = type
1014
+ return type
1015
+ }
1016
+
1017
+ /** The `product_type` a validate answer gives [productId]; null when it names none or another product. */
1018
+ private fun productTypeIn(answer: String?, productId: String): String? {
1019
+ val json = try {
1020
+ JSONObject(answer ?: return null)
1021
+ } catch (_: org.json.JSONException) {
1022
+ return null
1023
+ }
1024
+ if (json.isNull("product_type") || json.optString("product_id") != productId) return null
1025
+ return json.optString("product_type").takeIf { it.isNotEmpty() }
558
1026
  }
559
1027
 
560
1028
  /**
@@ -597,12 +1065,69 @@ class BillingClientGateway(
597
1065
 
598
1066
  private fun acknowledge(purchase: Purchase) {
599
1067
  acknowledgeOverrideForTesting?.let { it(purchase); return }
600
- val client = billingClient ?: return
1068
+ // Already acknowledged, or an acknowledgement is in flight, in this process.
1069
+ if (!ackClaimed.add(purchase.purchaseToken)) return
1070
+ sendAcknowledge(purchase, attempt = 0)
1071
+ }
1072
+
1073
+ /**
1074
+ * One acknowledgePurchase call. A non-OK answer is retried after
1075
+ * 1 s, 2 s, ... up to [MAX_ACK_ATTEMPTS] calls in all; a terminal answer,
1076
+ * or the last failed attempt, releases the token so the next
1077
+ * [reconcilePurchases] tries again. Nothing else acknowledges: the backend
1078
+ * has no acknowledge job.
1079
+ */
1080
+ private fun sendAcknowledge(purchase: Purchase, attempt: Int) {
1081
+ val token = purchase.purchaseToken
1082
+ val client = billingClient ?: run { ackClaimed.remove(token); return }
601
1083
  val params = AcknowledgePurchaseParams.newBuilder()
602
- .setPurchaseToken(purchase.purchaseToken)
1084
+ .setPurchaseToken(token)
1085
+ .build()
1086
+ client.acknowledgePurchase(params) { result ->
1087
+ val code = result.responseCode
1088
+ if (code == BillingClient.BillingResponseCode.OK) return@acknowledgePurchase
1089
+ if (attempt + 1 < MAX_ACK_ATTEMPTS && code !in TERMINAL_ACK_CODES) {
1090
+ reconnectScheduler.schedule(ACK_RETRY_BASE_DELAY_MS shl attempt) {
1091
+ sendAcknowledge(purchase, attempt + 1)
1092
+ }
1093
+ } else {
1094
+ ackClaimed.remove(token)
1095
+ Log.w(TAG, "acknowledgePurchase failed (code=$code, attempts=${attempt + 1}); left for the next reconcile")
1096
+ }
1097
+ }
1098
+ }
1099
+
1100
+ /**
1101
+ * Consume [purchase] (which also acknowledges it), so Play sells the product
1102
+ * again. Called only after the backend recorded the purchase and answered
1103
+ * that it is a consumable. Same bounded retry as [acknowledge]; a consume
1104
+ * that still fails is left to the next reconcile, which finds the purchase
1105
+ * owned and validates it again (the backend grants it once) before consuming.
1106
+ */
1107
+ private fun consume(purchase: Purchase) {
1108
+ // Consumed, or a consume is in flight, in this process.
1109
+ if (!consumeClaimed.add(purchase.purchaseToken)) return
1110
+ sendConsume(purchase, attempt = 0)
1111
+ }
1112
+
1113
+ private fun sendConsume(purchase: Purchase, attempt: Int) {
1114
+ val token = purchase.purchaseToken
1115
+ val client = billingClient ?: run { consumeClaimed.remove(token); return }
1116
+ val params = ConsumeParams.newBuilder()
1117
+ .setPurchaseToken(token)
603
1118
  .build()
604
- client.acknowledgePurchase(params) { /* fire-and-forget; failures will
605
- be re-tried on next purchase or via the backend's pull job */ }
1119
+ client.consumeAsync(params) { result, _ ->
1120
+ val code = result.responseCode
1121
+ if (code == BillingClient.BillingResponseCode.OK) return@consumeAsync
1122
+ if (attempt + 1 < MAX_ACK_ATTEMPTS && code !in TERMINAL_ACK_CODES) {
1123
+ reconnectScheduler.schedule(ACK_RETRY_BASE_DELAY_MS shl attempt) {
1124
+ sendConsume(purchase, attempt + 1)
1125
+ }
1126
+ } else {
1127
+ consumeClaimed.remove(token)
1128
+ Log.w(TAG, "consumeAsync failed (code=$code, attempts=${attempt + 1}); left for the next reconcile")
1129
+ }
1130
+ }
606
1131
  }
607
1132
 
608
1133
  private fun Purchase.toStoreTransaction(): StoreTransaction = object : StoreTransaction {
@@ -634,8 +1159,42 @@ class BillingClientGateway(
634
1159
 
635
1160
  companion object {
636
1161
  private const val TAG = "SwissKnife.Billing"
1162
+
1163
+ /** The backend's `product_type` for a one-time product that is bought again and again. */
1164
+ private const val CONSUMABLE = "consumable"
1165
+ private val ANONYMOUS_ID_PREFIXES = listOf("\$SKAnonymousID:", "\$RCAnonymousID:")
1166
+
1167
+ private fun newFallbackAnonymousId(): String =
1168
+ "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
1169
+
637
1170
  @VisibleForTesting internal const val MAX_RECONNECT_ATTEMPTS = 5
638
1171
 
1172
+ /** Total acknowledgePurchase calls per purchase before it is left to the reconcile. */
1173
+ @VisibleForTesting internal const val MAX_ACK_ATTEMPTS = 3
1174
+ @VisibleForTesting internal const val ACK_RETRY_BASE_DELAY_MS = 1_000L
1175
+
1176
+ /** How long a purchase or restore waits for a reconnect before failing. */
1177
+ @VisibleForTesting internal const val CONNECT_WAIT_TIMEOUT_MS = 15_000L
1178
+
1179
+ /** How long pricing offerings waits for Play to connect before using dashboard prices. */
1180
+ @VisibleForTesting internal const val PRICE_CONNECT_WAIT_MS = 5_000L
1181
+
1182
+ /**
1183
+ * The Play product types the SDK sells and restores: subscriptions and
1184
+ * one-time products (consumables included). Play answers a query for one
1185
+ * type only, so purchases, restore and the reconcile ask for each.
1186
+ */
1187
+ private val PRODUCT_TYPES = listOf(
1188
+ BillingClient.ProductType.SUBS,
1189
+ BillingClient.ProductType.INAPP,
1190
+ )
1191
+
1192
+ /** Answers a retry cannot change: the purchase is gone or the request is malformed. */
1193
+ private val TERMINAL_ACK_CODES = setOf(
1194
+ BillingClient.BillingResponseCode.ITEM_NOT_OWNED,
1195
+ BillingClient.BillingResponseCode.DEVELOPER_ERROR,
1196
+ )
1197
+
639
1198
  /** Map Play Billing error codes to our [PurchasesError] hierarchy. */
640
1199
  @VisibleForTesting
641
1200
  internal fun toPurchasesError(result: BillingResult): PurchasesError {
@@ -659,6 +1218,8 @@ class BillingClientGateway(
659
1218
 
660
1219
  private fun toPurchasesError(t: Throwable): PurchasesError = when (t) {
661
1220
  is PurchasesError -> t
1221
+ is com.appswissknife.net.BillingBackendException -> PurchasesError(
1222
+ PurchasesErrorCode.UnexpectedBackendResponseError, t.message ?: "Purchase validation failed", t)
662
1223
  is IOException -> PurchasesError.NetworkError(t.message ?: "Network error", t)
663
1224
  else -> PurchasesError.Unknown(t.message ?: "Unknown error", t)
664
1225
  }
@@ -680,6 +1241,54 @@ interface BillingHttpClient {
680
1241
  fun post(url: String, body: String, headers: Map<String, String>): String
681
1242
  }
682
1243
 
1244
+ /**
1245
+ * The SDK's unified backend transport as a [BillingHttpClient] — what the Play
1246
+ * gateway validates through. Public so a store add-on that lives outside this
1247
+ * module (the RuStore gateway) uses the same transport instead of opening its
1248
+ * own connection. A non-2xx answer throws an [IOException] whose message never
1249
+ * echoes the response body.
1250
+ */
1251
+ fun defaultBillingHttpClient(): BillingHttpClient = com.appswissknife.net.BackendHttpClientAdapter()
1252
+
1253
+ /**
1254
+ * A [BillingHttpClient] that retries transient failures: transport errors,
1255
+ * HTTP 429 and 5xx, after 1 s, 2 s, ... ([maxRetries] retries after the first
1256
+ * attempt). Any other HTTP status is the backend's answer and is thrown at once.
1257
+ *
1258
+ * Safe for `/api/sdk/subscriptions/validate`: the backend keys the ledger and the
1259
+ * subscription row on the store's transaction id, so a retried POST cannot record
1260
+ * a purchase twice.
1261
+ */
1262
+ class RetryingBillingHttpClient @JvmOverloads constructor(
1263
+ private val delegate: BillingHttpClient = defaultBillingHttpClient(),
1264
+ private val maxRetries: Int = 2,
1265
+ private val sleeper: (Long) -> Unit = { Thread.sleep(it) },
1266
+ ) : BillingHttpClient {
1267
+ @Throws(IOException::class)
1268
+ override fun post(url: String, body: String, headers: Map<String, String>): String {
1269
+ var attempt = 0
1270
+ while (true) {
1271
+ try {
1272
+ return delegate.post(url, body, headers)
1273
+ } catch (e: IOException) {
1274
+ if (attempt >= maxRetries || !isTransient(e)) throw e
1275
+ try {
1276
+ sleeper(1_000L shl attempt)
1277
+ } catch (_: InterruptedException) {
1278
+ Thread.currentThread().interrupt()
1279
+ throw e
1280
+ }
1281
+ attempt++
1282
+ }
1283
+ }
1284
+ }
1285
+
1286
+ private fun isTransient(e: IOException): Boolean {
1287
+ val status = (e as? com.appswissknife.net.BillingBackendException)?.httpStatus ?: return true
1288
+ return status == 429 || status >= 500
1289
+ }
1290
+ }
1291
+
683
1292
  /** Schedule a delayed task. Tests use a synchronous-immediate impl to
684
1293
  * exercise reconnect logic without sleeping. */
685
1294
  interface ReconnectScheduler {