Skip to content
Open
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
75 changes: 73 additions & 2 deletions Tests/KeystoneTests/Tests/Utility/RemoteFeatureFlagTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""

Expand Down Expand Up @@ -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
Expand All @@ -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))
}
}
}
64 changes: 63 additions & 1 deletion Tests/KeystoneTests/Tests/Utility/RemoteParameterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,75 @@ struct MockRemoteParameter: RemoteParameter {
class MockRemoteConfigRemote: RemoteConfigRemote {

var config: RemoteConfigDictionary
var fetchCount = 0
var error: Error?

init(config: [String: Any] = [:]) {
self.config = config
super.init()
}

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)
}
}
44 changes: 42 additions & 2 deletions WordPress/Classes/Stores/RemoteConfigStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -36,28 +42,62 @@ 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):
DDLogError("🚩 Unable to update remote config values: \(error.localizedDescription)")
}
}
}

/// 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 {
Expand Down
44 changes: 43 additions & 1 deletion WordPress/Classes/Stores/RemoteFeatureFlagStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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?()
Expand All @@ -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
Expand All @@ -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 {
Expand Down
6 changes: 4 additions & 2 deletions WordPress/Classes/System/WordPressAppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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() {
Expand Down
4 changes: 2 additions & 2 deletions WordPress/Classes/Utility/AccountHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down