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
@@ -0,0 +1,180 @@
1
+ """Encode database values in the wire format (docs/api-contract.md)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import enum
6
+ import math
7
+ import re
8
+ from collections.abc import Callable, Sequence
9
+ from datetime import date, datetime
10
+ from decimal import Decimal, InvalidOperation
11
+ from uuid import UUID
12
+
13
+ from sqlalchemy.ext.asyncio import AsyncSession
14
+
15
+ from faststudio.introspection._fields import FieldSpec, JsonValue, is_plain_json
16
+ from faststudio.introspection._types import FieldType
17
+ from faststudio.query._list import label_statement
18
+ from faststudio.registry import RegisteredModel, Registry
19
+ from faststudio.schemas.contract import MAX_SAFE_INTEGER, Row
20
+
21
+ MAX_UNSUPPORTED_LENGTH = 200
22
+ MAX_LABEL_LENGTH = 200
23
+
24
+
25
+ def _text(value: object, limit: int) -> str:
26
+ text = str(value)
27
+ return text if len(text) <= limit else text[: limit - 1] + "…"
28
+
29
+
30
+ def _safe_json(value: JsonValue) -> JsonValue:
31
+ """Nested integers outside the JavaScript-safe range become strings too."""
32
+ if isinstance(value, bool) or not isinstance(value, int | list | dict):
33
+ return value
34
+ if isinstance(value, int):
35
+ return value if abs(value) <= MAX_SAFE_INTEGER else str(value)
36
+ if isinstance(value, list):
37
+ return [_safe_json(item) for item in value]
38
+ return {key: _safe_json(item) for key, item in value.items()}
39
+
40
+
41
+ def encode_value(field_type: FieldType, value: object) -> JsonValue: # noqa: PLR0911
42
+ """Encode one value for JSON; large integers and decimals become strings."""
43
+ if value is None:
44
+ return None
45
+ if field_type == "integer" and isinstance(value, int):
46
+ return value if abs(value) <= MAX_SAFE_INTEGER else str(value)
47
+ if field_type == "float" and isinstance(value, int | float):
48
+ return float(value) if math.isfinite(value) else None
49
+ if field_type == "decimal" and isinstance(value, Decimal | int | float):
50
+ number = value if isinstance(value, Decimal) else Decimal(str(value))
51
+ return str(number) if number.is_finite() else None
52
+ if field_type in {"date", "datetime"} and isinstance(value, date | datetime):
53
+ return value.isoformat()
54
+ if field_type == "enum":
55
+ return value.name if isinstance(value, enum.Enum) else str(value)
56
+ if field_type == "json":
57
+ return _safe_json(value) if is_plain_json(value) else None
58
+ if field_type in {"string", "text", "uuid"} or (
59
+ field_type == "boolean" and isinstance(value, bool)
60
+ ):
61
+ return value if isinstance(value, bool) else str(value)
62
+ if isinstance(value, bytes | bytearray | memoryview):
63
+ return f"<{len(value)} bytes>"
64
+ return _text(value, MAX_UNSUPPORTED_LENGTH)
65
+
66
+
67
+ def encode_field(spec: FieldSpec, value: object) -> JsonValue:
68
+ """Encode a value of `spec`'s field (foreign keys use their own column type)."""
69
+ field_type = spec.relation.value_type if spec.relation is not None else spec.type
70
+ return encode_value(field_type, value)
71
+
72
+
73
+ def encode_pk(value: object) -> str:
74
+ """Primary keys are always strings in URLs and `Row.pk`."""
75
+ if isinstance(value, datetime | date):
76
+ return value.isoformat()
77
+ return str(value)
78
+
79
+
80
+ _ASCII_INT = re.compile(r"-?[0-9]{1,19}")
81
+ _INT64 = (-(2**63), 2**63 - 1)
82
+
83
+
84
+ def parse_int_key(raw: str, low: int | None, high: int | None) -> int:
85
+ """Parse an ASCII integer within the column's range (64-bit when unknown)."""
86
+ if not _ASCII_INT.fullmatch(raw):
87
+ raise ValueError(raw)
88
+ value = int(raw)
89
+ lower = _INT64[0] if low is None else low
90
+ upper = _INT64[1] if high is None else high
91
+ if not lower <= value <= upper:
92
+ raise ValueError(raw)
93
+ return value
94
+
95
+
96
+ def _parse_decimal(raw: str) -> Decimal:
97
+ number = Decimal(raw)
98
+ if not number.is_finite():
99
+ raise ValueError(raw)
100
+ return number
101
+
102
+
103
+ _PK_PARSERS: dict[str, Callable[[str], object]] = {
104
+ "uuid": UUID,
105
+ "decimal": _parse_decimal,
106
+ "date": date.fromisoformat,
107
+ "datetime": datetime.fromisoformat,
108
+ "string": str,
109
+ "text": str,
110
+ }
111
+
112
+
113
+ def parse_key(
114
+ field_type: str, raw: str, *, low: int | None = None, high: int | None = None
115
+ ) -> object | None:
116
+ """Parse a key of `field_type` from text; None if it cannot be a valid key."""
117
+ try:
118
+ if field_type == "integer":
119
+ return parse_int_key(raw, low, high)
120
+ parser = _PK_PARSERS.get(field_type)
121
+ return parser(raw) if parser is not None else None
122
+ except (ValueError, InvalidOperation):
123
+ return None
124
+
125
+
126
+ def parse_pk(registered: RegisteredModel, raw: str) -> object | None:
127
+ """Parse a primary key from a URL; None if it cannot be a valid key."""
128
+ spec = registered.field_specs[registered.pk_field]
129
+ field_type = spec.relation.value_type if spec.relation is not None else spec.type
130
+ return parse_key(field_type, raw, low=spec.min_value, high=spec.max_value)
131
+
132
+
133
+ def format_label(pk: object, label: object) -> str:
134
+ """Display label of a related record: its label value, or its key when empty."""
135
+ if label is None or label == "":
136
+ return encode_pk(pk)
137
+ if isinstance(label, datetime | date):
138
+ return label.isoformat()
139
+ return _text(label, MAX_LABEL_LENGTH)
140
+
141
+
142
+ async def relation_labels(
143
+ session: AsyncSession,
144
+ registry: Registry,
145
+ registered: RegisteredModel,
146
+ rows: Sequence[object],
147
+ fields: Sequence[str],
148
+ ) -> list[dict[str, str]]:
149
+ """Display labels of foreign-key values, one query per relation field."""
150
+ labels: list[dict[str, str]] = [{} for _ in rows]
151
+ for name in fields:
152
+ spec = registered.field_specs[name]
153
+ target = registry.target_of(spec.relation.target) if spec.relation else None
154
+ if target is None:
155
+ continue
156
+ values = {getattr(row, name) for row in rows} - {None}
157
+ if not values:
158
+ continue
159
+ result = await session.execute(label_statement(target, values))
160
+ by_pk = {pk: format_label(pk, label) for pk, label in result.all()}
161
+ for index, row in enumerate(rows):
162
+ value = getattr(row, name)
163
+ if value in by_pk:
164
+ labels[index][name] = by_pk[value]
165
+ return labels
166
+
167
+
168
+ def to_row(
169
+ registered: RegisteredModel,
170
+ obj: object,
171
+ fields: Sequence[str],
172
+ labels: dict[str, str],
173
+ ) -> Row:
174
+ """Serialize one ORM object: primary key, the given visible fields, labels."""
175
+ specs = registered.field_specs
176
+ return Row(
177
+ pk=encode_pk(getattr(obj, registered.pk_field)),
178
+ data={name: encode_field(specs[name], getattr(obj, name)) for name in fields},
179
+ labels=labels,
180
+ )
faststudio/api/auth.py ADDED
@@ -0,0 +1,135 @@
1
+ """Authentication routes and the session dependency (ADR-0004)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hmac
6
+ import logging
7
+ import unicodedata
8
+ from typing import Annotated
9
+
10
+ from fastapi import APIRouter, Depends, Request
11
+ from fastapi.responses import JSONResponse, Response
12
+
13
+ from faststudio._spa import ADMIN_ROOT_KEY
14
+ from faststudio.api._context import AdminContext
15
+ from faststudio.api._paths import API_PREFIX
16
+ from faststudio.api.errors import ApiError
17
+ from faststudio.auth.backend import AuthenticatedUser
18
+ from faststudio.auth.cookies import (
19
+ csrf_cookie,
20
+ expired_session_cookie,
21
+ session_cookie,
22
+ single_cookie,
23
+ )
24
+ from faststudio.auth.session import SESSION_COOKIE
25
+ from faststudio.schemas.contract import LoginRequest, UserMeta, UserResponse
26
+
27
+ logger = logging.getLogger("faststudio.auth")
28
+
29
+
30
+ def get_context(request: Request) -> AdminContext:
31
+ """Return the admin context of the current sub-application."""
32
+ context: AdminContext = request.app.state.faststudio
33
+ return context
34
+
35
+
36
+ def _cookie_path(request: Request) -> str:
37
+ path: str = request.scope.get(ADMIN_ROOT_KEY, request.scope.get("root_path", ""))
38
+ return path or "/"
39
+
40
+
41
+ async def current_user(request: Request) -> AuthenticatedUser:
42
+ """Require a valid session whose user may still sign in (401 otherwise)."""
43
+ context = get_context(request)
44
+ raw = single_cookie(request.scope, SESSION_COOKIE)
45
+ session = context.sessions.load(raw)
46
+ user = await context.auth_backend.get_user(request, session.user_id) if session else None
47
+ if (
48
+ session is None
49
+ or user is None
50
+ or not hmac.compare_digest(user.auth_version.encode(), session.auth_version.encode())
51
+ ):
52
+ cookies: list[str] = []
53
+ if raw is not None:
54
+ # Clear the dead session and its session-bound CSRF token together,
55
+ # so the next login works with the fresh anonymous token.
56
+ path, secure = _cookie_path(request), context.settings.secure_cookies
57
+ cookies = [
58
+ expired_session_cookie(path=path, secure=secure),
59
+ csrf_cookie(context.csrf.issue(session_id=None), path=path, secure=secure),
60
+ ]
61
+ raise ApiError(401, "not_authenticated", set_cookies=cookies)
62
+ return user
63
+
64
+
65
+ CurrentUser = Annotated[AuthenticatedUser, Depends(current_user)]
66
+
67
+ #: Routes that work without a session (only login).
68
+ public_router = APIRouter(prefix=API_PREFIX)
69
+ #: Every other API route: a session is required for all of them.
70
+ protected_router = APIRouter(prefix=API_PREFIX, dependencies=[Depends(current_user)])
71
+
72
+
73
+ def rate_limit_username(username: str) -> str:
74
+ """Normalize a username for rate-limit keys (NFKC, case-folded, trimmed).
75
+
76
+ Variants a database collation may treat as equal ("Admin", " admin",
77
+ full-width letters) then share one bucket.
78
+ """
79
+ return unicodedata.normalize("NFKC", username).casefold().strip()
80
+
81
+
82
+ def _user_response(user: AuthenticatedUser) -> UserResponse:
83
+ return UserResponse(user=UserMeta(id=user.id, username=user.username))
84
+
85
+
86
+ @public_router.post("/auth/login", response_model=UserResponse)
87
+ async def login(body: LoginRequest, request: Request) -> Response:
88
+ """Verify credentials, start a session and rotate the CSRF token."""
89
+ context = get_context(request)
90
+ client = request.client.host if request.client else "unknown"
91
+ key = f"{client}|{rate_limit_username(body.username)}"
92
+ decision = await context.client_rate_limiter.hit(client)
93
+ if decision.allowed:
94
+ decision = await context.rate_limiter.hit(key)
95
+ if not decision.allowed:
96
+ logger.warning("Login rate limit reached for client %s", client)
97
+ raise ApiError(429, "rate_limited", headers={"Retry-After": str(decision.retry_after)})
98
+ user = await context.auth_backend.authenticate(request, body.username, body.password)
99
+ if user is None:
100
+ logger.info("Failed login attempt from client %s", client)
101
+ raise ApiError(401, "invalid_credentials")
102
+ await context.rate_limiter.reset(key)
103
+ value, session = context.sessions.issue(user_id=user.id, auth_version=user.auth_version)
104
+ secure = context.settings.secure_cookies
105
+ path = _cookie_path(request)
106
+ response = JSONResponse(_user_response(user).model_dump(mode="json"))
107
+ response.headers.append(
108
+ "set-cookie",
109
+ session_cookie(value, path=path, max_age=context.sessions.max_age, secure=secure),
110
+ )
111
+ response.headers.append(
112
+ "set-cookie",
113
+ csrf_cookie(context.csrf.issue(session_id=session.session_id), path=path, secure=secure),
114
+ )
115
+ return response
116
+
117
+
118
+ @protected_router.get("/auth/me", response_model=UserResponse)
119
+ async def me(user: CurrentUser) -> UserResponse:
120
+ """Return the signed-in admin."""
121
+ return _user_response(user)
122
+
123
+
124
+ @protected_router.post("/auth/logout", status_code=204)
125
+ async def logout(request: Request) -> Response:
126
+ """End the session (cookie cleared) and issue a fresh anonymous CSRF token."""
127
+ context = get_context(request)
128
+ secure = context.settings.secure_cookies
129
+ path = _cookie_path(request)
130
+ response = Response(status_code=204)
131
+ response.headers.append("set-cookie", expired_session_cookie(path=path, secure=secure))
132
+ response.headers.append(
133
+ "set-cookie", csrf_cookie(context.csrf.issue(session_id=None), path=path, secure=secure)
134
+ )
135
+ return response
@@ -0,0 +1,176 @@
1
+ """Contract error responses (`{"error": {"code", "message", "details"}}`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import TYPE_CHECKING, cast
8
+
9
+ from fastapi import FastAPI, Request
10
+ from fastapi.exceptions import RequestValidationError
11
+ from fastapi.responses import JSONResponse, Response
12
+ from sqlalchemy.exc import StatementError
13
+ from starlette.exceptions import HTTPException as StarletteHTTPException
14
+
15
+ from faststudio.schemas.contract import ErrorBody, ErrorCode, ErrorResponse, ValidationIssue
16
+
17
+ if TYPE_CHECKING:
18
+ from faststudio._spa import SpaSite
19
+
20
+ logger = logging.getLogger("faststudio.api")
21
+
22
+ _MESSAGES: dict[ErrorCode, str] = {
23
+ "invalid_query": "Invalid request.",
24
+ "not_authenticated": "Authentication required.",
25
+ "invalid_credentials": "Invalid username or password.",
26
+ "csrf_failed": "CSRF validation failed.",
27
+ "forbidden": "Forbidden.",
28
+ "not_found": "Not found.",
29
+ "method_not_allowed": "Method not allowed.",
30
+ "conflict": "Conflict.",
31
+ "validation_error": "Invalid input.",
32
+ "payload_too_large": "Request body too large.",
33
+ "rate_limited": "Too many requests.",
34
+ "internal_error": "Internal server error.",
35
+ }
36
+ _STATUS_CODES: dict[int, ErrorCode] = {
37
+ 400: "invalid_query",
38
+ 401: "not_authenticated",
39
+ 403: "forbidden",
40
+ 404: "not_found",
41
+ 405: "method_not_allowed",
42
+ 409: "conflict",
43
+ 413: "payload_too_large",
44
+ 422: "validation_error",
45
+ 429: "rate_limited",
46
+ }
47
+ _SAFE_METHODS = frozenset({"GET", "HEAD"})
48
+ _NOT_FOUND = 404
49
+ _SERVER_ERROR = 500
50
+ # 422 bodies may contain client-chosen keys in `loc`; bound their size.
51
+ _MAX_ISSUES = 50
52
+ _MAX_LOC_PART = 64
53
+
54
+
55
+ class ApiError(Exception):
56
+ """Raise from FastStudio routes to return a contract error."""
57
+
58
+ def __init__(
59
+ self,
60
+ status_code: int,
61
+ code: ErrorCode,
62
+ message: str | None = None,
63
+ *,
64
+ headers: dict[str, str] | None = None,
65
+ set_cookies: Sequence[str] = (),
66
+ details: list[ValidationIssue] | None = None,
67
+ ) -> None:
68
+ """Create an error; `message` defaults to a generic text for `code`."""
69
+ super().__init__(code)
70
+ self.status_code = status_code
71
+ self.code = code
72
+ self.message = message or _MESSAGES[code]
73
+ self.headers = headers
74
+ self.set_cookies = tuple(set_cookies)
75
+ self.details = details
76
+
77
+
78
+ def error_response(
79
+ status_code: int,
80
+ code: ErrorCode,
81
+ message: str | None = None,
82
+ *,
83
+ details: list[ValidationIssue] | None = None,
84
+ headers: dict[str, str] | None = None,
85
+ ) -> JSONResponse:
86
+ """Build a contract error response. Messages are generic unless given."""
87
+ body = ErrorResponse(
88
+ error=ErrorBody(code=code, message=message or _MESSAGES[code], details=details)
89
+ )
90
+ return JSONResponse(body.model_dump(mode="json"), status_code=status_code, headers=headers)
91
+
92
+
93
+ def _loc_part(part: object) -> str | int:
94
+ if isinstance(part, int) and not isinstance(part, bool):
95
+ return part
96
+ text = str(part)
97
+ return text if len(text) <= _MAX_LOC_PART else text[: _MAX_LOC_PART - 1] + "…"
98
+
99
+
100
+ def validation_issues(errors: Sequence[Mapping[str, object]]) -> list[ValidationIssue]:
101
+ """Reduce pydantic errors to `loc`/`msg`/`type`.
102
+
103
+ Submitted values (`input`, `ctx`) are dropped. `loc` can contain
104
+ client-chosen keys (e.g. unknown body fields), so each part is truncated
105
+ and at most `_MAX_ISSUES` issues are returned.
106
+ """
107
+ issues: list[ValidationIssue] = []
108
+ for error in errors[:_MAX_ISSUES]:
109
+ loc = error.get("loc", ())
110
+ parts = loc if isinstance(loc, tuple | list) else (loc,)
111
+ issues.append(
112
+ ValidationIssue(
113
+ loc=[_loc_part(part) for part in parts],
114
+ msg=str(error.get("msg", "")),
115
+ type=str(error.get("type", "")),
116
+ )
117
+ )
118
+ return issues
119
+
120
+
121
+ def install_error_handlers(app: FastAPI, site: SpaSite) -> None:
122
+ """Route every error through the contract format; unmatched GETs render the SPA."""
123
+
124
+ # Starlette dispatches handlers by exception type, so the casts are safe.
125
+ async def on_api_error(request: Request, exc: Exception) -> Response:
126
+ error = cast("ApiError", exc)
127
+ response = error_response(
128
+ error.status_code,
129
+ error.code,
130
+ error.message,
131
+ details=error.details,
132
+ headers=error.headers,
133
+ )
134
+ for cookie in error.set_cookies:
135
+ response.headers.append("set-cookie", cookie)
136
+ return response
137
+
138
+ async def on_http_error(request: Request, exc: Exception) -> Response:
139
+ http_error = cast("StarletteHTTPException", exc)
140
+ status = http_error.status_code
141
+ if status == _NOT_FOUND:
142
+ fallback = site.fallback(request)
143
+ if fallback is not None:
144
+ return fallback
145
+ if request.method not in _SAFE_METHODS and not site.is_reserved(request):
146
+ return error_response(405, "method_not_allowed", headers={"Allow": "GET, HEAD"})
147
+ default: ErrorCode = "internal_error" if status >= _SERVER_ERROR else "invalid_query"
148
+ headers = dict(http_error.headers) if http_error.headers else None
149
+ return error_response(status, _STATUS_CODES.get(status, default), headers=headers)
150
+
151
+ async def on_validation_error(request: Request, exc: Exception) -> Response:
152
+ errors = cast("RequestValidationError", exc).errors()
153
+ return error_response(422, "validation_error", details=validation_issues(errors))
154
+
155
+ async def on_unhandled(request: Request, exc: Exception) -> Response:
156
+ # Starlette re-raises after this response is sent, so host error handlers
157
+ # and monitoring still see admin failures (documented in ADR-0008).
158
+ if isinstance(exc, StatementError):
159
+ # Database errors embed the SQL and its parameters (row values):
160
+ # log only the error types.
161
+ logger.error(
162
+ "Database error in %s %r: %s (%s)",
163
+ request.method,
164
+ request.url.path,
165
+ type(exc).__name__,
166
+ type(exc.orig).__name__,
167
+ )
168
+ else:
169
+ # %r: a decoded path may carry control characters (log injection).
170
+ logger.error("Unhandled error in %s %r", request.method, request.url.path, exc_info=exc)
171
+ return error_response(500, "internal_error")
172
+
173
+ app.add_exception_handler(ApiError, on_api_error)
174
+ app.add_exception_handler(StarletteHTTPException, on_http_error)
175
+ app.add_exception_handler(RequestValidationError, on_validation_error)
176
+ app.add_exception_handler(Exception, on_unhandled)
@@ -0,0 +1,95 @@
1
+ """Read API: metadata, lists, single records and relation choices (M7)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import APIRouter, Depends, Request
6
+
7
+ from faststudio.api._deps import DbSession, ModelDep
8
+ from faststudio.api._paths import API_PREFIX
9
+ from faststudio.api._records import detail_row, load_or_404
10
+ from faststudio.api._serialize import encode_pk, format_label, relation_labels, to_row
11
+ from faststudio.api.auth import CurrentUser, current_user, get_context
12
+ from faststudio.api.errors import ApiError
13
+ from faststudio.query._list import choices_statements, list_statements
14
+ from faststudio.query._params import parse_choices_params, parse_list_params
15
+ from faststudio.schemas._meta import build_models_meta
16
+ from faststudio.schemas.contract import (
17
+ SCHEMA_VERSION,
18
+ ChoiceMeta,
19
+ ChoicesResponse,
20
+ ListResponse,
21
+ MetaResponse,
22
+ Row,
23
+ UserMeta,
24
+ )
25
+
26
+ router = APIRouter(prefix=API_PREFIX, dependencies=[Depends(current_user)])
27
+
28
+
29
+ @router.get("/meta", response_model=MetaResponse)
30
+ async def meta(request: Request, user: CurrentUser) -> MetaResponse:
31
+ """Describe every registered model for the SPA."""
32
+ # Imported here: `faststudio/__init__.py` (the version's single source) imports the app.
33
+ from faststudio import __version__ # noqa: PLC0415
34
+
35
+ context = get_context(request)
36
+ return MetaResponse(
37
+ schema_version=SCHEMA_VERSION,
38
+ version=__version__,
39
+ title=context.settings.title,
40
+ show_powered_by=context.settings.show_powered_by,
41
+ user=UserMeta(id=user.id, username=user.username),
42
+ models=build_models_meta(context.registry),
43
+ )
44
+
45
+
46
+ @router.get("/models/{identity}/items", response_model=ListResponse)
47
+ async def list_items(request: Request, registered: ModelDep, session: DbSession) -> ListResponse:
48
+ """Return a page of records with search, filters and sorting from the allowlists."""
49
+ context = get_context(request)
50
+ params = parse_list_params(
51
+ request.query_params.multi_items(), registered, context.settings.max_page_size
52
+ )
53
+ page_query, count_query = list_statements(registered, params)
54
+ rows = (await session.execute(page_query)).scalars().all()
55
+ total = (await session.execute(count_query)).scalar_one()
56
+ fields = registered.list_display
57
+ labels = await relation_labels(session, context.registry, registered, rows, fields)
58
+ return ListResponse(
59
+ items=[
60
+ to_row(registered, row, fields, label) for row, label in zip(rows, labels, strict=True)
61
+ ],
62
+ total=total,
63
+ page=params.page,
64
+ page_size=params.page_size,
65
+ )
66
+
67
+
68
+ @router.get("/models/{identity}/items/{pk}", response_model=Row)
69
+ async def retrieve_item(request: Request, registered: ModelDep, pk: str, session: DbSession) -> Row:
70
+ """Return one record with all visible fields."""
71
+ obj = await load_or_404(session, registered, pk)
72
+ return await detail_row(session, get_context(request).registry, registered, obj)
73
+
74
+
75
+ @router.get("/models/{identity}/fields/{field}/choices", response_model=ChoicesResponse)
76
+ async def choices(
77
+ request: Request, registered: ModelDep, field: str, session: DbSession
78
+ ) -> ChoicesResponse:
79
+ """Return options for a foreign-key field whose target model is registered."""
80
+ registry = get_context(request).registry
81
+ spec = registered.field_specs.get(field)
82
+ target = registry.target_of(spec.relation.target) if spec and spec.relation else None
83
+ if target is None:
84
+ raise ApiError(404, "not_found")
85
+ page, q = parse_choices_params(request.query_params.multi_items())
86
+ page_query, count_query = choices_statements(target, q, page)
87
+ total = (await session.execute(count_query)).scalar_one()
88
+ result = await session.execute(page_query)
89
+ return ChoicesResponse(
90
+ items=[
91
+ ChoiceMeta(value=encode_pk(pk), label=format_label(pk, label))
92
+ for pk, label in result.all()
93
+ ],
94
+ total=total,
95
+ )