|
| 1 | +// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +// file, You can obtain one at http://mozilla.org/MPL/2.0/ |
| 4 | + |
| 5 | +import Common |
| 6 | +import Foundation |
| 7 | +import Glean |
| 8 | +import Shared |
| 9 | + |
| 10 | +import class MozillaAppServices.NimbusGleanPings |
| 11 | +import func MozillaAppServices.getCalculatedAttributes |
| 12 | +import func MozillaAppServices.getLocaleTag |
| 13 | +import struct MozillaAppServices.JsonObject |
| 14 | +import protocol MozillaAppServices.RecordedContext |
| 15 | +import MozillaRustComponents |
| 16 | + |
| 17 | +private extension Double? { |
| 18 | + func toInt64() -> Int64? { |
| 19 | + guard let self = self else { return nil } |
| 20 | + return Int64(self) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +extension Int32? { |
| 25 | + func toInt64() -> Int64? { |
| 26 | + guard let self = self else { return nil } |
| 27 | + return Int64(self) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/// TODO(FXIOS-12942): Implement proper thread-safety |
| 32 | +final class RecordedNimbusContext: RecordedContext, @unchecked Sendable { |
| 33 | + /** |
| 34 | + * The following constants are string constants of the keys that appear in the [EVENT_QUERIES] map. |
| 35 | + */ |
| 36 | + static let DAYS_OPENED_IN_LAST_28 = "days_opened_in_last_28" |
| 37 | + |
| 38 | + /** |
| 39 | + * [EVENT_QUERIES] is a map of keys to Nimbus SDK EventStore queries. |
| 40 | + */ |
| 41 | + static let EVENT_QUERIES = [ |
| 42 | + DAYS_OPENED_IN_LAST_28: "'events.app_opened'|eventCountNonZero('Days', 28, 0)", |
| 43 | + ] |
| 44 | + |
| 45 | + var isFirstRun: Bool |
| 46 | + var isPhone: Bool |
| 47 | + var isDefaultBrowser: Bool |
| 48 | + var isBottomToolbarUser: Bool |
| 49 | + var hasEnabledTipsNotifications: Bool |
| 50 | + var hasAcceptedTermsOfUse: Bool |
| 51 | + var userDisabledAi: Bool |
| 52 | + var isAppleIntelligenceAvailable: Bool |
| 53 | + var cannotUseAppleIntelligence: Bool |
| 54 | + var appVersion: String? |
| 55 | + var region: String? |
| 56 | + var language: String? |
| 57 | + var locale: String |
| 58 | + var daysSinceInstall: Int32? |
| 59 | + var daysSinceUpdate: Int32? |
| 60 | + var touExperiencePoints: Int32? |
| 61 | + |
| 62 | + private var eventQueries: [String: String] |
| 63 | + private var eventQueryValues: [String: Double] = [:] |
| 64 | + |
| 65 | + private var logger: Logger |
| 66 | + |
| 67 | + init(isFirstRun: Bool, |
| 68 | + isDefaultBrowser: Bool, |
| 69 | + isBottomToolbarUser: Bool, |
| 70 | + hasEnabledTipsNotifications: Bool, |
| 71 | + hasAcceptedTermsOfUse: Bool, |
| 72 | + userDisabledAi: Bool, |
| 73 | + isAppleIntelligenceAvailable: Bool, |
| 74 | + cannotUseAppleIntelligence: Bool, |
| 75 | + eventQueries: [String: String] = RecordedNimbusContext.EVENT_QUERIES, |
| 76 | + isPhone: Bool = UIDeviceDetails.userInterfaceIdiom == .phone, |
| 77 | + bundle: Bundle = Bundle.main, |
| 78 | + logger: Logger = DefaultLogger.shared) { |
| 79 | + self.logger = logger |
| 80 | + logger.log("init start", level: .debug, category: .experiments) |
| 81 | + self.eventQueries = eventQueries |
| 82 | + |
| 83 | + self.isFirstRun = isFirstRun |
| 84 | + self.isPhone = isPhone |
| 85 | + self.isDefaultBrowser = isDefaultBrowser |
| 86 | + self.isBottomToolbarUser = isBottomToolbarUser |
| 87 | + self.hasEnabledTipsNotifications = hasEnabledTipsNotifications |
| 88 | + self.hasAcceptedTermsOfUse = hasAcceptedTermsOfUse |
| 89 | + self.userDisabledAi = userDisabledAi |
| 90 | + self.isAppleIntelligenceAvailable = isAppleIntelligenceAvailable |
| 91 | + self.cannotUseAppleIntelligence = cannotUseAppleIntelligence |
| 92 | + |
| 93 | + let info = bundle.infoDictionary ?? [:] |
| 94 | + appVersion = info["CFBundleShortVersionString"] as? String |
| 95 | + |
| 96 | + locale = getLocaleTag() |
| 97 | + var inferredDateInstalledOn: Date? { |
| 98 | + guard |
| 99 | + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last, |
| 100 | + let attributes = try? FileManager.default.attributesOfItem(atPath: documentsURL.path) |
| 101 | + else { return nil } |
| 102 | + return attributes[.creationDate] as? Date |
| 103 | + } |
| 104 | + let installationDateSinceEpoch = inferredDateInstalledOn.map { |
| 105 | + Int64(($0.timeIntervalSince1970 * 1000).rounded()) |
| 106 | + } |
| 107 | + guard let dbPath = Experiments.dbPath else { |
| 108 | + self.logger.log("Unable to obtain dbPath, skipping calculating attributes", |
| 109 | + level: .warning, |
| 110 | + category: .experiments) |
| 111 | + return |
| 112 | + } |
| 113 | + guard let calculatedAttributes = try? getCalculatedAttributes(installationDate: installationDateSinceEpoch, |
| 114 | + dbPath: dbPath, |
| 115 | + locale: locale) |
| 116 | + else { return } |
| 117 | + |
| 118 | + daysSinceInstall = calculatedAttributes.daysSinceInstall |
| 119 | + daysSinceUpdate = calculatedAttributes.daysSinceUpdate |
| 120 | + language = calculatedAttributes.language |
| 121 | + region = calculatedAttributes.region |
| 122 | + touExperiencePoints = Experiments.touExperiencePoints(region: region) |
| 123 | + self.logger.log("init end", level: .debug, category: .experiments) |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * [getEventQueries] is called by the Nimbus SDK Rust code to retrieve the map of event |
| 128 | + * queries. The are then executed against the Nimbus SDK's EventStore to retrieve their values. |
| 129 | + * |
| 130 | + * @return Map<String, String> |
| 131 | + */ |
| 132 | + func getEventQueries() -> [String: String] { |
| 133 | + logger.log("getEventQueries", level: .debug, category: .experiments) |
| 134 | + return eventQueries |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * [record] is called when experiment enrollments are evolved. It should apply the |
| 139 | + * [RecordedNimbusContext]'s values to a [NimbusSystem.RecordedNimbusContextObject] instance, |
| 140 | + * and use that instance to record the values to Glean. |
| 141 | + */ |
| 142 | + func record() { |
| 143 | + logger.log("record start", level: .debug, category: .experiments) |
| 144 | + |
| 145 | + // Bring the ping into scope so that Glean knows it exists and includes NimbusSystem.recordedNimbusContext |
| 146 | + _ = NimbusGleanPings.nimbusTargetingContext |
| 147 | + |
| 148 | + let eventQueryValuesObject = GleanMetrics.NimbusSystem.RecordedNimbusContextObjectItemEventQueryValuesObject( |
| 149 | + daysOpenedInLast28: eventQueryValues[RecordedNimbusContext.DAYS_OPENED_IN_LAST_28].toInt64() |
| 150 | + ) |
| 151 | + |
| 152 | + GleanMetrics.NimbusSystem.recordedNimbusContext.set( |
| 153 | + GleanMetrics.NimbusSystem.RecordedNimbusContextObject( |
| 154 | + isFirstRun: isFirstRun, |
| 155 | + eventQueryValues: eventQueryValuesObject, |
| 156 | + isPhone: isPhone, |
| 157 | + appVersion: appVersion, |
| 158 | + locale: locale, |
| 159 | + daysSinceInstall: daysSinceInstall.toInt64(), |
| 160 | + daysSinceUpdate: daysSinceUpdate.toInt64(), |
| 161 | + language: language, |
| 162 | + region: region, |
| 163 | + isDefaultBrowser: isDefaultBrowser, |
| 164 | + isBottomToolbarUser: isBottomToolbarUser, |
| 165 | + hasEnabledTipsNotifications: hasEnabledTipsNotifications, |
| 166 | + hasAcceptedTermsOfUse: hasAcceptedTermsOfUse, |
| 167 | + userDisabledAi: userDisabledAi, |
| 168 | + isAppleIntelligenceAvailable: isAppleIntelligenceAvailable, |
| 169 | + cannotUseAppleIntelligence: cannotUseAppleIntelligence, |
| 170 | + touExperiencePoints: touExperiencePoints.toInt64() |
| 171 | + ) |
| 172 | + ) |
| 173 | + logger.log("record end", level: .debug, category: .experiments) |
| 174 | + } |
| 175 | + |
| 176 | + /** |
| 177 | + * [setEventQueryValues] is called by the Nimbus SDK Rust code after the event queries have been |
| 178 | + * executed. The [eventQueryValues] should be written back to the Kotlin object. |
| 179 | + * |
| 180 | + * @param [eventQueryValues] The values for each query after they have been executed in the |
| 181 | + * Nimbus SDK Rust environment. |
| 182 | + */ |
| 183 | + func setEventQueryValues(eventQueryValues: [String: Double]) { |
| 184 | + logger.log("setEventQueryValues", level: .debug, category: .experiments) |
| 185 | + self.eventQueryValues = eventQueryValues |
| 186 | + } |
| 187 | + |
| 188 | + /** |
| 189 | + * [toJson] is called by the Nimbus SDK Rust code after the event queries have been executed, |
| 190 | + * and before experiment enrollments have been evolved. The value returned from this method |
| 191 | + * will be applied directly to the Nimbus targeting context, and its keys/values take |
| 192 | + * precedence over those in the main Nimbus targeting context. |
| 193 | + * |
| 194 | + * @return JsonObject |
| 195 | + */ |
| 196 | + func toJson() -> JsonObject { |
| 197 | + logger.log("toJson start", level: .debug, category: .experiments) |
| 198 | + guard let data = try? JSONSerialization.data(withJSONObject: [ |
| 199 | + "is_first_run": isFirstRun, |
| 200 | + "isFirstRun": "\(isFirstRun)", |
| 201 | + "is_phone": isPhone, |
| 202 | + "events": eventQueryValues, |
| 203 | + "app_version": appVersion as Any, |
| 204 | + "region": region as Any, |
| 205 | + "language": language as Any, |
| 206 | + "locale": locale as Any, |
| 207 | + "days_since_install": daysSinceInstall as Any, |
| 208 | + "days_since_update": daysSinceUpdate as Any, |
| 209 | + "is_default_browser": isDefaultBrowser, |
| 210 | + "is_bottom_toolbar_user": isBottomToolbarUser, |
| 211 | + "has_enabled_tips_notifications": hasEnabledTipsNotifications, |
| 212 | + "has_accepted_terms_of_use": hasAcceptedTermsOfUse, |
| 213 | + "user_disabled_ai": userDisabledAi, |
| 214 | + "is_apple_intelligence_available": isAppleIntelligenceAvailable, |
| 215 | + "cannot_use_apple_intelligence": cannotUseAppleIntelligence, |
| 216 | + "tou_experience_points": touExperiencePoints as Any |
| 217 | + ]), |
| 218 | + let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String |
| 219 | + else { |
| 220 | + logger.log("toJson error thrown while creating JSON string", level: .warning, category: .experiments) |
| 221 | + return "{}" |
| 222 | + } |
| 223 | + logger.log("toJson end", level: .debug, category: .experiments, extra: ["json": jsonString]) |
| 224 | + return jsonString |
| 225 | + } |
| 226 | +} |
0 commit comments