|
| 1 | +import 'package:core/core.dart'; |
| 2 | + |
| 3 | +/// {@template rate_limit_service} |
| 4 | +/// Defines the interface for a service that provides rate-limiting capabilities. |
| 5 | +/// |
| 6 | +/// This service is used to check and record requests against a specific key |
| 7 | +/// (e.g., an IP address or email) to prevent abuse of sensitive or expensive |
| 8 | +/// endpoints. |
| 9 | +/// {@endtemplate} |
| 10 | +abstract class RateLimitService { |
| 11 | + /// {@macro rate_limit_service} |
| 12 | + const RateLimitService(); |
| 13 | + |
| 14 | + /// Checks if a request associated with the given [key] is allowed. |
| 15 | + /// |
| 16 | + /// This method performs the following logic: |
| 17 | + /// 1. Counts the number of recent requests for the [key] within the [window]. |
| 18 | + /// 2. If the count is greater than or equal to the [limit], it throws a |
| 19 | + /// [ForbiddenException] indicating the rate limit has been exceeded. |
| 20 | + /// 3. If the count is below the limit, it records the current request |
| 21 | + /// (e.g., by storing a timestamp) and allows the request to proceed. |
| 22 | + /// |
| 23 | + /// - [key]: A unique identifier for the request source (e.g., IP address). |
| 24 | + /// - [limit]: The maximum number of requests allowed within the window. |
| 25 | + /// - [window]: The time duration to consider for counting requests. |
| 26 | + /// |
| 27 | + /// Throws [ForbiddenException] if the rate limit is exceeded. |
| 28 | + /// Throws [OperationFailedException] for unexpected errors during the check. |
| 29 | + Future<void> checkRequest({ |
| 30 | + required String key, |
| 31 | + required int limit, |
| 32 | + required Duration window, |
| 33 | + }); |
| 34 | + |
| 35 | + /// Disposes of any resources used by the service (e.g., timers). |
| 36 | + void dispose(); |
| 37 | +} |
0 commit comments