/
AdClickAttributionRulesProvider.swift
182 lines (147 loc) · 7.48 KB
/
AdClickAttributionRulesProvider.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
//
// AdClickAttributionRulesSource.swift
// DuckDuckGo
//
// Copyright © 2022 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
import TrackerRadarKit
import os
public protocol AdClickAttributionRulesProviding {
var globalAttributionRules: ContentBlockerRulesManager.Rules? { get }
func requestAttribution(forVendor vendor: String,
completion: @escaping (ContentBlockerRulesManager.Rules?) -> Void)
}
public class AdClickAttributionRulesProvider: AdClickAttributionRulesProviding {
public enum Constants {
public static let attributedTempRuleListName = "TemporaryAttributed"
}
struct AttributionTask: Equatable {
let sourceRulesIdentifier: String
let vendor: String
let completion: (ContentBlockerRulesManager.Rules?) -> Void
static func == (lhs: AdClickAttributionRulesProvider.AttributionTask,
rhs: AdClickAttributionRulesProvider.AttributionTask) -> Bool {
return lhs.vendor == rhs.vendor && lhs.sourceRulesIdentifier == rhs.sourceRulesIdentifier
}
}
private let attributionConfig: AdClickAttributing
private let compiledRulesSource: CompiledRuleListsSource
private let exceptionsSource: ContentBlockerRulesExceptionsSource
private let errorReporting: EventMapping<AdClickAttributionDebugEvents>?
private let compilationErrorReporting: EventMapping<ContentBlockerDebugEvents>?
private let lock = NSLock()
private var tasks = [AttributionTask]()
private var isProcessingTask = false
private let workQueue = DispatchQueue(label: "AdAttribution compilation queue",
qos: .userInitiated)
private let log: OSLog
public init(config: AdClickAttributing,
compiledRulesSource: CompiledRuleListsSource,
exceptionsSource: ContentBlockerRulesExceptionsSource,
errorReporting: EventMapping<AdClickAttributionDebugEvents>? = nil,
compilationErrorReporting: EventMapping<ContentBlockerDebugEvents>? = nil,
log: OSLog = .disabled) {
self.attributionConfig = config
self.compiledRulesSource = compiledRulesSource
self.exceptionsSource = exceptionsSource
self.errorReporting = errorReporting
self.compilationErrorReporting = compilationErrorReporting
self.log = log
}
public var globalAttributionRules: ContentBlockerRulesManager.Rules? {
return compiledRulesSource.currentAttributionRules
}
public func requestAttribution(forVendor vendor: String,
completion: @escaping (ContentBlockerRulesManager.Rules?) -> Void) {
lock.lock()
defer { lock.unlock() }
os_log(.debug, log: log, "Preparing attribution rules for vendor %{private}s", vendor)
guard let globalAttributionRules = compiledRulesSource.currentAttributionRules else {
errorReporting?.fire(.adAttributionGlobalAttributedRulesDoNotExist)
os_log(.error, log: log, "Global attribution list does not exist")
completion(nil)
return
}
let task = AttributionTask(sourceRulesIdentifier: globalAttributionRules.identifier.stringValue,
vendor: vendor,
completion: completion)
tasks.append(task)
workQueue.async {
self.popTaskAndExecute()
}
}
private func popTaskAndExecute() {
lock.lock()
defer { lock.unlock() }
guard !isProcessingTask, !tasks.isEmpty else { return }
let task = tasks.removeFirst()
isProcessingTask = true
prepareRules(for: task)
}
private func prepareRules(for task: AttributionTask) {
guard let sourceRules = compiledRulesSource.currentAttributionRules else {
isProcessingTask = false
workQueue.async {
self.popTaskAndExecute()
}
return
}
os_log(.debug, log: log, "Compiling attribution rules for vendor %{private}s", task.vendor)
let mutator = AdClickAttributionRulesMutator(trackerData: sourceRules.trackerData,
config: attributionConfig)
let attributedRules = mutator.addException(vendorDomain: task.vendor)
let attributedDataSet = TrackerDataManager.DataSet(tds: attributedRules,
etag: sourceRules.etag)
let attributedRulesList = ContentBlockerRulesList(name: Constants.attributedTempRuleListName,
trackerData: nil,
fallbackTrackerData: attributedDataSet)
let sourceManager = ContentBlockerRulesSourceManager(rulesList: attributedRulesList,
exceptionsSource: exceptionsSource,
errorReporting: compilationErrorReporting)
let compilationTask = ContentBlockerRulesManager.CompilationTask(workQueue: workQueue,
rulesList: attributedRulesList,
sourceManager: sourceManager)
compilationTask.start(ignoreCache: true) { compilationTask, _ in
self.onTaskCompleted(attributionTask: task, compilationTask: compilationTask)
}
}
private func onTaskCompleted(attributionTask: AttributionTask,
compilationTask: ContentBlockerRulesManager.CompilationTask) {
lock.lock()
defer { lock.unlock() }
isProcessingTask = false
// Take all tasks with same parameters (rules & vendor) and report completion
// This is optimization: in case multiple tabs request same attribution at the same time, we will respond quickly.
var matchingTasks = tasks.filter { $0 == attributionTask }
tasks.removeAll(where: { $0 == attributionTask })
matchingTasks.append(attributionTask)
os_log(.debug, log: log,
"Returning attribution rules for vendor %{private}s to %{public}d caller(s)",
attributionTask.vendor, matchingTasks.count)
let rules = ContentBlockerRulesManager.Rules(task: compilationTask)
DispatchQueue.main.async {
for task in matchingTasks {
task.completion(rules)
}
}
if rules == nil {
errorReporting?.fire(.adAttributionCompilationFailedForAttributedRulesList)
}
workQueue.async {
self.popTaskAndExecute()
}
}
}