TelemetryDeck / SwiftSDK

Swift SDK for TelemetryDeck, a privacy-conscious analytics service for apps and websites.
https://telemetrydeck.com/
Other
149 stars 31 forks source link

Add limit, throttle and debounce algorithms for sending signals #59

Closed Jeehut closed 1 year ago

Jeehut commented 2 years ago

In my app, I have places where users can adjust some strings such as file paths to search or ignore. I would like to track how often these fields are being changed (or if they are changed at all), but I don't want to send a signal for every key change a user enters as this would result to too many signals.

Therefore I need to implement an algorithm that limits how often I send this event. While I will probably add this to my app, I thought maybe this might be useful to add right into the client itself for others convenience. Here are 3 additions I would suggest:

  1. Limit: Add a send(String, with: [String: String], limit: Int, context: Equatable) overload where limit is the max count a signal with the same name can be sent for a given context, where the context could be a selected item, for example.
  2. Throttle: Add a send(String, with: [String: String], limit: Int, for: TimeInterval) overload where limit is the max count a signal with the same name can be sent within a given period of time, so any signals with the same name that exceed this limit are simply dropped and ignored.
  3. Debounce: Add a send(String, with: [String: String], first/last: Int, after: TimeInterval) overload where first/last is the max count of first/last signals to be sent after waiting at least the amount of time to pass since the last sending of the signal.

With these 3 I could reach my goal of only sending my event once in 3 different ways depending on what I need in a given context. Of course, instead of overloading the send method, we could also introduce a wrapper type and go for a more function chained API with func limit(count: 1, context: Equatable) -> Self, func throttle(count: Int = 1, for: TimeInterval) -> Self, and func debounce(count: Int = 1, after: TimeInterval).

I would be up to implement this based on which API design you prefer and which of these 3 you would accept.

winsmith commented 1 year ago

Hi, I think this is out of scope for the SDK as it is now. I recommend you implement this in a wrapper around the TelemetryDeck SDK instead!

Jeehut commented 1 year ago

Thank you for the clarification, I have already implemented the part I need for my app. I will probably write an article sometime with my solution and maybe even extract the entire Analytics engine as an open source library. I will make sure to post the link here once it's published for anyone who's interested in a similar thing.