runapi 0.2.0__tar.gz → 0.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {runapi-0.2.0 → runapi-0.3.5}/.gitignore +3 -0
  2. {runapi-0.2.0 → runapi-0.3.5}/PKG-INFO +21 -1
  3. runapi-0.3.5/examples/basic-crud/README.md +36 -0
  4. runapi-0.3.5/examples/postgres-todo/README.md +44 -0
  5. {runapi-0.2.0 → runapi-0.3.5}/pyproject.toml +25 -1
  6. {runapi-0.2.0 → runapi-0.3.5}/runapi/__init__.py +25 -1
  7. {runapi-0.2.0 → runapi-0.3.5}/runapi/_version.py +2 -2
  8. {runapi-0.2.0 → runapi-0.3.5}/runapi/auth.py +10 -29
  9. runapi-0.3.5/runapi/backends.py +156 -0
  10. runapi-0.3.5/runapi/cli/__init__.py +53 -0
  11. runapi-0.3.5/runapi/cli/_app.py +7 -0
  12. runapi-0.3.5/runapi/cli/_templates.py +28 -0
  13. runapi-0.3.5/runapi/cli/commands/__init__.py +1 -0
  14. runapi-0.3.5/runapi/cli/commands/db.py +102 -0
  15. runapi-0.3.5/runapi/cli/commands/generate.py +153 -0
  16. runapi-0.3.5/runapi/cli/commands/inspect.py +223 -0
  17. runapi-0.3.5/runapi/cli/commands/project.py +127 -0
  18. runapi-0.3.5/runapi/cli/commands/server.py +186 -0
  19. runapi-0.3.5/runapi/cli/templates/db/alembic.ini.tmpl +5 -0
  20. runapi-0.3.5/runapi/cli/templates/db/db.py.tmpl +5 -0
  21. runapi-0.3.5/runapi/cli/templates/db/docker-compose.yml.tmpl +19 -0
  22. runapi-0.3.5/runapi/cli/templates/db/env.py.tmpl +61 -0
  23. runapi-0.3.5/runapi/cli/templates/db/main.py.tmpl +15 -0
  24. runapi-0.3.5/runapi/cli/templates/db/models_init.py.tmpl +3 -0
  25. runapi-0.3.5/runapi/cli/templates/db/models_item.py.tmpl +11 -0
  26. runapi-0.3.5/runapi/cli/templates/db/route_items.py.tmpl +25 -0
  27. runapi-0.3.5/runapi/cli/templates/db/script.py.mako.tmpl +24 -0
  28. runapi-0.3.5/runapi/cli/templates/generate/crud_index.py.tmpl +19 -0
  29. runapi-0.3.5/runapi/cli/templates/generate/crud_item.py.tmpl +20 -0
  30. runapi-0.3.5/runapi/cli/templates/generate/crud_service_footer.py.tmpl +14 -0
  31. runapi-0.3.5/runapi/cli/templates/generate/main.py.tmpl +23 -0
  32. runapi-0.3.5/runapi/cli/templates/generate/middleware.py.tmpl +31 -0
  33. runapi-0.3.5/runapi/cli/templates/generate/repository.py.tmpl +72 -0
  34. runapi-0.3.5/runapi/cli/templates/generate/route.py.tmpl +38 -0
  35. runapi-0.3.5/runapi/cli/templates/generate/schema.py.tmpl +49 -0
  36. runapi-0.3.5/runapi/cli/templates/generate/service.py.tmpl +101 -0
  37. runapi-0.3.5/runapi/cli/templates/project/Dockerfile.tmpl +16 -0
  38. runapi-0.3.5/runapi/cli/templates/project/README.md.tmpl +56 -0
  39. runapi-0.3.5/runapi/cli/templates/project/dockerignore.tmpl +5 -0
  40. runapi-0.3.5/runapi/cli/templates/project/env.tmpl +23 -0
  41. runapi-0.3.5/runapi/cli/templates/project/gitignore.tmpl +30 -0
  42. runapi-0.3.5/runapi/cli/templates/project/main.py.tmpl +17 -0
  43. runapi-0.3.5/runapi/cli/templates/project/route_hello.py.tmpl +12 -0
  44. runapi-0.3.5/runapi/cli/templates/project/route_index.py.tmpl +14 -0
  45. runapi-0.3.5/runapi/config.py +214 -0
  46. {runapi-0.2.0 → runapi-0.3.5}/runapi/core.py +115 -115
  47. runapi-0.3.5/runapi/database.py +157 -0
  48. {runapi-0.2.0 → runapi-0.3.5}/runapi/errors.py +50 -19
  49. runapi-0.3.5/runapi/lifecycle.py +77 -0
  50. runapi-0.3.5/runapi/logging.py +98 -0
  51. {runapi-0.2.0 → runapi-0.3.5}/runapi/middleware.py +49 -54
  52. {runapi-0.2.0 → runapi-0.3.5}/runapi/repository.py +5 -4
  53. runapi-0.3.5/runapi/routing.py +145 -0
  54. {runapi-0.2.0 → runapi-0.3.5}/runapi/schemas.py +7 -5
  55. {runapi-0.2.0 → runapi-0.3.5}/runapi/service.py +3 -3
  56. runapi-0.2.0/runapi/cli.py +0 -1226
  57. runapi-0.2.0/runapi/config.py +0 -143
  58. {runapi-0.2.0 → runapi-0.3.5}/LICENSE +0 -0
  59. {runapi-0.2.0 → runapi-0.3.5}/README.md +0 -0
  60. {runapi-0.2.0 → runapi-0.3.5}/examples/basic/README.md +0 -0
  61. {runapi-0.2.0 → runapi-0.3.5}/release-notes/README.md +0 -0
  62. {runapi-0.2.0 → runapi-0.3.5}/runapi/py.typed +0 -0
@@ -107,3 +107,6 @@ credentials.json
107
107
 
108
108
  # Generated by hatch-vcs at build time
109
109
  runapi/_version.py
110
+
111
+ # MkDocs build output
112
+ site/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: runapi
3
- Version: 0.2.0
3
+ Version: 0.3.5
4
4
  Summary: A Next.js-inspired file-based routing framework built on FastAPI
5
5
  Project-URL: Homepage, https://github.com/Amanbig/runapi
6
6
  Project-URL: Repository, https://github.com/Amanbig/runapi
@@ -52,6 +52,7 @@ Requires-Dist: aiofiles>=23.2.1
52
52
  Requires-Dist: bcrypt>=4.0.1
53
53
  Requires-Dist: fastapi>=0.115.6
54
54
  Requires-Dist: psutil>=6.0.0
55
+ Requires-Dist: pydantic-settings>=2.2
55
56
  Requires-Dist: pyjwt>=2.10.1
56
57
  Requires-Dist: python-multipart>=0.0.18
57
58
  Requires-Dist: rich>=13.7.0
@@ -72,11 +73,30 @@ Requires-Dist: mkdocs>=1.6; extra == 'docs'
72
73
  Provides-Extra: lint
73
74
  Requires-Dist: mypy>=1.0.0; extra == 'lint'
74
75
  Requires-Dist: ruff>=0.1.0; extra == 'lint'
76
+ Provides-Extra: mysql
77
+ Requires-Dist: aiomysql>=0.2; extra == 'mysql'
78
+ Requires-Dist: alembic>=1.13; extra == 'mysql'
79
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'mysql'
80
+ Provides-Extra: postgres
81
+ Requires-Dist: alembic>=1.13; extra == 'postgres'
82
+ Requires-Dist: asyncpg>=0.29; extra == 'postgres'
83
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'postgres'
84
+ Provides-Extra: redis
85
+ Requires-Dist: redis>=5.0; extra == 'redis'
86
+ Provides-Extra: sqlite
87
+ Requires-Dist: aiosqlite>=0.19; extra == 'sqlite'
88
+ Requires-Dist: alembic>=1.13; extra == 'sqlite'
89
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'sqlite'
75
90
  Provides-Extra: test
91
+ Requires-Dist: aiosqlite>=0.19; extra == 'test'
92
+ Requires-Dist: alembic>=1.13; extra == 'test'
93
+ Requires-Dist: fakeredis>=2.20; extra == 'test'
76
94
  Requires-Dist: httpx>=0.24.0; extra == 'test'
77
95
  Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
78
96
  Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
79
97
  Requires-Dist: pytest>=7.0.0; extra == 'test'
98
+ Requires-Dist: redis>=5.0; extra == 'test'
99
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'test'
80
100
  Description-Content-Type: text/markdown
81
101
 
82
102
  # Runapi 🚀
@@ -0,0 +1,36 @@
1
+ # CRUD example: a todo API
2
+
3
+ A small REST API showing file-based routing, validation, a service layer and a repository.
4
+
5
+ ```bash
6
+ pip install runapi
7
+ cp .env.example .env # then set SECRET_KEY
8
+ runapi dev
9
+ ```
10
+
11
+ | Request | File |
12
+ |---------|------|
13
+ | `GET /todos`, `POST /todos` | `routes/todos/index.py` |
14
+ | `GET /todos/{id}`, `PUT /todos/{id}`, `DELETE /todos/{id}` | `routes/todos/[id].py` |
15
+
16
+ ```bash
17
+ curl -X POST localhost:8000/todos -H 'content-type: application/json' -d '{"title": "write docs"}'
18
+ curl localhost:8000/todos
19
+ curl -X PUT localhost:8000/todos/1 -H 'content-type: application/json' -d '{"done": true}'
20
+ curl 'localhost:8000/todos?done=true'
21
+ curl -X DELETE localhost:8000/todos/1
22
+ ```
23
+
24
+ Interactive docs: http://localhost:8000/docs
25
+
26
+ ## How it fits together
27
+
28
+ ```
29
+ route (HTTP) -> service (rules) -> repository (storage)
30
+ ```
31
+
32
+ Data is stored in memory and resets on restart. To keep data, replace
33
+ `InMemoryRepository` with a database repository: see the
34
+ [database docs](https://github.com/Amanbig/runapi/blob/main/docs/database.md).
35
+
36
+ Want the same thing generated for your own resource? Run `runapi generate crud <name>`.
@@ -0,0 +1,44 @@
1
+ # PostgreSQL example: todo API with SQLAlchemy and Alembic
2
+
3
+ An async CRUD API backed by PostgreSQL, with schema migrations. The same code runs on SQLite:
4
+ only `DATABASE_URL` changes.
5
+
6
+ ```bash
7
+ pip install -r requirements.txt # runapi[postgres]
8
+ cp .env.example .env # set SECRET_KEY
9
+ docker compose up -d db # PostgreSQL 16 on localhost:5432
10
+ runapi db upgrade # apply migrations/ (creates the todos table)
11
+ runapi dev
12
+ ```
13
+
14
+ No Docker? Use SQLite instead: `pip install "runapi[sqlite]"` and set
15
+ `DATABASE_URL=sqlite+aiosqlite:///./app.db` in `.env`.
16
+
17
+ ```bash
18
+ curl -X POST localhost:8000/todos -H 'content-type: application/json' -d '{"title": "ship it"}'
19
+ curl localhost:8000/todos
20
+ curl -X PUT localhost:8000/todos/1 -H 'content-type: application/json' -d '{"done": true}'
21
+ curl localhost:8000/ready # {"status":"ready","checks":{"database":true}}
22
+ ```
23
+
24
+ ## How it fits together
25
+
26
+ | File | Role |
27
+ |------|------|
28
+ | `db.py` | `database = Database()` reads `DATABASE_URL` |
29
+ | `main.py` | `runapi_app.use_database(database)`: connect on startup, dispose on shutdown, adds a `/ready` check |
30
+ | `models/todo.py` | SQLAlchemy model on `runapi.Base` |
31
+ | `routes/todos/*.py` | handlers get a session with `Depends(database.get_session)`; it commits when the request finishes and rolls back on errors |
32
+ | `migrations/` | Alembic (async). `env.py` reads `DATABASE_URL` and `Base.metadata` |
33
+
34
+ ## Changing the model
35
+
36
+ ```bash
37
+ # edit models/todo.py, then:
38
+ runapi db migrate -m "add due date" # autogenerate a migration, review it!
39
+ runapi db upgrade
40
+ runapi db downgrade # undo one step
41
+ ```
42
+
43
+ Autogenerated migrations should always be reviewed. Generate them against the database you deploy
44
+ to (PostgreSQL), since SQLite renders some defaults differently.
@@ -12,6 +12,7 @@ dependencies = [
12
12
  "typer>=0.12.0",
13
13
  "rich>=13.7.0",
14
14
  "bcrypt>=4.0.1",
15
+ "pydantic-settings>=2.2",
15
16
  "PyJWT>=2.10.1",
16
17
  "python-multipart>=0.0.18",
17
18
  "aiofiles>=23.2.1",
@@ -58,11 +59,29 @@ Issues = "https://github.com/Amanbig/runapi/issues"
58
59
  Changelog = "https://github.com/Amanbig/runapi/tree/main/release-notes"
59
60
 
60
61
  [project.optional-dependencies]
62
+ redis = [
63
+ "redis>=5.0",
64
+ ]
61
65
  db = [
62
66
  "sqlalchemy[asyncio]>=2.0",
63
67
  "alembic>=1.13",
64
68
  "aiosqlite>=0.19",
65
69
  ]
70
+ sqlite = [
71
+ "sqlalchemy[asyncio]>=2.0",
72
+ "alembic>=1.13",
73
+ "aiosqlite>=0.19",
74
+ ]
75
+ postgres = [
76
+ "sqlalchemy[asyncio]>=2.0",
77
+ "alembic>=1.13",
78
+ "asyncpg>=0.29",
79
+ ]
80
+ mysql = [
81
+ "sqlalchemy[asyncio]>=2.0",
82
+ "alembic>=1.13",
83
+ "aiomysql>=0.2",
84
+ ]
66
85
  dev = [
67
86
  "pytest>=7.0.0",
68
87
  "httpx>=0.24.0",
@@ -74,6 +93,11 @@ test = [
74
93
  "httpx>=0.24.0",
75
94
  "pytest-asyncio>=0.21.0",
76
95
  "pytest-cov>=4.0.0",
96
+ "redis>=5.0",
97
+ "fakeredis>=2.20",
98
+ "sqlalchemy[asyncio]>=2.0",
99
+ "alembic>=1.13",
100
+ "aiosqlite>=0.19",
77
101
  ]
78
102
  docs = [
79
103
  "mkdocs>=1.6",
@@ -125,7 +149,7 @@ known-first-party = ["runapi"]
125
149
 
126
150
  [tool.mypy]
127
151
  python_version = "3.10"
128
- warn_return_any = true
152
+ warn_return_any = false
129
153
  warn_unused_ignores = true
130
154
  disallow_untyped_defs = false
131
155
  ignore_missing_imports = true
@@ -40,13 +40,24 @@ from .auth import (
40
40
  )
41
41
 
42
42
  # Configuration
43
+ from .backends import (
44
+ MemoryRateLimitBackend,
45
+ RateLimitBackend,
46
+ RedisRateLimitBackend,
47
+ RedisTokenBlacklist,
48
+ TokenBlacklist,
49
+ )
43
50
  from .config import RunApiConfig, get_config, load_config
44
51
  from .core import RunApiApp, create_app, create_runapi_app
45
52
 
53
+ # Conditional SQLAlchemy import
54
+ from .database import DATABASE_AVAILABLE, Base, Database, check_driver
55
+
46
56
  # Error handling
47
57
  from .errors import (
48
58
  AuthenticationError,
49
59
  AuthorizationError,
60
+ ConfigurationError,
50
61
  ConflictError,
51
62
  DatabaseError,
52
63
  ErrorHandler,
@@ -54,6 +65,7 @@ from .errors import (
54
65
  ExternalServiceError,
55
66
  NotFoundError,
56
67
  RateLimitError,
68
+ RouteLoadError,
57
69
  RunApiException,
58
70
  ServerError,
59
71
  ValidationError,
@@ -76,6 +88,7 @@ from .errors import (
76
88
  )
77
89
 
78
90
  # Middleware
91
+ from .logging import get_request_id
79
92
  from .middleware import (
80
93
  AuthMiddleware,
81
94
  CompressionMiddleware,
@@ -122,7 +135,6 @@ from .schemas import (
122
135
  ErrorResponse as SchemaErrorResponse,
123
136
  )
124
137
 
125
- # Conditional SQLAlchemy import
126
138
  if SQLALCHEMY_AVAILABLE:
127
139
  from .repository import SQLAlchemyRepository
128
140
  else:
@@ -157,6 +169,8 @@ __all__ = [
157
169
  "load_config",
158
170
  # Error handling
159
171
  "RunApiException",
172
+ "ConfigurationError",
173
+ "RouteLoadError",
160
174
  "ValidationError",
161
175
  "AuthenticationError",
162
176
  "AuthorizationError",
@@ -195,6 +209,12 @@ __all__ = [
195
209
  "create_access_token",
196
210
  "create_refresh_token",
197
211
  "verify_token",
212
+ "RateLimitBackend",
213
+ "MemoryRateLimitBackend",
214
+ "RedisRateLimitBackend",
215
+ "TokenBlacklist",
216
+ "RedisTokenBlacklist",
217
+ "get_request_id",
198
218
  "revoke_token",
199
219
  "rotate_refresh_token",
200
220
  "get_current_user",
@@ -239,6 +259,10 @@ __all__ = [
239
259
  "InMemoryRepository",
240
260
  "TypedInMemoryRepository",
241
261
  "SQLAlchemyRepository",
262
+ "Database",
263
+ "Base",
264
+ "check_driver",
265
+ "DATABASE_AVAILABLE",
242
266
  "RepositoryFactory",
243
267
  "create_repository",
244
268
  "SQLALCHEMY_AVAILABLE",
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.2.0'
22
- __version_tuple__ = version_tuple = (0, 2, 0)
21
+ __version__ = version = '0.3.5'
22
+ __version_tuple__ = version_tuple = (0, 3, 5)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -8,12 +8,13 @@ from typing import Any, Dict, Optional
8
8
  try:
9
9
  import bcrypt
10
10
  except ImportError: # pragma: no cover
11
- bcrypt = None
11
+ bcrypt = None # type: ignore[assignment]
12
12
 
13
13
  import jwt
14
14
  from fastapi import Depends, HTTPException
15
15
  from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
16
16
 
17
+ from .backends import RedisTokenBlacklist, TokenBlacklist, uses_redis
17
18
  from .config import get_config
18
19
 
19
20
 
@@ -23,7 +24,7 @@ class PasswordManager:
23
24
  # bcrypt only considers the first 72 bytes of a password
24
25
  _MAX_BYTES = 72
25
26
 
26
- def __init__(self, schemes: list = None, rounds: int = 12):
27
+ def __init__(self, schemes: Optional[list] = None, rounds: int = 12):
27
28
  if bcrypt is None:
28
29
  raise ImportError(
29
30
  "bcrypt is required for password hashing. Install with: pip install bcrypt"
@@ -55,39 +56,17 @@ class PasswordManager:
55
56
  _RESERVED_CLAIMS = ("exp", "iat", "type", "jti")
56
57
 
57
58
 
58
- class TokenBlacklist:
59
- """In-memory store of revoked token ids (``jti``).
60
-
61
- Subclass and override ``add``/``is_revoked`` to back it with Redis or a database
62
- when running multiple workers.
63
- """
64
-
65
- def __init__(self):
66
- self._revoked: Dict[str, float] = {}
67
-
68
- def add(self, jti: str, expires_at: float) -> None:
69
- self._purge()
70
- self._revoked[jti] = expires_at
71
-
72
- def is_revoked(self, jti: str) -> bool:
73
- return jti in self._revoked
74
-
75
- def _purge(self) -> None:
76
- now = time.time()
77
- for key in [k for k, exp in self._revoked.items() if exp < now]:
78
- del self._revoked[key]
79
-
80
-
81
59
  class JWTManager:
82
60
  """JWT token management utilities using PyJWT."""
83
61
 
84
- def __init__(self, secret_key: str = None, algorithm: str = "HS256"):
62
+ def __init__(self, secret_key: Optional[str] = None, algorithm: str = "HS256"):
85
63
  self.config = get_config()
86
64
  self.secret_key = secret_key or self.config.secret_key
87
65
  self.algorithm = algorithm or self.config.jwt_algorithm
88
66
  self.access_token_expire = self.config.jwt_expiry
89
67
  self.refresh_token_expire = self.config.jwt_refresh_expiry
90
- self.blacklist = TokenBlacklist()
68
+ redis_url = uses_redis(self.config)
69
+ self.blacklist = RedisTokenBlacklist.from_url(redis_url) if redis_url else TokenBlacklist()
91
70
 
92
71
  if self.secret_key == "dev-secret-key-change-in-production":
93
72
  raise ValueError("Change the SECRET_KEY in production!")
@@ -205,7 +184,7 @@ class APIKeyManager:
205
184
  class AuthDependencies:
206
185
  """FastAPI dependency classes for authentication."""
207
186
 
208
- def __init__(self, jwt_manager: JWTManager = None):
187
+ def __init__(self, jwt_manager: Optional[JWTManager] = None):
209
188
  self.jwt_manager = jwt_manager or JWTManager()
210
189
  self.bearer_scheme = HTTPBearer()
211
190
 
@@ -380,7 +359,9 @@ def generate_password(length: int = 12) -> str:
380
359
  class TokenResponse:
381
360
  """Standard token response format."""
382
361
 
383
- def __init__(self, access_token: str, refresh_token: str = None, token_type: str = "bearer"):
362
+ def __init__(
363
+ self, access_token: str, refresh_token: Optional[str] = None, token_type: str = "bearer"
364
+ ):
384
365
  self.access_token = access_token
385
366
  self.refresh_token = refresh_token
386
367
  self.token_type = token_type
@@ -0,0 +1,156 @@
1
+ """Pluggable state backends (in-memory or Redis) for rate limiting and token revocation.
2
+
3
+ In-memory backends are per-process: with several workers each one keeps its own
4
+ counters. Set ``CACHE_BACKEND=redis`` and ``REDIS_URL`` (install ``runapi[redis]``)
5
+ to share state across workers and hosts.
6
+ """
7
+
8
+ import asyncio
9
+ import logging
10
+ import time
11
+ from typing import Any, Dict, List, Optional, Tuple
12
+
13
+ logger = logging.getLogger("runapi")
14
+
15
+
16
+ def _require_redis():
17
+ try:
18
+ import redis # noqa: F401
19
+ except ImportError as exc:
20
+ raise ImportError(
21
+ "The Redis backend needs the 'redis' package. Install with: pip install runapi[redis]"
22
+ ) from exc
23
+
24
+
25
+ # --------------------------------------------------------------------------- #
26
+ # Rate limiting
27
+ # --------------------------------------------------------------------------- #
28
+ class RateLimitBackend:
29
+ """Counts hits per key inside a fixed window."""
30
+
31
+ async def hit(self, key: str, period: int) -> Tuple[int, float]:
32
+ """Record a hit. Returns ``(count_in_window, seconds_until_window_resets)``."""
33
+ raise NotImplementedError
34
+
35
+
36
+ class MemoryRateLimitBackend(RateLimitBackend):
37
+ """Fixed-window counter held in process memory."""
38
+
39
+ def __init__(self):
40
+ self._windows: Dict[str, List[float]] = {} # key -> [count, window_start]
41
+ self._lock = asyncio.Lock()
42
+ self._last_purge = time.time()
43
+
44
+ async def hit(self, key: str, period: int) -> Tuple[int, float]:
45
+ now = time.time()
46
+ async with self._lock:
47
+ if now - self._last_purge > period:
48
+ self._purge(now, period)
49
+ window = self._windows.get(key)
50
+ if window is None or now > window[1] + period:
51
+ window = self._windows[key] = [0, now]
52
+ window[0] += 1
53
+ return int(window[0]), max(window[1] + period - now, 0.0)
54
+
55
+ def _purge(self, now: float, period: int) -> None:
56
+ """Drop expired windows so memory does not grow with every client seen."""
57
+ self._last_purge = now
58
+ for key in [k for k, (_, start) in self._windows.items() if now > start + period]:
59
+ del self._windows[key]
60
+
61
+
62
+ class RedisRateLimitBackend(RateLimitBackend):
63
+ """Fixed-window counter stored in Redis (shared across workers).
64
+
65
+ Fails open: if Redis is unreachable the request is allowed and an error is logged.
66
+ """
67
+
68
+ def __init__(self, client: Any, prefix: str = "runapi:rl:"):
69
+ self.client = client
70
+ self.prefix = prefix
71
+
72
+ @classmethod
73
+ def from_url(cls, url: str, **kwargs: Any) -> "RedisRateLimitBackend":
74
+ _require_redis()
75
+ import redis.asyncio as aioredis
76
+
77
+ return cls(aioredis.from_url(url), **kwargs)
78
+
79
+ async def hit(self, key: str, period: int) -> Tuple[int, float]:
80
+ redis_key = f"{self.prefix}{key}"
81
+ try:
82
+ count = await self.client.incr(redis_key)
83
+ if count == 1:
84
+ await self.client.expire(redis_key, period)
85
+ ttl = await self.client.ttl(redis_key)
86
+ if ttl is None or ttl < 0: # key lost its expiry; restore it
87
+ await self.client.expire(redis_key, period)
88
+ ttl = period
89
+ return int(count), float(ttl)
90
+ except Exception:
91
+ logger.exception("Redis rate limit backend unavailable; allowing request")
92
+ return 0, float(period)
93
+
94
+
95
+ # --------------------------------------------------------------------------- #
96
+ # Token revocation
97
+ # --------------------------------------------------------------------------- #
98
+ class TokenBlacklist:
99
+ """In-memory store of revoked token ids (``jti``).
100
+
101
+ Subclass and override ``add``/``is_revoked`` for other storage.
102
+ """
103
+
104
+ def __init__(self):
105
+ self._revoked: Dict[str, float] = {}
106
+
107
+ def add(self, jti: str, expires_at: float) -> None:
108
+ self._purge()
109
+ self._revoked[jti] = expires_at
110
+
111
+ def is_revoked(self, jti: str) -> bool:
112
+ return jti in self._revoked
113
+
114
+ def _purge(self) -> None:
115
+ now = time.time()
116
+ for key in [k for k, exp in self._revoked.items() if exp < now]:
117
+ del self._revoked[key]
118
+
119
+
120
+ class RedisTokenBlacklist(TokenBlacklist):
121
+ """Revoked token ids stored in Redis with a TTL equal to the token's remaining life.
122
+
123
+ Uses a synchronous client because token verification is synchronous. If Redis is
124
+ unreachable, revocation checks fail closed (the token is treated as revoked).
125
+ """
126
+
127
+ def __init__(self, client: Any, prefix: str = "runapi:revoked:"):
128
+ self.client = client
129
+ self.prefix = prefix
130
+
131
+ @classmethod
132
+ def from_url(cls, url: str, **kwargs: Any) -> "RedisTokenBlacklist":
133
+ _require_redis()
134
+ import redis
135
+
136
+ return cls(redis.Redis.from_url(url), **kwargs)
137
+
138
+ def add(self, jti: str, expires_at: float) -> None:
139
+ ttl = max(int(expires_at - time.time()) + 1, 1)
140
+ self.client.setex(f"{self.prefix}{jti}", ttl, "1")
141
+
142
+ def is_revoked(self, jti: str) -> bool:
143
+ try:
144
+ return bool(self.client.exists(f"{self.prefix}{jti}"))
145
+ except Exception:
146
+ logger.exception("Redis token blacklist unavailable; rejecting token")
147
+ return True
148
+
149
+
150
+ def uses_redis(config: Any) -> Optional[str]:
151
+ """Return the Redis URL when the config selects the Redis backend, else None."""
152
+ if config.cache_backend == "redis":
153
+ if not config.redis_url:
154
+ raise ValueError("CACHE_BACKEND=redis requires REDIS_URL")
155
+ return config.redis_url
156
+ return None
@@ -0,0 +1,53 @@
1
+ """The ``runapi`` command-line interface.
2
+
3
+ Layout:
4
+ _app.py shared Typer ``app`` and ``console``
5
+ _templates.py renderer for the files the CLI generates
6
+ commands/ one module per group of commands (importing registers them)
7
+ templates/ the generated files themselves, as plain ``*.tmpl`` files
8
+ """
9
+
10
+ import typer
11
+
12
+ from .. import __version__
13
+ from . import commands # noqa: F401
14
+ from ._app import app, console
15
+ from .commands import db, generate, inspect, project, server # noqa: F401 (registers commands)
16
+
17
+
18
+ def _version_callback(value: bool):
19
+ if value:
20
+ typer.echo(f"runapi {__version__}")
21
+ raise typer.Exit()
22
+
23
+
24
+ @app.callback()
25
+ def _root(
26
+ version: bool = typer.Option(
27
+ False,
28
+ "--version",
29
+ "-V",
30
+ callback=_version_callback,
31
+ is_eager=True,
32
+ help="Show the runapi version and exit.",
33
+ ),
34
+ ):
35
+ """RunApi - Next.js-inspired Python Backend Framework."""
36
+
37
+
38
+ def main():
39
+ """Main entry point for CLI."""
40
+ from ..errors import ConfigurationError
41
+
42
+ try:
43
+ app()
44
+ except ConfigurationError as exc:
45
+ console.print(f"[red]❌ {exc}[/red]")
46
+ raise SystemExit(1) from None
47
+
48
+
49
+ __all__ = ["app", "console", "main"]
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
@@ -0,0 +1,7 @@
1
+ """The shared Typer app and console used by every command module."""
2
+
3
+ import typer
4
+ from rich.console import Console
5
+
6
+ app = typer.Typer(name="runapi", help="RunApi - Next.js-inspired Python Backend Framework")
7
+ console = Console()
@@ -0,0 +1,28 @@
1
+ """Tiny template renderer for the files the CLI generates.
2
+
3
+ Templates live in ``runapi/cli/templates`` as plain files so they can be read, diffed and
4
+ syntax-checked like any other code. Placeholders look like ``@@name@@``.
5
+ """
6
+
7
+ import re
8
+ from importlib import resources
9
+ from typing import Dict
10
+
11
+ _PLACEHOLDER = re.compile(r"@@(\w+)@@")
12
+
13
+
14
+ def render(template: str, **context: str) -> str:
15
+ """Render ``templates/<template>.tmpl`` replacing every ``@@key@@`` from ``context``."""
16
+ text = (resources.files("runapi.cli") / "templates" / f"{template}.tmpl").read_text(
17
+ encoding="utf-8"
18
+ )
19
+ missing = set(_PLACEHOLDER.findall(text)) - set(context)
20
+ if missing:
21
+ raise KeyError(f"Template {template!r} needs values for: {', '.join(sorted(missing))}")
22
+ values: Dict[str, str] = {key: str(value) for key, value in context.items()}
23
+ return _PLACEHOLDER.sub(lambda match: values[match.group(1)], text)
24
+
25
+
26
+ def class_name_for(name: str) -> str:
27
+ """Convert ``my-thing`` / ``my_thing`` to ``MyThing``."""
28
+ return "".join(word.capitalize() for word in name.replace("-", "_").split("_"))
@@ -0,0 +1 @@
1
+ """CLI command modules. Importing them registers their commands on the app."""