Files
microfish/backend/app/services/rate_limiter.py
Kunthawat Greethong 8b84378fe1 feat: SaaS foundation for CrowdSight
Elevate MiroFish/CrowdSight from single-container dev to a SaaS foundation:

- Local memory backend (Zep-compatible): memory services/models, local graph
  builder + updater, AgentActivity seam, import-boundary isolation; Zep stays
  default, local is opt-in behind MEMORY_BACKEND. Semantic parity not yet proven.
- Durable product persistence: projects/simulations/reports schema (migration
  0007) + tenant/owner-scoped ProductRepository + dual-write + scoped_project
  read-first + ArtifactStore abstraction; durable JobQueue + worker.py.
- SaaS hardening: durable RateLimiter (wired to login), UsageService (LLM
  accounting), redacted AuditService, idempotency, CORS allowlist, safe API
  errors, single-use PasswordResetService + endpoints (covers invite-pending).
- Exactly 3 roles (super_admin/admin/user) with tenant authz policy.
- Admin UI: GET/POST/PATCH /api/admin/users + GET/PUT /api/admin/settings
  (super-admin only, encrypted/masked); AdminView.vue + SettingsView.vue with
  admin/super-admin route guards, th/en i18n.
- Production deploy topology: multi-stage Dockerfile (frontend build + gunicorn
  wsgi + nginx SPA-proxy + supervisord worker), backend/wsgi.py, gunicorn dep.

Backend 197 passed; frontend 10 tests + build green. ruff unavailable (gap).
No commit of credentials; secrets handled via env/.env.example.
Deferred: Zep semantic A/B parity, object storage cutover, mobile QA, EasyPanel
container build of deploy topology.
2026-08-31 13:05:21 +07:00

50 lines
1.7 KiB
Python

"""Durable rate limiting (sliding-window counter) over the rate_limit_events table.
A durable counter table means limits survive worker restarts and multi-instance
deploys. Keys are typically ``<operation>:<email-or-ip>``. No secrets are stored.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from sqlalchemy.orm import Session
from ..models.rate_limit import RateLimitEvent
def _utc_now() -> datetime:
return datetime.now(timezone.utc)
class RateLimiter:
"""Flush-only rate limiter; caller owns the transaction boundary."""
def __init__(self, session: Session, *, window: timedelta | None = None, limit: int | None = None):
self.session = session
self.window = window or timedelta(minutes=15)
self.limit = limit or 60
def check_and_record(self, operation: str, *, key: str, organization_id: str | None = None) -> bool:
"""Record a hit if under the limit; return False when over the limit."""
cutoff = _utc_now() - self.window
count = self.session.query(RateLimitEvent).filter(
RateLimitEvent.operation == operation,
RateLimitEvent.key == key,
RateLimitEvent.created_at >= cutoff,
).count()
if count >= self.limit:
return False
self.session.add(
RateLimitEvent(
operation=operation,
key=key,
organization_id=organization_id,
)
)
# Rate-limit events are append-only side effects that must survive even
# if the surrounding request transaction is later rolled back, so commit
# them immediately.
self.session.commit()
return True