Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement experiment manager #1066

Merged
merged 19 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//
// ExperimentCohortsManager.swift
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
//
// Copyright © 2024 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation

struct ExperimentSubfeature {
let subfeatureID: SubfeatureID
let cohorts: [PrivacyConfigurationData.Cohort]
}

typealias CohortID = String
typealias SubfeatureID = String

struct ExperimentData: Codable, Equatable {
let cohort: String
let enrollmentDate: Date
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
}

typealias Experiments = [String: ExperimentData]

protocol ExperimentCohortsManaging {
/// Retrieves the cohort ID associated with the specified subfeature.
/// - Parameter subfeature: The experiment subfeature for which the cohort ID is needed.
/// - Returns: The cohort ID as a `String` if one exists; otherwise, returns `nil`.
func cohort(for subfeatureID: SubfeatureID) -> CohortID?

/// Retrieves the enrollment date for the specified subfeature.
/// - Parameter subfeatureID: The experiment subfeature for which the enrollment date is needed.
/// - Returns: The `Date` of enrollment if one exists; otherwise, returns `nil`.
func enrolmentDate(for subfeatureID: SubfeatureID) -> Date?
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved

/// Assigns a cohort to the given subfeature based on defined weights and saves it to UserDefaults.
/// - Parameter subfeature: The experiment subfeature to assign a cohort for.
/// - Returns: The name of the assigned cohort, or `nil` if no cohort could be assigned.
func assignCohort(for subfeature: ExperimentSubfeature) -> CohortID?
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved

/// Removes the assigned cohort data for the specified subfeature.
/// - Parameter subfeature: The experiment subfeature for which the cohort data should be removed.
func removeCohort(for subfeatureID: SubfeatureID)
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
}

final class ExperimentCohortsManager: ExperimentCohortsManaging {

private var store: ExperimentsDataStoring
private let queue = DispatchQueue(label: "com.experimentManager.queue")
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
private let randomizer: (Range<Double>) -> Double
private let experimentsDataKey = "ExperimentsData"
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved

init(store: ExperimentsDataStoring = ExperimentsDataStore(), randomizer: @escaping (Range<Double>) -> Double) {
self.store = store
self.randomizer = randomizer
}

func cohort(for subfeatureID: SubfeatureID) -> CohortID? {
guard let experiments = getExperimentData() else { return nil }
return experiments[subfeatureID]?.cohort
}

func enrolmentDate(for subfeatureID: SubfeatureID) -> Date? {
guard let experiments = getExperimentData() else { return nil }
return experiments[subfeatureID]?.enrollmentDate
}

func assignCohort(for subfeature: ExperimentSubfeature) -> CohortID? {
let cohorts = subfeature.cohorts
let totalWeight = cohorts.reduce(0, { $0 + $1.weight })
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
guard totalWeight > 0 else { return nil }

let randomValue = randomizer(0..<Double(totalWeight))
var cumulativeWeight = 0.0

for cohort in cohorts {
cumulativeWeight += Double(cohort.weight)
if randomValue < cumulativeWeight {
saveCohort(cohort.name, in: subfeature.subfeatureID)
return cohort.name
}
}
return nil
}

func removeCohort(for subfeatureID: SubfeatureID) {
guard var experiments = getExperimentData() else { return }
experiments.removeValue(forKey: subfeatureID)
saveExperimentData(experiments)
}

private func getExperimentData() -> Experiments? {
return store.experiments
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
}

private func saveExperimentData(_ experiments: Experiments) {
store.experiments = experiments
}
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved

private func saveCohort(_ cohort: CohortID, in experimentID: SubfeatureID) {
var experiments = getExperimentData() ?? Experiments()
let experimentData = ExperimentData(cohort: cohort, enrollmentDate: Date())
experiments[experimentID] = experimentData
saveExperimentData(experiments)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//
// ExperimentsDataStore.swift
//
// Copyright © 2024 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation

protocol ExperimentsDataStoring {
var experiments: Experiments? { get set }
}

protocol LocalDataStoring {
func data(forKey defaultName: String) -> Data?
func set(_ value: Any?, forKey defaultName: String)
}

struct ExperimentsDataStore: ExperimentsDataStoring {
private let localDataStoring: LocalDataStoring
private let experimentsDataKey = "ExperimentsData"
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
private let queue = DispatchQueue(label: "com.experimentManager.queue")
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()

init(localDataStoring: LocalDataStoring = UserDefaults.standard) {
self.localDataStoring = localDataStoring
encoder.dateEncodingStrategy = .secondsSince1970
decoder.dateDecodingStrategy = .secondsSince1970
}

var experiments: Experiments? {
get {
queue.sync {
guard let savedData = localDataStoring.data(forKey: experimentsDataKey) else { return nil }
return try? decoder.decode(Experiments.self, from: savedData)
}
}
set {
queue.sync {
if let encodedData = try? encoder.encode(newValue) {
localDataStoring.set(encodedData, forKey: experimentsDataKey)
}
}
}
}
}

extension UserDefaults: LocalDataStoring {}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,20 @@ public struct PrivacyConfigurationData {
static public let enabled = "enabled"
}

public struct Cohort {
public let name: String
public let weight: Int

public init?(json: [String: Any]) {
guard let name = json["name"] as? String,
let weightValue = json["weight"] as? Int else {
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

self.name = name
self.weight = weightValue
}
}
public let features: [FeatureName: PrivacyFeature]
public let trackerAllowlist: TrackerAllowlist
public let unprotectedTemporary: [ExceptionEntry]
Expand Down Expand Up @@ -121,6 +135,7 @@ public struct PrivacyConfigurationData {
case state
case minSupportedVersion
case rollout
case cohorts
}

public struct Rollout: Hashable {
Expand Down Expand Up @@ -157,6 +172,7 @@ public struct PrivacyConfigurationData {
public let state: FeatureState
public let minSupportedVersion: FeatureSupportedVersion?
public let rollout: Rollout?
public let cohorts: [Cohort]?

public init?(json: [String: Any]) {
guard let state = json[CodingKeys.state.rawValue] as? String else {
Expand All @@ -171,6 +187,13 @@ public struct PrivacyConfigurationData {
} else {
self.rollout = nil
}

if let cohortData = json[CodingKeys.cohorts.rawValue] as? [[String: Any]] {
let parsedCohorts = cohortData.compactMap { Cohort(json: $0) }
self.cohorts = parsedCohorts.isEmpty ? nil : parsedCohorts
} else {
self.cohorts = nil
SabrinaTardio marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

Expand Down
Loading
Loading