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
swiftapi/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""SwiftAPI:异步微服务工程内核。
|
|
2
|
+
|
|
3
|
+
包导入保持**零副作用**:`import swiftapi` 不会顺带加载路由、模型或数据库驱动。
|
|
4
|
+
需要 `create_app` / `build_app` 时按需解析(PEP 562 延迟导入)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from swiftapi.config.settings import Settings, load_settings
|
|
12
|
+
from swiftapi.version import __version__
|
|
13
|
+
|
|
14
|
+
__all__ = ["Settings", "__version__", "build_app", "create_app", "load_settings"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def __getattr__(name: str) -> Any:
|
|
18
|
+
if name in {"build_app", "create_app"}:
|
|
19
|
+
from swiftapi.app import factory
|
|
20
|
+
|
|
21
|
+
return getattr(factory, name)
|
|
22
|
+
raise AttributeError(f"module 'swiftapi' has no attribute {name!r}")
|
swiftapi/app/__init__.py
ADDED
|
File without changes
|
swiftapi/app/factory.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""应用装配:全项目唯一的 `create_app()` 入口(架构文档 §6.1)。
|
|
2
|
+
|
|
3
|
+
装配顺序固定:配置 → 日志 → 容器 → 中间件 → 异常处理 → 路由。
|
|
4
|
+
任何一步失败都必须在启动期暴露,不做"先跑起来再说"。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from swiftapi.app.lifespan import build_lifespan
|
|
12
|
+
from swiftapi.app.routers import build_system_router
|
|
13
|
+
from swiftapi.config.settings import Settings, SettingsError, load_settings
|
|
14
|
+
from swiftapi.core.admin.registry import AdminModel, AdminRegistry
|
|
15
|
+
from swiftapi.core.admin.views import build_admin_router
|
|
16
|
+
from swiftapi.core.cache.factory import create_cache
|
|
17
|
+
from swiftapi.core.container import Container, Provider, Scope
|
|
18
|
+
from swiftapi.core.db.engine import Database, create_database, ping
|
|
19
|
+
from swiftapi.core.db.health import HealthRegistry
|
|
20
|
+
from swiftapi.core.db.tenant_router import TenantDatabaseRouter
|
|
21
|
+
from swiftapi.core.db.unit_of_work import UnitOfWork
|
|
22
|
+
from swiftapi.core.docs.router import build_docs_router
|
|
23
|
+
from swiftapi.core.errors.handlers import register_exception_handlers
|
|
24
|
+
from swiftapi.core.http import App, Router
|
|
25
|
+
from swiftapi.core.http.middleware import install_default_middlewares
|
|
26
|
+
from swiftapi.core.messaging.factory import create_bus
|
|
27
|
+
from swiftapi.core.observability import metrics
|
|
28
|
+
from swiftapi.core.observability.logging import configure_logging, get_logger
|
|
29
|
+
from swiftapi.core.resilience.client import OutboundClient
|
|
30
|
+
from swiftapi.core.security.jwt import JwtVerifier
|
|
31
|
+
from swiftapi.core.tenant.catalog import StaticTenantCatalog
|
|
32
|
+
from swiftapi.core.tenant.isolation import install_tenant_isolation
|
|
33
|
+
from swiftapi.core.tenant.resolver import TenantResolverService
|
|
34
|
+
from swiftapi.modules.users import router as users_router
|
|
35
|
+
from swiftapi.modules.users.model.user import User
|
|
36
|
+
from swiftapi.modules.users.schema.user import UserUpdate
|
|
37
|
+
from swiftapi.version import __version__
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_container(
|
|
41
|
+
settings: Settings,
|
|
42
|
+
database: Database,
|
|
43
|
+
tenant_router: TenantDatabaseRouter | None = None,
|
|
44
|
+
) -> Container:
|
|
45
|
+
"""注册内核级 provider。业务模块的自有 provider 由应用自己注册。"""
|
|
46
|
+
container = Container()
|
|
47
|
+
container.register_value("settings", settings)
|
|
48
|
+
container.register_value("database", database)
|
|
49
|
+
router = tenant_router or TenantDatabaseRouter(database, settings)
|
|
50
|
+
container.register_value("tenant_router", router)
|
|
51
|
+
|
|
52
|
+
async def _make_uow(tenant_router: TenantDatabaseRouter) -> UnitOfWork:
|
|
53
|
+
from swiftapi.core.tenant.context import current_tenant
|
|
54
|
+
|
|
55
|
+
factory = await tenant_router.session_factory(current_tenant())
|
|
56
|
+
return UnitOfWork(factory)
|
|
57
|
+
|
|
58
|
+
container.register(
|
|
59
|
+
Provider(key="uow", factory=_make_uow, scope=Scope.REQUEST, deps=("tenant_router",))
|
|
60
|
+
)
|
|
61
|
+
return container
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _warn_config_mismatches(settings: Settings) -> None:
|
|
65
|
+
"""启动时把"配了但不会生效"的组合喊出来——比线上 413 好查得多。"""
|
|
66
|
+
logger = get_logger("swiftapi.config")
|
|
67
|
+
if settings.uploads.enabled and settings.uploads.max_bytes > settings.server.max_request_body_bytes:
|
|
68
|
+
logger.warning(
|
|
69
|
+
"config.upload_exceeds_body_limit",
|
|
70
|
+
upload_max_bytes=settings.uploads.max_bytes,
|
|
71
|
+
body_limit=settings.server.max_request_body_bytes,
|
|
72
|
+
hint="把 server.max_request_body_bytes 调到 >= uploads.max_bytes,否则大文件先被 413",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def build_app(
|
|
77
|
+
settings: Settings,
|
|
78
|
+
*,
|
|
79
|
+
extra_routers: tuple[Router, ...] = (),
|
|
80
|
+
include_builtin_modules: bool = True,
|
|
81
|
+
) -> App:
|
|
82
|
+
"""装配应用。
|
|
83
|
+
|
|
84
|
+
真实项目通常不需要内置示例模块:`include_users=False` + `extra_routers=(...)`。
|
|
85
|
+
(可行性验证发现的第一个 DX 问题:早期版本把 users 写死在工厂里。)
|
|
86
|
+
"""
|
|
87
|
+
configure_logging(settings)
|
|
88
|
+
_warn_config_mismatches(settings)
|
|
89
|
+
metrics.mark_info(version=__version__, env=settings.app.env.value)
|
|
90
|
+
|
|
91
|
+
database = create_database(settings)
|
|
92
|
+
tenant_router = TenantDatabaseRouter(database, settings)
|
|
93
|
+
container = build_container(settings, database, tenant_router)
|
|
94
|
+
health = HealthRegistry(timeout_s=1.0, cache_ttl_s=5.0)
|
|
95
|
+
|
|
96
|
+
async def _check_settings() -> None:
|
|
97
|
+
if not settings.app.name:
|
|
98
|
+
raise RuntimeError("app.name 为空")
|
|
99
|
+
|
|
100
|
+
async def _check_container() -> None:
|
|
101
|
+
if "settings" not in container:
|
|
102
|
+
raise RuntimeError("容器缺少 settings")
|
|
103
|
+
|
|
104
|
+
async def _check_database() -> None:
|
|
105
|
+
await ping(database)
|
|
106
|
+
|
|
107
|
+
health.register("settings", _check_settings)
|
|
108
|
+
health.register("container", _check_container)
|
|
109
|
+
health.register("database", _check_database)
|
|
110
|
+
# 单一实例:容器与 app.state 共享同一个 registry(禁止两处 new)
|
|
111
|
+
container.register_value("health", health)
|
|
112
|
+
|
|
113
|
+
app = App(
|
|
114
|
+
title=f"{settings.app.name} API",
|
|
115
|
+
version=__version__,
|
|
116
|
+
description="SwiftAPI —— 异步微服务工程内核",
|
|
117
|
+
openapi_url="/openapi.json",
|
|
118
|
+
lifespan=build_lifespan(settings, container, health),
|
|
119
|
+
container=container,
|
|
120
|
+
request_timeout_s=settings.server.request_timeout_s,
|
|
121
|
+
graceful_shutdown_timeout_s=settings.server.graceful_shutdown_timeout_s,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
app.state.settings = settings
|
|
125
|
+
app.state.database = database
|
|
126
|
+
app.state.tenant_router = tenant_router
|
|
127
|
+
app.state.outbound = OutboundClient.from_settings(settings)
|
|
128
|
+
app.state.container = container
|
|
129
|
+
app.state.health = health
|
|
130
|
+
|
|
131
|
+
cache = create_cache(settings)
|
|
132
|
+
bus = create_bus(settings)
|
|
133
|
+
app.state.bus = bus
|
|
134
|
+
container.register_value("bus", bus)
|
|
135
|
+
app.state.cache = cache
|
|
136
|
+
container.register_value("cache", cache)
|
|
137
|
+
|
|
138
|
+
verifier = None
|
|
139
|
+
if settings.security.jwt_public_key is not None or settings.security.jwt_private_key is not None:
|
|
140
|
+
verifier = JwtVerifier(settings)
|
|
141
|
+
|
|
142
|
+
catalog = StaticTenantCatalog(
|
|
143
|
+
strategy=settings.tenant.strategy,
|
|
144
|
+
schema_prefix=settings.tenant.schema_prefix,
|
|
145
|
+
database_url_template=(
|
|
146
|
+
settings.tenant.database_url_template.get_secret_value()
|
|
147
|
+
if settings.tenant.database_url_template is not None
|
|
148
|
+
else None
|
|
149
|
+
),
|
|
150
|
+
)
|
|
151
|
+
catalog.register(settings.tenant.default_slug)
|
|
152
|
+
app.state.tenant_catalog = catalog
|
|
153
|
+
|
|
154
|
+
install_default_middlewares(
|
|
155
|
+
app,
|
|
156
|
+
settings,
|
|
157
|
+
tenant_resolver=TenantResolverService(settings, catalog)
|
|
158
|
+
if settings.tenant.enabled
|
|
159
|
+
else None,
|
|
160
|
+
auth_verifier=verifier,
|
|
161
|
+
rate_limit_cache=cache,
|
|
162
|
+
)
|
|
163
|
+
install_tenant_isolation()
|
|
164
|
+
register_exception_handlers(app)
|
|
165
|
+
app.include_router(build_system_router(settings, health))
|
|
166
|
+
if include_builtin_modules:
|
|
167
|
+
app.include_router(users_router, prefix="/api/v1")
|
|
168
|
+
for router in extra_routers:
|
|
169
|
+
app.include_router(router, prefix="/api/v1")
|
|
170
|
+
if settings.docs.enabled:
|
|
171
|
+
app.include_router(build_docs_router(settings.docs, app.openapi))
|
|
172
|
+
|
|
173
|
+
# 后台只要 enabled 就挂载:模型由项目通过 app.state.admin_registry 注册。
|
|
174
|
+
# (内置 users 只在 include_builtin_modules=True 时自动注册,避免示例模块污染真实项目)
|
|
175
|
+
if settings.admin.enabled:
|
|
176
|
+
registry = AdminRegistry()
|
|
177
|
+
if include_builtin_modules:
|
|
178
|
+
registry.register(
|
|
179
|
+
AdminModel(
|
|
180
|
+
slug="users",
|
|
181
|
+
model=User,
|
|
182
|
+
form_schema=UserUpdate,
|
|
183
|
+
list_fields=("id", "email", "display_name", "status"),
|
|
184
|
+
search_field="email",
|
|
185
|
+
)
|
|
186
|
+
)
|
|
187
|
+
app.state.admin_registry = registry
|
|
188
|
+
app.include_router(build_admin_router(settings, registry, health=health))
|
|
189
|
+
return app
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def create_app(settings: Settings | None = None, settings_module: str | None = None) -> App:
|
|
193
|
+
"""ASGI 入口:`uvicorn --factory swiftapi.app.factory:create_app`。"""
|
|
194
|
+
try:
|
|
195
|
+
resolved = settings or load_settings(settings_module)
|
|
196
|
+
except SettingsError as exc:
|
|
197
|
+
# 配置非法 → 进程退出,而不是带病运行
|
|
198
|
+
print(str(exc), file=sys.stderr)
|
|
199
|
+
raise SystemExit(1) from exc
|
|
200
|
+
return build_app(resolved)
|
swiftapi/app/lifespan.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""启动/关闭编排(架构文档 §26)。
|
|
2
|
+
|
|
3
|
+
顺序原则:
|
|
4
|
+
- 启动:先校验依赖图,再置 ready,最后打启动摘要;
|
|
5
|
+
- 关闭:先置 not-ready(摘流量),再等/关资源,最后退出。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import contextlib
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import AsyncIterator, Callable
|
|
14
|
+
from contextlib import AbstractAsyncContextManager, asynccontextmanager
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from swiftapi.config.settings import Settings
|
|
18
|
+
from swiftapi.core.admin.maintenance import prune_throttle_once, throttle_prune_loop
|
|
19
|
+
from swiftapi.core.container import Container, RequestScope
|
|
20
|
+
from swiftapi.core.db.health import HealthRegistry
|
|
21
|
+
from swiftapi.core.observability.archive import LogArchiver
|
|
22
|
+
from swiftapi.core.observability.logging import get_logger
|
|
23
|
+
from swiftapi.version import __version__
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
26
|
+
from swiftapi.core.http.app import App
|
|
27
|
+
|
|
28
|
+
logger = get_logger("swiftapi.lifecycle")
|
|
29
|
+
|
|
30
|
+
Lifespan = Callable[["App"], AbstractAsyncContextManager[None]]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_lifespan(
|
|
34
|
+
settings: Settings,
|
|
35
|
+
container: Container,
|
|
36
|
+
health: HealthRegistry,
|
|
37
|
+
) -> Lifespan:
|
|
38
|
+
@asynccontextmanager
|
|
39
|
+
async def lifespan(app: App) -> AsyncIterator[None]:
|
|
40
|
+
# 1) 依赖图校验:缺失/环/作用域倒挂 → 直接拒绝启动
|
|
41
|
+
container.seal()
|
|
42
|
+
# 1.5) 解析单例(引擎不建连接,但确保关闭时能 dispose)
|
|
43
|
+
if "database" in container:
|
|
44
|
+
await container.resolve("database", RequestScope())
|
|
45
|
+
# 2) 就绪
|
|
46
|
+
app.state.ready = True
|
|
47
|
+
logger.info(
|
|
48
|
+
"app.started",
|
|
49
|
+
version=__version__,
|
|
50
|
+
env=settings.app.env.value,
|
|
51
|
+
config=settings.redacted_summary(),
|
|
52
|
+
)
|
|
53
|
+
prune_task: asyncio.Task[None] | None = None
|
|
54
|
+
if settings.admin.enabled and settings.admin.throttle_prune_enabled:
|
|
55
|
+
database = getattr(app.state, "database", None)
|
|
56
|
+
if database is not None:
|
|
57
|
+
# 启动补一次(上次停机错过的清理),之后按周期跑
|
|
58
|
+
await prune_throttle_once(database, settings)
|
|
59
|
+
prune_task = asyncio.create_task(throttle_prune_loop(database, settings))
|
|
60
|
+
|
|
61
|
+
archive_task: asyncio.Task[None] | None = None
|
|
62
|
+
if settings.observability.log_archive_enabled:
|
|
63
|
+
archiver = LogArchiver(settings)
|
|
64
|
+
# 启动时先补一次(上次停机错过的周期),再按周期后台跑
|
|
65
|
+
await asyncio.to_thread(archiver.archive_if_due)
|
|
66
|
+
archive_task = asyncio.create_task(_archive_loop(archiver))
|
|
67
|
+
|
|
68
|
+
relay_task = _start_outbox_relay(app, settings)
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
yield
|
|
72
|
+
finally:
|
|
73
|
+
await _cancel(prune_task)
|
|
74
|
+
await _cancel(archive_task)
|
|
75
|
+
await _cancel(relay_task)
|
|
76
|
+
# 3) 优雅停机:先摘流量 → 等在飞请求 → 释放资源
|
|
77
|
+
drain_started = time.monotonic()
|
|
78
|
+
app.begin_drain()
|
|
79
|
+
app.state.ready = False
|
|
80
|
+
timeout = settings.server.graceful_shutdown_timeout_s
|
|
81
|
+
idle = await app.wait_idle(timeout)
|
|
82
|
+
if not idle:
|
|
83
|
+
logger.warning("shutdown.forced", active=app.active_requests, timeout_s=timeout)
|
|
84
|
+
health.invalidate()
|
|
85
|
+
tenant_router = getattr(app.state, "tenant_router", None)
|
|
86
|
+
if tenant_router is not None:
|
|
87
|
+
await tenant_router.aclose()
|
|
88
|
+
cache = getattr(app.state, "cache", None)
|
|
89
|
+
if cache is not None:
|
|
90
|
+
await cache.close()
|
|
91
|
+
bus = getattr(app.state, "bus", None)
|
|
92
|
+
if bus is not None:
|
|
93
|
+
await bus.close()
|
|
94
|
+
outbound = getattr(app.state, "outbound", None)
|
|
95
|
+
if outbound is not None:
|
|
96
|
+
await outbound.aclose()
|
|
97
|
+
await container.aclose()
|
|
98
|
+
logger.info(
|
|
99
|
+
"app.stopped",
|
|
100
|
+
version=__version__,
|
|
101
|
+
drain_ms=round((time.monotonic() - drain_started) * 1000, 3),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
return lifespan
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _start_outbox_relay(app: App, settings: Settings) -> asyncio.Task[None] | None:
|
|
108
|
+
"""按配置启动 Outbox 中继;未启用/无总线时返回 None。"""
|
|
109
|
+
if not settings.messaging.outbox_relay_enabled:
|
|
110
|
+
return None
|
|
111
|
+
database = getattr(app.state, "database", None)
|
|
112
|
+
bus = getattr(app.state, "bus", None)
|
|
113
|
+
if database is None or bus is None:
|
|
114
|
+
return None
|
|
115
|
+
from swiftapi.core.messaging.relay import OutboxRelay
|
|
116
|
+
|
|
117
|
+
relay = OutboxRelay(
|
|
118
|
+
database.session_factory,
|
|
119
|
+
bus,
|
|
120
|
+
max_attempts=settings.messaging.outbox_relay_max_attempts,
|
|
121
|
+
batch_size=settings.messaging.outbox_relay_batch_size,
|
|
122
|
+
lease_s=settings.messaging.outbox_relay_lease_s,
|
|
123
|
+
)
|
|
124
|
+
return asyncio.create_task(
|
|
125
|
+
_outbox_relay_loop(relay, settings.messaging.outbox_relay_interval_s)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def _cancel(task: asyncio.Task[None] | None) -> None:
|
|
130
|
+
if task is None:
|
|
131
|
+
return
|
|
132
|
+
task.cancel()
|
|
133
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
134
|
+
await task
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
async def _archive_loop(archiver: LogArchiver) -> None:
|
|
138
|
+
"""按 `log_archive_interval_days` 周期归档;异常只记日志,不退出循环。"""
|
|
139
|
+
interval = archiver.interval.total_seconds()
|
|
140
|
+
while True:
|
|
141
|
+
await asyncio.sleep(interval)
|
|
142
|
+
await asyncio.to_thread(archiver.archive_if_due)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
async def _outbox_relay_loop(relay: Any, interval_s: float) -> None:
|
|
146
|
+
"""Outbox → 总线:周期投递,单次失败不影响下一轮。
|
|
147
|
+
|
|
148
|
+
多副本安全:PG/MySQL 使用 `SKIP LOCKED` 选批 + 租约 CAS claim,
|
|
149
|
+
同一行不会被两个副本同时处理;崩溃后最多等一个租约(默认 60s)接手。
|
|
150
|
+
投递语义仍是**至少一次**(publish 后、标记前崩溃会重投),消费端必须用
|
|
151
|
+
`mark_processed` 做幂等。
|
|
152
|
+
"""
|
|
153
|
+
while True:
|
|
154
|
+
try:
|
|
155
|
+
result = await relay.run_once()
|
|
156
|
+
if result.published or result.failed or result.dead:
|
|
157
|
+
logger.info(
|
|
158
|
+
"outbox.relayed",
|
|
159
|
+
published=result.published,
|
|
160
|
+
failed=result.failed,
|
|
161
|
+
dead=result.dead,
|
|
162
|
+
)
|
|
163
|
+
except asyncio.CancelledError:
|
|
164
|
+
raise
|
|
165
|
+
except Exception as exc: # 表还没迁移 / 库暂时不可用:记日志,下一轮再试
|
|
166
|
+
logger.warning("outbox.relay_error", error=str(exc))
|
|
167
|
+
await asyncio.sleep(interval_s)
|
swiftapi/app/routers.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""系统路由:探针、版本、指标。
|
|
2
|
+
|
|
3
|
+
这些端点不参与业务契约(`include_in_schema=False`),避免污染 OpenAPI。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from swiftapi.config.settings import Settings
|
|
9
|
+
from swiftapi.core.db.health import HealthRegistry
|
|
10
|
+
from swiftapi.core.http import JSONResponse, Response, Router
|
|
11
|
+
from swiftapi.core.observability import metrics
|
|
12
|
+
from swiftapi.version import __version__
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_system_router(settings: Settings, health: HealthRegistry) -> Router:
|
|
16
|
+
router = Router(tags=("system",))
|
|
17
|
+
|
|
18
|
+
@router.get("/livez", include_in_schema=False)
|
|
19
|
+
async def livez() -> dict[str, str]:
|
|
20
|
+
"""进程存活:不查任何外部依赖。"""
|
|
21
|
+
return {"status": "ok"}
|
|
22
|
+
|
|
23
|
+
@router.get("/readyz", include_in_schema=False)
|
|
24
|
+
async def readyz() -> Response:
|
|
25
|
+
"""就绪:依赖检查(带超时与缓存),失败返回 503。"""
|
|
26
|
+
results = await health.run()
|
|
27
|
+
healthy = all(item.healthy for item in results)
|
|
28
|
+
payload = {
|
|
29
|
+
"status": "ok" if healthy else "degraded",
|
|
30
|
+
"version": __version__,
|
|
31
|
+
"checks": [
|
|
32
|
+
{
|
|
33
|
+
"name": item.name,
|
|
34
|
+
"healthy": item.healthy,
|
|
35
|
+
"latency_ms": item.latency_ms,
|
|
36
|
+
**({"detail": item.detail} if item.detail else {}),
|
|
37
|
+
}
|
|
38
|
+
for item in results
|
|
39
|
+
],
|
|
40
|
+
}
|
|
41
|
+
return JSONResponse(payload, status_code=200 if healthy else 503)
|
|
42
|
+
|
|
43
|
+
@router.get("/version", summary="服务版本")
|
|
44
|
+
async def version() -> dict[str, str]:
|
|
45
|
+
return {
|
|
46
|
+
"name": settings.app.name,
|
|
47
|
+
"version": __version__,
|
|
48
|
+
"env": settings.app.env.value,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if settings.observability.metrics_enabled:
|
|
52
|
+
|
|
53
|
+
@router.get(settings.observability.metrics_path, include_in_schema=False)
|
|
54
|
+
async def prometheus_metrics() -> Response:
|
|
55
|
+
body, content_type = metrics.render_metrics()
|
|
56
|
+
return Response(body, media_type=content_type)
|
|
57
|
+
|
|
58
|
+
return router
|
swiftapi/cli/__init__.py
ADDED
|
File without changes
|
swiftapi/cli/admin.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""`swiftapi admin`:后台账号的创建与维护(不经过 Web,避免"首个账号"死锁)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import getpass
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
from rich.table import Table
|
|
11
|
+
from sqlalchemy import select
|
|
12
|
+
from sqlalchemy.exc import OperationalError
|
|
13
|
+
|
|
14
|
+
from swiftapi.config.settings import SettingsError, load_settings
|
|
15
|
+
from swiftapi.core.admin.accounts import (
|
|
16
|
+
AdminRole,
|
|
17
|
+
AdminStatus,
|
|
18
|
+
AdminUser,
|
|
19
|
+
create_user,
|
|
20
|
+
get_user_by_username,
|
|
21
|
+
prune_login_throttle,
|
|
22
|
+
set_password,
|
|
23
|
+
)
|
|
24
|
+
from swiftapi.core.db.engine import create_database
|
|
25
|
+
|
|
26
|
+
admin_app = typer.Typer(help="后台账号:创建 / 列表 / 改密 / 启停", no_args_is_help=True)
|
|
27
|
+
console = Console()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _settings(settings_module: str | None) -> object:
|
|
31
|
+
try:
|
|
32
|
+
return load_settings(settings_module)
|
|
33
|
+
except SettingsError as exc:
|
|
34
|
+
console.print(f"[red]{exc}[/red]")
|
|
35
|
+
raise typer.Exit(code=1) from exc
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _password(value: str | None) -> str:
|
|
39
|
+
if value:
|
|
40
|
+
return value
|
|
41
|
+
first = getpass.getpass("口令: ")
|
|
42
|
+
second = getpass.getpass("再输一次: ")
|
|
43
|
+
if first != second:
|
|
44
|
+
console.print("[red]两次输入不一致[/red]")
|
|
45
|
+
raise typer.Exit(code=1)
|
|
46
|
+
return first
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def _run(settings: object, action: str, **kwargs: object) -> None:
|
|
50
|
+
database = create_database(settings) # type: ignore[arg-type]
|
|
51
|
+
try:
|
|
52
|
+
async with database.session_factory() as session, session.begin():
|
|
53
|
+
if action == "create":
|
|
54
|
+
user = await create_user(
|
|
55
|
+
session,
|
|
56
|
+
username=str(kwargs["username"]),
|
|
57
|
+
password=str(kwargs["password"]),
|
|
58
|
+
role=AdminRole(str(kwargs["role"])),
|
|
59
|
+
tenant_slug=kwargs.get("tenant"), # type: ignore[arg-type]
|
|
60
|
+
)
|
|
61
|
+
console.print(f"[green]已创建[/green] {user.username}({user.role})")
|
|
62
|
+
elif action == "list":
|
|
63
|
+
rows = list((await session.execute(select(AdminUser))).scalars())
|
|
64
|
+
table = Table(title="后台账号")
|
|
65
|
+
table.add_column("用户名")
|
|
66
|
+
table.add_column("角色")
|
|
67
|
+
table.add_column("状态")
|
|
68
|
+
table.add_column("租户")
|
|
69
|
+
table.add_column("最近登录")
|
|
70
|
+
for row in rows:
|
|
71
|
+
table.add_row(
|
|
72
|
+
row.username,
|
|
73
|
+
row.role,
|
|
74
|
+
row.status,
|
|
75
|
+
row.tenant_slug or "-",
|
|
76
|
+
row.last_login_at.strftime("%Y-%m-%d %H:%M") if row.last_login_at else "-",
|
|
77
|
+
)
|
|
78
|
+
console.print(table)
|
|
79
|
+
elif action == "password":
|
|
80
|
+
target = await get_user_by_username(session, str(kwargs["username"]))
|
|
81
|
+
if target is None:
|
|
82
|
+
console.print("[red]账号不存在[/red]")
|
|
83
|
+
raise typer.Exit(code=1)
|
|
84
|
+
await set_password(session, target, str(kwargs["password"]))
|
|
85
|
+
console.print(f"[green]已重置[/green] {target.username} 的口令")
|
|
86
|
+
elif action == "prune":
|
|
87
|
+
removed = await prune_login_throttle(
|
|
88
|
+
session,
|
|
89
|
+
older_than_s=int(str(kwargs["hours"])) * 3600,
|
|
90
|
+
dry_run=bool(kwargs["dry_run"]),
|
|
91
|
+
)
|
|
92
|
+
verb = "可清理" if kwargs["dry_run"] else "已清理"
|
|
93
|
+
console.print(f"[green]{verb}[/green] {removed} 条过期节流记录")
|
|
94
|
+
elif action == "status":
|
|
95
|
+
target = await get_user_by_username(session, str(kwargs["username"]))
|
|
96
|
+
if target is None:
|
|
97
|
+
console.print("[red]账号不存在[/red]")
|
|
98
|
+
raise typer.Exit(code=1)
|
|
99
|
+
target.status = (
|
|
100
|
+
AdminStatus.DISABLED.value
|
|
101
|
+
if kwargs["enable"] is False
|
|
102
|
+
else AdminStatus.ACTIVE.value
|
|
103
|
+
)
|
|
104
|
+
target.failed_attempts = 0
|
|
105
|
+
target.locked_until = None
|
|
106
|
+
target.session_epoch = int(target.session_epoch or 0) + 1
|
|
107
|
+
await session.flush()
|
|
108
|
+
console.print(f"[green]已更新[/green] {target.username} → {target.status}")
|
|
109
|
+
except OperationalError as exc:
|
|
110
|
+
console.print(f"[red]数据库表不存在[/red],先执行迁移:swiftapi db upgrade\n{exc}")
|
|
111
|
+
raise typer.Exit(code=1) from exc
|
|
112
|
+
finally:
|
|
113
|
+
await database.aclose()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@admin_app.command("create-user")
|
|
117
|
+
def create_user_command(
|
|
118
|
+
username: str = typer.Option(..., "--username", "-u", help="登录名"),
|
|
119
|
+
password: str | None = typer.Option(None, "--password", "-p", help="口令(留空则交互输入)"),
|
|
120
|
+
role: str = typer.Option("admin", "--role", help="admin / admin_operator / admin_viewer"),
|
|
121
|
+
tenant: str | None = typer.Option(None, "--tenant", help="登录后绑定的租户 slug"),
|
|
122
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
123
|
+
) -> None:
|
|
124
|
+
"""创建后台账号(首个管理员用)。"""
|
|
125
|
+
resolved = _settings(settings)
|
|
126
|
+
try:
|
|
127
|
+
AdminRole(role)
|
|
128
|
+
except ValueError:
|
|
129
|
+
console.print(f"[red]未知角色[/red] {role}")
|
|
130
|
+
raise typer.Exit(code=2) from None
|
|
131
|
+
asyncio.run(
|
|
132
|
+
_run(
|
|
133
|
+
resolved,
|
|
134
|
+
"create",
|
|
135
|
+
username=username,
|
|
136
|
+
password=_password(password),
|
|
137
|
+
role=role,
|
|
138
|
+
tenant=tenant,
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@admin_app.command("list-users")
|
|
144
|
+
def list_users(
|
|
145
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
146
|
+
) -> None:
|
|
147
|
+
"""列出所有后台账号。"""
|
|
148
|
+
asyncio.run(_run(_settings(settings), "list"))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@admin_app.command("set-password")
|
|
152
|
+
def set_password_command(
|
|
153
|
+
username: str = typer.Option(..., "--username", "-u"),
|
|
154
|
+
password: str | None = typer.Option(None, "--password", "-p"),
|
|
155
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
156
|
+
) -> None:
|
|
157
|
+
"""重置某个账号的口令(同时清除锁定)。"""
|
|
158
|
+
asyncio.run(
|
|
159
|
+
_run(_settings(settings), "password", username=username, password=_password(password))
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@admin_app.command("disable")
|
|
164
|
+
def disable_user(
|
|
165
|
+
username: str = typer.Option(..., "--username", "-u"),
|
|
166
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
167
|
+
) -> None:
|
|
168
|
+
"""停用账号(已签发的 Cookie 会在下次请求时被拒)。"""
|
|
169
|
+
asyncio.run(_run(_settings(settings), "status", username=username, enable=False))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@admin_app.command("enable")
|
|
173
|
+
def enable_user(
|
|
174
|
+
username: str = typer.Option(..., "--username", "-u"),
|
|
175
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
176
|
+
) -> None:
|
|
177
|
+
"""启用账号并清除失败计数。"""
|
|
178
|
+
asyncio.run(_run(_settings(settings), "status", username=username, enable=True))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
__all__ = ["admin_app"]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@admin_app.command("prune-throttle")
|
|
185
|
+
def prune_throttle(
|
|
186
|
+
older_than_hours: int = typer.Option(24, "--older-than-hours", help="清理多少小时前的记录"),
|
|
187
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="只统计,不删除"),
|
|
188
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
189
|
+
) -> None:
|
|
190
|
+
"""清理过期的登录节流记录(建议放 cron,每天一次)。"""
|
|
191
|
+
asyncio.run(
|
|
192
|
+
_run(
|
|
193
|
+
_settings(settings),
|
|
194
|
+
"prune",
|
|
195
|
+
hours=older_than_hours,
|
|
196
|
+
dry_run=dry_run,
|
|
197
|
+
)
|
|
198
|
+
)
|