-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathBatchEventBuilder.swift
More file actions
234 lines (188 loc) · 9.68 KB
/
Copy pathBatchEventBuilder.swift
File metadata and controls
234 lines (188 loc) · 9.68 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//
// Copyright 2019, 2021-2022, Optimizely, Inc. and contributors
//
// 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
class BatchEventBuilder {
static private var logger = OPTLoggerFactory.getLogger()
// MARK: - Impression Event
static func createImpressionEvent(config: ProjectConfig,
experiment: ExperimentCore?,
variation: Variation?,
userId: String,
attributes: OptimizelyAttributes?,
flagKey: String,
ruleType: String,
enabled: Bool,
cmabUUID: String?) -> Data? {
let metaData = DecisionMetadata(ruleType: ruleType, ruleKey: experiment?.key ?? "", flagKey: flagKey, variationKey: variation?.key ?? "", enabled: enabled, cmabUUID: cmabUUID)
let decision = Decision(variationID: variation?.id ?? "",
campaignID: experiment?.layerId ?? "",
experimentID: experiment?.id ?? "",
metaData: metaData)
let dispatchEvent = DispatchEvent(timestamp: timestampSince1970,
key: DispatchEvent.activateEventKey,
entityID: experiment?.layerId ?? "",
uuid: uuid)
return createBatchEvent(config: config,
userId: userId,
attributes: attributes,
decisions: [decision],
dispatchEvents: [dispatchEvent],
region: config.region)
}
// MARK: - Converison Event
static func createConversionEvent(config: ProjectConfig,
eventKey: String,
userId: String,
attributes: OptimizelyAttributes?,
eventTags: [String: Any]?) -> Data? {
guard let event = config.getEvent(key: eventKey) else {
return nil
}
// filter and convert event tags
let (tags, value, revenue) = filterEventTags(eventTags)
let dispatchEvent = DispatchEvent(timestamp: timestampSince1970,
key: event.key,
entityID: event.id,
uuid: uuid,
tags: tags,
value: value,
revenue: revenue)
return createBatchEvent(config: config,
userId: userId,
attributes: attributes,
decisions: nil,
dispatchEvents: [dispatchEvent],
region: config.region)
}
// MARK: - Create Event
static func createBatchEvent(config: ProjectConfig,
userId: String,
attributes: OptimizelyAttributes?,
decisions: [Decision]?,
dispatchEvents: [DispatchEvent],
region: Region? = nil) -> Data? {
let eventRegion = region ?? config.region
let snapShot = Snapshot(decisions: decisions, events: dispatchEvents)
let eventAttributes = getEventAttributes(config: config, attributes: attributes)
let visitor = Visitor(attributes: eventAttributes, snapshots: [snapShot], visitorID: userId)
let batchEvent = BatchEvent(revision: config.project.revision,
accountID: config.project.accountId,
clientVersion: Utils.sdkVersion,
visitors: [visitor],
projectID: config.project.projectId,
clientName: Utils.swiftSdkClientName,
anonymizeIP: config.project.anonymizeIP,
enrichDecisions: true,
region: eventRegion.rawValue)
let data = try? JSONEncoder().encode(batchEvent)
let eventForDispatch = EventForDispatch(url: nil, body: data ?? Data(), region: eventRegion)
return eventForDispatch.body
}
// MARK: - Event Tags
static func filterEventTags(_ eventTags: [String: Any]?) -> ([String: AttributeValue], Double?, Int64?) {
guard let eventTags = eventTags else {
return ([:], nil, nil)
}
// should not pass tags of invalid types to the server (which will drop entire event if so)
let filteredTags = filterTagsWithInvalidTypes(eventTags)
// {revenue, value} keys are special - must be copied as separate properties
let value = extractValueEventTag(filteredTags)
let revenue = extractRevenueEventTag(filteredTags)
return (filteredTags, value, revenue)
}
static func filterTagsWithInvalidTypes(_ eventTags: [String: Any]) -> [String: AttributeValue] {
return eventTags.compactMapValues { AttributeValue(value: $0) }
}
static func extractValueEventTag(_ eventTags: [String: AttributeValue]) -> Double? {
guard let valueFromTags = eventTags[DispatchEvent.valueKey] else { return nil }
// export {value, revenue} only for {double, int64} types
var value: Double?
switch valueFromTags {
case .double(let attrValue):
// valid value type
value = attrValue
case .int(let attrValue):
value = Double(attrValue)
default:
value = nil
}
if let value = value {
logger.i(.extractValueFromEventTags("\(value)"))
} else {
logger.i(.failedToExtractValueFromEventTags(valueFromTags.stringValue))
}
return value
}
static func extractRevenueEventTag(_ eventTags: [String: AttributeValue]) -> Int64? {
guard let revenueFromTags = eventTags[DispatchEvent.revenueKey] else { return nil }
// export {value, revenue} only for {double, int64} types
var revenue: Int64?
switch revenueFromTags {
case .int(let value):
// valid revenue type
revenue = Int64(value)
case .double(let value):
// not accurate but acceptable ("3.14" -> "3")
revenue = Int64(value)
default:
revenue = nil
}
if let revenue = revenue {
logger.i(.extractRevenueFromEventTags("\(revenue)"))
} else {
logger.i(.failedToExtractRevenueFromEventTags(revenueFromTags.stringValue))
}
return revenue
}
// MARK: - Event Attributes
static func getEventAttributes(config: ProjectConfig,
attributes: OptimizelyAttributes?) -> [EventAttribute] {
var eventAttributes = [EventAttribute]()
if let attributes = attributes {
for attr in attributes.keys {
if let attributeId = config.getAttributeId(key: attr) ?? (attr.hasPrefix("$opt_") ? attr : nil) {
let attrValue = attributes[attr] ?? nil // default to nil to avoid warning "coerced from 'Any??' to 'Any?'"
if let eventValue = AttributeValue(value: attrValue) {
let eventAttribute = EventAttribute(value: eventValue,
key: attr,
type: "custom",
entityID: attributeId)
eventAttributes.append(eventAttribute)
}
} else {
logger.d(.unrecognizedAttribute(attr))
}
}
}
if let botFiltering = config.project.botFiltering, let eventValue = AttributeValue(value: botFiltering) {
let botAttr = EventAttribute(value: eventValue,
key: Constants.Attributes.reservedBotFilteringAttribute,
type: "custom",
entityID: Constants.Attributes.reservedBotFilteringAttribute)
eventAttributes.append(botAttr)
}
return eventAttributes
}
// MARK: - Utils
static var timestampSince1970: Int64 {
let early = Date.timeIntervalBetween1970AndReferenceDate * 1000
let after = Date.timeIntervalSinceReferenceDate * 1000
return Int64(early + after)
}
static var uuid: String {
return UUID().uuidString
}
}