Last active
April 7, 2020 10:41
-
-
Save mukund-murali/72cf03a045767584ae4fbbaa6b5bbe41 to your computer and use it in GitHub Desktop.
Sentry supports per project rate limiting only in it's business plan and it's controlled at the server side. Here is some monkey patching that makes it available at the SDK level.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Rate limiting monkey patch for Sentry error reporting SDK.""" | |
from datetime import datetime | |
from typing import Callable | |
import sentry_sdk | |
class RateLimit: | |
def __init__(self, limit: int = 100, period: int = 60 * 60): | |
"""Initialize the rate limiter. | |
Args: | |
limit (int): Number of calls to allow with the period. | |
period (int): Number of seconds to be considered as one interval. | |
""" | |
self.limit = limit | |
self.period = period | |
self.reset_time = datetime.now() | |
self.num_calls = 0 | |
def __call__(self, func: Callable, *args, **kwargs): | |
def inner(*args, **kwargs): | |
diff_seconds = (datetime.now() - self.reset_time).seconds | |
if diff_seconds > self.period: | |
self.reset_time = datetime.now() | |
self.num_calls = 0 | |
self.num_calls += 1 | |
if self.num_calls > self.limit: | |
return | |
func(*args, **kwargs) | |
return inner | |
orig_capture_event = sentry_sdk.hub.Hub.current.capture_event | |
@RateLimit() | |
def rate_limited_capture_event(*args, **kwargs): | |
orig_capture_event(*args, **kwargs) | |
sentry_sdk.hub.Hub.current.capture_event = rate_limited_capture_event |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import the rate limiter after you initialize sentry sdk. | |
import sentry_sdk | |
def init_sentry(): | |
SENTRY_DSN = "" | |
sentry_sdk.init(dsn=SENTRY_DSN) | |
import sentry_rate_limiter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment