1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
|
import logging
from datetime import datetime, timedelta, timezone
from typing import Optional
from uuid import UUID
from core.base import Handler
from shared.abstractions import User
from ...base.providers.database import DatabaseConfig, LimitSettings
from .base import PostgresConnectionManager
logger = logging.getLogger(__name__)
class PostgresLimitsHandler(Handler):
TABLE_NAME = "request_log"
def __init__(
self,
project_name: str,
connection_manager: PostgresConnectionManager,
config: DatabaseConfig,
):
"""
:param config: The global DatabaseConfig with default rate limits.
"""
super().__init__(project_name, connection_manager)
self.config = config
logger.debug(
f"Initialized PostgresLimitsHandler with project: {project_name}"
)
async def create_tables(self):
query = f"""
CREATE TABLE IF NOT EXISTS {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)} (
time TIMESTAMPTZ NOT NULL,
user_id UUID NOT NULL,
route TEXT NOT NULL
);
"""
logger.debug("Creating request_log table if not exists")
await self.connection_manager.execute_query(query)
async def _count_requests(
self,
user_id: UUID,
route: Optional[str],
since: datetime,
) -> int:
"""Count how many requests a user (optionally for a specific route) has
made since the given datetime."""
if route:
query = f"""
SELECT COUNT(*)::int
FROM {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)}
WHERE user_id = $1
AND route = $2
AND time >= $3
"""
params = [user_id, route, since]
logger.debug(
f"Counting requests for user={user_id}, route={route}"
)
else:
query = f"""
SELECT COUNT(*)::int
FROM {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)}
WHERE user_id = $1
AND time >= $2
"""
params = [user_id, since]
logger.debug(f"Counting all requests for user={user_id}")
result = await self.connection_manager.fetchrow_query(query, params)
return result["count"] if result else 0
async def _count_monthly_requests(
self,
user_id: UUID,
route: Optional[str] = None, # <--- ADDED THIS
) -> int:
"""Count the number of requests so far this month for a given user.
If route is provided, count only for that route. Otherwise, count
globally.
"""
now = datetime.now(timezone.utc)
start_of_month = now.replace(
day=1, hour=0, minute=0, second=0, microsecond=0
)
return await self._count_requests(
user_id, route=route, since=start_of_month
)
def determine_effective_limits(
self, user: User, route: str
) -> LimitSettings:
"""
Determine the final effective limits for a user+route combination,
respecting:
1) Global defaults
2) Route-specific overrides
3) User-level overrides
"""
# ------------------------
# 1) Start with global/base
# ------------------------
base_limits = self.config.limits
# We’ll make a copy so we don’t mutate self.config.limits directly
effective = LimitSettings(
global_per_min=base_limits.global_per_min,
route_per_min=base_limits.route_per_min,
monthly_limit=base_limits.monthly_limit,
)
# ------------------------
# 2) Route-level overrides
# ------------------------
route_config = self.config.route_limits.get(route)
if route_config:
if route_config.global_per_min is not None:
effective.global_per_min = route_config.global_per_min
if route_config.route_per_min is not None:
effective.route_per_min = route_config.route_per_min
if route_config.monthly_limit is not None:
effective.monthly_limit = route_config.monthly_limit
# ------------------------
# 3) User-level overrides
# ------------------------
# The user object might have a dictionary of overrides
# which can include route_overrides, global_per_min, monthly_limit, etc.
user_overrides = user.limits_overrides or {}
# (a) "global" user overrides
if user_overrides.get("global_per_min") is not None:
effective.global_per_min = user_overrides["global_per_min"]
if user_overrides.get("monthly_limit") is not None:
effective.monthly_limit = user_overrides["monthly_limit"]
# (b) route-level user overrides
route_overrides = user_overrides.get("route_overrides", {})
specific_config = route_overrides.get(route, {})
if specific_config.get("global_per_min") is not None:
effective.global_per_min = specific_config["global_per_min"]
if specific_config.get("route_per_min") is not None:
effective.route_per_min = specific_config["route_per_min"]
if specific_config.get("monthly_limit") is not None:
effective.monthly_limit = specific_config["monthly_limit"]
return effective
async def check_limits(self, user: User, route: str):
"""Perform rate limit checks for a user on a specific route.
:param user: The fully-fetched User object with .limits_overrides, etc.
:param route: The route/path being accessed.
:raises ValueError: if any limit is exceeded.
"""
user_id = user.id
now = datetime.now(timezone.utc)
one_min_ago = now - timedelta(minutes=1)
# 1) Compute the final (effective) limits for this user & route
limits = self.determine_effective_limits(user, route)
# 2) Check each of them in turn, if they exist
# ------------------------------------------------------------
# Global per-minute limit
# ------------------------------------------------------------
if limits.global_per_min is not None:
user_req_count = await self._count_requests(
user_id, None, one_min_ago
)
if user_req_count > limits.global_per_min:
logger.warning(
f"Global per-minute limit exceeded for "
f"user_id={user_id}, route={route}"
)
raise ValueError("Global per-minute rate limit exceeded")
# ------------------------------------------------------------
# Route-specific per-minute limit
# ------------------------------------------------------------
if limits.route_per_min is not None:
route_req_count = await self._count_requests(
user_id, route, one_min_ago
)
if route_req_count > limits.route_per_min:
logger.warning(
f"Per-route per-minute limit exceeded for "
f"user_id={user_id}, route={route}"
)
raise ValueError("Per-route per-minute rate limit exceeded")
# ------------------------------------------------------------
# Monthly limit
# ------------------------------------------------------------
if limits.monthly_limit is not None:
# If you truly want a per-route monthly limit, we pass 'route'.
# If you want a global monthly limit, pass 'None'.
monthly_count = await self._count_monthly_requests(user_id, route)
if monthly_count > limits.monthly_limit:
logger.warning(
f"Monthly limit exceeded for user_id={user_id}, "
f"route={route}"
)
raise ValueError("Monthly rate limit exceeded")
async def log_request(self, user_id: UUID, route: str):
"""Log a successful request to the request_log table."""
query = f"""
INSERT INTO {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)}
(time, user_id, route)
VALUES (CURRENT_TIMESTAMP AT TIME ZONE 'UTC', $1, $2)
"""
await self.connection_manager.execute_query(query, [user_id, route])
# import logging
# from datetime import datetime, timedelta, timezone
# from typing import Optional
# from uuid import UUID
# from core.base import Handler
# from shared.abstractions import User
# from ..base.providers.database import DatabaseConfig, LimitSettings
# from .base import PostgresConnectionManager
# logger = logging.getLogger(__name__)
# class PostgresLimitsHandler(Handler):
# TABLE_NAME = "request_log"
# def __init__(
# self,
# project_name: str,
# connection_manager: PostgresConnectionManager,
# config: DatabaseConfig,
# ):
# """
# :param config: The global DatabaseConfig with default rate limits.
# """
# super().__init__(project_name, connection_manager)
# self.config = config
# logger.debug(
# f"Initialized PostgresLimitsHandler with project: {project_name}"
# )
# async def create_tables(self):
# query = f"""
# CREATE TABLE IF NOT EXISTS {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)} (
# time TIMESTAMPTZ NOT NULL,
# user_id UUID NOT NULL,
# route TEXT NOT NULL
# );
# """
# logger.debug("Creating request_log table if not exists")
# await self.connection_manager.execute_query(query)
# async def _count_requests(
# self,
# user_id: UUID,
# route: Optional[str],
# since: datetime,
# ) -> int:
# """
# Count how many requests a user (optionally for a specific route)
# has made since the given datetime.
# """
# if route:
# query = f"""
# SELECT COUNT(*)::int
# FROM {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)}
# WHERE user_id = $1
# AND route = $2
# AND time >= $3
# """
# params = [user_id, route, since]
# logger.debug(f"Counting requests for user={user_id}, route={route}")
# else:
# query = f"""
# SELECT COUNT(*)::int
# FROM {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)}
# WHERE user_id = $1
# AND time >= $2
# """
# params = [user_id, since]
# logger.debug(f"Counting all requests for user={user_id}")
# result = await self.connection_manager.fetchrow_query(query, params)
# return result["count"] if result else 0
# async def _count_monthly_requests(self, user_id: UUID) -> int:
# """
# Count the number of requests so far this month for a given user.
# """
# now = datetime.now(timezone.utc)
# start_of_month = now.replace(
# day=1, hour=0, minute=0, second=0, microsecond=0
# )
# return await self._count_requests(
# user_id, route=None, since=start_of_month
# )
# def determine_effective_limits(
# self, user: User, route: str
# ) -> LimitSettings:
# """
# Determine the final effective limits for a user+route combination,
# respecting:
# 1) Global defaults
# 2) Route-specific overrides
# 3) User-level overrides
# """
# # ------------------------
# # 1) Start with global/base
# # ------------------------
# base_limits = self.config.limits
# # We’ll make a copy so we don’t mutate self.config.limits directly
# effective = LimitSettings(
# global_per_min=base_limits.global_per_min,
# route_per_min=base_limits.route_per_min,
# monthly_limit=base_limits.monthly_limit,
# )
# # ------------------------
# # 2) Route-level overrides
# # ------------------------
# route_config = self.config.route_limits.get(route)
# if route_config:
# if route_config.global_per_min is not None:
# effective.global_per_min = route_config.global_per_min
# if route_config.route_per_min is not None:
# effective.route_per_min = route_config.route_per_min
# if route_config.monthly_limit is not None:
# effective.monthly_limit = route_config.monthly_limit
# # ------------------------
# # 3) User-level overrides
# # ------------------------
# # The user object might have a dictionary of overrides
# # which can include route_overrides, global_per_min, monthly_limit, etc.
# user_overrides = user.limits_overrides or {}
# # (a) "global" user overrides
# if user_overrides.get("global_per_min") is not None:
# effective.global_per_min = user_overrides["global_per_min"]
# if user_overrides.get("monthly_limit") is not None:
# effective.monthly_limit = user_overrides["monthly_limit"]
# # (b) route-level user overrides
# route_overrides = user_overrides.get("route_overrides", {})
# specific_config = route_overrides.get(route, {})
# if specific_config.get("global_per_min") is not None:
# effective.global_per_min = specific_config["global_per_min"]
# if specific_config.get("route_per_min") is not None:
# effective.route_per_min = specific_config["route_per_min"]
# if specific_config.get("monthly_limit") is not None:
# effective.monthly_limit = specific_config["monthly_limit"]
# return effective
# async def check_limits(self, user: User, route: str):
# """
# Perform rate limit checks for a user on a specific route.
# :param user: The fully-fetched User object with .limits_overrides, etc.
# :param route: The route/path being accessed.
# :raises ValueError: if any limit is exceeded.
# """
# user_id = user.id
# now = datetime.now(timezone.utc)
# one_min_ago = now - timedelta(minutes=1)
# # 1) Compute the final (effective) limits for this user & route
# limits = self.determine_effective_limits(user, route)
# # 2) Check each of them in turn, if they exist
# # ------------------------------------------------------------
# # Global per-minute limit
# # ------------------------------------------------------------
# if limits.global_per_min is not None:
# user_req_count = await self._count_requests(
# user_id, None, one_min_ago
# )
# if user_req_count > limits.global_per_min:
# logger.warning(
# f"Global per-minute limit exceeded for "
# f"user_id={user_id}, route={route}"
# )
# raise ValueError("Global per-minute rate limit exceeded")
# # ------------------------------------------------------------
# # Route-specific per-minute limit
# # ------------------------------------------------------------
# if limits.route_per_min is not None:
# route_req_count = await self._count_requests(
# user_id, route, one_min_ago
# )
# if route_req_count > limits.route_per_min:
# logger.warning(
# f"Per-route per-minute limit exceeded for "
# f"user_id={user_id}, route={route}"
# )
# raise ValueError("Per-route per-minute rate limit exceeded")
# # ------------------------------------------------------------
# # Monthly limit
# # ------------------------------------------------------------
# if limits.monthly_limit is not None:
# monthly_count = await self._count_monthly_requests(user_id)
# if monthly_count > limits.monthly_limit:
# logger.warning(
# f"Monthly limit exceeded for user_id={user_id}, "
# f"route={route}"
# )
# raise ValueError("Monthly rate limit exceeded")
# async def log_request(self, user_id: UUID, route: str):
# """
# Log a successful request to the request_log table.
# """
# query = f"""
# INSERT INTO {self._get_table_name(PostgresLimitsHandler.TABLE_NAME)}
# (time, user_id, route)
# VALUES (CURRENT_TIMESTAMP AT TIME ZONE 'UTC', $1, $2)
# """
# await self.connection_manager.execute_query(query, [user_id, route])
|