-
Notifications
You must be signed in to change notification settings - Fork 23
/
Amplitude.swift
482 lines (423 loc) · 17.4 KB
/
Amplitude.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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import Foundation
public class Amplitude {
public private(set) var configuration: Configuration
private var inForeground = false
var sessionId: Int64 {
sessions.sessionId
}
var state: State = State()
var contextPlugin: ContextPlugin
lazy var storage: any Storage = {
return self.configuration.storageProvider
}()
lazy var identifyStorage: any Storage = {
return self.configuration.identifyStorageProvider
}()
lazy var timeline: Timeline = {
return Timeline()
}()
lazy var sessions: Sessions = {
return Sessions(amplitude: self)
}()
public lazy var logger: (any Logger)? = {
return self.configuration.loggerProvider
}()
let trackingQueue = DispatchQueue(label: "com.amplitude.analytics", target: .global(qos: .utility))
public init(
configuration: Configuration
) {
self.configuration = configuration
let contextPlugin = ContextPlugin()
self.contextPlugin = contextPlugin
migrateApiKeyStorages()
migrateDefaultInstanceStorages()
if configuration.migrateLegacyData && getStorageVersion() < .API_KEY_AND_INSTANCE_NAME && isSandboxEnabled() {
RemnantDataMigration(self).execute()
}
migrateInstanceOnlyStorages()
if let deviceId: String? = configuration.storageProvider.read(key: .DEVICE_ID) {
state.deviceId = deviceId
}
if let userId: String? = configuration.storageProvider.read(key: .USER_ID) {
state.userId = userId
}
if configuration.offline != NetworkConnectivityCheckerPlugin.Disabled,
VendorSystem.current.networkConnectivityCheckingEnabled {
_ = add(plugin: NetworkConnectivityCheckerPlugin())
}
// required plugin for specific platform, only has lifecyclePlugin now
if let requiredPlugin = VendorSystem.current.requiredPlugin {
_ = add(plugin: requiredPlugin)
}
_ = add(plugin: contextPlugin)
_ = add(plugin: AnalyticsConnectorPlugin())
_ = add(plugin: AnalyticsConnectorIdentityPlugin())
_ = add(plugin: AmplitudeDestinationPlugin())
// Monitor changes to optOut to send to Timeline
configuration.optOutChanged = { [weak self] optOut in
self?.timeline.onOptOutChanged(optOut)
}
trackingQueue.async { [self] in
self.trimQueuedEvents()
}
}
convenience init(apiKey: String, configuration: Configuration) {
configuration.apiKey = apiKey
self.init(configuration: configuration)
}
@discardableResult
public func track(event: BaseEvent, options: EventOptions? = nil, callback: EventCallback? = nil) -> Amplitude {
if options != nil {
event.mergeEventOptions(eventOptions: options!)
}
if callback != nil {
event.callback = callback
}
process(event: event)
return self
}
@discardableResult
public func track(eventType: String, eventProperties: [String: Any]? = nil, options: EventOptions? = nil) -> Amplitude {
let event = BaseEvent(eventType: eventType)
event.eventProperties = eventProperties
if let eventOptions = options {
event.mergeEventOptions(eventOptions: eventOptions)
}
process(event: event)
return self
}
@discardableResult
@available(*, deprecated, message: "use 'track' instead")
public func logEvent(event: BaseEvent) -> Amplitude {
return track(event: event)
}
@discardableResult
public func identify(userProperties: [String: Any]?, options: EventOptions? = nil) -> Amplitude {
return identify(identify: convertPropertiesToIdentify(userProperties: userProperties), options: options)
}
@discardableResult
public func identify(identify: Identify, options: EventOptions? = nil) -> Amplitude {
let event = IdentifyEvent()
event.userProperties = identify.properties as [String: Any]
if let eventOptions = options {
event.mergeEventOptions(eventOptions: eventOptions)
if eventOptions.userId != nil {
setUserId(userId: eventOptions.userId)
}
if eventOptions.deviceId != nil {
setDeviceId(deviceId: eventOptions.deviceId)
}
}
process(event: event)
return self
}
private func convertPropertiesToIdentify(userProperties: [String: Any]?) -> Identify {
let identify = Identify()
userProperties?.forEach { key, value in
_ = identify.set(property: key, value: value)
}
return identify
}
@discardableResult
public func groupIdentify(
groupType: String,
groupName: String,
groupProperties: [String: Any]?,
options: EventOptions? = nil
) -> Amplitude {
return groupIdentify(
groupType: groupType,
groupName: groupName,
identify: convertPropertiesToIdentify(userProperties: groupProperties),
options: options
)
}
@discardableResult
public func groupIdentify(
groupType: String,
groupName: String,
identify: Identify,
options: EventOptions? = nil
) -> Amplitude {
let event = GroupIdentifyEvent()
var groups = [String: Any]()
groups[groupType] = groupName
event.groups = groups
event.groupProperties = identify.properties
if let eventOptions = options {
event.mergeEventOptions(eventOptions: eventOptions)
}
process(event: event)
return self
}
@discardableResult
public func setGroup(
groupType: String,
groupName: String,
options: EventOptions? = nil
) -> Amplitude {
let identify = Identify().set(property: groupType, value: groupName)
let event = IdentifyEvent()
event.groups = [groupType: groupName]
event.userProperties = identify.properties
track(event: event, options: options)
return self
}
@discardableResult
public func setGroup(
groupType: String,
groupName: [String],
options: EventOptions? = nil
) -> Amplitude {
let identify = Identify().set(property: groupType, value: groupName)
let event = IdentifyEvent()
event.groups = [groupType: groupName]
event.userProperties = identify.properties
track(event: event, options: options)
return self
}
@discardableResult
@available(*, deprecated, message: "use 'revenue' instead")
public func logRevenue() -> Amplitude {
return self
}
@discardableResult
public func revenue(
revenue: Revenue,
options: EventOptions? = nil
) -> Amplitude {
guard revenue.isValid() else {
logger?.warn(message: "Invalid revenue object, missing required fields")
return self
}
let event = revenue.toRevenueEvent()
if let eventOptions = options {
event.mergeEventOptions(eventOptions: eventOptions)
}
_ = self.revenue(event: event)
return self
}
@discardableResult
public func revenue(event: RevenueEvent) -> Amplitude {
process(event: event)
return self
}
@discardableResult
public func add(plugin: Plugin) -> Amplitude {
plugin.setup(amplitude: self)
if let _plugin = plugin as? ObservePlugin {
state.add(plugin: _plugin)
} else {
timeline.add(plugin: plugin)
}
return self
}
@discardableResult
public func remove(plugin: Plugin) -> Amplitude {
if let _plugin = plugin as? ObservePlugin {
state.remove(plugin: _plugin)
} else {
timeline.remove(plugin: plugin)
}
return self
}
@discardableResult
public func flush() -> Amplitude {
trackingQueue.async {
self.timeline.apply { plugin in
if let _plugin = plugin as? EventPlugin {
_plugin.flush()
}
}
}
return self
}
@discardableResult
public func setUserId(userId: String?) -> Amplitude {
try? storage.write(key: .USER_ID, value: userId)
state.userId = userId
timeline.onUserIdChanged(userId)
return self
}
@discardableResult
public func setDeviceId(deviceId: String?) -> Amplitude {
try? storage.write(key: .DEVICE_ID, value: deviceId)
state.deviceId = deviceId
timeline.onDeviceIdChanged(deviceId)
return self
}
public func getUserId() -> String? {
return state.userId
}
public func getDeviceId() -> String? {
return state.deviceId
}
public func getSessionId() -> Int64 {
return sessions.sessionId
}
@discardableResult
public func setSessionId(timestamp: Int64) -> Amplitude {
trackingQueue.async { [self] in
let sessionEvents: [BaseEvent]
if timestamp >= 0 {
sessionEvents = self.sessions.startNewSession(timestamp: timestamp)
} else {
sessionEvents = self.sessions.endCurrentSession()
}
self.sessions.assignEventId(events: sessionEvents).forEach { e in
self.timeline.processEvent(event: e)
}
}
return self
}
@discardableResult
public func setSessionId(date: Date) -> Amplitude {
let timestamp = Int64(date.timeIntervalSince1970 * 1000)
setSessionId(timestamp: timestamp)
return self
}
@discardableResult
public func reset() -> Amplitude {
setUserId(userId: nil)
contextPlugin.initializeDeviceId(forceReset: true)
return self
}
public func apply(closure: (Plugin) -> Void) {
timeline.apply(closure)
}
private func process(event: BaseEvent) {
if configuration.optOut {
logger?.log(message: "Skip event based on opt out configuration")
return
}
let inForeground = inForeground
trackingQueue.async { [self] in
let events = self.sessions.processEvent(event: event, inForeground: inForeground)
events.forEach { e in self.timeline.processEvent(event: e) }
}
}
func onEnterForeground(timestamp: Int64) {
inForeground = true
let dummySessionStartEvent = BaseEvent(
timestamp: timestamp,
eventType: Constants.AMP_SESSION_START_EVENT
)
trackingQueue.async { [self] in
// set inForeground to false to represent state before event was fired
let events = self.sessions.processEvent(event: dummySessionStartEvent, inForeground: false)
events.forEach { e in self.timeline.processEvent(event: e) }
}
}
func onExitForeground(timestamp: Int64) {
inForeground = false
trackingQueue.async { [self] in
self.sessions.lastEventTime = timestamp
}
if configuration.flushEventsOnClose == true {
flush()
}
}
private func getStorageVersion() -> PersistentStorageVersion {
let storageVersionInt: Int? = configuration.storageProvider.read(key: .STORAGE_VERSION)
let storageVersion: PersistentStorageVersion = (storageVersionInt == nil) ? PersistentStorageVersion.NO_VERSION : PersistentStorageVersion(rawValue: storageVersionInt!)!
return storageVersion
}
private func migrateApiKeyStorages() {
if getStorageVersion() >= PersistentStorageVersion.API_KEY {
return
}
configuration.loggerProvider.debug(message: "Running migrateApiKeyStorages")
if let persistentStorage = configuration.storageProvider as? PersistentStorage {
let apiKeyStorage = PersistentStorage(storagePrefix: "\(PersistentStorage.DEFAULT_STORAGE_PREFIX)-\(configuration.apiKey)", logger: self.logger, diagonostics: configuration.diagonostics)
StoragePrefixMigration(source: apiKeyStorage, destination: persistentStorage, logger: logger).execute()
}
if let persistentIdentifyStorage = configuration.identifyStorageProvider as? PersistentStorage {
let apiKeyIdentifyStorage = PersistentStorage(storagePrefix: "\(PersistentStorage.DEFAULT_STORAGE_PREFIX)-identify-\(configuration.apiKey)", logger: self.logger, diagonostics: configuration.diagonostics)
StoragePrefixMigration(source: apiKeyIdentifyStorage, destination: persistentIdentifyStorage, logger: logger).execute()
}
}
private func migrateDefaultInstanceStorages() {
if getStorageVersion() >= PersistentStorageVersion.INSTANCE_NAME ||
configuration.instanceName != Constants.Configuration.DEFAULT_INSTANCE {
return
}
configuration.loggerProvider.debug(message: "Running migrateDefaultInstanceStorages")
let legacyDefaultInstanceName = "default_instance"
if let persistentStorage = configuration.storageProvider as? PersistentStorage {
let legacyStorage = PersistentStorage(storagePrefix: "storage-\(legacyDefaultInstanceName)", logger: self.logger, diagonostics: configuration.diagonostics)
StoragePrefixMigration(source: legacyStorage, destination: persistentStorage, logger: logger).execute()
}
if let persistentIdentifyStorage = configuration.identifyStorageProvider as? PersistentStorage {
let legacyIdentifyStorage = PersistentStorage(storagePrefix: "identify-\(legacyDefaultInstanceName)", logger: self.logger, diagonostics: configuration.diagonostics)
StoragePrefixMigration(source: legacyIdentifyStorage, destination: persistentIdentifyStorage, logger: logger).execute()
}
}
internal func migrateInstanceOnlyStorages() {
if getStorageVersion() >= .API_KEY_AND_INSTANCE_NAME {
configuration.loggerProvider.debug(message: "Skipping migrateInstanceOnlyStorages based on STORAGE_VERSION")
return
}
configuration.loggerProvider.debug(message: "Running migrateInstanceOnlyStorages")
let skipEventMigration = !isSandboxEnabled()
// Only migrate sandboxed apps to avoid potential data pollution
if skipEventMigration {
configuration.loggerProvider.debug(message: "Skipping event migration in non-sandboxed app. Transfering UserDefaults only.")
}
let instanceName = configuration.getNormalizeInstanceName()
if let persistentStorage = configuration.storageProvider as? PersistentStorage {
let instanceOnlyEventPrefix = "\(PersistentStorage.DEFAULT_STORAGE_PREFIX)-storage-\(instanceName)"
let instanceNameOnlyStorage = PersistentStorage(storagePrefix: instanceOnlyEventPrefix, logger: self.logger, diagonostics: configuration.diagonostics)
StoragePrefixMigration(
source: instanceNameOnlyStorage,
destination: persistentStorage,
logger: logger
).execute(skipEventFiles: skipEventMigration)
}
if let persistentIdentifyStorage = configuration.identifyStorageProvider as? PersistentStorage {
let instanceOnlyIdentifyPrefix = "\(PersistentStorage.DEFAULT_STORAGE_PREFIX)-identify-\(instanceName)"
let instanceNameOnlyIdentifyStorage = PersistentStorage(storagePrefix: instanceOnlyIdentifyPrefix, logger: self.logger, diagonostics: configuration.diagonostics)
StoragePrefixMigration(
source: instanceNameOnlyIdentifyStorage,
destination: persistentIdentifyStorage,
logger: logger
).execute(skipEventFiles: skipEventMigration)
}
do {
// Store the current storage version
try configuration.storageProvider.write(
key: .STORAGE_VERSION,
value: PersistentStorageVersion.API_KEY_AND_INSTANCE_NAME.rawValue as Int
)
configuration.loggerProvider.debug(message: "Updated STORAGE_VERSION to .API_KEY_AND_INSTANCE_NAME")
} catch {
configuration.loggerProvider.error(message: "Unable to set STORAGE_VERSION in storageProvider during migration")
}
}
internal func isSandboxEnabled() -> Bool {
return SandboxHelper().isSandboxEnabled()
}
func trimQueuedEvents() {
logger?.debug(message: "Trimming queued events..")
guard configuration.maxQueuedEventCount > 0,
let eventBlocks: [URL] = storage.read(key: .EVENTS),
!eventBlocks.isEmpty else {
return
}
var eventCount = 0
// Blocks are returned in sorted order, oldest -> newest. Reverse to count newest blocks first.
// Only whole blocks are deleted, meaning up to maxQueuedEventCount + flushQueueSize - 1
// events may be left on device.
for eventBlock in eventBlocks.reversed() {
if eventCount < configuration.maxQueuedEventCount {
if let eventString = storage.getEventsString(eventBlock: eventBlock),
let eventArray = BaseEvent.fromArrayString(jsonString: eventString) {
eventCount += eventArray.count
}
} else {
logger?.debug(message: "Trimming \(eventBlock)")
storage.remove(eventBlock: eventBlock)
}
}
logger?.debug(message: "Completed trimming events, kept \(eventCount) most recent events")
}
}