Skip to content

Commit

Permalink
Fixed flush policy over-flush potential; Added example policy aggrega…
Browse files Browse the repository at this point in the history
…tor. (#362)
  • Loading branch information
bsneed authored Sep 17, 2024
1 parent be28488 commit 1ce2974
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
60 changes: 60 additions & 0 deletions Examples/tasks/UncleFlushPolicy.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//
// UncleFlushPolicy.swift
// Segment
//
// Created by Brandon Sneed on 9/17/24.
//

import Foundation

public class UncleFlushPolicy: FlushPolicy {
public weak var analytics: Analytics?
internal var basePolicies: [FlushPolicy] = [CountBasedFlushPolicy(), IntervalBasedFlushPolicy(), /* .. add your own here .. */]

public init() {
/*
or add your own here ...

```
self.basePolicies.append(MyCrazyUnclesOtherPolicy(onThanksgiving: true)
```
*/
}

private func shouldWeREALLYFlush() -> Bool {
// do some meaningful calculation or check here.
// Ol Unc's was right i guess since we're gonna do what he says.
return true
}

public func configure(analytics: Analytics) {
self.analytics = analytics
basePolicies.forEach { $0.configure(analytics: analytics) }
}

public func shouldFlush() -> Bool {
guard let a = analytics else {
return false
}

var shouldFlush = false
for policy in basePolicies {
shouldFlush = policy.shouldFlush() || shouldFlush
}

if shouldFlush {
// ask the know it all ...
shouldFlush = shouldWeREALLYFlush()
}

return shouldFlush
}

public func updateState(event: RawEvent) {
basePolicies.forEach { $0.updateState(event: event) }
}

public func reset() {
basePolicies.forEach { $0.reset() }
}
}
23 changes: 22 additions & 1 deletion Sources/Segment/Analytics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,35 @@ public class Analytics {

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

let flushPolicies = configuration.values.flushPolicies
/*let flushPolicies = configuration.values.flushPolicies
for policy in flushPolicies {
policy.updateState(event: event)

if (policy.shouldFlush() == true) {
flush()
policy.reset()
}
}*/

let flushPolicies = configuration.values.flushPolicies

var shouldFlush = false
// if any policy says to flush, make note of that
for policy in flushPolicies {
policy.updateState(event: event)
if policy.shouldFlush() {
shouldFlush = true
// we don't need to updateState on any others since we're gonna reset it below.
break
}
}
// if we were told to flush do it.
if shouldFlush {
// reset all the policies if one decided to flush.
flushPolicies.forEach {
$0.reset()
}
flush()
}
}

Expand Down

0 comments on commit 1ce2974

Please sign in to comment.