Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Data race in Ratelimiter. #4440

Open
jesus-mg-ios opened this issue Nov 6, 2024 · 4 comments
Open

Bug: Data race in Ratelimiter. #4440

jesus-mg-ios opened this issue Nov 6, 2024 · 4 comments

Comments

@jesus-mg-ios
Copy link

https://github.com/RevenueCat/purchases-ios/blame/72b06f69438eff747fe0d6baa408b3a7745d4087/Sources/Misc/RateLimiter.swift#L41

https://github.com/RevenueCat/purchases-ios/blame/72b06f69438eff747fe0d6baa408b3a7745d4087/Sources/Misc/RateLimiter.swift#L42

internal class RateLimiter {
    private var timestamps: [Date?]
    private var index: Int = 0
    private let maxCallsInclusive: Int

    let maxCalls: Int
    let period: TimeInterval

    init(maxCalls: Int, period: TimeInterval) {
        self.maxCalls = maxCalls
        self.maxCallsInclusive = self.maxCalls + 1
        self.period = period

        self.timestamps = Array(repeating: nil, count: maxCallsInclusive)
    }

    func shouldProceed() -> Bool {
        let now = Date()
        let oldestIndex = (index + 1) % maxCallsInclusive
        let oldestTimestamp = timestamps[oldestIndex]

        // Check if the oldest timestamp is outside the rate limiting period or if it's nil
        if let oldestTimestamp = oldestTimestamp, now.timeIntervalSince(oldestTimestamp) <= period {
            return false
        } else {
            timestamps[index] = now
            index = oldestIndex
            return true
        }
    }
}

Some alternatives here:

  • Make it an actor, so the shouldProceed signature changes to async
  • Use atomics in all properties, maybe is too much
  • Use a dispatchqueue as class property and use it in the whole shouldProceed method making it sync
  • Use a lock(.recursive)
@RCGitBot
Copy link
Contributor

RCGitBot commented Nov 6, 2024

👀 We've just linked this issue to our internal tracker and notified the team. Thank you for reporting, we're checking this out!

@nyeu
Copy link
Contributor

nyeu commented Nov 8, 2024

Hi @jesus-mg-ios,
Would you mind explaining in more detail the issue you are finding?

@jesus-mg-ios
Copy link
Author

Well Xcode points there about data races. I'm not getting a wrong working, at least, on my tests. I cannot provide more details.

@jesus-mg-ios
Copy link
Author

jesus-mg-ios commented Nov 22, 2024

@nyeu Do you need something else to tackle it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants