Skip to content

Commit 1ce2974

Browse files
authored
Fixed flush policy over-flush potential; Added example policy aggregator. (#362)
1 parent be28488 commit 1ce2974

File tree

2 files changed

+82
-1
lines changed

2 files changed

+82
-1
lines changed

Examples/tasks/UncleFlushPolicy.swift

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
//
2+
// UncleFlushPolicy.swift
3+
// Segment
4+
//
5+
// Created by Brandon Sneed on 9/17/24.
6+
//
7+
8+
import Foundation
9+
10+
public class UncleFlushPolicy: FlushPolicy {
11+
public weak var analytics: Analytics?
12+
internal var basePolicies: [FlushPolicy] = [CountBasedFlushPolicy(), IntervalBasedFlushPolicy(), /* .. add your own here .. */]
13+
14+
public init() {
15+
/*
16+
or add your own here ...
17+
18+
```
19+
self.basePolicies.append(MyCrazyUnclesOtherPolicy(onThanksgiving: true)
20+
```
21+
*/
22+
}
23+
24+
private func shouldWeREALLYFlush() -> Bool {
25+
// do some meaningful calculation or check here.
26+
// Ol Unc's was right i guess since we're gonna do what he says.
27+
return true
28+
}
29+
30+
public func configure(analytics: Analytics) {
31+
self.analytics = analytics
32+
basePolicies.forEach { $0.configure(analytics: analytics) }
33+
}
34+
35+
public func shouldFlush() -> Bool {
36+
guard let a = analytics else {
37+
return false
38+
}
39+
40+
var shouldFlush = false
41+
for policy in basePolicies {
42+
shouldFlush = policy.shouldFlush() || shouldFlush
43+
}
44+
45+
if shouldFlush {
46+
// ask the know it all ...
47+
shouldFlush = shouldWeREALLYFlush()
48+
}
49+
50+
return shouldFlush
51+
}
52+
53+
public func updateState(event: RawEvent) {
54+
basePolicies.forEach { $0.updateState(event: event) }
55+
}
56+
57+
public func reset() {
58+
basePolicies.forEach { $0.reset() }
59+
}
60+
}

Sources/Segment/Analytics.swift

+22-1
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,35 @@ public class Analytics {
9999

100100
_ = timeline.process(incomingEvent: event, enrichments: enrichments)
101101

102-
let flushPolicies = configuration.values.flushPolicies
102+
/*let flushPolicies = configuration.values.flushPolicies
103103
for policy in flushPolicies {
104104
policy.updateState(event: event)
105105

106106
if (policy.shouldFlush() == true) {
107107
flush()
108108
policy.reset()
109109
}
110+
}*/
111+
112+
let flushPolicies = configuration.values.flushPolicies
113+
114+
var shouldFlush = false
115+
// if any policy says to flush, make note of that
116+
for policy in flushPolicies {
117+
policy.updateState(event: event)
118+
if policy.shouldFlush() {
119+
shouldFlush = true
120+
// we don't need to updateState on any others since we're gonna reset it below.
121+
break
122+
}
123+
}
124+
// if we were told to flush do it.
125+
if shouldFlush {
126+
// reset all the policies if one decided to flush.
127+
flushPolicies.forEach {
128+
$0.reset()
129+
}
130+
flush()
110131
}
111132
}
112133

0 commit comments

Comments
 (0)