Skip to content

Commit

Permalink
PIR Time-Based Pixel: 24 Opt-Out Request Success Rate (#2942)
Browse files Browse the repository at this point in the history
Task/Issue URL:
https://app.asana.com/0/1206488453854252/1207733191644528/f
Tech Design URL:
https://app.asana.com/0/481882893211075/1207774401221083/f
CC:

**Description**:
Adds new pixels to indicate how many opt outs are successfully submitted
within 24 hours

**Steps to test this PR**:
1. With opt out jobs already existing (older than 24 hours), check the
pixels fire appropriately

<!--
Tagging instructions
If this PR isn't ready to be merged for whatever reason it should be
marked with the `DO NOT MERGE` label (particularly if it's a draft)
If it's pending Product Review/PFR, please add the `Pending Product
Review` label.

If at any point it isn't actively being worked on/ready for
review/otherwise moving forward (besides the above PR/PFR exception)
strongly consider closing it (or not opening it in the first place). If
you decide not to close it, make sure it's labelled to make it clear the
PRs state and comment with more information.
-->

**Definition of Done**:

* [x] Does this PR satisfy our [Definition of
Done](https://app.asana.com/0/1202500774821704/1207634633537039/f)?

---
###### Internal references:
[Pull Request Review
Checklist](https://app.asana.com/0/1202500774821704/1203764234894239/f)
[Software Engineering
Expectations](https://app.asana.com/0/59792373528535/199064865822552)
[Technical Design
Template](https://app.asana.com/0/59792373528535/184709971311943)
[Pull Request
Documentation](https://app.asana.com/0/1202500774821704/1204012835277482/f)

---------

Co-authored-by: Elle Sullivan <[email protected]>
  • Loading branch information
aataraxiaa and THISISDINOSAUR authored Aug 23, 2024
1 parent bb8dd79 commit 338c923
Show file tree
Hide file tree
Showing 10 changed files with 721 additions and 83 deletions.
4 changes: 3 additions & 1 deletion DuckDuckGo/DBP/DataBrokerProtectionPixelsHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ public class DataBrokerProtectionPixelsHandler: EventMapping<DataBrokerProtectio
.dataBrokerMetricsWeeklyStats,
.dataBrokerMetricsMonthlyStats,
.gatekeeperNotAuthenticated,
.gatekeeperEntitlementsInvalid:
.gatekeeperEntitlementsInvalid,
.customDataBrokerStatsOptoutSubmit,
.customGlobalStatsOptoutSubmit:

PixelKit.fire(event)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ struct DataBrokerProfileQueryOperationManager: OperationsManager {
}
}

// swiftlint:disable:next cyclomatic_complexity
// swiftlint:disable cyclomatic_complexity
internal func runScanOperation(on runner: WebJobRunner,
brokerProfileQueryData: BrokerProfileQueryData,
database: DataBrokerProtectionRepository,
Expand Down Expand Up @@ -254,6 +254,7 @@ struct DataBrokerProfileQueryOperationManager: OperationsManager {
throw error
}
}
// swiftlint:enable cyclomatic_complexity

private func sendProfileRemovedNotificationIfNecessary(userNotificationService: DataBrokerProtectionUserNotificationService, database: DataBrokerProtectionRepository) {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
//
// DataBrokerProtectionCustomStatsProvider.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

/// Type encapsulating custom data broker and global stats
struct CustomOptOutStats: Equatable {
let customIndividualDataBrokerStat: [CustomIndividualDataBrokerStat]
let customAggregateBrokersStat: CustomAggregateBrokersStat
}

/// Encapsulates data broker stats
struct CustomIndividualDataBrokerStat: Equatable {
let dataBrokerName: String
let optoutSubmitSuccessRate: Double
}

/// Encapsulates aggregate (i.e across all data broker) stats
struct CustomAggregateBrokersStat: Equatable {
let optoutSubmitSuccessRate: Double
}

// Conforming types provide a method to calculate `CustomOptOutStats`
protocol DataBrokerProtectionCustomOptOutStatsProvider {

/// This method calculates custom statistics for data brokers based on the provided query data within a specified date range.
/// - Parameters:
/// - startDate: An optional start date to filter optout creation and request events. If nil, the filtering starts from the earliest date available.
/// - endDate: The end date to filter optout creation events. All optout creation events considered up to this date.
/// - queryData: An array of BrokerProfileQueryData objects containing data broker query information, scan job data, and opt-out job data.
/// - Returns: A CustomStats object containing the statistics for each data broker and the global statistics.
func customOptOutStats(startDate: Date?,
endDate: Date,
andQueryData queryData: [BrokerProfileQueryData]) -> CustomOptOutStats
}

struct DefaultDataBrokerProtectionCustomOptOutStatsProvider: DataBrokerProtectionCustomOptOutStatsProvider {

func customOptOutStats(startDate: Date?,
endDate: Date,
andQueryData queryData: [BrokerProfileQueryData]) -> CustomOptOutStats {

var customIndividualDataBrokerStats: [CustomIndividualDataBrokerStat] = []
var totalGlobalOptOuts: Int = 0
var totalGlobalRequests: Int = 0

// Group by broker
let groupedByBroker = Dictionary(grouping: queryData) { $0.dataBroker.id }

// Loop over each group
for (dataBroker, brokerQueryData) in groupedByBroker {

// Get opt-out jobs between start - end dates
let optOutJobs = optOutJobsBetween(startDate: startDate, endDate: endDate, queryData: brokerQueryData)

let optOutJobsCount = optOutJobs.count

// If optOutCount is zero, skip to the next data broker
guard optOutJobsCount != 0 else { continue }

totalGlobalOptOuts += optOutJobsCount

// Get opt-out request count since start date
let requestsCountSinceStartDate = optOutSuccessfulRequestCountSince(startDate: startDate, for: optOutJobs)

totalGlobalRequests += requestsCountSinceStartDate

// Calculate opt-out success rate
let optOutSuccessRate = optOutJobsCount > 0 ? Double(requestsCountSinceStartDate) / Double(optOutJobsCount) : 0
let roundedOptOutSuccessRate = (optOutSuccessRate * 100).rounded() / 100

let dataBrokerName = groupedByBroker[dataBroker]?.first?.dataBroker.name ?? ""

let customIndividualDataBrokerStat = CustomIndividualDataBrokerStat(dataBrokerName: dataBrokerName,
optoutSubmitSuccessRate: roundedOptOutSuccessRate)

customIndividualDataBrokerStats.append(customIndividualDataBrokerStat)

}

let globalSuccessRate = totalGlobalOptOuts > 0 ? Double(totalGlobalRequests) / Double(totalGlobalOptOuts) : 0
let roundedGlobalSuccessRate = (globalSuccessRate * 100).rounded() / 100
let aggregateStats = CustomAggregateBrokersStat(optoutSubmitSuccessRate: roundedGlobalSuccessRate)
return CustomOptOutStats(customIndividualDataBrokerStat: customIndividualDataBrokerStats, customAggregateBrokersStat: aggregateStats)
}
}

private extension DefaultDataBrokerProtectionCustomOptOutStatsProvider {

func optOutJobsBetween(startDate: Date?, endDate: Date, queryData: [BrokerProfileQueryData]) -> [OptOutJobData] {
let allOptOuts = queryData.flatMap { $0.optOutJobData }
return allOptOuts.filter { optOutJob in
if let startDate = startDate {
return optOutJob.createdDate >= startDate && optOutJob.createdDate <= endDate
} else {
return optOutJob.createdDate <= endDate
}
}
}

func optOutSuccessfulRequestCountSince(startDate: Date?,
for optOutJobData: [OptOutJobData]) -> Int {

return optOutJobData.reduce(0) { result, optOutJobData in
let optOutRequested = optOutJobData.historyEvents.contains { historyEvent in
let matchDatePlus24 = Calendar.current.date(byAdding: .hour, value: 24, to: optOutJobData.createdDate) ?? Date()
return historyEvent.type == .optOutRequested && (historyEvent.date < matchDatePlus24 && historyEvent.date > optOutJobData.createdDate)
}
return result + (optOutRequested ? 1 : 0)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public enum DataBrokerProtectionPixels {
static let durationOfFirstOptOut = "duration_firstoptout"
static let numberOfNewRecordsFound = "num_new_found"
static let numberOfReappereances = "num_reappeared"
static let optOutSubmitSuccessRate = "optout_submit_success_rate"
}

case error(error: DataBrokerProtectionError, dataBroker: String)
Expand Down Expand Up @@ -198,6 +199,10 @@ public enum DataBrokerProtectionPixels {
// Feature Gatekeeper
case gatekeeperNotAuthenticated
case gatekeeperEntitlementsInvalid

// Custom stats
case customDataBrokerStatsOptoutSubmit(dataBrokerName: String, optOutSubmitSuccessRate: Double)
case customGlobalStatsOptoutSubmit(optOutSubmitSuccessRate: Double)
}

extension DataBrokerProtectionPixels: PixelKitEvent {
Expand Down Expand Up @@ -325,6 +330,9 @@ extension DataBrokerProtectionPixels: PixelKitEvent {
// Feature Gatekeeper
case .gatekeeperNotAuthenticated: return "m_mac_dbp_gatekeeper_not_authenticated"
case .gatekeeperEntitlementsInvalid: return "m_mac_dbp_gatekeeper_entitlements_invalid"

case .customDataBrokerStatsOptoutSubmit: return "m_mac_dbp_databroker_custom_stats_optoutsubmit"
case .customGlobalStatsOptoutSubmit: return "m_mac_dbp_custom_stats_optoutsubmit"
}
}

Expand Down Expand Up @@ -490,6 +498,11 @@ extension DataBrokerProtectionPixels: PixelKitEvent {
Consts.durationOfFirstOptOut: String(durationOfFirstOptOut),
Consts.numberOfNewRecordsFound: String(numberOfNewRecordsFound),
Consts.numberOfReappereances: String(numberOfReappereances)]
case .customDataBrokerStatsOptoutSubmit(let dataBrokerName, let optOutSubmitSuccessRate):
return [Consts.dataBrokerParamKey: dataBrokerName,
Consts.optOutSubmitSuccessRate: String(optOutSubmitSuccessRate)]
case .customGlobalStatsOptoutSubmit(let optOutSubmitSuccessRate):
return [Consts.optOutSubmitSuccessRate: String(optOutSubmitSuccessRate)]
}
}
}
Expand Down Expand Up @@ -580,7 +593,9 @@ public class DataBrokerProtectionPixelsHandler: EventMapping<DataBrokerProtectio
.dataBrokerMetricsWeeklyStats,
.dataBrokerMetricsMonthlyStats,
.gatekeeperNotAuthenticated,
.gatekeeperEntitlementsInvalid:
.gatekeeperEntitlementsInvalid,
.customDataBrokerStatsOptoutSubmit,
.customGlobalStatsOptoutSubmit:

PixelKit.fire(event)

Expand Down
Loading

0 comments on commit 338c923

Please sign in to comment.