An open source, non-profit web search engine
Merge branch 'main' into combined-search-api-billing
Claude8bd9c9c94783
diff --cc mwmbl/quota.pyindex aad4fe0,facf781..81d655d--- a/mwmbl/quota.py+++ b/mwmbl/quota.py@@@ -153,40 -144,19 +153,53 @@@ def decrement_monthly_combined_search(upass+def get_monthly_combined_search_api_count(user_id: int) -> int:+ """Return the current monthly keyed (billed) combined-search count for a user (0 if not set)."""+ return cache.get(_combined_search_api_monthly_key(user_id), default=0)+++# Count one request only if the counter is below the limit, in a single Redis step. An+# increment-then-refund would leave the counter one over the limit between the two steps,+# and an hourly sync reading it then would store, and later bill, a request that was refused.+_INCREMENT_IF_BELOW_LIMIT = """+local count = tonumber(redis.call('GET', KEYS[1]) or '0')+if count >= tonumber(ARGV[1]) then+ return -1+end+count = redis.call('INCR', KEYS[1])+if count == 1 then+ redis.call('EXPIRE', KEYS[1], ARGV[2])+end+return count+"""+++def increment_monthly_combined_search_api_if_below(user_id: int, limit: int) -> int | None:+ """Count one keyed (billed) combined-search request if the user is below `limit`.++ Returns the new count, or None when the user is already at the limit, in which case+ nothing is counted: the counter never goes over the limit, even for an instant.+ Requires the django-redis cache backend.+ """+ key = cache.make_key(_combined_search_api_monthly_key(user_id))+ conn = get_redis_connection("default")+ count = conn.eval(_INCREMENT_IF_BELOW_LIMIT, 1, key, limit, MONTHLY_TTL)+ return None if count == -1 else count+++ def get_all_monthly_combined_search_counts() -> dict[int, int]:+ """This month's combined-search count for every user who has used it, by user id.++ Scans the keyspace via django-redis, so it is for admin pages and background jobs, not+ the search path.+ """+ now = datetime.now(timezone.utc)+ keys = list(cache.iter_keys(f"combined_search:monthly:*:{now.year}:{now.month:02d}"))+ counts_by_key = cache.get_many(keys)+ # Keys are combined_search:monthly:<user_id>:<year>:<month>.+ return {int(key.split(":")[2]): count for key, count in counts_by_key.items()}++# ---------------------------------------------------------------------------# Key scanning (used by background jobs only — requires django-redis)# ---------------------------------------------------------------------------