From d5c12e7bd5df30df5f3f82c451df2e35e8a33b71 Mon Sep 17 00:00:00 2001 From: feather2222 <1402479908@qq.com> Date: Sat, 24 Oct 2026 00:14:41 +0800 Subject: [PATCH] Rate-limit remote feature-flag and remote-config fetches After the UIScene adoption (#25643), WordPressAppDelegate refreshes both stores on cold launch twice (willFinishLaunch + the foreground transition), and the stores themselves have no client-side throttle, so any caller asking twice in quick succession hits the network twice. Give each store a persisted last-fetched date and a 5-minute minimum refresh interval, shaped after AppUpdateCoordinator.shouldFetchAppStoreInfo: update() serves the cache (still invoking its callback) within the interval. A force: bypass keeps per-user flag refreshes working on account change/logout, and failed fetches don't stamp the date so retries aren't suppressed. Fixes #25665 --- .../Utility/RemoteFeatureFlagTests.swift | 75 ++++++++++++++++++- .../Tests/Utility/RemoteParameterTests.swift | 64 +++++++++++++++- .../Classes/Stores/RemoteConfigStore.swift | 44 ++++++++++- .../Stores/RemoteFeatureFlagStore.swift | 44 ++++++++++- .../Classes/System/WordPressAppDelegate.swift | 6 +- WordPress/Classes/Utility/AccountHelper.swift | 4 +- 6 files changed, 227 insertions(+), 10 deletions(-) diff --git a/Tests/KeystoneTests/Tests/Utility/RemoteFeatureFlagTests.swift b/Tests/KeystoneTests/Tests/Utility/RemoteFeatureFlagTests.swift index 734c90839b25..dd18bcc0fa99 100644 --- a/Tests/KeystoneTests/Tests/Utility/RemoteFeatureFlagTests.swift +++ b/Tests/KeystoneTests/Tests/Utility/RemoteFeatureFlagTests.swift @@ -10,7 +10,8 @@ class RemoteFeatureFlagTests: XCTestCase { } func testThatDeviceIdIsTheSameForEveryInstanceOfTheStore() { - let store = RemoteFeatureFlagStore(persistenceStore: mockUserDefaults) + // Disable the refresh rate limit: this test expects both updates to fetch. + let store = RemoteFeatureFlagStore(persistenceStore: mockUserDefaults, minimumRefreshInterval: 0) let mock = MockFeatureFlagRemote() var deviceId = "" @@ -62,12 +63,77 @@ class RemoteFeatureFlagTests: XCTestCase { XCTAssertFalse(store.value(for: MockFeatureFlag.remotelyDisabledLocallyEnabledFeature.remoteKey)!) XCTAssertFalse(store.value(for: MockFeatureFlag.remotelyDisabledLocallyDisabledFeature.remoteKey)!) } + + // MARK: - Rate Limiting + + func testThatSecondUpdateWithinMinimumRefreshIntervalIsSkipped() { + let store = RemoteFeatureFlagStore(persistenceStore: mockUserDefaults) + let mock = MockFeatureFlagRemote() + + let exp = expectation(description: "Both callbacks fire") + exp.expectedFulfillmentCount = 2 + + store.update(using: mock) { exp.fulfill() } + store.update(using: mock) { exp.fulfill() } + + wait(for: [exp], timeout: 1.0) + XCTAssertEqual(mock.fetchCount, 1) + } + + func testThatForcedUpdateBypassesMinimumRefreshInterval() { + let store = RemoteFeatureFlagStore(persistenceStore: mockUserDefaults) + let mock = MockFeatureFlagRemote() + + let exp = expectation(description: "Both callbacks fire") + exp.expectedFulfillmentCount = 2 + + store.update(using: mock) { exp.fulfill() } + store.update(using: mock, force: true) { exp.fulfill() } + + wait(for: [exp], timeout: 1.0) + XCTAssertEqual(mock.fetchCount, 2) + } + + func testThatUpdateWithRecentFetchIsSkipped() { + mockUserDefaults.set(Date(), forKey: RemoteFeatureFlagStore.Constants.LastFetchedDateKey) + let store = RemoteFeatureFlagStore(persistenceStore: mockUserDefaults) + let mock = MockFeatureFlagRemote() + + store.update(using: mock, waitOn: self) + + XCTAssertEqual(mock.fetchCount, 0) + } + + func testThatUpdateAfterMinimumRefreshIntervalFetchesAgain() { + mockUserDefaults.set(Date().addingTimeInterval(-600), forKey: RemoteFeatureFlagStore.Constants.LastFetchedDateKey) + let store = RemoteFeatureFlagStore(persistenceStore: mockUserDefaults) + let mock = MockFeatureFlagRemote() + + store.update(using: mock, waitOn: self) + + XCTAssertEqual(mock.fetchCount, 1) + } + + func testThatFailedUpdateDoesNotSuppressRetry() { + let store = RemoteFeatureFlagStore(persistenceStore: mockUserDefaults) + let mock = MockFeatureFlagRemote() + mock.error = NSError(domain: "test", code: 0) + + store.update(using: mock, waitOn: self) + // The failure must not stamp the last-fetched date, so the next + // update retries instead of being rate limited. + store.update(using: mock, waitOn: self) + + XCTAssertEqual(mock.fetchCount, 2) + } } class MockFeatureFlagRemote: FeatureFlagRemote { var flags: FeatureFlagList var deviceIdCallback: ((String) -> Void)? + var fetchCount = 0 + var error: Error? init(mockFlags: [MockFeatureFlag] = []) { self.flags = mockFlags @@ -81,7 +147,12 @@ class MockFeatureFlagRemote: FeatureFlagRemote { } public override func getRemoteFeatureFlags(forDeviceId deviceId: String, callback: @escaping FeatureFlagResponseCallback) { + fetchCount += 1 deviceIdCallback?(deviceId) - callback(.success(flags)) + if let error { + callback(.failure(error)) + } else { + callback(.success(flags)) + } } } diff --git a/Tests/KeystoneTests/Tests/Utility/RemoteParameterTests.swift b/Tests/KeystoneTests/Tests/Utility/RemoteParameterTests.swift index f28649f494f8..c1b2e153b6f5 100644 --- a/Tests/KeystoneTests/Tests/Utility/RemoteParameterTests.swift +++ b/Tests/KeystoneTests/Tests/Utility/RemoteParameterTests.swift @@ -60,6 +60,8 @@ struct MockRemoteParameter: RemoteParameter { class MockRemoteConfigRemote: RemoteConfigRemote { var config: RemoteConfigDictionary + var fetchCount = 0 + var error: Error? init(config: [String: Any] = [:]) { self.config = config @@ -67,6 +69,66 @@ class MockRemoteConfigRemote: RemoteConfigRemote { } override func getRemoteConfig(callback: @escaping RemoteConfigRemote.RemoteConfigResponseCallback) { - callback(.success(config)) + fetchCount += 1 + if let error { + callback(.failure(error)) + } else { + callback(.success(config)) + } + } +} + +final class RemoteConfigStoreRateLimitTests: XCTestCase { + + private var mockUserDefaults: InMemoryUserDefaults! + private var mock: MockRemoteConfigRemote! + private var store: RemoteConfigStore! + + override func setUp() { + mockUserDefaults = InMemoryUserDefaults() + mock = MockRemoteConfigRemote(config: ["param_key": "server_value"]) + store = RemoteConfigStore(remote: mock, persistenceStore: mockUserDefaults) + } + + func testThatSecondUpdateWithinMinimumRefreshIntervalIsSkipped() { + store.update() + store.update() + + XCTAssertEqual(mock.fetchCount, 1) + XCTAssertEqual(store.value(for: "param_key") as? String, "server_value") + } + + func testThatForcedUpdateBypassesMinimumRefreshInterval() { + store.update() + store.update(force: true) + + XCTAssertEqual(mock.fetchCount, 2) + } + + func testThatUpdateWithRecentFetchIsSkipped() { + mockUserDefaults.set(Date(), forKey: RemoteConfigStore.Constants.LastFetchedDateKey) + + store.update() + + XCTAssertEqual(mock.fetchCount, 0) + } + + func testThatUpdateAfterMinimumRefreshIntervalFetchesAgain() { + mockUserDefaults.set(Date().addingTimeInterval(-600), forKey: RemoteConfigStore.Constants.LastFetchedDateKey) + + store.update() + + XCTAssertEqual(mock.fetchCount, 1) + } + + func testThatFailedUpdateDoesNotSuppressRetry() { + mock.error = NSError(domain: "test", code: 0) + + store.update() + // The failure must not stamp the last-fetched date, so the next + // update retries instead of being rate limited. + store.update() + + XCTAssertEqual(mock.fetchCount, 2) } } diff --git a/WordPress/Classes/Stores/RemoteConfigStore.swift b/WordPress/Classes/Stores/RemoteConfigStore.swift index 581b54e5e3ab..b7bc7866c7dc 100644 --- a/WordPress/Classes/Stores/RemoteConfigStore.swift +++ b/WordPress/Classes/Stores/RemoteConfigStore.swift @@ -16,14 +16,20 @@ class RemoteConfigStore { private let remote: RemoteConfigRemote private let persistenceStore: UserPersistentRepository + /// Minimum time between remote fetches. Calls to `update` within this + /// interval serve the cache instead of hitting the network, unless forced. + private let minimumRefreshInterval: TimeInterval + // MARK: Initializer init(queue: DispatchQueue = .remoteConfigStoreQueue, remote: RemoteConfigRemote = RemoteConfigRemote(wordPressComRestApi: WordPressComRestApi.defaultApi()), - persistenceStore: UserPersistentRepository = UserDefaults.standard) { + persistenceStore: UserPersistentRepository = UserDefaults.standard, + minimumRefreshInterval: TimeInterval = Constants.defaultMinimumRefreshInterval) { self.queue = queue self.remote = remote self.persistenceStore = persistenceStore + self.minimumRefreshInterval = minimumRefreshInterval } // MARK: Public Functions @@ -36,12 +42,20 @@ class RemoteConfigStore { } /// Fetches remote config values from the server. + /// - Parameter force: When `true`, bypasses the minimum refresh interval. /// - Parameter callback: An optional callback that can be used to update UI following the fetch. It is not called on the UI thread. - public func update(then callback: FetchCallback? = nil) { + public func update(force: Bool = false, then callback: FetchCallback? = nil) { + guard force || shouldFetch else { + DDLogInfo("🚩 Skipping remote config update – fetched recently, serving cached values") + callback?() + return + } + remote.getRemoteConfig { [weak self] result in switch result { case .success(let response): self?.cache = response + self?.lastFetchedDate = Date() DDLogInfo("🚩 Successfully updated remote config values: \(response)") callback?() case .failure(let error): @@ -49,15 +63,41 @@ class RemoteConfigStore { } } } + + /// Whether a remote fetch should happen now, given the last fetch time. + private var shouldFetch: Bool { + queue.sync { + guard let lastFetchedDate = persistenceStore.object(forKey: Constants.LastFetchedDateKey) as? Date else { + return true + } + return Date().timeIntervalSince(lastFetchedDate) >= minimumRefreshInterval + } + } } extension RemoteConfigStore { struct Constants { static let CachedResponseKey = "RemoteConfigStoreCache" + static let LastFetchedDateKey = "RemoteConfigStoreLastFetchedDate" + static let defaultMinimumRefreshInterval: TimeInterval = 5 * 60 } typealias FetchCallback = () -> Void + /// The last time the config values were successfully fetched from the server. + private var lastFetchedDate: Date? { + get { + queue.sync { + persistenceStore.object(forKey: Constants.LastFetchedDateKey) as? Date + } + } + set { + queue.sync { + persistenceStore.set(newValue, forKey: Constants.LastFetchedDateKey) + } + } + } + /// The local cache stores remote config values between runs so that the most recently fetched set are ready to go as soon as this object is instantiated. private var cache: [String: Any] { get { diff --git a/WordPress/Classes/Stores/RemoteFeatureFlagStore.swift b/WordPress/Classes/Stores/RemoteFeatureFlagStore.swift index 90829c331e58..b0a9f8d924fd 100644 --- a/WordPress/Classes/Stores/RemoteFeatureFlagStore.swift +++ b/WordPress/Classes/Stores/RemoteFeatureFlagStore.swift @@ -7,6 +7,11 @@ class RemoteFeatureFlagStore { /// Thread Safety Coordinator private var lock = NSLock() private var persistenceStore: UserPersistentRepository + + /// Minimum time between remote fetches. Calls to `update` within this + /// interval serve the cache instead of hitting the network, unless + /// forced (e.g. on account change). + private let minimumRefreshInterval: TimeInterval private lazy var operationQueue: OperationQueue = { var queue = OperationQueue() queue.name = "Feature Flags Refresh Queue" @@ -33,22 +38,33 @@ class RemoteFeatureFlagStore { persistenceStore.string(forKey: Constants.DeviceIdKey) == nil } - init(persistenceStore: UserPersistentRepository = UserDefaults.standard) { + init(persistenceStore: UserPersistentRepository = UserDefaults.standard, + minimumRefreshInterval: TimeInterval = Constants.defaultMinimumRefreshInterval) { self.persistenceStore = persistenceStore + self.minimumRefreshInterval = minimumRefreshInterval } /// Fetches remote feature flags from the server. /// - Parameter remote: An optional FeatureFlagRemote with a default WordPressComRestApi instance. Inject a FeatureFlagRemote with a different WordPressComRestApi instance /// to authenticate with the Remote Feature Flags endpoint – this allows customizing flags server-side on a per-user basis. + /// - Parameter force: When `true`, bypasses the minimum refresh interval. Use it when the authenticated user changes, since flags are customized per-user server-side. /// - Parameter callback: An optional callback that can be used to update UI following the fetch. It is not called on the UI thread. public func update(using remote: FeatureFlagRemote = FeatureFlagRemote(wordPressComRestApi: WordPressComRestApi.defaultApi()), + force: Bool = false, then callback: FetchCallback? = nil) { + guard force || shouldFetch else { + DDLogInfo("🚩 Skipping feature flags update – fetched recently, serving cached flags") + callback?() + return + } + let refreshOperation = FetchRemoteFeatureFlagsOperation(remote: remote, deviceID: deviceID, completion: { [weak self] result in switch result { case .success(let flags): self?.cache = flags + self?.lastFetchedDate = Date() callback?() case .failure: callback?() @@ -58,6 +74,16 @@ class RemoteFeatureFlagStore { operationQueue.addOperation(refreshOperation) } + /// Whether a remote fetch should happen now, given the last fetch time. + private var shouldFetch: Bool { + lock.withLock { + guard let lastFetchedDate = persistenceStore.object(forKey: Constants.LastFetchedDateKey) as? Date else { + return true + } + return Date().timeIntervalSince(lastFetchedDate) >= minimumRefreshInterval + } + } + /// Checks if the local cache has a value for a given `FeatureFlag` public func hasValue(for flagKey: String) -> Bool { return value(for: flagKey) != nil @@ -73,10 +99,26 @@ extension RemoteFeatureFlagStore { struct Constants { static let DeviceIdKey = "FeatureFlagDeviceId" static let CachedFlagsKey = "FeatureFlagStoreCache" + static let LastFetchedDateKey = "FeatureFlagStoreLastFetchedDate" + static let defaultMinimumRefreshInterval: TimeInterval = 5 * 60 } typealias FetchCallback = () -> Void + /// The last time the flags were successfully fetched from the server. + private var lastFetchedDate: Date? { + get { + lock.withLock { + persistenceStore.object(forKey: Constants.LastFetchedDateKey) as? Date + } + } + set { + lock.withLock { + persistenceStore.set(newValue, forKey: Constants.LastFetchedDateKey) + } + } + } + /// The local cache stores feature flags between runs so that the most recently fetched set are ready to go as soon as this object is instantiated. private var cache: [String: Bool] { get { diff --git a/WordPress/Classes/System/WordPressAppDelegate.swift b/WordPress/Classes/System/WordPressAppDelegate.swift index 82a7fbc9f00a..979fb81dbb5b 100644 --- a/WordPress/Classes/System/WordPressAppDelegate.swift +++ b/WordPress/Classes/System/WordPressAppDelegate.swift @@ -641,7 +641,7 @@ extension WordPressAppDelegate { /// Updates the remote feature flags using an authenticated remote if a token is provided or an account exists /// Otherwise an anonymous remote will be used - func updateFeatureFlags(authToken: String? = nil, completion: (() -> Void)? = nil) { + func updateFeatureFlags(authToken: String? = nil, force: Bool = false, completion: (() -> Void)? = nil) { /// - warning: must be called before the `update(using:then:)`. if remoteFeatureFlagStore.isFreshInstall { FeatureFlagOverrideStore().override(FeatureFlag.newStats, withValue: true) @@ -654,7 +654,9 @@ extension WordPressAppDelegate { api = WordPressComRestApi.defaultV2Api(in: mainContext) } let remote = FeatureFlagRemote(wordPressComRestApi: api) - remoteFeatureFlagStore.update(using: remote, then: completion) + // An explicit auth token means the account context changed; flags are + // customized per-user server-side, so bypass the refresh rate limit. + remoteFeatureFlagStore.update(using: remote, force: force || authToken != nil, then: completion) } func updateRemoteConfig() { diff --git a/WordPress/Classes/Utility/AccountHelper.swift b/WordPress/Classes/Utility/AccountHelper.swift index 8d1083a65186..ce9a4a0c5b0f 100644 --- a/WordPress/Classes/Utility/AccountHelper.swift +++ b/WordPress/Classes/Utility/AccountHelper.swift @@ -111,8 +111,8 @@ import WordPressData // Delete donated user activities (e.g., for Siri Shortcuts) NSUserActivity.deleteAllSavedUserActivities {} - // Refresh Remote Feature Flags - WordPressAppDelegate.shared?.updateFeatureFlags() + // Refresh Remote Feature Flags (forced: the account context changed) + WordPressAppDelegate.shared?.updateFeatureFlags(force: true) // Delete all the logs after logging out WPLogger.shared().deleteAllLogs()