-
Notifications
You must be signed in to change notification settings - Fork 230
/
Flush.swift
178 lines (157 loc) · 5.71 KB
/
Flush.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
//
// Flush.swift
// Mixpanel
//
// Created by Yarden Eitan on 6/3/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
protocol FlushDelegate: AnyObject {
func flush(performFullFlush: Bool, completion: (() -> Void)?)
func flushSuccess(type: FlushType, ids: [Int32])
#if os(iOS)
func updateNetworkActivityIndicator(_ on: Bool)
#endif // os(iOS)
}
class Flush: AppLifecycle {
var timer: Timer?
weak var delegate: FlushDelegate?
var useIPAddressForGeoLocation = true
var flushRequest: FlushRequest
var flushOnBackground = true
var _flushInterval = 0.0
var _flushBatchSize = APIConstants.maxBatchSize
private var _serverURL = BasePath.DefaultMixpanelAPI
private let flushRequestReadWriteLock: DispatchQueue
var serverURL: String {
get {
flushRequestReadWriteLock.sync {
return _serverURL
}
}
set {
flushRequestReadWriteLock.sync(flags: .barrier, execute: {
_serverURL = newValue
self.flushRequest.serverURL = newValue
})
}
}
var flushInterval: Double {
get {
flushRequestReadWriteLock.sync {
return _flushInterval
}
}
set {
flushRequestReadWriteLock.sync(flags: .barrier, execute: {
_flushInterval = newValue
})
delegate?.flush(performFullFlush: false, completion: nil)
startFlushTimer()
}
}
var flushBatchSize: Int {
get {
return _flushBatchSize
}
set {
_flushBatchSize = newValue
}
}
required init(serverURL: String) {
self.flushRequest = FlushRequest(serverURL: serverURL)
_serverURL = serverURL
flushRequestReadWriteLock = DispatchQueue(label: "com.mixpanel.flush_interval.lock", qos: .utility, attributes: .concurrent, autoreleaseFrequency: .workItem)
}
func flushQueue(_ queue: Queue, type: FlushType, headers: [String: String], queryItems: [URLQueryItem]) {
if flushRequest.requestNotAllowed() {
return
}
flushQueueInBatches(queue, type: type, headers: headers, queryItems: queryItems)
}
func startFlushTimer() {
stopFlushTimer()
DispatchQueue.main.async { [weak self] in
guard let self = self else {
return
}
if self.flushInterval > 0 {
self.timer?.invalidate()
self.timer = Timer.scheduledTimer(timeInterval: self.flushInterval,
target: self,
selector: #selector(self.flushSelector),
userInfo: nil,
repeats: true)
}
}
}
@objc func flushSelector() {
delegate?.flush(performFullFlush: false, completion: nil)
}
func stopFlushTimer() {
if let timer = timer {
DispatchQueue.main.async { [weak self, timer] in
timer.invalidate()
self?.timer = nil
}
}
}
func flushQueueInBatches(_ queue: Queue, type: FlushType, headers: [String: String], queryItems: [URLQueryItem]) {
var mutableQueue = queue
while !mutableQueue.isEmpty {
let batchSize = min(mutableQueue.count, flushBatchSize)
let range = 0..<batchSize
let batch = Array(mutableQueue[range])
let ids: [Int32] = batch.map { entity in
(entity["id"] as? Int32) ?? 0
}
// Log data payload sent
Logger.debug(message: "Sending batch of data")
Logger.debug(message: batch as Any)
let requestData = JSONHandler.encodeAPIData(batch)
if let requestData = requestData {
#if os(iOS)
if !MixpanelInstance.isiOSAppExtension() {
delegate?.updateNetworkActivityIndicator(true)
}
#endif // os(iOS)
let success = flushRequest.sendRequest(requestData,
type: type,
useIP: useIPAddressForGeoLocation,
headers: headers,
queryItems: queryItems)
#if os(iOS)
if !MixpanelInstance.isiOSAppExtension() {
delegate?.updateNetworkActivityIndicator(false)
}
#endif // os(iOS)
if success {
// remove
delegate?.flushSuccess(type: type, ids: ids)
mutableQueue = self.removeProcessedBatch(batchSize: batchSize,
queue: mutableQueue,
type: type)
} else {
break
}
}
}
}
func removeProcessedBatch(batchSize: Int, queue: Queue, type: FlushType) -> Queue {
var shadowQueue = queue
let range = 0..<batchSize
if let lastIndex = range.last, shadowQueue.count - 1 > lastIndex {
shadowQueue.removeSubrange(range)
} else {
shadowQueue.removeAll()
}
return shadowQueue
}
// MARK: - Lifecycle
func applicationDidBecomeActive() {
startFlushTimer()
}
func applicationWillResignActive() {
stopFlushTimer()
}
}