Fix running many session duration timers at once #272
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Bug
If user code changes the SDK configuration while the app is in the background, then the SDK can create a
SessionManager.updateSessionDuration()timer that it never invalidates. After a while, these runaway timers add up, and can trigger many times a second, consuming problematic amounts of CPU power.When I first noticed this behavior, it was causing Retcon.app to use 15-25% CPU while in the background, as it was trying to persist 2,834 sessions, extremely frequently.
Fix
This commit adds a check for foreground state before creating the timer.
Cause
Changing SDK configuration (by calling
TelemetryDeck.initialize()), or even just by setting a new value onTelemetryManagerConfiguration.sessionID, causes TelemetryDeck to create a new session update timer, regardless of foreground state. This is a problem, because the SDK only invalidates the session update timer when going back to a background state. As such, the reference to the timer created in the background is silently replaced when creating a new timer, instead of first invalidating the former timer.Calling
TelemetryDeck.initialize()actually causes the timer to be created after a fixed 0.5s delay, making the bug very likely to occur if a macOS app updates its TelemetryDeck configuration upon being focused.The following code reliably triggers the issue, if the user switches to the app, then quickly switches away: