Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions RevenueCat.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,7 @@
A1B2C3D42FE7000000000002 /* RemoteConfigTopic.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D42FE7000000000001 /* RemoteConfigTopic.swift */; };
A1B2C3D42FE8000000000002 /* RemoteConfigIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D42FE8000000000001 /* RemoteConfigIntegrationTests.swift */; };
A1B2C3D42FE9000000000002 /* GenerationGuardedCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D42FE9000000000001 /* GenerationGuardedCache.swift */; };
A1B2C3D42FEB000000000002 /* ProductEntitlementMappingTopicProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D42FEB000000000001 /* ProductEntitlementMappingTopicProvider.swift */; };
A1B2C3D42FE9000000000004 /* GenerationGuardedCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D42FE9000000000003 /* GenerationGuardedCacheTests.swift */; };
A1B2C3D4E5F60718293A4B5C /* MiscOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4E5F60718293A4B5C6D7E8F /* MiscOperators.swift */; };
A1E0F0022F297A0100000001 /* EventsManagerStrings.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1E0F0012F297A0100000001 /* EventsManagerStrings.swift */; };
Expand Down Expand Up @@ -2823,6 +2824,7 @@
A1B2C3D42FE7000000000001 /* RemoteConfigTopic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteConfigTopic.swift; sourceTree = "<group>"; };
A1B2C3D42FE8000000000001 /* RemoteConfigIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteConfigIntegrationTests.swift; sourceTree = "<group>"; };
A1B2C3D42FE9000000000001 /* GenerationGuardedCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GenerationGuardedCache.swift; sourceTree = "<group>"; };
A1B2C3D42FEB000000000001 /* ProductEntitlementMappingTopicProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProductEntitlementMappingTopicProvider.swift; sourceTree = "<group>"; };
A1B2C3D42FE9000000000003 /* GenerationGuardedCacheTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GenerationGuardedCacheTests.swift; sourceTree = "<group>"; };
A1B2C3D42FEA000000000001 /* RecordingBlobDownloader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordingBlobDownloader.swift; sourceTree = "<group>"; };
A1B2C3D42FEA000000000002 /* RemoteConfigBlobHealthTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteConfigBlobHealthTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -4658,6 +4660,7 @@
A1B2C3D42FE3000000000001 /* RemoteConfigFetchContext.swift */,
A1B2C3D42FE9000000000001 /* GenerationGuardedCache.swift */,
DB021C52E3CCC5EB17FFF795 /* UiConfigProvider.swift */,
A1B2C3D42FEB000000000001 /* ProductEntitlementMappingTopicProvider.swift */,
4C390BBAC430231B23B4B5F8 /* WorkflowsConfigProvider.swift */,
A1B2C3D42FE7000000000001 /* RemoteConfigTopic.swift */,
A1B2C3D42FE1000000000011 /* RemoteConfigSignatureContextProvider.swift */,
Expand Down Expand Up @@ -7324,6 +7327,7 @@
A1B2C3D42FE3000000000002 /* RemoteConfigFetchContext.swift in Sources */,
A1B2C3D42FE9000000000002 /* GenerationGuardedCache.swift in Sources */,
B8EF700CBF25815EC2BF1253 /* UiConfigProvider.swift in Sources */,
A1B2C3D42FEB000000000002 /* ProductEntitlementMappingTopicProvider.swift in Sources */,
49B8016629C29C4691C0774A /* WorkflowsConfigProvider.swift in Sources */,
A1B2C3D42FE2000000000006 /* RemoteConfigStrings.swift in Sources */,
A1B2C3D42FE7000000000002 /* RemoteConfigTopic.swift in Sources */,
Expand Down
4 changes: 4 additions & 0 deletions Sources/Logging/Strings/OfflineEntitlementsStrings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ enum OfflineEntitlementsStrings {
case product_entitlement_mapping_updated_from_network
case product_entitlement_mapping_unavailable
case product_entitlement_mapping_fetching_error(BackendError)
case product_entitlement_mapping_remote_config_decoding_error(Error)
case found_unverified_transactions_in_sk2(transactionID: UInt64, Error)

case computing_offline_customer_info_with_no_entitlement_mapping
Expand Down Expand Up @@ -60,6 +61,9 @@ extension OfflineEntitlementsStrings: LogMessage {
case let .product_entitlement_mapping_fetching_error(error):
return "Failed updating ProductEntitlementMapping from network: \(error.localizedDescription)"

case let .product_entitlement_mapping_remote_config_decoding_error(error):
return "Failed decoding ProductEntitlementMapping from Remote Config: \(error.localizedDescription)"

case let .found_unverified_transactions_in_sk2(transactionID, error):
return """
Found an unverified transaction. It will be ignored and will not be a part of CustomerInfo.
Expand Down
55 changes: 55 additions & 0 deletions Sources/Networking/ProductEntitlementMappingTopicProvider.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//
// ProductEntitlementMappingTopicProvider.swift
// RevenueCat
//
// Created by Rick van der Linden.
// Copyright © 2026 RevenueCat, Inc. All rights reserved.

import Foundation

protocol EntitlementMappingTopicProviderType: AnyObject {

var isAvailable: Bool { get }

/// Returns the mapping when its remote-config blob is available and decodes successfully.
func getProductEntitlementMapping() async -> ProductEntitlementMappingResponse?

}

/// Decodes the `product_entitlement_mapping.default` remote-config blob.
final class ProductEntitlementMappingTopicProvider: EntitlementMappingTopicProviderType {

private static let itemKey = "default"

private weak var manager: RemoteConfigManagerType?

init(manager: RemoteConfigManagerType) {
self.manager = manager
}

var isAvailable: Bool {
guard let manager = self.manager else { return false }
return !manager.isDisabled
}

func getProductEntitlementMapping() async -> ProductEntitlementMappingResponse? {
guard let manager = self.manager,
let blobData = await manager.blobData(
for: .productEntitlementMapping,
itemKey: Self.itemKey
) else { return nil }

do {
return try JSONDecoder.default.decode(
ProductEntitlementMappingResponse.self,
from: blobData
)
} catch {
Logger.error(Strings.offlineEntitlements.product_entitlement_mapping_remote_config_decoding_error(error))
return nil
}
}

}

extension ProductEntitlementMappingTopicProvider: @unchecked Sendable {}
1 change: 1 addition & 0 deletions Sources/Networking/RemoteConfigTopic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ enum RemoteConfigTopic: String {
case workflows
case uiConfig = "ui_config"
case sources
case productEntitlementMapping = "product_entitlement_mapping"

var wireName: String {
return self.rawValue
Expand Down
134 changes: 90 additions & 44 deletions Sources/OfflineEntitlements/OfflineEntitlementsManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,39 +16,109 @@ import Foundation
class OfflineEntitlementsManager {

private let deviceCache: DeviceCache
private let operationDispatcher: OperationDispatcher
private let api: OfflineEntitlementsAPI
private let systemInfo: SystemInfo

private var productEntitlementMappingTopicProvider: EntitlementMappingTopicProviderType?
private let productEntitlementMappingLock = Lock()
private var productEntitlementMappingTask: Task<Void, Never>?
private var isClosed = false

init(deviceCache: DeviceCache,
operationDispatcher: OperationDispatcher,
api: OfflineEntitlementsAPI,
systemInfo: SystemInfo) {
self.deviceCache = deviceCache
self.operationDispatcher = operationDispatcher
self.api = api
self.systemInfo = systemInfo
}

func updateProductsEntitlementsCacheIfStale(
isAppBackgrounded: Bool,
completion: (@MainActor @Sendable (Result<(), Error>) -> Void)?
) {
// Late-bound to break the OfflineEntitlementsManager → IdentityManager → RemoteConfigManager dependency cycle.
func setProductEntitlementMappingTopicProvider(_ provider: EntitlementMappingTopicProviderType) {
self.productEntitlementMappingTopicProvider = provider
}

func updateProductsEntitlementsCacheIfStale(isAppBackgrounded: Bool) {
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *),
self.systemInfo.supportsOfflineEntitlements else {
Logger.debug(Strings.offlineEntitlements.product_entitlement_mapping_unavailable)
return
}

guard self.deviceCache.isProductEntitlementMappingCacheStale else { return }

self.dispatchCompletionOnMainThreadIfPossible(completion, result: .failure(.notAvailable))
Logger.debug(Strings.offlineEntitlements.product_entitlement_mapping_stale_updating)

guard let provider = self.productEntitlementMappingTopicProvider,
provider.isAvailable else {
self.productEntitlementMappingLock.perform {
guard !self.isClosed else { return }
self.fetchLegacyProductEntitlementMapping(isAppBackgrounded: isAppBackgrounded)
}
return
}

guard self.deviceCache.isProductEntitlementMappingCacheStale else {
self.dispatchCompletionOnMainThreadIfPossible(completion, result: .success(()))
self.productEntitlementMappingLock.perform {
guard !self.isClosed, self.productEntitlementMappingTask == nil else { return }

self.productEntitlementMappingTask = Task { [weak self, provider] in
let remoteResult = await provider.getProductEntitlementMapping()
guard let self else { return }

await self.completeProductEntitlementMappingUpdate(
remoteResult: remoteResult, isAppBackgrounded: isAppBackgrounded
)
}
}
}

func close() {
let task = self.productEntitlementMappingLock.perform {
self.isClosed = true
let task = self.productEntitlementMappingTask
self.productEntitlementMappingTask = nil
return task
}
task?.cancel()
}

@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
private func completeProductEntitlementMappingUpdate(
remoteResult: ProductEntitlementMappingResponse?,
isAppBackgrounded: Bool
) async {
if let remoteResult {
let didCacheRemoteResult = self.productEntitlementMappingLock.perform {
guard !self.isClosed, !Task.isCancelled else { return false }
self.handleProductEntitlementMappingBackendResult(with: remoteResult)
self.productEntitlementMappingTask = nil
return true
}
if didCacheRemoteResult { return }
}

guard self.productEntitlementMappingLock.perform({
!self.isClosed && !Task.isCancelled
}) else {
return
}

Logger.debug(Strings.offlineEntitlements.product_entitlement_mapping_stale_updating)
let result = await self.fetchLegacyProductEntitlementMappingResult(isAppBackgrounded: isAppBackgrounded)
self.productEntitlementMappingLock.perform {
guard !self.isClosed, !Task.isCancelled else { return }
switch result {
case let .success(response):
self.handleProductEntitlementMappingBackendResult(with: response)

case let .failure(error):
self.handleProductsEntitlementsUpdateError(error)
}

self.productEntitlementMappingTask = nil
}
}

@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
private func fetchLegacyProductEntitlementMapping(isAppBackgrounded: Bool) {
self.api.getProductEntitlementMapping(isAppBackgrounded: isAppBackgrounded) { result in
switch result {
case let .success(response):
Expand All @@ -57,13 +127,16 @@ class OfflineEntitlementsManager {
case let .failure(error):
self.handleProductsEntitlementsUpdateError(error)
}
}
}

self.dispatchCompletionOnMainThreadIfPossible(
completion,
result: result
.map { _ in () }
.mapError(Error.backend)
)
private func fetchLegacyProductEntitlementMappingResult(
isAppBackgrounded: Bool
) async -> Result<ProductEntitlementMappingResponse, BackendError> {
return await withCheckedContinuation { continuation in
self.api.getProductEntitlementMapping(isAppBackgrounded: isAppBackgrounded) {
continuation.resume(returning: $0)
}
}
}

Expand All @@ -79,18 +152,6 @@ class OfflineEntitlementsManager {

}

extension OfflineEntitlementsManager {

enum Error: Swift.Error {

case backend(BackendError)
/// Offline entitlements require iOS 15+, and not available for custom entitlements computation
case notAvailable

}

}

@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
private extension OfflineEntitlementsManager {

Expand All @@ -105,18 +166,3 @@ private extension OfflineEntitlementsManager {
}

}

private extension OfflineEntitlementsManager {

func dispatchCompletionOnMainThreadIfPossible<Value, Error: Swift.Error>(
_ completion: (@MainActor @Sendable (Result<Value, Error>) -> Void)?,
result: Result<Value, Error>
) {
if let completion = completion {
self.operationDispatcher.dispatchOnMainActor {
completion(result)
}
}
}

}
19 changes: 11 additions & 8 deletions Sources/Purchasing/Purchases/Purchases.swift
Original file line number Diff line number Diff line change
Expand Up @@ -464,10 +464,11 @@ public typealias StartPurchaseBlock = (@escaping PurchaseCompletedBlock) -> Void
localTransactionMetadataStore: localTransactionMetadataStore
)

let offlineEntitlementsManager = OfflineEntitlementsManager(deviceCache: deviceCache,
operationDispatcher: operationDispatcher,
api: backend.offlineEntitlements,
systemInfo: systemInfo)
let offlineEntitlementsManager = OfflineEntitlementsManager(
deviceCache: deviceCache,
api: backend.offlineEntitlements,
systemInfo: systemInfo
)

let customerInfoManager: CustomerInfoManager
if #available(iOS 15.0, tvOS 15.0, macOS 12.0, watchOS 8.0, *) {
Expand Down Expand Up @@ -869,6 +870,9 @@ public typealias StartPurchaseBlock = (@escaping PurchaseCompletedBlock) -> Void
super.init()

self.identityManager.remoteConfigManager = self.remoteConfigManager
self.offlineEntitlementsManager.setProductEntitlementMappingTopicProvider(
ProductEntitlementMappingTopicProvider(manager: self.remoteConfigManager)
)
self.remoteConfigManager.onRemoteConfigDisabled = { [weak self] in
guard let self else { return }
self.offeringsManager.invalidateAndReFetchCachedOfferingsIfAppropiate(appUserID: self.appUserID)
Expand Down Expand Up @@ -931,6 +935,7 @@ public typealias StartPurchaseBlock = (@escaping PurchaseCompletedBlock) -> Void
self.notificationCenter.removeObserver(self)
self.paymentQueueWrapper.sk1Wrapper?.delegate = nil
self.paymentQueueWrapper.sk2Wrapper?.delegate = nil
self.offlineEntitlementsManager.close()
self.remoteConfigManager.close()
self.customerInfoObservationDisposable?()
self.privateDelegate = nil
Expand Down Expand Up @@ -2781,8 +2786,7 @@ private extension Purchases {
isAppBackgrounded: isAppBackgrounded,
completion: nil)
self.offlineEntitlementsManager.updateProductsEntitlementsCacheIfStale(
isAppBackgrounded: isAppBackgrounded,
completion: nil
isAppBackgrounded: isAppBackgrounded
)
}

Expand Down Expand Up @@ -2829,8 +2833,7 @@ private extension Purchases {
}

self.offlineEntitlementsManager.updateProductsEntitlementsCacheIfStale(
isAppBackgrounded: isAppBackgrounded,
completion: nil
isAppBackgrounded: isAppBackgrounded
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ class MockOfflineEntitlementsManager: OfflineEntitlementsManager {

init() {
super.init(deviceCache: MockDeviceCache(),
operationDispatcher: MockOperationDispatcher(),
api: MockOfflineEntitlementsAPI(),
systemInfo: MockSystemInfo(finishTransactions: false))
}
Expand All @@ -28,10 +27,7 @@ class MockOfflineEntitlementsManager: OfflineEntitlementsManager {
var invokedUpdateProductsEntitlementsCacheIfStaleParameters: Bool?
var invokedUpdateProductsEntitlementsCacheIfStaleParametersList = [Bool]()

override func updateProductsEntitlementsCacheIfStale(
isAppBackgrounded: Bool,
completion: (@MainActor @Sendable (Result<(), Error>) -> Void)?
) {
override func updateProductsEntitlementsCacheIfStale(isAppBackgrounded: Bool) {
self.invokedUpdateProductsEntitlementsCacheIfStale = true
self.invokedUpdateProductsEntitlementsCacheIfStaleCount += 1
self.invokedUpdateProductsEntitlementsCacheIfStaleParameters = isAppBackgrounded
Expand Down
Loading