-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathOdpManager.swift
179 lines (147 loc) · 7.08 KB
/
OdpManager.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
//
// Copyright 2022-2023, 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
public class OdpManager {
var enabled: Bool
var odpConfig: OdpConfig!
var segmentManager: OdpSegmentManager!
var eventManager: OdpEventManager!
let logger = OPTLoggerFactory.getLogger()
var vuid: String?
/// OdpManager init
/// - Parameters:
/// - sdkKey: datafile sdkKey
/// - disable: disable ODP
/// - cacheSize: segment cache size
/// - cacheTimeoutInSecs: segment cache timeout
/// - timeoutForSegmentFetchInSecs: timeout for segment fetch
/// - timeoutForEventDispatchInSecs: timeout for event dispatch
/// - segmentManager: ODPSegmentManager
/// - eventManager: ODPEventManager
public init(sdkKey: String,
disable: Bool,
vuid: String? = nil,
cacheSize: Int,
cacheTimeoutInSecs: Int,
timeoutForSegmentFetchInSecs: Int? = nil,
timeoutForEventDispatchInSecs: Int? = nil,
segmentManager: OdpSegmentManager? = nil,
eventManager: OdpEventManager? = nil) {
self.enabled = !disable
self.vuid = vuid
guard enabled else {
logger.i(.odpNotEnabled)
return
}
self.segmentManager = segmentManager ?? OdpSegmentManager(cacheSize: cacheSize,
cacheTimeoutInSecs: cacheTimeoutInSecs,
resourceTimeoutInSecs: timeoutForSegmentFetchInSecs)
self.eventManager = eventManager ?? OdpEventManager(sdkKey: sdkKey,
resourceTimeoutInSecs: timeoutForEventDispatchInSecs)
self.odpConfig = OdpConfig()
self.segmentManager.odpConfig = odpConfig
self.eventManager.odpConfig = odpConfig
}
func fetchQualifiedSegments(userId: String,
options: [OptimizelySegmentOption],
completionHandler: @escaping ([String]?, OptimizelyError?) -> Void) {
guard enabled else {
completionHandler(nil, .odpNotEnabled)
return
}
let userKey = VuidManager.isVuid(userId) ? Constants.ODP.keyForVuid : Constants.ODP.keyForUserId
let userValue = userId
segmentManager.fetchQualifiedSegments(userKey: userKey,
userValue: userValue,
options: options,
completionHandler: completionHandler)
}
func sendInitializedEvent(vuid: String) throws {
guard enabled else { throw OptimizelyError.odpNotEnabled }
guard odpConfig.eventQueueingAllowed else { throw OptimizelyError.odpNotIntegrated }
eventManager.sendInitializedEvent(vuid: vuid)
}
func identifyUser(userId: String) {
guard enabled else {
logger.d("ODP identify event is not dispatched (ODP disabled).")
return
}
guard odpConfig.eventQueueingAllowed else {
logger.d("ODP identify event is not dispatched (ODP not integrated).")
return
}
if VuidManager.isVuid(userId) {
// overwrite if userId is vuid (when userContext is created with vuid)
eventManager.identifyUser(vuid: userId, userId: nil)
} else {
eventManager.identifyUser(vuid: self.vuid, userId: userId)
}
}
/// Send an event to the ODP server.
///
/// - Parameters:
/// - type: the event type.
/// - action: the event action name.
/// - identifiers: a dictionary for identifiers.
/// - data: a dictionary for associated data. The default event data will be added to this data before sending to the ODP server.
/// - Throws: `OptimizelyError` if error is detected
func sendEvent(type: String?, action: String, identifiers: [String: String], data: [String: Any?]) throws {
guard enabled else { throw OptimizelyError.odpNotEnabled }
guard odpConfig.eventQueueingAllowed else { throw OptimizelyError.odpNotIntegrated }
guard eventManager.isDataValidType(data) else { throw OptimizelyError.odpInvalidData }
if action.isEmpty { throw OptimizelyError.odpInvalidAction }
let typeUpdated = (type ?? "").isEmpty ? Constants.ODP.eventType : type!
var identifiersUpdated = identifiers
if identifiers[Constants.ODP.keyForVuid] == nil, let _vuid = vuid {
identifiersUpdated[Constants.ODP.keyForVuid] = _vuid
}
// replace aliases (fs-user-id, FS_USER_ID, FS-USER-ID) with "fs_user_id".
for (idKey, idValue) in identifiersUpdated {
if idKey == Constants.ODP.keyForUserId { break }
if [Constants.ODP.keyForUserId, Constants.ODP.keyForUserIdAlias].contains(idKey.lowercased()) {
identifiersUpdated.removeValue(forKey: idKey)
identifiersUpdated[Constants.ODP.keyForUserId] = idValue
break
}
}
eventManager.sendEvent(type: typeUpdated, action: action, identifiers: identifiersUpdated, data: data)
}
func updateOdpConfig(apiKey: String?, apiHost: String?, segmentsToCheck: [String]) {
guard enabled else { return }
// flush old events using old odp publicKey (if exists) before updating odp key.
// NOTE: It should be rare but possible that odp public key is changed for the same datafile (sdkKey).
// Try to send all old events with the previous public key.
// If it fails to flush all the old events here (network error), remaning events will be discarded.
eventManager.flush()
let configChanged = odpConfig.update(apiKey: apiKey,
apiHost: apiHost,
segmentsToCheck: segmentsToCheck)
if configChanged {
// reset segments cache when odp integration or segmentsToCheck are changed
segmentManager.reset()
}
}
}
extension OdpManager: BackgroundingCallbacks {
func applicationDidEnterBackground() {
guard enabled else { return }
eventManager.flush()
}
func applicationDidBecomeActive() {
guard enabled else { return }
// no actions here for now
}
}