faststudio 0.1.0__py3-none-any.whl

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 (55) hide show
  1. faststudio/__init__.py +26 -0
  2. faststudio/_spa.py +163 -0
  3. faststudio/admin.py +227 -0
  4. faststudio/api/__init__.py +1 -0
  5. faststudio/api/_app.py +52 -0
  6. faststudio/api/_context.py +31 -0
  7. faststudio/api/_deps.py +31 -0
  8. faststudio/api/_paths.py +4 -0
  9. faststudio/api/_records.py +28 -0
  10. faststudio/api/_serialize.py +180 -0
  11. faststudio/api/auth.py +135 -0
  12. faststudio/api/errors.py +176 -0
  13. faststudio/api/models.py +95 -0
  14. faststudio/api/write.py +159 -0
  15. faststudio/auth/__init__.py +0 -0
  16. faststudio/auth/backend.py +70 -0
  17. faststudio/auth/cookies.py +70 -0
  18. faststudio/auth/csrf.py +47 -0
  19. faststudio/auth/model_backend.py +207 -0
  20. faststudio/auth/passwords.py +88 -0
  21. faststudio/auth/session.py +78 -0
  22. faststudio/config.py +123 -0
  23. faststudio/exceptions.py +15 -0
  24. faststudio/introspection/__init__.py +1 -0
  25. faststudio/introspection/_columns.py +102 -0
  26. faststudio/introspection/_fields.py +271 -0
  27. faststudio/introspection/_types.py +106 -0
  28. faststudio/model_admin.py +89 -0
  29. faststudio/py.typed +0 -0
  30. faststudio/query/__init__.py +5 -0
  31. faststudio/query/_list.py +108 -0
  32. faststudio/query/_params.py +150 -0
  33. faststudio/query/_write.py +44 -0
  34. faststudio/registry.py +579 -0
  35. faststudio/schemas/__init__.py +1 -0
  36. faststudio/schemas/_dynamic.py +209 -0
  37. faststudio/schemas/_meta.py +101 -0
  38. faststudio/schemas/contract.py +240 -0
  39. faststudio/schemas/contract.schema.json +674 -0
  40. faststudio/security/__init__.py +0 -0
  41. faststudio/security/csrf.py +104 -0
  42. faststudio/security/headers.py +60 -0
  43. faststudio/security/origin.py +86 -0
  44. faststudio/security/rate_limit.py +103 -0
  45. faststudio/security/secret.py +133 -0
  46. faststudio/static/assets/ListPage-_dV1b5eQ.js +1 -0
  47. faststudio/static/assets/RecordPages-DqN2e2EH.js +1 -0
  48. faststudio/static/assets/index-BQwHVfIa.js +66 -0
  49. faststudio/static/assets/index-Ch4jsWay.css +2 -0
  50. faststudio/static/assets/query-56TKFQKO.js +1 -0
  51. faststudio/static/index.html +14 -0
  52. faststudio-0.1.0.dist-info/METADATA +236 -0
  53. faststudio-0.1.0.dist-info/RECORD +55 -0
  54. faststudio-0.1.0.dist-info/WHEEL +4 -0
  55. faststudio-0.1.0.dist-info/licenses/LICENSE +21 -0
faststudio/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """FastStudio: a modern, beautiful admin studio for FastAPI."""
2
+
3
+ from faststudio.admin import Admin
4
+ from faststudio.auth.backend import AuthBackend, AuthenticatedUser
5
+ from faststudio.auth.model_backend import ModelUserBackend
6
+ from faststudio.auth.passwords import hash_password
7
+ from faststudio.exceptions import ConfigurationError, FastStudioError
8
+ from faststudio.model_admin import ModelAdmin
9
+ from faststudio.security.rate_limit import InMemoryRateLimiter, RateLimitDecision, RateLimiter
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "Admin",
15
+ "AuthBackend",
16
+ "AuthenticatedUser",
17
+ "ConfigurationError",
18
+ "FastStudioError",
19
+ "InMemoryRateLimiter",
20
+ "ModelAdmin",
21
+ "ModelUserBackend",
22
+ "RateLimitDecision",
23
+ "RateLimiter",
24
+ "__version__",
25
+ "hash_password",
26
+ ]
faststudio/_spa.py ADDED
@@ -0,0 +1,163 @@
1
+ """Serve the bundled SPA with runtime configuration (ADR-0005)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+
10
+ from fastapi import Request
11
+ from fastapi.responses import FileResponse, HTMLResponse, Response
12
+ from starlette.types import ASGIApp, Receive, Scope, Send
13
+
14
+ from faststudio.config import API_PREFIX, Settings
15
+ from faststudio.exceptions import FastStudioError
16
+ from faststudio.schemas.contract import SCHEMA_VERSION, SpaConfig
17
+
18
+ HEAD_MARKER = "<!-- faststudio:head -->"
19
+ #: Scope key holding the admin mount root as the browser sees it (proxy prefix + base_url).
20
+ ADMIN_ROOT_KEY = "faststudio.admin_root"
21
+ _TITLE = re.compile(r"<title>.*?</title>", re.DOTALL)
22
+ _JSON_ESCAPES = {"<": "\\u003c", ">": "\\u003e", "&": "\\u0026"}
23
+ # First path segments that never fall back to the SPA.
24
+ _RESERVED = frozenset({"api", "assets"})
25
+ _MAX_CACHED_ROOTS = 16
26
+ _PLACEHOLDER = """<!doctype html>
27
+ <html lang="en"><head><meta charset="utf-8"><title>FastStudio</title></head>
28
+ <body><h1>FastStudio UI is not built</h1>
29
+ <p>Run <code>pnpm -C frontend install &amp;&amp; pnpm -C frontend build</code>,
30
+ or install FastStudio from a wheel.</p></body></html>
31
+ """
32
+
33
+
34
+ class AdminRootRecorder:
35
+ """Record the admin mount root in the scope.
36
+
37
+ Nested mounts (e.g. `/assets`) replace `root_path`; handlers that need the
38
+ admin root (SPA fallback) read `ADMIN_ROOT_KEY` instead.
39
+ """
40
+
41
+ def __init__(self, app: ASGIApp) -> None:
42
+ """Wrap the admin application."""
43
+ self.app = app
44
+
45
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
46
+ """Store `root_path` (already proxy prefix + base_url at the mount)."""
47
+ if scope["type"] == "http":
48
+ scope[ADMIN_ROOT_KEY] = scope.get("root_path", "")
49
+ await self.app(scope, receive, send)
50
+
51
+
52
+ def config_json(config: SpaConfig) -> str:
53
+ """Serialize the config for embedding inside a `<script>` element.
54
+
55
+ `<`, `>` and `&` are escaped so no value can close the element; non-ASCII
56
+ (including U+2028/U+2029) is escaped by `ensure_ascii`.
57
+ """
58
+ text = json.dumps(config.model_dump(mode="json"), ensure_ascii=True, sort_keys=True)
59
+ for char, escape in _JSON_ESCAPES.items():
60
+ text = text.replace(char, escape)
61
+ return text
62
+
63
+
64
+ def validate_template(template: str) -> str:
65
+ """Return `template` if it has the head marker, else raise."""
66
+ if HEAD_MARKER not in template:
67
+ msg = f"FastStudio SPA index.html is missing the {HEAD_MARKER!r} marker."
68
+ raise FastStudioError(msg)
69
+ return template
70
+
71
+
72
+ def render_index(template: str, *, admin_root: str, title: str) -> str:
73
+ """Insert `<base href>`, the JSON config block and the page title.
74
+
75
+ `admin_root` is the mount path as the browser sees it, including any proxy
76
+ prefix (`root_path`), e.g. `/proxy/admin`.
77
+ """
78
+ config = SpaConfig(
79
+ schema_version=SCHEMA_VERSION,
80
+ base_url=admin_root,
81
+ api_url=f"{admin_root}{API_PREFIX}",
82
+ title=title,
83
+ )
84
+ head = (
85
+ f'<base href="{html.escape(admin_root + "/", quote=True)}">\n'
86
+ f' <script type="application/json" id="fs-config">{config_json(config)}</script>'
87
+ )
88
+ rendered = validate_template(template).replace(HEAD_MARKER, head, 1)
89
+ escaped_title = f"<title>{html.escape(title, quote=True)}</title>"
90
+ return _TITLE.sub(lambda _: escaped_title, rendered, count=1)
91
+
92
+
93
+ class SpaSite:
94
+ """The SPA's static directory, its index template and top-level files."""
95
+
96
+ def __init__(self, static_dir: Path, settings: Settings) -> None:
97
+ """Load the index template and an allowlist of top-level files once.
98
+
99
+ Top-level files are served only by exact name from this allowlist, so
100
+ requests never touch the filesystem (no case-folding aliases such as
101
+ `INDEX.HTML`, no NUL/long-name errors, no symlinks or dotfiles).
102
+ """
103
+ self.settings = settings
104
+ index = static_dir / "index.html"
105
+ self.template = (
106
+ validate_template(index.read_text(encoding="utf-8")) if index.is_file() else None
107
+ )
108
+ self.root_files = _top_level_files(static_dir)
109
+ self._rendered: dict[str, str] = {}
110
+
111
+ @staticmethod
112
+ def admin_root(request: Request) -> str:
113
+ """Mount path as seen by the browser (proxy prefix + base_url)."""
114
+ root: str = request.scope.get(ADMIN_ROOT_KEY, request.scope.get("root_path", ""))
115
+ return root
116
+
117
+ def route_path(self, request: Request) -> str:
118
+ """Path relative to the admin mount, without the leading slash."""
119
+ path: str = request.scope["path"]
120
+ root = self.admin_root(request)
121
+ if root and path.startswith(root):
122
+ path = path[len(root) :]
123
+ return path.lstrip("/")
124
+
125
+ def is_reserved(self, request: Request) -> bool:
126
+ """Return True for API and asset paths, which never render the SPA."""
127
+ return self.route_path(request).split("/", 1)[0] in _RESERVED
128
+
129
+ def fallback(self, request: Request) -> Response | None:
130
+ """Response for an unmatched GET/HEAD: a top-level file or the SPA shell."""
131
+ if request.method not in {"GET", "HEAD"} or self.is_reserved(request):
132
+ return None
133
+ root_file = self.root_files.get(self.route_path(request))
134
+ if root_file is not None:
135
+ return FileResponse(root_file)
136
+ if self.template is None:
137
+ return HTMLResponse(_PLACEHOLDER, status_code=503)
138
+ return HTMLResponse(self.index_for(self.admin_root(request)))
139
+
140
+ def index_for(self, admin_root: str) -> str:
141
+ """Render (and cache) the shell for one mount root."""
142
+ if self.template is None:
143
+ msg = "FastStudio SPA is not built; there is no index.html to render."
144
+ raise FastStudioError(msg)
145
+ cached = self._rendered.get(admin_root)
146
+ if cached is None:
147
+ cached = render_index(self.template, admin_root=admin_root, title=self.settings.title)
148
+ if len(self._rendered) < _MAX_CACHED_ROOTS:
149
+ self._rendered[admin_root] = cached
150
+ return cached
151
+
152
+
153
+ def _top_level_files(static_dir: Path) -> dict[str, Path]:
154
+ if not static_dir.is_dir():
155
+ return {}
156
+ files: dict[str, Path] = {}
157
+ for entry in static_dir.iterdir():
158
+ name = entry.name
159
+ if name.startswith(".") or name.casefold() == "index.html" or entry.is_symlink():
160
+ continue
161
+ if entry.is_file():
162
+ files[name] = entry
163
+ return files
faststudio/admin.py ADDED
@@ -0,0 +1,227 @@
1
+ """The :class:`Admin` entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from datetime import timedelta
7
+ from pathlib import Path
8
+ from typing import TypeVar, cast
9
+
10
+ from fastapi import FastAPI
11
+ from fastapi.responses import RedirectResponse
12
+ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
13
+ from starlette.routing import Route
14
+ from starlette.types import Receive, Scope, Send
15
+
16
+ from faststudio.api._app import create_admin_app, wrap_admin_app
17
+ from faststudio.api._context import AdminContext
18
+ from faststudio.auth.backend import AuthBackend
19
+ from faststudio.auth.csrf import CsrfTokens
20
+ from faststudio.auth.session import SessionManager
21
+ from faststudio.config import Settings, resolve_settings
22
+ from faststudio.exceptions import ConfigurationError
23
+ from faststudio.model_admin import ModelAdmin
24
+ from faststudio.registry import Registry, resolve_model_admin
25
+ from faststudio.security.headers import SecurityHeadersMiddleware
26
+ from faststudio.security.rate_limit import (
27
+ CLIENT_MAX_ATTEMPTS,
28
+ CLIENT_WINDOW_SECONDS,
29
+ InMemoryRateLimiter,
30
+ RateLimiter,
31
+ )
32
+
33
+ _T = TypeVar("_T")
34
+ _A = TypeVar("_A", bound=type[ModelAdmin])
35
+ _STATIC_DIR = Path(__file__).resolve().parent / "static"
36
+
37
+
38
+ class Admin:
39
+ """A FastStudio admin site attached to a FastAPI application.
40
+
41
+ All options are validated eagerly; misconfiguration raises
42
+ :class:`~faststudio.ConfigurationError` at startup rather than at request
43
+ time. The admin is mounted on ``app`` at ``base_url`` as an isolated
44
+ sub-application (its own error handling and security headers; nothing is
45
+ added to the host's OpenAPI schema).
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ app: FastAPI,
51
+ *,
52
+ engine: AsyncEngine | None = None,
53
+ session_maker: async_sessionmaker[AsyncSession] | None = None,
54
+ auth_backend: AuthBackend,
55
+ secret_key: str | None = None,
56
+ title: str = "FastStudio",
57
+ base_url: str = "/admin",
58
+ session_max_age: timedelta = timedelta(hours=8),
59
+ secure_cookies: bool = True,
60
+ max_page_size: int = 100,
61
+ rate_limiter: RateLimiter | None = None,
62
+ show_powered_by: bool = True,
63
+ ) -> None:
64
+ """Configure FastStudio for ``app``.
65
+
66
+ Args:
67
+ app: The host FastAPI application.
68
+ engine: An ``AsyncEngine``; FastStudio creates its own session factory.
69
+ session_maker: Alternatively, your own ``async_sessionmaker``.
70
+ Exactly one of ``engine`` and ``session_maker`` is required.
71
+ auth_backend: Authenticates admins, e.g. ``ModelUserBackend(User)``.
72
+ secret_key: Signs sessions and CSRF tokens. Defaults to the
73
+ ``FASTSTUDIO_SECRET_KEY`` environment variable. Must be at least
74
+ 32 random characters.
75
+ title: Title shown in the UI.
76
+ base_url: Mount path, e.g. ``/admin``.
77
+ session_max_age: Absolute session lifetime.
78
+ secure_cookies: Set the ``Secure`` cookie flag. Disable only for
79
+ plain-HTTP development on non-localhost hosts.
80
+ max_page_size: Upper bound for list page sizes.
81
+ rate_limiter: Login throttling; defaults to `InMemoryRateLimiter()`
82
+ (5 attempts per 15 minutes per client IP and username, per process).
83
+ show_powered_by: Show the "Powered by FastStudio" footer.
84
+
85
+ Raises:
86
+ ConfigurationError: if any option is invalid.
87
+
88
+ """
89
+ self._app = _require_instance(
90
+ app, FastAPI, f"app must be a FastAPI instance, got {type(app).__name__}."
91
+ )
92
+ self._session_maker = _resolve_session_maker(engine, session_maker)
93
+ self._auth_backend = _validate_auth_backend(auth_backend)
94
+ self._settings: Settings = resolve_settings(
95
+ secret_key=secret_key,
96
+ title=title,
97
+ base_url=base_url,
98
+ session_max_age=session_max_age,
99
+ secure_cookies=secure_cookies,
100
+ max_page_size=max_page_size,
101
+ show_powered_by=show_powered_by,
102
+ )
103
+
104
+ self._registry = Registry()
105
+ context = AdminContext(
106
+ settings=self._settings,
107
+ registry=self._registry,
108
+ session_maker=self._session_maker,
109
+ auth_backend=self._auth_backend,
110
+ static_dir=_STATIC_DIR,
111
+ sessions=SessionManager(
112
+ self._settings.secret_key,
113
+ max_age=int(self._settings.session_max_age.total_seconds()),
114
+ ),
115
+ csrf=CsrfTokens(self._settings.secret_key),
116
+ rate_limiter=_validate_rate_limiter(rate_limiter),
117
+ client_rate_limiter=InMemoryRateLimiter(
118
+ max_attempts=CLIENT_MAX_ATTEMPTS, window_seconds=CLIENT_WINDOW_SECONDS
119
+ ),
120
+ )
121
+ self._sub_app = create_admin_app(context)
122
+ base_url = self._settings.base_url
123
+ app.router.routes.append(
124
+ Route(
125
+ base_url,
126
+ SecurityHeadersMiddleware(_TrailingSlashRedirect()),
127
+ include_in_schema=False,
128
+ )
129
+ )
130
+ app.mount(base_url, wrap_admin_app(self._sub_app, context), name="faststudio")
131
+
132
+ def register(self, model_admin: _A) -> _A:
133
+ """Validate and register a :class:`ModelAdmin` subclass.
134
+
135
+ Usable as a class decorator. Returns the class unchanged.
136
+
137
+ Raises:
138
+ ConfigurationError: on unknown or misspelled options, unknown field
139
+ names, search/filter fields of unsupported types, excluded fields
140
+ used elsewhere, composite primary keys, or a duplicate identity
141
+ or model.
142
+
143
+ """
144
+ self._registry.add(
145
+ resolve_model_admin(model_admin, max_page_size=self._settings.max_page_size)
146
+ )
147
+ return model_admin
148
+
149
+ @property
150
+ def base_url(self) -> str:
151
+ """Normalized mount path, without a trailing slash."""
152
+ return self._settings.base_url
153
+
154
+ @property
155
+ def title(self) -> str:
156
+ """Title shown in the UI."""
157
+ return self._settings.title
158
+
159
+
160
+ class _TrailingSlashRedirect:
161
+ """Redirect `{base_url}` to `{base_url}/`, keeping the query string."""
162
+
163
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
164
+ # Per the ASGI spec `path` already includes any proxy `root_path`.
165
+ target = f"{scope['path']}/"
166
+ if scope.get("query_string"):
167
+ target += "?" + scope["query_string"].decode("latin-1")
168
+ await RedirectResponse(target, status_code=307)(scope, receive, send)
169
+
170
+
171
+ def _require_instance(value: object, cls: type[_T], msg: str) -> _T:
172
+ """Runtime type guard: static types are bypassed by untyped callers."""
173
+ if not isinstance(value, cls):
174
+ raise ConfigurationError(msg)
175
+ return value
176
+
177
+
178
+ def _validate_auth_backend(backend: AuthBackend) -> AuthBackend:
179
+ msg = (
180
+ "auth_backend must be an instance implementing the AuthBackend protocol with "
181
+ "async authenticate() and get_user() methods, e.g. ModelUserBackend(User)."
182
+ )
183
+ candidate = cast("object", backend)
184
+ if isinstance(candidate, type) or not isinstance(candidate, AuthBackend):
185
+ raise ConfigurationError(msg)
186
+ if not all(
187
+ inspect.iscoroutinefunction(getattr(backend, name)) for name in ("authenticate", "get_user")
188
+ ):
189
+ raise ConfigurationError(msg)
190
+ return backend
191
+
192
+
193
+ def _validate_rate_limiter(limiter: RateLimiter | None) -> RateLimiter:
194
+ if limiter is None:
195
+ return InMemoryRateLimiter()
196
+ candidate = cast("object", limiter)
197
+ if (
198
+ isinstance(candidate, type)
199
+ or not isinstance(candidate, RateLimiter)
200
+ or not all(inspect.iscoroutinefunction(getattr(limiter, m)) for m in ("hit", "reset"))
201
+ ):
202
+ msg = "rate_limiter must implement RateLimiter (async hit() and reset())."
203
+ raise ConfigurationError(msg)
204
+ return limiter
205
+
206
+
207
+ def _resolve_session_maker(
208
+ engine: AsyncEngine | None,
209
+ session_maker: async_sessionmaker[AsyncSession] | None,
210
+ ) -> async_sessionmaker[AsyncSession]:
211
+ if (engine is None) == (session_maker is None):
212
+ msg = "Pass exactly one of engine= or session_maker= to Admin()."
213
+ raise ConfigurationError(msg)
214
+ if session_maker is not None:
215
+ maker: async_sessionmaker[AsyncSession] = _require_instance(
216
+ session_maker,
217
+ async_sessionmaker,
218
+ "session_maker must be an sqlalchemy.ext.asyncio.async_sessionmaker.",
219
+ )
220
+ return maker
221
+ async_engine = _require_instance(
222
+ engine,
223
+ AsyncEngine,
224
+ "engine must be an sqlalchemy AsyncEngine (use create_async_engine() with an "
225
+ "async driver such as aiosqlite or asyncpg).",
226
+ )
227
+ return async_sessionmaker(async_engine, class_=AsyncSession, expire_on_commit=False)
@@ -0,0 +1 @@
1
+ """The admin sub-application: HTTP routes, error handling, SPA serving (private)."""
faststudio/api/_app.py ADDED
@@ -0,0 +1,52 @@
1
+ """Build the isolated admin FastAPI application (ADR-0006)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import FastAPI
6
+ from starlette.staticfiles import StaticFiles
7
+ from starlette.types import ASGIApp
8
+
9
+ from faststudio._spa import AdminRootRecorder, SpaSite
10
+ from faststudio.api._context import AdminContext
11
+ from faststudio.api.auth import protected_router, public_router
12
+ from faststudio.api.errors import install_error_handlers
13
+ from faststudio.api.models import router as models_router
14
+ from faststudio.api.write import router as write_router
15
+ from faststudio.security.csrf import CsrfMiddleware
16
+ from faststudio.security.headers import SecurityHeadersMiddleware
17
+ from faststudio.security.origin import SameOriginGuard
18
+
19
+
20
+ def create_admin_app(context: AdminContext) -> FastAPI:
21
+ """Create the admin sub-application with its API routers.
22
+
23
+ New data routes go on `protected_router` (session required); only login
24
+ is public. A test enumerates every API route to enforce this.
25
+ """
26
+ site = SpaSite(context.static_dir, context.settings)
27
+ app = FastAPI(
28
+ title=context.settings.title,
29
+ openapi_url=None,
30
+ docs_url=None,
31
+ redoc_url=None,
32
+ redirect_slashes=False,
33
+ )
34
+ app.state.faststudio = context
35
+ app.include_router(public_router)
36
+ app.include_router(protected_router)
37
+ app.include_router(models_router)
38
+ app.include_router(write_router)
39
+ app.mount(
40
+ "/assets",
41
+ StaticFiles(directory=context.static_dir / "assets", check_dir=False),
42
+ name="assets",
43
+ )
44
+ install_error_handlers(app, site)
45
+ return app
46
+
47
+
48
+ def wrap_admin_app(app: ASGIApp, context: AdminContext) -> ASGIApp:
49
+ """Outer layers, outermost first: headers, admin root, same-origin guard, CSRF."""
50
+ return SecurityHeadersMiddleware(
51
+ AdminRootRecorder(SameOriginGuard(CsrfMiddleware(app, context)))
52
+ )
@@ -0,0 +1,31 @@
1
+ """Shared state for request handling (private)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
9
+
10
+ from faststudio.auth.backend import AuthBackend
11
+ from faststudio.auth.csrf import CsrfTokens
12
+ from faststudio.auth.session import SessionManager
13
+ from faststudio.config import Settings
14
+ from faststudio.registry import Registry
15
+ from faststudio.security.rate_limit import RateLimiter
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class AdminContext:
20
+ """Everything request handling needs; stored on `app.state.faststudio`."""
21
+
22
+ settings: Settings
23
+ registry: Registry
24
+ session_maker: async_sessionmaker[AsyncSession]
25
+ auth_backend: AuthBackend
26
+ static_dir: Path
27
+ sessions: SessionManager
28
+ csrf: CsrfTokens
29
+ rate_limiter: RateLimiter
30
+ #: Per-client budget across all usernames (in-process; see api/auth.py).
31
+ client_rate_limiter: RateLimiter
@@ -0,0 +1,31 @@
1
+ """Shared FastAPI dependencies for admin API routes (private)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+ from typing import Annotated
7
+
8
+ from fastapi import Depends, Request
9
+ from sqlalchemy.ext.asyncio import AsyncSession
10
+
11
+ from faststudio.api.auth import get_context
12
+ from faststudio.api.errors import ApiError
13
+ from faststudio.registry import RegisteredModel
14
+
15
+
16
+ async def db_session(request: Request) -> AsyncIterator[AsyncSession]:
17
+ """One database session per request."""
18
+ async with get_context(request).session_maker() as session:
19
+ yield session
20
+
21
+
22
+ def registered_model(identity: str, request: Request) -> RegisteredModel:
23
+ """Look up a model by identity; unknown identities are 404."""
24
+ try:
25
+ return get_context(request).registry.get(identity)
26
+ except KeyError:
27
+ raise ApiError(404, "not_found") from None
28
+
29
+
30
+ DbSession = Annotated[AsyncSession, Depends(db_session)]
31
+ ModelDep = Annotated[RegisteredModel, Depends(registered_model)]
@@ -0,0 +1,4 @@
1
+ """Admin API paths, relative to the admin mount (single source of truth)."""
2
+
3
+ API_PREFIX = "/api/v1"
4
+ LOGIN_PATH = f"{API_PREFIX}/auth/login"
@@ -0,0 +1,28 @@
1
+ """Loading records and building `Row` responses (shared by read and write routes)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+
7
+ from faststudio.api._serialize import parse_pk, relation_labels, to_row
8
+ from faststudio.api.errors import ApiError
9
+ from faststudio.registry import RegisteredModel, Registry
10
+ from faststudio.schemas.contract import Row
11
+
12
+
13
+ async def load_or_404(session: AsyncSession, registered: RegisteredModel, pk: str) -> object:
14
+ """Load one record of `registered` by its URL key, or raise 404."""
15
+ key = parse_pk(registered, pk)
16
+ obj = await session.get(registered.model, key) if key is not None else None
17
+ if obj is None:
18
+ raise ApiError(404, "not_found")
19
+ return obj
20
+
21
+
22
+ async def detail_row(
23
+ session: AsyncSession, registry: Registry, registered: RegisteredModel, obj: object
24
+ ) -> Row:
25
+ """`Row` with every visible field and relation labels."""
26
+ fields = list(registered.fields)
27
+ (labels,) = await relation_labels(session, registry, registered, [obj], fields)
28
+ return to_row(registered, obj, fields, labels)