|
| 1 | +import Foundation |
| 2 | +import UIKit |
| 3 | +import CocoaLumberjackSwift |
| 4 | +import Yosemite |
| 5 | +import Experiments |
| 6 | + |
| 7 | +/// Periodically syncs POS catalog while the app is in the foreground. |
| 8 | +/// Triggers `catalogCoordinator.performSmartSync()` every hour when active. |
| 9 | +/// |
| 10 | +final actor ForegroundPOSCatalogSyncDispatcher { |
| 11 | + private enum Constants { |
| 12 | + static let syncInterval: TimeInterval = 60 * 60 // 1 hour |
| 13 | + static let initialSyncDelay: TimeInterval = 5 // 5 seconds after becoming active |
| 14 | + static let leeway: Int = 5 // 5 seconds leeway to give a system more flexibility in managing resources |
| 15 | + } |
| 16 | + |
| 17 | + private let interval: TimeInterval |
| 18 | + private let notificationCenter: NotificationCenter |
| 19 | + private let timerProvider: DispatchTimerProviding |
| 20 | + private let featureFlagService: FeatureFlagService |
| 21 | + private let storeProvider: POSCatalogStoreProviding |
| 22 | + private let isAppActive: () async -> Bool |
| 23 | + private var observers: [NSObjectProtocol] = [] |
| 24 | + private var timer: DispatchTimerProtocol? |
| 25 | + |
| 26 | + private var isRunning: Bool { |
| 27 | + syncSiteID != nil |
| 28 | + } |
| 29 | + private var syncSiteID: Int64? |
| 30 | + |
| 31 | + init(interval: TimeInterval = Constants.syncInterval, |
| 32 | + notificationCenter: NotificationCenter = .default, |
| 33 | + timerProvider: DispatchTimerProviding = DefaultDispatchTimerProvider(), |
| 34 | + featureFlagService: FeatureFlagService = ServiceLocator.featureFlagService, |
| 35 | + storeProvider: POSCatalogStoreProviding = DefaultPOSCatalogStoreProvider(), |
| 36 | + isAppActive: @escaping () async -> Bool = UIApplication.isApplicationActive) { |
| 37 | + self.interval = interval |
| 38 | + self.notificationCenter = notificationCenter |
| 39 | + self.timerProvider = timerProvider |
| 40 | + self.featureFlagService = featureFlagService |
| 41 | + self.storeProvider = storeProvider |
| 42 | + self.isAppActive = isAppActive |
| 43 | + } |
| 44 | + |
| 45 | + func start() async { |
| 46 | + guard featureFlagService.isFeatureFlagEnabled(.pointOfSaleLocalCatalogi1) else { |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + if syncSiteID != nil, syncSiteID != storeProvider.defaultStoreID { |
| 51 | + DDLogInfo("🔄 ForegroundPOSCatalogSyncDispatcher: Site has changed, resetting the sync") |
| 52 | + stop() |
| 53 | + } |
| 54 | + |
| 55 | + guard !isRunning else { return } |
| 56 | + |
| 57 | + DDLogInfo("🔄 ForegroundPOSCatalogSyncDispatcher: Starting foreground sync dispatcher for site \(storeProvider.defaultStoreID ?? 0)") |
| 58 | + |
| 59 | + let activeObserver = notificationCenter.addObserver( |
| 60 | + forName: UIApplication.didBecomeActiveNotification, |
| 61 | + object: nil, |
| 62 | + queue: .main |
| 63 | + ) { [weak self] _ in |
| 64 | + Task { |
| 65 | + await self?.startTimer() |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + let backgroundObserver = notificationCenter.addObserver( |
| 70 | + forName: UIApplication.didEnterBackgroundNotification, |
| 71 | + object: nil, |
| 72 | + queue: .main |
| 73 | + ) { [weak self] _ in |
| 74 | + Task { |
| 75 | + await self?.stopTimer() |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + let defaultSiteObserver = notificationCenter.addObserver( |
| 80 | + forName: .StoresManagerDidUpdateDefaultSite, |
| 81 | + object: nil, |
| 82 | + queue: .main |
| 83 | + ) { [weak self] _ in |
| 84 | + Task { |
| 85 | + await self?.stop() |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + observers = [activeObserver, backgroundObserver, defaultSiteObserver] |
| 90 | + |
| 91 | + if await isAppActive() { |
| 92 | + startTimer() |
| 93 | + } |
| 94 | + |
| 95 | + syncSiteID = storeProvider.defaultStoreID |
| 96 | + } |
| 97 | + |
| 98 | + func stop() { |
| 99 | + guard isRunning else { return } |
| 100 | + |
| 101 | + DDLogInfo("🛑 ForegroundPOSCatalogSyncDispatcher: Stopping foreground sync dispatcher for site \(syncSiteID ?? 0)") |
| 102 | + observers.forEach(notificationCenter.removeObserver) |
| 103 | + observers.removeAll() |
| 104 | + stopTimer() |
| 105 | + syncSiteID = nil |
| 106 | + } |
| 107 | + |
| 108 | + private func startTimer() { |
| 109 | + guard timer == nil else { return } |
| 110 | + |
| 111 | + DDLogInfo("⏱️ ForegroundPOSCatalogSyncDispatcher: Starting timer (interval: \(Int(interval))s, initial delay: \(Int(Constants.initialSyncDelay))s)") |
| 112 | + |
| 113 | + let queue = DispatchQueue(label: "com.automattic.woocommerce.posCatalogForegroundSync.timer", qos: .utility) |
| 114 | + let timer = timerProvider.makeTimer(queue: queue) |
| 115 | + timer.schedule(deadline: .now() + Constants.initialSyncDelay, repeating: interval, leeway: .seconds(Constants.leeway)) |
| 116 | + timer.setEventHandler { [weak self] in |
| 117 | + Task { |
| 118 | + await self?.performSync() |
| 119 | + } |
| 120 | + } |
| 121 | + timer.resume() |
| 122 | + self.timer = timer |
| 123 | + } |
| 124 | + |
| 125 | + private func stopTimer() { |
| 126 | + guard timer != nil else { return } |
| 127 | + DDLogInfo("⏱️ ForegroundPOSCatalogSyncDispatcher: Stopping timer") |
| 128 | + timer?.cancel() |
| 129 | + timer = nil |
| 130 | + } |
| 131 | + |
| 132 | + private func performSync() { |
| 133 | + guard featureFlagService.isFeatureFlagEnabled(.pointOfSaleLocalCatalogi1) else { |
| 134 | + DDLogInfo("📋 ForegroundPOSCatalogSyncDispatcher: Feature flag disabled, skipping sync") |
| 135 | + stop() |
| 136 | + return |
| 137 | + } |
| 138 | + |
| 139 | + guard let siteID = storeProvider.defaultStoreID else { |
| 140 | + DDLogInfo("📋 ForegroundPOSCatalogSyncDispatcher: No default store, skipping sync") |
| 141 | + stop() |
| 142 | + return |
| 143 | + } |
| 144 | + |
| 145 | + guard let coordinator = storeProvider.posCatalogSyncCoordinator else { |
| 146 | + DDLogInfo("📋 ForegroundPOSCatalogSyncDispatcher: Coordinator unavailable, skipping sync") |
| 147 | + stop() |
| 148 | + return |
| 149 | + } |
| 150 | + |
| 151 | + DDLogInfo("🔄 ForegroundPOSCatalogSyncDispatcher: Starting sync for site \(siteID)") |
| 152 | + |
| 153 | + Task.detached(priority: .utility) { |
| 154 | + do { |
| 155 | + try await coordinator.performSmartSync(for: siteID) |
| 156 | + DDLogInfo("✅ ForegroundPOSCatalogSyncDispatcher: Sync completed for site \(siteID)") |
| 157 | + } catch let error as POSCatalogSyncError { |
| 158 | + switch error { |
| 159 | + case .syncAlreadyInProgress: |
| 160 | + DDLogInfo("ℹ️ ForegroundPOSCatalogSyncDispatcher: Sync already in progress for site \(siteID)") |
| 161 | + case .negativeMaxAge: |
| 162 | + DDLogError("⛔️ ForegroundPOSCatalogSyncDispatcher: Invalid max age for site \(siteID)") |
| 163 | + } |
| 164 | + } catch { |
| 165 | + DDLogError("⛔️ ForegroundPOSCatalogSyncDispatcher: Sync failed for site \(siteID): \(error)") |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +// MARK: - Helpers |
| 172 | + |
| 173 | +/// Simplified protocol for dispatch source timers, only exposing methods actually used. |
| 174 | +protocol DispatchTimerProtocol { |
| 175 | + func schedule(deadline: DispatchTime, repeating: Double, leeway: DispatchTimeInterval) |
| 176 | + func setEventHandler(handler: (() -> Void)?) |
| 177 | + func resume() |
| 178 | + func cancel() |
| 179 | +} |
| 180 | + |
| 181 | +extension DispatchSourceTimer { |
| 182 | + func asTimer() -> DispatchTimerProtocol { |
| 183 | + DispatchTimerWrapper(timer: self) |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +private struct DispatchTimerWrapper: DispatchTimerProtocol { |
| 188 | + let timer: DispatchSourceTimer |
| 189 | + |
| 190 | + func schedule(deadline: DispatchTime, repeating: Double, leeway: DispatchTimeInterval) { |
| 191 | + timer.schedule(deadline: deadline, repeating: repeating, leeway: leeway) |
| 192 | + } |
| 193 | + |
| 194 | + func setEventHandler(handler: (() -> Void)?) { |
| 195 | + timer.setEventHandler(handler: handler) |
| 196 | + } |
| 197 | + |
| 198 | + func resume() { |
| 199 | + timer.resume() |
| 200 | + } |
| 201 | + |
| 202 | + func cancel() { |
| 203 | + timer.cancel() |
| 204 | + } |
| 205 | +} |
| 206 | + |
| 207 | +/// Protocol for creating dispatch timers, enabling testability. |
| 208 | +protocol DispatchTimerProviding { |
| 209 | + func makeTimer(queue: DispatchQueue) -> DispatchTimerProtocol |
| 210 | +} |
| 211 | + |
| 212 | +/// Default implementation using system DispatchSource. |
| 213 | +struct DefaultDispatchTimerProvider: DispatchTimerProviding { |
| 214 | + func makeTimer(queue: DispatchQueue) -> DispatchTimerProtocol { |
| 215 | + DispatchSource.makeTimerSource(queue: queue).asTimer() |
| 216 | + } |
| 217 | +} |
| 218 | + |
| 219 | +extension UIApplication { |
| 220 | + static func isApplicationActive() async -> Bool { |
| 221 | + shared.applicationState == .active |
| 222 | + } |
| 223 | +} |
| 224 | + |
| 225 | +/// Protocol for accessing store ID and POS catalog sync coordinator. |
| 226 | +protocol POSCatalogStoreProviding { |
| 227 | + var defaultStoreID: Int64? { get } |
| 228 | + var posCatalogSyncCoordinator: POSCatalogSyncCoordinatorProtocol? { get } |
| 229 | +} |
| 230 | + |
| 231 | +/// Default implementation using StoresManager. |
| 232 | +struct DefaultPOSCatalogStoreProvider: POSCatalogStoreProviding { |
| 233 | + private let stores: StoresManager |
| 234 | + |
| 235 | + init(stores: StoresManager = ServiceLocator.stores) { |
| 236 | + self.stores = stores |
| 237 | + } |
| 238 | + |
| 239 | + var defaultStoreID: Int64? { |
| 240 | + stores.sessionManager.defaultStoreID |
| 241 | + } |
| 242 | + |
| 243 | + var posCatalogSyncCoordinator: POSCatalogSyncCoordinatorProtocol? { |
| 244 | + stores.posCatalogSyncCoordinator |
| 245 | + } |
| 246 | +} |
0 commit comments