svc-infra 0.1.600__py3-none-any.whl → 0.1.640__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.

Potentially problematic release.


This version of svc-infra might be problematic. Click here for more details.

Files changed (118) hide show
  1. svc_infra/api/fastapi/admin/__init__.py +3 -0
  2. svc_infra/api/fastapi/admin/add.py +231 -0
  3. svc_infra/api/fastapi/billing/router.py +64 -0
  4. svc_infra/api/fastapi/billing/setup.py +19 -0
  5. svc_infra/api/fastapi/db/sql/add.py +32 -13
  6. svc_infra/api/fastapi/db/sql/crud_router.py +178 -16
  7. svc_infra/api/fastapi/db/sql/session.py +16 -0
  8. svc_infra/api/fastapi/dependencies/ratelimit.py +57 -7
  9. svc_infra/api/fastapi/docs/add.py +160 -0
  10. svc_infra/api/fastapi/docs/landing.py +1 -1
  11. svc_infra/api/fastapi/middleware/errors/handlers.py +45 -7
  12. svc_infra/api/fastapi/middleware/graceful_shutdown.py +87 -0
  13. svc_infra/api/fastapi/middleware/ratelimit.py +59 -1
  14. svc_infra/api/fastapi/middleware/ratelimit_store.py +12 -6
  15. svc_infra/api/fastapi/middleware/timeout.py +148 -0
  16. svc_infra/api/fastapi/openapi/mutators.py +114 -0
  17. svc_infra/api/fastapi/ops/add.py +73 -0
  18. svc_infra/api/fastapi/pagination.py +3 -1
  19. svc_infra/api/fastapi/routers/ping.py +1 -0
  20. svc_infra/api/fastapi/setup.py +11 -1
  21. svc_infra/api/fastapi/tenancy/add.py +19 -0
  22. svc_infra/api/fastapi/tenancy/context.py +112 -0
  23. svc_infra/app/README.md +5 -5
  24. svc_infra/billing/__init__.py +23 -0
  25. svc_infra/billing/async_service.py +147 -0
  26. svc_infra/billing/jobs.py +230 -0
  27. svc_infra/billing/models.py +131 -0
  28. svc_infra/billing/quotas.py +101 -0
  29. svc_infra/billing/schemas.py +33 -0
  30. svc_infra/billing/service.py +115 -0
  31. svc_infra/bundled_docs/README.md +5 -0
  32. svc_infra/bundled_docs/__init__.py +1 -0
  33. svc_infra/bundled_docs/getting-started.md +6 -0
  34. svc_infra/cache/__init__.py +4 -0
  35. svc_infra/cache/add.py +158 -0
  36. svc_infra/cache/backend.py +5 -2
  37. svc_infra/cache/decorators.py +19 -1
  38. svc_infra/cache/keys.py +24 -4
  39. svc_infra/cli/__init__.py +28 -8
  40. svc_infra/cli/cmds/__init__.py +8 -0
  41. svc_infra/cli/cmds/db/nosql/mongo/mongo_cmds.py +4 -3
  42. svc_infra/cli/cmds/db/nosql/mongo/mongo_scaffold_cmds.py +4 -4
  43. svc_infra/cli/cmds/db/sql/alembic_cmds.py +80 -11
  44. svc_infra/cli/cmds/db/sql/sql_export_cmds.py +80 -0
  45. svc_infra/cli/cmds/db/sql/sql_scaffold_cmds.py +3 -3
  46. svc_infra/cli/cmds/docs/docs_cmds.py +140 -0
  47. svc_infra/cli/cmds/dx/__init__.py +12 -0
  48. svc_infra/cli/cmds/dx/dx_cmds.py +99 -0
  49. svc_infra/cli/cmds/help.py +4 -0
  50. svc_infra/cli/cmds/obs/obs_cmds.py +4 -3
  51. svc_infra/cli/cmds/sdk/__init__.py +0 -0
  52. svc_infra/cli/cmds/sdk/sdk_cmds.py +102 -0
  53. svc_infra/data/add.py +61 -0
  54. svc_infra/data/backup.py +53 -0
  55. svc_infra/data/erasure.py +45 -0
  56. svc_infra/data/fixtures.py +40 -0
  57. svc_infra/data/retention.py +55 -0
  58. svc_infra/db/nosql/mongo/README.md +13 -13
  59. svc_infra/db/sql/repository.py +51 -11
  60. svc_infra/db/sql/resource.py +5 -0
  61. svc_infra/db/sql/templates/setup/env_async.py.tmpl +9 -1
  62. svc_infra/db/sql/templates/setup/env_sync.py.tmpl +9 -2
  63. svc_infra/db/sql/tenant.py +79 -0
  64. svc_infra/db/sql/utils.py +18 -4
  65. svc_infra/docs/acceptance-matrix.md +71 -0
  66. svc_infra/docs/acceptance.md +44 -0
  67. svc_infra/docs/admin.md +425 -0
  68. svc_infra/docs/adr/0002-background-jobs-and-scheduling.md +40 -0
  69. svc_infra/docs/adr/0003-webhooks-framework.md +24 -0
  70. svc_infra/docs/adr/0004-tenancy-model.md +42 -0
  71. svc_infra/docs/adr/0005-data-lifecycle.md +86 -0
  72. svc_infra/docs/adr/0006-ops-slos-and-metrics.md +47 -0
  73. svc_infra/docs/adr/0007-docs-and-sdks.md +83 -0
  74. svc_infra/docs/adr/0008-billing-primitives.md +143 -0
  75. svc_infra/docs/adr/0009-acceptance-harness.md +40 -0
  76. svc_infra/docs/adr/0010-timeouts-and-resource-limits.md +54 -0
  77. svc_infra/docs/adr/0011-admin-scope-and-impersonation.md +73 -0
  78. svc_infra/docs/api.md +59 -0
  79. svc_infra/docs/auth.md +11 -0
  80. svc_infra/docs/billing.md +190 -0
  81. svc_infra/docs/cache.md +76 -0
  82. svc_infra/docs/cli.md +74 -0
  83. svc_infra/docs/contributing.md +34 -0
  84. svc_infra/docs/data-lifecycle.md +52 -0
  85. svc_infra/docs/database.md +14 -0
  86. svc_infra/docs/docs-and-sdks.md +62 -0
  87. svc_infra/docs/environment.md +114 -0
  88. svc_infra/docs/getting-started.md +63 -0
  89. svc_infra/docs/idempotency.md +111 -0
  90. svc_infra/docs/jobs.md +67 -0
  91. svc_infra/docs/observability.md +16 -0
  92. svc_infra/docs/ops.md +37 -0
  93. svc_infra/docs/rate-limiting.md +125 -0
  94. svc_infra/docs/repo-review.md +48 -0
  95. svc_infra/docs/security.md +176 -0
  96. svc_infra/docs/tenancy.md +35 -0
  97. svc_infra/docs/timeouts-and-resource-limits.md +147 -0
  98. svc_infra/docs/webhooks.md +112 -0
  99. svc_infra/dx/add.py +63 -0
  100. svc_infra/dx/changelog.py +74 -0
  101. svc_infra/dx/checks.py +67 -0
  102. svc_infra/http/__init__.py +13 -0
  103. svc_infra/http/client.py +72 -0
  104. svc_infra/jobs/builtins/webhook_delivery.py +14 -2
  105. svc_infra/jobs/queue.py +9 -1
  106. svc_infra/jobs/runner.py +75 -0
  107. svc_infra/jobs/worker.py +17 -1
  108. svc_infra/mcp/svc_infra_mcp.py +85 -28
  109. svc_infra/obs/add.py +54 -7
  110. svc_infra/obs/grafana/dashboards/http-overview.json +45 -0
  111. svc_infra/security/headers.py +15 -2
  112. svc_infra/security/hibp.py +6 -2
  113. svc_infra/security/permissions.py +1 -0
  114. svc_infra/webhooks/service.py +10 -2
  115. {svc_infra-0.1.600.dist-info → svc_infra-0.1.640.dist-info}/METADATA +40 -14
  116. {svc_infra-0.1.600.dist-info → svc_infra-0.1.640.dist-info}/RECORD +118 -44
  117. {svc_infra-0.1.600.dist-info → svc_infra-0.1.640.dist-info}/WHEEL +0 -0
  118. {svc_infra-0.1.600.dist-info → svc_infra-0.1.640.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,3 @@
1
+ from .add import add_admin, admin_router
2
+
3
+ __all__ = ["add_admin", "admin_router"]
@@ -0,0 +1,231 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hmac
5
+ import inspect
6
+ import json
7
+ import logging
8
+ import os
9
+ import time
10
+ from hashlib import sha256
11
+ from types import SimpleNamespace
12
+ from typing import Any, Callable, Optional
13
+
14
+ from fastapi import APIRouter, Depends, HTTPException, Request, Response
15
+
16
+ from ....app.env import get_current_environment
17
+ from ....security.permissions import RequirePermission
18
+ from ..auth.security import Identity, Principal, _current_principal
19
+ from ..auth.state import get_auth_state
20
+ from ..db.sql.session import SqlSessionDep
21
+ from ..dual.protected import roles_router
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def _b64u(data: bytes) -> str:
27
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
28
+
29
+
30
+ def _b64u_decode(s: str) -> bytes:
31
+ pad = "=" * ((4 - len(s) % 4) % 4)
32
+ return base64.urlsafe_b64decode(s + pad)
33
+
34
+
35
+ def _sign(payload: dict, *, secret: str) -> str:
36
+ body = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
37
+ sig = hmac.new(secret.encode("utf-8"), body, sha256).digest()
38
+ return _b64u(body) + "." + _b64u(sig)
39
+
40
+
41
+ def _verify(token: str, *, secret: str) -> dict:
42
+ try:
43
+ b64_body, b64_sig = token.split(".", 1)
44
+ body = _b64u_decode(b64_body)
45
+ exp_sig = _b64u_decode(b64_sig)
46
+ got_sig = hmac.new(secret.encode("utf-8"), body, sha256).digest()
47
+ if not hmac.compare_digest(exp_sig, got_sig):
48
+ raise ValueError("bad_signature")
49
+ payload = json.loads(body)
50
+ if int(payload.get("exp", 0)) < int(time.time()):
51
+ raise ValueError("expired")
52
+ return payload
53
+ except Exception as e:
54
+ raise ValueError("invalid_token") from e
55
+
56
+
57
+ def admin_router(*, dependencies: Optional[list[Any]] = None, **kwargs) -> APIRouter:
58
+ """Role-gated admin router for coarse access control.
59
+
60
+ Use permission guards inside endpoints for fine-grained control.
61
+ """
62
+
63
+ return roles_router("admin", **kwargs)
64
+
65
+
66
+ def add_admin(
67
+ app,
68
+ *,
69
+ base_path: str = "/admin",
70
+ enable_impersonation: bool = True,
71
+ secret: Optional[str] = None,
72
+ ttl_seconds: int = 15 * 60,
73
+ cookie_name: str = "impersonation",
74
+ impersonation_user_getter: Optional[Callable[[Any, str], Any]] = None,
75
+ ) -> None:
76
+ """Wire admin surfaces with sensible defaults.
77
+
78
+ - Mounts an admin router under base_path.
79
+ - Optionally enables impersonation start/stop endpoints guarded by permissions.
80
+ - Registers a dependency override to honor impersonation cookie globally (idempotent).
81
+
82
+ impersonation_user_getter: optional callable (request, user_id) -> user object.
83
+ If omitted, defaults to loading from SQLAlchemy User model returned by get_auth_state().
84
+ """
85
+
86
+ # Idempotency: only mount once per app instance
87
+ if getattr(app.state, "_admin_added", False):
88
+ return
89
+
90
+ env = get_current_environment()
91
+ _secret = (
92
+ secret or os.getenv("ADMIN_IMPERSONATION_SECRET") or os.getenv("APP_SECRET") or "dev-secret"
93
+ )
94
+ _ttl = int(os.getenv("ADMIN_IMPERSONATION_TTL", str(ttl_seconds)))
95
+ _cookie = os.getenv("ADMIN_IMPERSONATION_COOKIE", cookie_name)
96
+
97
+ r = admin_router(prefix=base_path, tags=["admin"]) # role-gated
98
+
99
+ async def _default_user_getter(request: Request, user_id: str, session: SqlSessionDep):
100
+ try:
101
+ UserModel, _, _ = get_auth_state()
102
+ except Exception:
103
+ # Fallback: simple shim if auth state not configured
104
+ return SimpleNamespace(id=user_id)
105
+ obj = await session.get(UserModel, user_id)
106
+ if not obj:
107
+ raise HTTPException(404, "user_not_found")
108
+ return obj
109
+
110
+ user_getter = impersonation_user_getter
111
+
112
+ @r.post(
113
+ "/impersonate/start", status_code=204, dependencies=[RequirePermission("admin.impersonate")]
114
+ )
115
+ async def start_impersonation(
116
+ body: dict, request: Request, response: Response, session: SqlSessionDep, identity: Identity
117
+ ):
118
+ target_id = (body or {}).get("user_id")
119
+ reason = (body or {}).get("reason", "")
120
+ if not target_id:
121
+ raise HTTPException(422, "user_id_required")
122
+ # Load target for validation (custom getter or default)
123
+ _res = (
124
+ user_getter(request, target_id)
125
+ if user_getter
126
+ else _default_user_getter(request, target_id, session)
127
+ )
128
+ target = await _res if inspect.isawaitable(_res) else _res
129
+ actor: Principal = identity
130
+ payload = {
131
+ "actor_id": getattr(getattr(actor, "user", None), "id", None),
132
+ "target_id": str(getattr(target, "id", target_id)),
133
+ "iat": int(time.time()),
134
+ "exp": int(time.time()) + _ttl,
135
+ "nonce": _b64u(os.urandom(8)),
136
+ }
137
+ token = _sign(payload, secret=_secret)
138
+ response.set_cookie(
139
+ key=_cookie,
140
+ value=token,
141
+ httponly=True,
142
+ samesite="lax",
143
+ secure=(env in ("prod", "production")),
144
+ path="/",
145
+ max_age=_ttl,
146
+ )
147
+ logger.info(
148
+ "admin.impersonation.started",
149
+ extra={
150
+ "actor_id": payload["actor_id"],
151
+ "target_id": payload["target_id"],
152
+ "reason": reason,
153
+ "expires_in": _ttl,
154
+ },
155
+ )
156
+ # Re-compose override now to wrap any late overrides set by tests/harness
157
+ try:
158
+ _compose_override()
159
+ except Exception:
160
+ pass
161
+
162
+ @r.post("/impersonate/stop", status_code=204)
163
+ async def stop_impersonation(response: Response):
164
+ response.delete_cookie(_cookie, path="/")
165
+ logger.info("admin.impersonation.stopped")
166
+
167
+ app.include_router(r)
168
+
169
+ # Dependency override: wrap the base principal to honor impersonation cookie.
170
+ # Compose with any existing override (e.g., acceptance app/test harness) and
171
+ # re-compose at startup to capture late overrides.
172
+ def _compose_override():
173
+ existing = app.dependency_overrides.get(_current_principal)
174
+ if existing and getattr(existing, "_is_admin_impersonation_override", False):
175
+ dep_provider = getattr(existing, "_admin_impersonation_base", _current_principal)
176
+ else:
177
+ dep_provider = existing or _current_principal
178
+
179
+ async def _override_current_principal(
180
+ base: Principal = Depends(dep_provider),
181
+ request: Request = None,
182
+ session: SqlSessionDep = None,
183
+ ) -> Principal:
184
+ token = request.cookies.get(_cookie) if request else None
185
+ if not token:
186
+ return base
187
+ try:
188
+ payload = _verify(token, secret=_secret)
189
+ except Exception:
190
+ return base
191
+ # Load target user
192
+ target_id = payload.get("target_id")
193
+ if not target_id:
194
+ return base
195
+ # Preserve actor roles/claims so permissions remain that of the actor
196
+ actor_user = getattr(base, "user", None)
197
+ actor_roles = getattr(actor_user, "roles", []) or []
198
+ _res = (
199
+ user_getter(request, target_id)
200
+ if user_getter
201
+ else _default_user_getter(request, target_id, session)
202
+ )
203
+ target = await _res if inspect.isawaitable(_res) else _res
204
+ # Swap user but keep actor for audit if needed
205
+ setattr(base, "actor", getattr(base, "user", None))
206
+ # If target lacks roles, inherit actor roles to maintain permission checks
207
+ try:
208
+ if not getattr(target, "roles", None):
209
+ setattr(target, "roles", actor_roles)
210
+ except Exception:
211
+ # Best-effort; if target object is immutable, fallback by wrapping
212
+ target = SimpleNamespace(id=getattr(target, "id", target_id), roles=actor_roles)
213
+ base.user = target
214
+ base.via = "impersonated"
215
+ return base
216
+
217
+ app.dependency_overrides[_current_principal] = _override_current_principal
218
+ _override_current_principal._is_admin_impersonation_override = True # type: ignore[attr-defined]
219
+ _override_current_principal._admin_impersonation_base = dep_provider # type: ignore[attr-defined]
220
+
221
+ # Compose now (best-effort) and again on startup to wrap any later overrides
222
+ _compose_override()
223
+ try:
224
+ app.add_event_handler("startup", _compose_override)
225
+ except Exception:
226
+ # Best-effort; if app doesn't support event handlers, we already composed once
227
+ pass
228
+ app.state._admin_added = True
229
+
230
+
231
+ # no extra helpers
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timezone
4
+ from typing import Annotated, Optional
5
+
6
+ from fastapi import APIRouter, Depends, Response, status
7
+
8
+ from svc_infra.api.fastapi.db.sql.session import SqlSessionDep
9
+ from svc_infra.api.fastapi.middleware.idempotency import require_idempotency_key
10
+ from svc_infra.api.fastapi.tenancy.context import TenantId
11
+ from svc_infra.billing.async_service import AsyncBillingService
12
+ from svc_infra.billing.schemas import UsageAckOut, UsageAggregateRow, UsageAggregatesOut, UsageIn
13
+
14
+ router = APIRouter(prefix="/_billing", tags=["Billing"])
15
+
16
+
17
+ def get_service(tenant_id: TenantId, session: SqlSessionDep) -> AsyncBillingService:
18
+ return AsyncBillingService(session=session, tenant_id=tenant_id)
19
+
20
+
21
+ @router.post(
22
+ "/usage",
23
+ name="billing_record_usage",
24
+ status_code=status.HTTP_202_ACCEPTED,
25
+ response_model=UsageAckOut,
26
+ dependencies=[Depends(require_idempotency_key)],
27
+ )
28
+ async def record_usage(
29
+ data: UsageIn, svc: Annotated[AsyncBillingService, Depends(get_service)], response: Response
30
+ ):
31
+ at = data.at or datetime.now(tz=timezone.utc)
32
+ evt_id = await svc.record_usage(
33
+ metric=data.metric,
34
+ amount=int(data.amount),
35
+ at=at,
36
+ idempotency_key=data.idempotency_key,
37
+ metadata=data.metadata,
38
+ )
39
+ # For 202, no Location header is required, but we can surface the id in the body
40
+ return UsageAckOut(id=evt_id, accepted=True)
41
+
42
+
43
+ @router.get(
44
+ "/usage",
45
+ name="billing_list_aggregates",
46
+ response_model=UsageAggregatesOut,
47
+ )
48
+ async def list_aggregates(
49
+ metric: str,
50
+ date_from: Optional[datetime] = None,
51
+ date_to: Optional[datetime] = None,
52
+ svc: Annotated[AsyncBillingService, Depends(get_service)] = None,
53
+ ):
54
+ rows = await svc.list_daily_aggregates(metric=metric, date_from=date_from, date_to=date_to)
55
+ items = [
56
+ UsageAggregateRow(
57
+ period_start=r.period_start,
58
+ granularity=r.granularity,
59
+ metric=r.metric,
60
+ total=int(r.total),
61
+ )
62
+ for r in rows
63
+ ]
64
+ return UsageAggregatesOut(items=items, next_cursor=None)
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ from fastapi import FastAPI
4
+
5
+ from .router import router as billing_router
6
+
7
+
8
+ def add_billing(app: FastAPI, *, prefix: str = "/_billing") -> None:
9
+ # Mount under the chosen prefix; default is /_billing
10
+ if prefix and prefix != "/_billing":
11
+ # If a custom prefix is desired, clone router with new prefix
12
+ from fastapi import APIRouter
13
+
14
+ custom = APIRouter(prefix=prefix, tags=["Billing"])
15
+ for route in billing_router.routes:
16
+ custom.routes.append(route)
17
+ app.include_router(custom)
18
+ else:
19
+ app.include_router(billing_router)
@@ -10,7 +10,7 @@ from svc_infra.db.sql.management import make_crud_schemas
10
10
  from svc_infra.db.sql.repository import SqlRepository
11
11
  from svc_infra.db.sql.resource import SqlResource
12
12
 
13
- from .crud_router import make_crud_router_plus_sql
13
+ from .crud_router import make_crud_router_plus_sql, make_tenant_crud_router_plus_sql
14
14
  from .health import _make_db_health_router
15
15
  from .session import dispose_session, initialize_session
16
16
 
@@ -37,18 +37,37 @@ def add_sql_resources(app: FastAPI, resources: Sequence[SqlResource]) -> None:
37
37
  update_name=r.update_name,
38
38
  )
39
39
 
40
- router = make_crud_router_plus_sql(
41
- model=r.model,
42
- service=svc,
43
- read_schema=Read,
44
- create_schema=Create,
45
- update_schema=Update,
46
- prefix=r.prefix,
47
- tags=r.tags,
48
- search_fields=r.search_fields,
49
- default_ordering=r.ordering_default,
50
- allowed_order_fields=r.allowed_order_fields,
51
- )
40
+ if r.tenant_field:
41
+ # wrap service factory/instance through tenant router
42
+ def _factory():
43
+ return svc
44
+
45
+ router = make_tenant_crud_router_plus_sql(
46
+ model=r.model,
47
+ service_factory=_factory,
48
+ read_schema=Read,
49
+ create_schema=Create,
50
+ update_schema=Update,
51
+ prefix=r.prefix,
52
+ tenant_field=r.tenant_field,
53
+ tags=r.tags,
54
+ search_fields=r.search_fields,
55
+ default_ordering=r.ordering_default,
56
+ allowed_order_fields=r.allowed_order_fields,
57
+ )
58
+ else:
59
+ router = make_crud_router_plus_sql(
60
+ model=r.model,
61
+ service=svc,
62
+ read_schema=Read,
63
+ create_schema=Create,
64
+ update_schema=Update,
65
+ prefix=r.prefix,
66
+ tags=r.tags,
67
+ search_fields=r.search_fields,
68
+ default_ordering=r.ordering_default,
69
+ allowed_order_fields=r.allowed_order_fields,
70
+ )
52
71
  app.include_router(router)
53
72
 
54
73
 
@@ -1,4 +1,4 @@
1
- from typing import Annotated, Any, Optional, Sequence, Type, TypeVar, cast
1
+ from typing import Annotated, Any, Optional, Sequence, Type, TypeVar
2
2
 
3
3
  from fastapi import APIRouter, Body, Depends, HTTPException
4
4
  from pydantic import BaseModel
@@ -15,7 +15,9 @@ from svc_infra.api.fastapi.db.http import (
15
15
  )
16
16
  from svc_infra.api.fastapi.dual.public import public_router
17
17
  from svc_infra.db.sql.service import SqlService
18
+ from svc_infra.db.sql.tenant import TenantSqlService
18
19
 
20
+ from ...tenancy.context import TenantId
19
21
  from .session import SqlSessionDep
20
22
 
21
23
  CreateModel = TypeVar("CreateModel", bound=BaseModel)
@@ -44,6 +46,18 @@ def make_crud_router_plus_sql(
44
46
  redirect_slashes=False,
45
47
  )
46
48
 
49
+ def _coerce_id(v: Any) -> Any:
50
+ """Best-effort coercion of path ids: cast digit-only strings to int.
51
+
52
+ Keeps original type otherwise to avoid breaking non-integer IDs.
53
+ """
54
+ if isinstance(v, str) and v.isdigit():
55
+ try:
56
+ return int(v)
57
+ except Exception:
58
+ return v
59
+ return v
60
+
47
61
  def _parse_ordering_to_fields(order_spec: Optional[str]) -> list[str]:
48
62
  if not order_spec:
49
63
  return []
@@ -59,7 +73,7 @@ def make_crud_router_plus_sql(
59
73
  # -------- LIST --------
60
74
  @router.get(
61
75
  "",
62
- response_model=cast(Any, Page[read_schema]),
76
+ response_model=Page[read_schema],
63
77
  description=f"List items of type {model.__name__}",
64
78
  )
65
79
  async def list_items(
@@ -85,18 +99,16 @@ def make_crud_router_plus_sql(
85
99
  else:
86
100
  items = await service.list(session, limit=lp.limit, offset=lp.offset, order_by=order_by)
87
101
  total = await service.count(session)
88
- return Page[read_schema].from_items(
89
- total=total, items=items, limit=lp.limit, offset=lp.offset
90
- )
102
+ return Page[Any].from_items(total=total, items=items, limit=lp.limit, offset=lp.offset)
91
103
 
92
104
  # -------- GET by id --------
93
105
  @router.get(
94
106
  "/{item_id}",
95
- response_model=cast(Any, read_schema),
107
+ response_model=read_schema,
96
108
  description=f"Get item of type {model.__name__}",
97
109
  )
98
110
  async def get_item(item_id: Any, session: SqlSessionDep): # type: ignore[name-defined]
99
- row = await service.get(session, item_id)
111
+ row = await service.get(session, _coerce_id(item_id))
100
112
  if not row:
101
113
  raise HTTPException(404, "Not found")
102
114
  return row
@@ -104,30 +116,40 @@ def make_crud_router_plus_sql(
104
116
  # -------- CREATE --------
105
117
  @router.post(
106
118
  "",
107
- response_model=cast(Any, read_schema),
119
+ response_model=read_schema,
108
120
  status_code=201,
109
121
  description=f"Create item of type {model.__name__}",
110
122
  )
111
123
  async def create_item(
112
124
  session: SqlSessionDep, # type: ignore[name-defined]
113
- payload: create_schema = Body(...),
125
+ payload: Any = Body(...),
114
126
  ):
115
- data = cast(BaseModel, payload).model_dump(exclude_unset=True)
127
+ if isinstance(payload, BaseModel):
128
+ data = payload.model_dump(exclude_unset=True)
129
+ elif isinstance(payload, dict):
130
+ data = payload
131
+ else:
132
+ raise HTTPException(422, "invalid_payload")
116
133
  return await service.create(session, data)
117
134
 
118
135
  # -------- UPDATE --------
119
136
  @router.patch(
120
137
  "/{item_id}",
121
- response_model=cast(Any, read_schema),
138
+ response_model=read_schema,
122
139
  description=f"Update item of type {model.__name__}",
123
140
  )
124
141
  async def update_item(
125
142
  item_id: Any,
126
143
  session: SqlSessionDep, # type: ignore[name-defined]
127
- payload: update_schema = Body(...),
144
+ payload: Any = Body(...),
128
145
  ):
129
- data = cast(BaseModel, payload).model_dump(exclude_unset=True)
130
- row = await service.update(session, item_id, data)
146
+ if isinstance(payload, BaseModel):
147
+ data = payload.model_dump(exclude_unset=True)
148
+ elif isinstance(payload, dict):
149
+ data = payload
150
+ else:
151
+ raise HTTPException(422, "invalid_payload")
152
+ row = await service.update(session, _coerce_id(item_id), data)
131
153
  if not row:
132
154
  raise HTTPException(404, "Not found")
133
155
  return row
@@ -137,7 +159,147 @@ def make_crud_router_plus_sql(
137
159
  "/{item_id}", status_code=204, description=f"Delete item of type {model.__name__}"
138
160
  )
139
161
  async def delete_item(item_id: Any, session: SqlSessionDep): # type: ignore[name-defined]
140
- ok = await service.delete(session, item_id)
162
+ ok = await service.delete(session, _coerce_id(item_id))
163
+ if not ok:
164
+ raise HTTPException(404, "Not found")
165
+ return
166
+
167
+ return router
168
+
169
+
170
+ def make_tenant_crud_router_plus_sql(
171
+ *,
172
+ model: type[Any],
173
+ service_factory: callable, # factory that returns a SqlService (will be wrapped)
174
+ read_schema: Type[ReadModel],
175
+ create_schema: Type[CreateModel],
176
+ update_schema: Type[UpdateModel],
177
+ prefix: str,
178
+ tenant_field: str = "tenant_id",
179
+ tags: list[str] | None = None,
180
+ search_fields: Optional[Sequence[str]] = None,
181
+ default_ordering: Optional[str] = None,
182
+ allowed_order_fields: Optional[list[str]] = None,
183
+ mount_under_db_prefix: bool = True,
184
+ ) -> APIRouter:
185
+ """Like make_crud_router_plus_sql, but requires TenantId and scopes all operations."""
186
+ router_prefix = ("/_sql" + prefix) if mount_under_db_prefix else prefix
187
+ router = public_router(
188
+ prefix=router_prefix,
189
+ tags=tags or [prefix.strip("/")],
190
+ redirect_slashes=False,
191
+ )
192
+
193
+ # Evaluate the base service once to preserve in-memory state across requests in tests/local.
194
+ # Consumers may pass either an instance or a zero-arg factory function.
195
+ try:
196
+ _base_instance = service_factory() if callable(service_factory) else service_factory # type: ignore[misc]
197
+ except TypeError:
198
+ # If the callable requires args, assume it's already an instance
199
+ _base_instance = service_factory # type: ignore[assignment]
200
+
201
+ def _coerce_id(v: Any) -> Any:
202
+ """Best-effort coercion of path ids: cast digit-only strings to int.
203
+ Keeps original type otherwise.
204
+ """
205
+ if isinstance(v, str) and v.isdigit():
206
+ try:
207
+ return int(v)
208
+ except Exception:
209
+ return v
210
+ return v
211
+
212
+ def _parse_ordering_to_fields(order_spec: Optional[str]) -> list[str]:
213
+ if not order_spec:
214
+ return []
215
+ pieces = [p.strip() for p in order_spec.split(",") if p.strip()]
216
+ fields: list[str] = []
217
+ for p in pieces:
218
+ name = p[1:] if p.startswith("-") else p
219
+ if allowed_order_fields and name not in (allowed_order_fields or []):
220
+ continue
221
+ fields.append(p)
222
+ return fields
223
+
224
+ # create per-request service with tenant scoping
225
+ async def _svc(session: SqlSessionDep, tenant_id: TenantId): # type: ignore[name-defined]
226
+ repo_or_service = getattr(_base_instance, "repo", _base_instance)
227
+ svc: Any = TenantSqlService(repo_or_service, tenant_id=tenant_id, tenant_field=tenant_field) # type: ignore[arg-type]
228
+ return svc # type: ignore[return-value]
229
+
230
+ @router.get("", response_model=Page[read_schema])
231
+ async def list_items(
232
+ lp: Annotated[LimitOffsetParams, Depends(dep_limit_offset)],
233
+ op: Annotated[OrderParams, Depends(dep_order)],
234
+ sp: Annotated[SearchParams, Depends(dep_search)],
235
+ session: SqlSessionDep, # type: ignore[name-defined]
236
+ tenant_id: TenantId,
237
+ ):
238
+ svc = await _svc(session, tenant_id)
239
+ order_spec = op.order_by or default_ordering
240
+ order_fields = _parse_ordering_to_fields(order_spec)
241
+ order_by = build_order_by(model, order_fields)
242
+ if sp.q:
243
+ fields = [
244
+ f.strip()
245
+ for f in (sp.fields or (",".join(search_fields or []) or "")).split(",")
246
+ if f.strip()
247
+ ]
248
+ items = await svc.search(
249
+ session, q=sp.q, fields=fields, limit=lp.limit, offset=lp.offset, order_by=order_by
250
+ )
251
+ total = await svc.count_filtered(session, q=sp.q, fields=fields)
252
+ else:
253
+ items = await svc.list(session, limit=lp.limit, offset=lp.offset, order_by=order_by)
254
+ total = await svc.count(session)
255
+ return Page[Any].from_items(total=total, items=items, limit=lp.limit, offset=lp.offset)
256
+
257
+ @router.get("/{item_id}", response_model=read_schema)
258
+ async def get_item(item_id: Any, session: SqlSessionDep, tenant_id: TenantId): # type: ignore[name-defined]
259
+ svc = await _svc(session, tenant_id)
260
+ obj = await svc.get(session, item_id)
261
+ if not obj:
262
+ raise HTTPException(404, "not_found")
263
+ return obj
264
+
265
+ @router.post("", response_model=read_schema, status_code=201)
266
+ async def create_item(
267
+ session: SqlSessionDep, # type: ignore[name-defined]
268
+ tenant_id: TenantId,
269
+ payload: Any = Body(...),
270
+ ):
271
+ svc = await _svc(session, tenant_id)
272
+ if isinstance(payload, BaseModel):
273
+ data = payload.model_dump(exclude_unset=True)
274
+ elif isinstance(payload, dict):
275
+ data = payload
276
+ else:
277
+ raise HTTPException(422, "invalid_payload")
278
+ return await svc.create(session, data)
279
+
280
+ @router.patch("/{item_id}", response_model=read_schema)
281
+ async def update_item(
282
+ item_id: Any,
283
+ session: SqlSessionDep, # type: ignore[name-defined]
284
+ tenant_id: TenantId,
285
+ payload: Any = Body(...),
286
+ ):
287
+ svc = await _svc(session, tenant_id)
288
+ if isinstance(payload, BaseModel):
289
+ data = payload.model_dump(exclude_unset=True)
290
+ elif isinstance(payload, dict):
291
+ data = payload
292
+ else:
293
+ raise HTTPException(422, "invalid_payload")
294
+ updated = await svc.update(session, item_id, data)
295
+ if not updated:
296
+ raise HTTPException(404, "not_found")
297
+ return updated
298
+
299
+ @router.delete("/{item_id}", status_code=204)
300
+ async def delete_item(item_id: Any, session: SqlSessionDep, tenant_id: TenantId): # type: ignore[name-defined]
301
+ svc = await _svc(session, tenant_id)
302
+ ok = await svc.delete(session, _coerce_id(item_id))
141
303
  if not ok:
142
304
  raise HTTPException(404, "Not found")
143
305
  return
@@ -145,4 +307,4 @@ def make_crud_router_plus_sql(
145
307
  return router
146
308
 
147
309
 
148
- __all__ = ["make_crud_router_plus_sql"]
310
+ __all__ = ["make_crud_router_plus_sql", "make_tenant_crud_router_plus_sql"]
@@ -1,9 +1,11 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import logging
4
+ import os
4
5
  from typing import Annotated, AsyncIterator, Tuple
5
6
 
6
7
  from fastapi import Depends
8
+ from sqlalchemy import text
7
9
  from sqlalchemy.ext.asyncio import (
8
10
  AsyncEngine,
9
11
  AsyncSession,
@@ -53,6 +55,20 @@ async def get_session() -> AsyncIterator[AsyncSession]:
53
55
  if _SessionLocal is None:
54
56
  raise RuntimeError("Database not initialized. Call add_sql_db(app, ...) first.")
55
57
  async with _SessionLocal() as session:
58
+ # Optional: set a per-transaction statement timeout for Postgres if configured
59
+ raw_ms = os.getenv("DB_STATEMENT_TIMEOUT_MS")
60
+ if raw_ms:
61
+ try:
62
+ ms = int(raw_ms)
63
+ if ms > 0:
64
+ try:
65
+ # SET LOCAL applies for the duration of the current transaction only
66
+ await session.execute(text("SET LOCAL statement_timeout = :ms"), {"ms": ms})
67
+ except Exception:
68
+ # Non-PG dialects (e.g., SQLite) will error; ignore silently
69
+ pass
70
+ except ValueError:
71
+ pass
56
72
  try:
57
73
  yield session
58
74
  await session.commit()