diff --git a/CHANGELOG.md b/CHANGELOG.md index df419dc7f..62718b098 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## Next +- `maxQueueSize` wasn't respected when capturing events [#116](https://github.com/PostHog/posthog-ios/pull/116) + ## 3.2.3 - 2024-03-05 - `optOut` wasn't respected in capture methods [#114](https://github.com/PostHog/posthog-ios/pull/114) diff --git a/PostHog/PostHogQueue.swift b/PostHog/PostHogQueue.swift index ed556fb33..7c135de03 100644 --- a/PostHog/PostHogQueue.swift +++ b/PostHog/PostHogQueue.swift @@ -168,6 +168,12 @@ class PostHogQueue { } func add(_ event: PostHogEvent) { + if fileQueue.depth >= config.maxQueueSize { + hedgeLog("Queue is full, dropping oldest event") + // first is always oldest + fileQueue.delete(index: 0) + } + var data: Data? do { data = try JSONSerialization.data(withJSONObject: event.toJSON()) diff --git a/PostHogTests/PostHogQueueTest.swift b/PostHogTests/PostHogQueueTest.swift index 109acf3b2..32aa945a0 100644 --- a/PostHogTests/PostHogQueueTest.swift +++ b/PostHogTests/PostHogQueueTest.swift @@ -12,9 +12,10 @@ import Quick import XCTest class PostHogQueueTest: QuickSpec { - func getSut() -> PostHogQueue { + func getSut(flushAt: Int = 1, maxQueueSize: Int = 1000) -> PostHogQueue { let config = PostHogConfig(apiKey: "123", host: "http://localhost:9001") - config.flushAt = 1 + config.flushAt = flushAt + config.maxQueueSize = maxQueueSize let storage = PostHogStorage(config) let api = PostHogApi(config) return PostHogQueue(config, storage, api, nil) @@ -64,5 +65,31 @@ class PostHogQueueTest: QuickSpec { sut.clear() } + + it("add item to queue and rotate queue") { + let sut = self.getSut(flushAt: 3, maxQueueSize: 2) + + let event = PostHogEvent(event: "event", distinctId: "distinctId") + let event2 = PostHogEvent(event: "event2", distinctId: "distinctId2") + let event3 = PostHogEvent(event: "event3", distinctId: "distinctId3") + sut.add(event) + sut.add(event2) + sut.add(event3) + + expect(sut.depth) == 2 + + sut.flush() + + let events = getBatchedEvents(server) + + expect(events.count) == 2 + + let first = events.first! + let last = events.last! + expect(first.event) == "event2" + expect(last.event) == "event3" + + sut.clear() + } } }