swiftapi-kernel 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.
Potentially problematic release.
This version of swiftapi-kernel might be problematic. Click here for more details.
- swiftapi/__init__.py +22 -0
- swiftapi/app/__init__.py +0 -0
- swiftapi/app/factory.py +200 -0
- swiftapi/app/lifespan.py +167 -0
- swiftapi/app/routers.py +58 -0
- swiftapi/cli/__init__.py +0 -0
- swiftapi/cli/admin.py +198 -0
- swiftapi/cli/appref.py +51 -0
- swiftapi/cli/audit.py +45 -0
- swiftapi/cli/db.py +185 -0
- swiftapi/cli/endpoint.py +169 -0
- swiftapi/cli/logs.py +100 -0
- swiftapi/cli/main.py +238 -0
- swiftapi/cli/new.py +113 -0
- swiftapi/cli/openapi.py +69 -0
- swiftapi/cli/resource.py +657 -0
- swiftapi/cli/scaffold.py +168 -0
- swiftapi/config/__init__.py +0 -0
- swiftapi/config/constants.py +51 -0
- swiftapi/config/environments.py +38 -0
- swiftapi/config/settings.py +764 -0
- swiftapi/core/__init__.py +0 -0
- swiftapi/core/admin/__init__.py +0 -0
- swiftapi/core/admin/accounts.py +385 -0
- swiftapi/core/admin/audit.py +203 -0
- swiftapi/core/admin/maintenance.py +53 -0
- swiftapi/core/admin/registry.py +53 -0
- swiftapi/core/admin/security.py +94 -0
- swiftapi/core/admin/session.py +154 -0
- swiftapi/core/admin/views.py +2428 -0
- swiftapi/core/cache/__init__.py +0 -0
- swiftapi/core/cache/base.py +29 -0
- swiftapi/core/cache/decorators.py +51 -0
- swiftapi/core/cache/factory.py +30 -0
- swiftapi/core/cache/keys.py +24 -0
- swiftapi/core/cache/memory.py +60 -0
- swiftapi/core/cache/null.py +28 -0
- swiftapi/core/cache/redis.py +50 -0
- swiftapi/core/container.py +209 -0
- swiftapi/core/db/__init__.py +0 -0
- swiftapi/core/db/base_model.py +122 -0
- swiftapi/core/db/crud.py +242 -0
- swiftapi/core/db/dialects/__init__.py +8 -0
- swiftapi/core/db/dialects/base.py +106 -0
- swiftapi/core/db/dialects/mysql.py +47 -0
- swiftapi/core/db/dialects/pg.py +51 -0
- swiftapi/core/db/dialects/registry.py +30 -0
- swiftapi/core/db/dialects/sqlite.py +47 -0
- swiftapi/core/db/engine.py +209 -0
- swiftapi/core/db/health.py +84 -0
- swiftapi/core/db/migrate/__init__.py +1 -0
- swiftapi/core/db/migrate/ddl.py +162 -0
- swiftapi/core/db/migrate/render.py +84 -0
- swiftapi/core/db/migrate/runner.py +159 -0
- swiftapi/core/db/migrate/schema.py +248 -0
- swiftapi/core/db/mixins.py +53 -0
- swiftapi/core/db/session.py +54 -0
- swiftapi/core/db/snapshot.py +33 -0
- swiftapi/core/db/tenant_model.py +43 -0
- swiftapi/core/db/tenant_router.py +114 -0
- swiftapi/core/db/types.py +109 -0
- swiftapi/core/db/unit_of_work.py +65 -0
- swiftapi/core/docs/__init__.py +0 -0
- swiftapi/core/docs/router.py +26 -0
- swiftapi/core/docs/tsgen.py +93 -0
- swiftapi/core/docs/ui.py +132 -0
- swiftapi/core/errors/__init__.py +0 -0
- swiftapi/core/errors/base.py +168 -0
- swiftapi/core/errors/codes.py +117 -0
- swiftapi/core/errors/handlers.py +155 -0
- swiftapi/core/errors/problem.py +58 -0
- swiftapi/core/errors/validation.py +11 -0
- swiftapi/core/framework_models.py +22 -0
- swiftapi/core/http/__init__.py +47 -0
- swiftapi/core/http/app.py +247 -0
- swiftapi/core/http/cors.py +100 -0
- swiftapi/core/http/idempotency.py +148 -0
- swiftapi/core/http/middleware/__init__.py +82 -0
- swiftapi/core/http/middleware/access_log.py +57 -0
- swiftapi/core/http/middleware/auth.py +105 -0
- swiftapi/core/http/middleware/body_limit.py +76 -0
- swiftapi/core/http/middleware/rate_limit.py +103 -0
- swiftapi/core/http/middleware/request_body.py +122 -0
- swiftapi/core/http/middleware/request_id.py +46 -0
- swiftapi/core/http/middleware/security_headers.py +46 -0
- swiftapi/core/http/middleware/tenant.py +93 -0
- swiftapi/core/http/middleware/timing.py +57 -0
- swiftapi/core/http/multipart.py +116 -0
- swiftapi/core/http/multipart_stream.py +216 -0
- swiftapi/core/http/openapi.py +148 -0
- swiftapi/core/http/pagination.py +55 -0
- swiftapi/core/http/params.py +302 -0
- swiftapi/core/http/request.py +145 -0
- swiftapi/core/http/responses.py +127 -0
- swiftapi/core/http/routing.py +200 -0
- swiftapi/core/http/types.py +86 -0
- swiftapi/core/http/uploads.py +222 -0
- swiftapi/core/messaging/__init__.py +0 -0
- swiftapi/core/messaging/base.py +33 -0
- swiftapi/core/messaging/consumer.py +57 -0
- swiftapi/core/messaging/factory.py +30 -0
- swiftapi/core/messaging/idempotency.py +61 -0
- swiftapi/core/messaging/inprocess.py +30 -0
- swiftapi/core/messaging/outbox.py +106 -0
- swiftapi/core/messaging/rabbitmq.py +186 -0
- swiftapi/core/messaging/relay.py +151 -0
- swiftapi/core/messaging/streams.py +141 -0
- swiftapi/core/observability/__init__.py +0 -0
- swiftapi/core/observability/archive.py +136 -0
- swiftapi/core/observability/context.py +102 -0
- swiftapi/core/observability/logging.py +192 -0
- swiftapi/core/observability/masking.py +74 -0
- swiftapi/core/observability/metrics.py +101 -0
- swiftapi/core/observability/volume.py +67 -0
- swiftapi/core/resilience/__init__.py +0 -0
- swiftapi/core/resilience/bulkhead.py +50 -0
- swiftapi/core/resilience/circuit_breaker.py +97 -0
- swiftapi/core/resilience/client.py +179 -0
- swiftapi/core/resilience/retry.py +59 -0
- swiftapi/core/security/__init__.py +0 -0
- swiftapi/core/security/jwt.py +78 -0
- swiftapi/core/security/principal.py +78 -0
- swiftapi/core/tenant/__init__.py +1 -0
- swiftapi/core/tenant/catalog.py +89 -0
- swiftapi/core/tenant/context.py +75 -0
- swiftapi/core/tenant/isolation.py +48 -0
- swiftapi/core/tenant/resolver.py +48 -0
- swiftapi/core/validation/__init__.py +0 -0
- swiftapi/core/validation/base.py +32 -0
- swiftapi/db.py +50 -0
- swiftapi/modules/__init__.py +0 -0
- swiftapi/modules/users/__init__.py +11 -0
- swiftapi/modules/users/api/__init__.py +0 -0
- swiftapi/modules/users/api/users.py +110 -0
- swiftapi/modules/users/crud/__init__.py +0 -0
- swiftapi/modules/users/crud/user.py +23 -0
- swiftapi/modules/users/errors.py +24 -0
- swiftapi/modules/users/mappers.py +19 -0
- swiftapi/modules/users/model/__init__.py +0 -0
- swiftapi/modules/users/model/user.py +37 -0
- swiftapi/modules/users/policies.py +19 -0
- swiftapi/modules/users/schema/__init__.py +0 -0
- swiftapi/modules/users/schema/user.py +40 -0
- swiftapi/modules/users/service/__init__.py +0 -0
- swiftapi/modules/users/service/user.py +107 -0
- swiftapi/py.typed +0 -0
- swiftapi/templates/__init__.py +0 -0
- swiftapi/templates/app_skeleton/README.md +17 -0
- swiftapi/templates/app_skeleton/__init__.py +1 -0
- swiftapi/templates/app_skeleton/api/__init__.py +23 -0
- swiftapi/templates/app_skeleton/api/health.py +12 -0
- swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
- swiftapi/templates/app_skeleton/model/__init__.py +1 -0
- swiftapi/templates/app_skeleton/router.py +16 -0
- swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
- swiftapi/templates/app_skeleton/service/__init__.py +1 -0
- swiftapi/templates/project/__init__.py +0 -0
- swiftapi/templates/project/api.py +135 -0
- swiftapi/templates/project/app.py +57 -0
- swiftapi/templates/project/endpoints/__init__.py +25 -0
- swiftapi/templates/project/events.py +43 -0
- swiftapi/templates/project/models.py +79 -0
- swiftapi/templates/project/resources/__init__.py +35 -0
- swiftapi/templates/project/schemas.py +45 -0
- swiftapi/templates/project/service.py +125 -0
- swiftapi/templates/project/settings.py +17 -0
- swiftapi/templates/project_skeleton/.env.example +5 -0
- swiftapi/templates/project_skeleton/.gitignore +6 -0
- swiftapi/templates/project_skeleton/README.md +25 -0
- swiftapi/templates/project_skeleton/__init__.py +1 -0
- swiftapi/templates/project_skeleton/app.py +26 -0
- swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
- swiftapi/templates/project_skeleton/common/__init__.py +4 -0
- swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
- swiftapi/templates/project_skeleton/conf/settings.py +73 -0
- swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
- swiftapi/templates/project_skeleton/models.py +12 -0
- swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
- swiftapi/templates/project_skeleton/router.py +46 -0
- swiftapi/templates/project_skeleton/script/start.sh +13 -0
- swiftapi/templates/project_skeleton/start.py +35 -0
- swiftapi/version.py +8 -0
- swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
- swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
- swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
- swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
- swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
|
File without changes
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""缓存后端协议:业务只依赖这 5 个方法。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TTLPrecision(StrEnum):
|
|
10
|
+
EXACT = "exact" # Redis / 内存
|
|
11
|
+
EVENTUAL = "eventual" # Mongo TTL 索引(分钟后过期)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CacheBackend(Protocol):
|
|
15
|
+
name: str
|
|
16
|
+
ttl_precision: TTLPrecision
|
|
17
|
+
|
|
18
|
+
async def get(self, key: str) -> bytes | None: ...
|
|
19
|
+
|
|
20
|
+
async def set(self, key: str, value: bytes, ttl_s: int | None = None) -> None: ...
|
|
21
|
+
|
|
22
|
+
async def delete(self, *keys: str) -> int: ...
|
|
23
|
+
|
|
24
|
+
async def incr(self, key: str, ttl_s: int) -> int: ...
|
|
25
|
+
|
|
26
|
+
async def close(self) -> None: ...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
__all__ = ["CacheBackend", "TTLPrecision"]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""读穿缓存 + 单飞(singleflight),防止缓存击穿。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import Awaitable, Callable
|
|
7
|
+
from typing import TypeVar
|
|
8
|
+
|
|
9
|
+
from swiftapi.core.cache.base import CacheBackend
|
|
10
|
+
|
|
11
|
+
T = TypeVar("T")
|
|
12
|
+
|
|
13
|
+
_inflight: dict[str, asyncio.Future[bytes]] = {}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def cached(
|
|
17
|
+
cache: CacheBackend,
|
|
18
|
+
key: str,
|
|
19
|
+
loader: Callable[[], Awaitable[bytes]],
|
|
20
|
+
*,
|
|
21
|
+
ttl_s: int | None = None,
|
|
22
|
+
) -> bytes:
|
|
23
|
+
"""缓存命中直接返回;未命中时**同一 key 只允许一次回源**。"""
|
|
24
|
+
hit = await cache.get(key)
|
|
25
|
+
if hit is not None:
|
|
26
|
+
return hit
|
|
27
|
+
|
|
28
|
+
existing = _inflight.get(key)
|
|
29
|
+
if existing is not None:
|
|
30
|
+
return await existing
|
|
31
|
+
|
|
32
|
+
loop = asyncio.get_running_loop()
|
|
33
|
+
future: asyncio.Future[bytes] = loop.create_future()
|
|
34
|
+
_inflight[key] = future
|
|
35
|
+
try:
|
|
36
|
+
value = await loader()
|
|
37
|
+
await cache.set(key, value, ttl_s)
|
|
38
|
+
if not future.done():
|
|
39
|
+
future.set_result(value)
|
|
40
|
+
return value
|
|
41
|
+
except BaseException as exc:
|
|
42
|
+
if not future.done():
|
|
43
|
+
future.set_exception(exc)
|
|
44
|
+
# 标记为已取回:没有跟随者时避免 "Future exception was never retrieved"
|
|
45
|
+
future.exception()
|
|
46
|
+
raise
|
|
47
|
+
finally:
|
|
48
|
+
_inflight.pop(key, None)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
__all__ = ["cached"]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""按配置选缓存后端:工厂是唯一的"选实现"入口。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from swiftapi.config.settings import CacheBackend as CacheBackendSetting
|
|
6
|
+
from swiftapi.config.settings import Settings
|
|
7
|
+
from swiftapi.core.cache.base import CacheBackend
|
|
8
|
+
from swiftapi.core.cache.memory import MemoryCache
|
|
9
|
+
from swiftapi.core.cache.null import NullCache
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def create_cache(settings: Settings) -> CacheBackend:
|
|
13
|
+
if not settings.cache.enabled:
|
|
14
|
+
return NullCache()
|
|
15
|
+
if settings.cache.backend is CacheBackendSetting.MEMORY:
|
|
16
|
+
return MemoryCache()
|
|
17
|
+
if settings.cache.backend is CacheBackendSetting.REDIS:
|
|
18
|
+
from swiftapi.core.cache.redis import RedisCache
|
|
19
|
+
|
|
20
|
+
assert settings.cache.url is not None # 启动校验已保证
|
|
21
|
+
return RedisCache(
|
|
22
|
+
settings.cache.url.get_secret_value(),
|
|
23
|
+
max_connections=settings.cache.max_connections,
|
|
24
|
+
)
|
|
25
|
+
if settings.cache.backend is CacheBackendSetting.MONGODB:
|
|
26
|
+
raise NotImplementedError("Mongo 缓存后端在 P4.1 提供(TTL 精度为 eventual)")
|
|
27
|
+
return NullCache()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
__all__ = ["create_cache"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""缓存 key 规范:{namespace}:v1:{tenant}:{module}:{entity}:{id}:{variant}
|
|
2
|
+
|
|
3
|
+
租户维度必须在前缀里——否则 A 租户会读到 B 租户的缓存。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from swiftapi.core.tenant.context import current_tenant
|
|
9
|
+
|
|
10
|
+
VERSION = "v1"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def cache_key(module: str, entity: str, ident: str | None = None, variant: str = "default") -> str:
|
|
14
|
+
parts = [VERSION, module, entity]
|
|
15
|
+
if ident:
|
|
16
|
+
parts.append(str(ident))
|
|
17
|
+
parts.append(variant)
|
|
18
|
+
tenant = current_tenant()
|
|
19
|
+
if tenant is not None:
|
|
20
|
+
parts.insert(0, f"t:{tenant.id}")
|
|
21
|
+
return ":".join(parts)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
__all__ = ["cache_key"]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""进程内缓存:本地开发与单测默认后端(生产禁用,多副本不一致)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from swiftapi.core.cache.base import TTLPrecision
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MemoryCache:
|
|
12
|
+
name = "memory"
|
|
13
|
+
ttl_precision = TTLPrecision.EXACT
|
|
14
|
+
|
|
15
|
+
def __init__(self) -> None:
|
|
16
|
+
self._data: dict[str, tuple[float | None, bytes]] = {}
|
|
17
|
+
self._lock = asyncio.Lock()
|
|
18
|
+
|
|
19
|
+
def _expired(self, key: str) -> bool:
|
|
20
|
+
entry = self._data.get(key)
|
|
21
|
+
if entry is None:
|
|
22
|
+
return True
|
|
23
|
+
expires_at, _ = entry
|
|
24
|
+
if expires_at is None:
|
|
25
|
+
return False
|
|
26
|
+
if expires_at <= time.monotonic():
|
|
27
|
+
self._data.pop(key, None)
|
|
28
|
+
return True
|
|
29
|
+
return False
|
|
30
|
+
|
|
31
|
+
async def get(self, key: str) -> bytes | None:
|
|
32
|
+
async with self._lock:
|
|
33
|
+
if self._expired(key):
|
|
34
|
+
return None
|
|
35
|
+
return self._data[key][1]
|
|
36
|
+
|
|
37
|
+
async def set(self, key: str, value: bytes, ttl_s: int | None = None) -> None:
|
|
38
|
+
async with self._lock:
|
|
39
|
+
expires_at = time.monotonic() + ttl_s if ttl_s else None
|
|
40
|
+
self._data[key] = (expires_at, value)
|
|
41
|
+
|
|
42
|
+
async def delete(self, *keys: str) -> int:
|
|
43
|
+
async with self._lock:
|
|
44
|
+
return sum(1 for key in keys if self._data.pop(key, None) is not None)
|
|
45
|
+
|
|
46
|
+
async def incr(self, key: str, ttl_s: int) -> int:
|
|
47
|
+
async with self._lock:
|
|
48
|
+
current = 0 if self._expired(key) else int(self._data[key][1])
|
|
49
|
+
value = current + 1
|
|
50
|
+
self._data[key] = (time.monotonic() + ttl_s, str(value).encode())
|
|
51
|
+
return value
|
|
52
|
+
|
|
53
|
+
async def close(self) -> None:
|
|
54
|
+
self._data.clear()
|
|
55
|
+
|
|
56
|
+
async def clear(self) -> None:
|
|
57
|
+
await self.close()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = ["MemoryCache"]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""空缓存:缓存关闭时的实现(调用方无需写 if cache.enabled)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from swiftapi.core.cache.base import TTLPrecision
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NullCache:
|
|
9
|
+
name = "disabled"
|
|
10
|
+
ttl_precision = TTLPrecision.EXACT
|
|
11
|
+
|
|
12
|
+
async def get(self, key: str) -> bytes | None:
|
|
13
|
+
return None
|
|
14
|
+
|
|
15
|
+
async def set(self, key: str, value: bytes, ttl_s: int | None = None) -> None:
|
|
16
|
+
return None
|
|
17
|
+
|
|
18
|
+
async def delete(self, *keys: str) -> int:
|
|
19
|
+
return 0
|
|
20
|
+
|
|
21
|
+
async def incr(self, key: str, ttl_s: int) -> int:
|
|
22
|
+
return 1
|
|
23
|
+
|
|
24
|
+
async def close(self) -> None:
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
__all__ = ["NullCache"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Redis 缓存:精确 TTL + 原子自增(限流令牌桶的基础)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from swiftapi.core.cache.base import TTLPrecision
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RedisCache:
|
|
11
|
+
name = "redis"
|
|
12
|
+
ttl_precision = TTLPrecision.EXACT
|
|
13
|
+
|
|
14
|
+
def __init__(self, url: str, *, max_connections: int = 20, client: Any = None) -> None:
|
|
15
|
+
self._client: Any
|
|
16
|
+
if client is not None:
|
|
17
|
+
self._client = client
|
|
18
|
+
return
|
|
19
|
+
try:
|
|
20
|
+
from redis.asyncio import Redis
|
|
21
|
+
except ImportError as exc: # pragma: no cover - 取决于可选依赖
|
|
22
|
+
raise RuntimeError(
|
|
23
|
+
"cache.backend=redis 需要安装 redis:uv pip install 'swiftapi[cache]'"
|
|
24
|
+
) from exc
|
|
25
|
+
self._client = Redis.from_url(
|
|
26
|
+
url, max_connections=max_connections, decode_responses=False
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
async def get(self, key: str) -> bytes | None:
|
|
30
|
+
value: bytes | None = await self._client.get(key)
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
async def set(self, key: str, value: bytes, ttl_s: int | None = None) -> None:
|
|
34
|
+
await self._client.set(key, value, ex=ttl_s)
|
|
35
|
+
|
|
36
|
+
async def delete(self, *keys: str) -> int:
|
|
37
|
+
return int(await self._client.delete(*keys))
|
|
38
|
+
|
|
39
|
+
async def incr(self, key: str, ttl_s: int) -> int:
|
|
40
|
+
pipeline = self._client.pipeline()
|
|
41
|
+
pipeline.incr(key)
|
|
42
|
+
pipeline.expire(key, ttl_s, nx=True)
|
|
43
|
+
value, _ = await pipeline.execute()
|
|
44
|
+
return int(value)
|
|
45
|
+
|
|
46
|
+
async def close(self) -> None:
|
|
47
|
+
await self._client.aclose()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
__all__ = ["RedisCache"]
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""显式依赖注入容器(架构文档 §11.2)。
|
|
2
|
+
|
|
3
|
+
核心保证:**依赖图在启动期校验**——缺 provider、循环依赖、作用域倒挂
|
|
4
|
+
都会让进程直接拒绝启动,而不是等到第一次请求才炸。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
from collections.abc import Awaitable, Callable, Iterator
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from enum import StrEnum
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
Factory = Callable[..., Awaitable[Any]]
|
|
16
|
+
Closer = Callable[[], Awaitable[None]]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Scope(StrEnum):
|
|
20
|
+
"""对象生命周期。"""
|
|
21
|
+
|
|
22
|
+
SINGLETON = "singleton" # 进程级,禁止持有请求态
|
|
23
|
+
REQUEST = "request" # 一次请求一个实例
|
|
24
|
+
TRANSIENT = "transient" # 每次解析都新建
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ContainerError(RuntimeError):
|
|
28
|
+
"""依赖图非法(缺失 / 环 / 作用域倒挂 / 重复注册 / 冻结后注册)。"""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class Provider:
|
|
33
|
+
key: str
|
|
34
|
+
factory: Factory
|
|
35
|
+
scope: Scope = Scope.SINGLETON
|
|
36
|
+
deps: tuple[str, ...] = ()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class RequestScope:
|
|
41
|
+
"""请求作用域:缓存 + 关闭钩子,由 lifespan/依赖结束时回收。"""
|
|
42
|
+
|
|
43
|
+
cache: dict[str, Any] = field(default_factory=dict)
|
|
44
|
+
closers: list[Closer] = field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
def add_closer(self, closer: Closer) -> None:
|
|
47
|
+
self.closers.append(closer)
|
|
48
|
+
|
|
49
|
+
async def close(self) -> None:
|
|
50
|
+
while self.closers:
|
|
51
|
+
closer = self.closers.pop()
|
|
52
|
+
with contextlib.suppress(Exception): # 关闭失败不应影响其他资源
|
|
53
|
+
await closer()
|
|
54
|
+
self.cache.clear()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Container:
|
|
58
|
+
"""注册 → 校验 → 解析。校验之后图冻结(seal),运行期不可再改。"""
|
|
59
|
+
|
|
60
|
+
def __init__(self) -> None:
|
|
61
|
+
self._providers: dict[str, Provider] = {}
|
|
62
|
+
self._instances: dict[str, Any] = {}
|
|
63
|
+
self._sealed = False
|
|
64
|
+
self._singleton_closers: list[Closer] = []
|
|
65
|
+
|
|
66
|
+
# ---------------- 注册 ----------------
|
|
67
|
+
|
|
68
|
+
def register(self, provider: Provider) -> None:
|
|
69
|
+
if self._sealed:
|
|
70
|
+
raise ContainerError(f'容器已冻结,无法注册 "{provider.key}"')
|
|
71
|
+
if provider.key in self._providers:
|
|
72
|
+
raise ContainerError(f'provider 重复注册: "{provider.key}"')
|
|
73
|
+
self._providers[provider.key] = provider
|
|
74
|
+
|
|
75
|
+
def register_value(self, key: str, value: Any) -> None:
|
|
76
|
+
async def _factory() -> Any:
|
|
77
|
+
return value
|
|
78
|
+
|
|
79
|
+
self.register(Provider(key=key, factory=_factory, scope=Scope.SINGLETON))
|
|
80
|
+
|
|
81
|
+
@contextlib.contextmanager
|
|
82
|
+
def override(self, key: str, factory: Factory) -> Iterator[None]:
|
|
83
|
+
"""测试替换:退出上下文即还原(不改变已构建的实例缓存)。"""
|
|
84
|
+
previous = self._providers.get(key)
|
|
85
|
+
was_sealed = self._sealed
|
|
86
|
+
self._sealed = False
|
|
87
|
+
self._providers[key] = Provider(key=key, factory=factory, scope=Scope.TRANSIENT)
|
|
88
|
+
try:
|
|
89
|
+
yield
|
|
90
|
+
finally:
|
|
91
|
+
if previous is not None:
|
|
92
|
+
self._providers[key] = previous
|
|
93
|
+
else:
|
|
94
|
+
self._providers.pop(key, None)
|
|
95
|
+
self._sealed = was_sealed
|
|
96
|
+
|
|
97
|
+
# ---------------- 查询 ----------------
|
|
98
|
+
|
|
99
|
+
def __contains__(self, key: str) -> bool:
|
|
100
|
+
return key in self._providers
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def keys(self) -> tuple[str, ...]:
|
|
104
|
+
return tuple(self._providers)
|
|
105
|
+
|
|
106
|
+
def provider(self, key: str) -> Provider:
|
|
107
|
+
try:
|
|
108
|
+
return self._providers[key]
|
|
109
|
+
except KeyError as exc:
|
|
110
|
+
raise ContainerError(f'未注册的 provider: "{key}"') from exc
|
|
111
|
+
|
|
112
|
+
# ---------------- 校验 ----------------
|
|
113
|
+
|
|
114
|
+
def seal(self) -> None:
|
|
115
|
+
"""校验并冻结依赖图。启动期调用,失败即拒绝启动。"""
|
|
116
|
+
self.validate()
|
|
117
|
+
self._sealed = True
|
|
118
|
+
|
|
119
|
+
def validate(self) -> None:
|
|
120
|
+
self._check_missing()
|
|
121
|
+
self._check_cycles()
|
|
122
|
+
self._check_scope_inversion()
|
|
123
|
+
|
|
124
|
+
def _check_missing(self) -> None:
|
|
125
|
+
problems: list[str] = []
|
|
126
|
+
for key, provider in self._providers.items():
|
|
127
|
+
for dep in provider.deps:
|
|
128
|
+
if dep not in self._providers:
|
|
129
|
+
problems.append(f' ✗ 缺失 provider: "{dep}"(被 "{key}" 依赖)')
|
|
130
|
+
if problems:
|
|
131
|
+
raise ContainerError("依赖图不完整:\n" + "\n".join(sorted(problems)))
|
|
132
|
+
|
|
133
|
+
def _check_cycles(self) -> None:
|
|
134
|
+
visiting: set[str] = set()
|
|
135
|
+
done: set[str] = set()
|
|
136
|
+
stack: list[str] = []
|
|
137
|
+
|
|
138
|
+
def walk(key: str) -> None:
|
|
139
|
+
if key in done:
|
|
140
|
+
return
|
|
141
|
+
if key in visiting:
|
|
142
|
+
cycle = [*stack[stack.index(key) :], key]
|
|
143
|
+
raise ContainerError("检测到循环依赖:\n " + " → ".join(cycle))
|
|
144
|
+
visiting.add(key)
|
|
145
|
+
stack.append(key)
|
|
146
|
+
for dep in self._providers[key].deps:
|
|
147
|
+
if dep in self._providers:
|
|
148
|
+
walk(dep)
|
|
149
|
+
stack.pop()
|
|
150
|
+
visiting.discard(key)
|
|
151
|
+
done.add(key)
|
|
152
|
+
|
|
153
|
+
for key in self._providers:
|
|
154
|
+
walk(key)
|
|
155
|
+
|
|
156
|
+
def _check_scope_inversion(self) -> None:
|
|
157
|
+
problems: list[str] = []
|
|
158
|
+
|
|
159
|
+
def walk(key: str, path: list[str]) -> None:
|
|
160
|
+
provider = self._providers[key]
|
|
161
|
+
for dep in provider.deps:
|
|
162
|
+
if dep not in self._providers:
|
|
163
|
+
continue
|
|
164
|
+
dep_provider = self._providers[dep]
|
|
165
|
+
if dep_provider.scope is Scope.REQUEST:
|
|
166
|
+
problems.append(
|
|
167
|
+
f' ✗ 作用域倒挂: {provider.scope.value} 级 "{key}" 依赖了 '
|
|
168
|
+
f'request 级 "{dep}"(路径: {" → ".join([*path, key, dep])})'
|
|
169
|
+
)
|
|
170
|
+
walk(dep, [*path, key])
|
|
171
|
+
|
|
172
|
+
for key, provider in self._providers.items():
|
|
173
|
+
if provider.scope is Scope.SINGLETON:
|
|
174
|
+
walk(key, [])
|
|
175
|
+
|
|
176
|
+
if problems:
|
|
177
|
+
raise ContainerError("作用域校验失败:\n" + "\n".join(sorted(set(problems))))
|
|
178
|
+
|
|
179
|
+
# ---------------- 解析 ----------------
|
|
180
|
+
|
|
181
|
+
async def resolve(self, key: str, scope: RequestScope) -> Any:
|
|
182
|
+
provider = self.provider(key)
|
|
183
|
+
if provider.scope is Scope.SINGLETON and key in self._instances:
|
|
184
|
+
return self._instances[key]
|
|
185
|
+
if provider.scope is Scope.REQUEST and key in scope.cache:
|
|
186
|
+
return scope.cache[key]
|
|
187
|
+
|
|
188
|
+
kwargs = {dep: await self.resolve(dep, scope) for dep in provider.deps}
|
|
189
|
+
instance = await provider.factory(**kwargs)
|
|
190
|
+
|
|
191
|
+
if provider.scope is Scope.SINGLETON:
|
|
192
|
+
self._instances[key] = instance
|
|
193
|
+
closer = getattr(instance, "aclose", None)
|
|
194
|
+
if callable(closer):
|
|
195
|
+
self._singleton_closers.append(closer)
|
|
196
|
+
elif provider.scope is Scope.REQUEST:
|
|
197
|
+
scope.cache[key] = instance
|
|
198
|
+
closer = getattr(instance, "aclose", None)
|
|
199
|
+
if callable(closer):
|
|
200
|
+
scope.add_closer(closer)
|
|
201
|
+
return instance
|
|
202
|
+
|
|
203
|
+
async def aclose(self) -> None:
|
|
204
|
+
"""关闭所有单例(需自行实现 `aclose`)。"""
|
|
205
|
+
while self._singleton_closers:
|
|
206
|
+
closer = self._singleton_closers.pop()
|
|
207
|
+
with contextlib.suppress(Exception):
|
|
208
|
+
await closer()
|
|
209
|
+
self._instances.clear()
|
|
File without changes
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""`BaseModel`:通用 ORM 基类(**用户可直接导入使用**)。
|
|
2
|
+
|
|
3
|
+
与 `TenantScopedModel` 的分工见架构文档 §17.5:
|
|
4
|
+
- 本类不感知租户,任何表都可以继承;
|
|
5
|
+
- 租户表继承 `TenantScopedModel`(它再加 tenant_id 与自动过滤)。
|
|
6
|
+
|
|
7
|
+
约束:
|
|
8
|
+
- 禁止直接继承 `sqlalchemy.orm.DeclarativeBase`(ruff banned-api 已拦截);
|
|
9
|
+
- 禁止在模型文件里手写 `Table(...)` 或调用 `create_all()`。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from decimal import Decimal
|
|
16
|
+
from typing import Any, ClassVar
|
|
17
|
+
|
|
18
|
+
from sqlalchemy import JSON, DateTime, MetaData, Numeric, Uuid
|
|
19
|
+
from sqlalchemy.orm import DeclarativeBase
|
|
20
|
+
|
|
21
|
+
from swiftapi.core.db.snapshot import ColumnSnapshot, TableSnapshot
|
|
22
|
+
|
|
23
|
+
NAMING_CONVENTION: dict[str, str] = {
|
|
24
|
+
"ix": "ix_%(table_name)s_%(column_0_name)s",
|
|
25
|
+
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
|
26
|
+
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
|
27
|
+
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
|
28
|
+
"pk": "pk_%(table_name)s",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class BaseModel(DeclarativeBase):
|
|
33
|
+
"""所有业务表的根基类。抽象类,不映射任何表。"""
|
|
34
|
+
|
|
35
|
+
__abstract__ = True
|
|
36
|
+
|
|
37
|
+
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
|
38
|
+
|
|
39
|
+
# 统一类型推导:`Mapped[dict]` 自动落 JSON,`Mapped[datetime]` 自动带时区
|
|
40
|
+
type_annotation_map: ClassVar[dict[Any, Any]] = {
|
|
41
|
+
dict[str, Any]: JSON,
|
|
42
|
+
list[str]: JSON,
|
|
43
|
+
datetime: DateTime(timezone=True),
|
|
44
|
+
Decimal: Numeric(18, 6),
|
|
45
|
+
"UUID": Uuid(as_uuid=True),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
# 命名空间:PG 上是 schema,MySQL/SQLite 上由适配器映射为表前缀(§16.6)
|
|
49
|
+
__module_schema__: ClassVar[str] = "public"
|
|
50
|
+
__tenant_scoped__: ClassVar[bool] = False
|
|
51
|
+
__allow_tenant_column__: ClassVar[bool] = False
|
|
52
|
+
|
|
53
|
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
|
54
|
+
# 必须在 super() 之前检查:SQLAlchemy 的声明式映射会把继承来的列写进 cls.__dict__
|
|
55
|
+
declared = set(cls.__dict__)
|
|
56
|
+
is_abstract = bool(cls.__dict__.get("__abstract__", False))
|
|
57
|
+
tenant_scoped = bool(cls.__tenant_scoped__)
|
|
58
|
+
allow_tenant_column = bool(cls.__allow_tenant_column__)
|
|
59
|
+
if not is_abstract and "tenant_id" in declared:
|
|
60
|
+
if tenant_scoped:
|
|
61
|
+
raise TypeError(
|
|
62
|
+
f"{cls.__name__} 继承自 TenantScopedModel,tenant_id 由基类提供,"
|
|
63
|
+
"请删除重复声明"
|
|
64
|
+
)
|
|
65
|
+
if not allow_tenant_column:
|
|
66
|
+
raise TypeError(
|
|
67
|
+
f"{cls.__name__} 是非租户模型,禁止声明 tenant_id;"
|
|
68
|
+
"如需记录租户维度但允许跨租户查询,"
|
|
69
|
+
"请显式设置 __allow_tenant_column__ = True"
|
|
70
|
+
)
|
|
71
|
+
super().__init_subclass__(**kwargs)
|
|
72
|
+
# 命名空间写进 Table.info:迁移引擎按它决定 schema / 表前缀(§16.6)
|
|
73
|
+
table = cls.__dict__.get("__table__")
|
|
74
|
+
if table is not None:
|
|
75
|
+
table.info["module_schema"] = str(cls.__module_schema__)
|
|
76
|
+
|
|
77
|
+
@classmethod
|
|
78
|
+
def namespace(cls) -> str:
|
|
79
|
+
return cls.__module_schema__
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def table_name(cls) -> str:
|
|
83
|
+
name = cls.__dict__.get("__tablename__")
|
|
84
|
+
if not isinstance(name, str):
|
|
85
|
+
raise TypeError(f"{cls.__name__} 未声明 __tablename__")
|
|
86
|
+
return name
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def qualified_name(cls) -> str:
|
|
90
|
+
"""逻辑限定名:`users.user`。物理落点由方言适配器决定。"""
|
|
91
|
+
return f"{cls.namespace()}.{cls.table_name()}"
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def __snapshot__(cls) -> TableSnapshot:
|
|
95
|
+
"""结构快照:迁移引擎与 `db check` 的唯一输入。"""
|
|
96
|
+
table = getattr(cls, "__table__", None)
|
|
97
|
+
if table is None:
|
|
98
|
+
raise TypeError(f"{cls.__name__} 不是映射类,无法生成快照")
|
|
99
|
+
|
|
100
|
+
columns = tuple(
|
|
101
|
+
ColumnSnapshot(
|
|
102
|
+
name=column.name,
|
|
103
|
+
type=str(column.type),
|
|
104
|
+
nullable=bool(column.nullable),
|
|
105
|
+
primary_key=bool(column.primary_key),
|
|
106
|
+
has_default=column.default is not None or column.server_default is not None,
|
|
107
|
+
)
|
|
108
|
+
for column in table.columns
|
|
109
|
+
)
|
|
110
|
+
indexes = tuple(sorted(index.name for index in table.indexes if index.name))
|
|
111
|
+
uniques = tuple(
|
|
112
|
+
sorted(constraint.name for constraint in table.constraints if constraint.name)
|
|
113
|
+
)
|
|
114
|
+
return TableSnapshot(
|
|
115
|
+
namespace=cls.namespace(),
|
|
116
|
+
name=cls.table_name(),
|
|
117
|
+
qualified_name=cls.qualified_name(),
|
|
118
|
+
tenant_scoped=cls.__tenant_scoped__,
|
|
119
|
+
columns=columns,
|
|
120
|
+
indexes=indexes,
|
|
121
|
+
unique_constraints=uniques,
|
|
122
|
+
)
|