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
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""异常 → `application/problem+json` 的唯一出口。
|
|
2
|
+
|
|
3
|
+
约定:
|
|
4
|
+
- 所有错误响应都是 RFC 9457 结构,且都带 `trace_id`;
|
|
5
|
+
- 500 绝不回显堆栈 / SQL / 主机名;
|
|
6
|
+
- 422 只回显字段路径与原因,**不回显原始输入值**。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, Final, Protocol
|
|
12
|
+
|
|
13
|
+
import structlog
|
|
14
|
+
from sqlalchemy.exc import DBAPIError as _DatabaseError
|
|
15
|
+
from sqlalchemy.exc import IntegrityError as _IntegrityError
|
|
16
|
+
|
|
17
|
+
from swiftapi.core.errors.base import AppError
|
|
18
|
+
from swiftapi.core.errors.codes import ErrorCode
|
|
19
|
+
from swiftapi.core.errors.problem import FieldError, build_problem
|
|
20
|
+
from swiftapi.core.errors.validation import RequestValidationError
|
|
21
|
+
from swiftapi.core.http.request import Request
|
|
22
|
+
from swiftapi.core.http.responses import JSONResponse, Response
|
|
23
|
+
from swiftapi.core.observability.context import current
|
|
24
|
+
|
|
25
|
+
logger = structlog.get_logger(__name__)
|
|
26
|
+
|
|
27
|
+
PROBLEM_MEDIA_TYPE: Final[str] = "application/problem+json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def problem_response(
|
|
31
|
+
code: ErrorCode,
|
|
32
|
+
*,
|
|
33
|
+
detail: str | None = None,
|
|
34
|
+
status: int | None = None,
|
|
35
|
+
headers: dict[str, str] | None = None,
|
|
36
|
+
errors: list[FieldError] | None = None,
|
|
37
|
+
instance: str | None = None,
|
|
38
|
+
) -> JSONResponse:
|
|
39
|
+
ctx = current()
|
|
40
|
+
payload = build_problem(
|
|
41
|
+
code,
|
|
42
|
+
detail=detail,
|
|
43
|
+
instance=instance,
|
|
44
|
+
trace_id=ctx.trace_id if ctx else None,
|
|
45
|
+
errors=errors,
|
|
46
|
+
status=status,
|
|
47
|
+
)
|
|
48
|
+
return JSONResponse(
|
|
49
|
+
payload,
|
|
50
|
+
status_code=int(payload["status"]),
|
|
51
|
+
headers=headers,
|
|
52
|
+
media_type=PROBLEM_MEDIA_TYPE,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def integrity_error_handler(request: Request, exc: BaseException) -> Response:
|
|
57
|
+
"""唯一约束/外键冲突 → 409,而不是 503。
|
|
58
|
+
|
|
59
|
+
这类是"客户端数据冲突",不是数据库不可用;细节(含 SQL/参数)只进日志。
|
|
60
|
+
"""
|
|
61
|
+
logger.warning(
|
|
62
|
+
"db.integrity_error",
|
|
63
|
+
error=type(exc).__name__,
|
|
64
|
+
path=request.path,
|
|
65
|
+
)
|
|
66
|
+
return problem_response(
|
|
67
|
+
ErrorCode.CONFLICT,
|
|
68
|
+
detail="数据冲突:唯一约束或关联记录不满足",
|
|
69
|
+
instance=request.path,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def database_error_handler(request: Request, exc: BaseException) -> Response:
|
|
74
|
+
"""数据库不可用 → 503,而不是 500。
|
|
75
|
+
|
|
76
|
+
绝不能回显 `str(exc)`:SQLAlchemy 的异常文本里带完整 SQL 和参数值。
|
|
77
|
+
"""
|
|
78
|
+
logger.error(
|
|
79
|
+
"db.unavailable",
|
|
80
|
+
error=type(exc).__name__,
|
|
81
|
+
path=request.path,
|
|
82
|
+
exc_info=exc,
|
|
83
|
+
)
|
|
84
|
+
return problem_response(
|
|
85
|
+
ErrorCode.DEPENDENCY_UNAVAILABLE,
|
|
86
|
+
detail="数据库暂不可用,请稍后重试",
|
|
87
|
+
instance=request.path,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def app_error_handler(request: Request, exc: BaseException) -> Response:
|
|
92
|
+
assert isinstance(exc, AppError)
|
|
93
|
+
ctx = current()
|
|
94
|
+
if exc.status >= 500:
|
|
95
|
+
logger.error(
|
|
96
|
+
"app.error",
|
|
97
|
+
code=str(exc.code),
|
|
98
|
+
detail=exc.detail,
|
|
99
|
+
path=request.path,
|
|
100
|
+
trace_id=ctx.trace_id if ctx else None,
|
|
101
|
+
exc_info=exc,
|
|
102
|
+
)
|
|
103
|
+
else:
|
|
104
|
+
logger.info("app.rejected", code=str(exc.code), path=request.path)
|
|
105
|
+
detail = exc.detail if exc.expose else "An unexpected error occurred"
|
|
106
|
+
return problem_response(
|
|
107
|
+
exc.code,
|
|
108
|
+
detail=detail,
|
|
109
|
+
headers=exc.headers or None,
|
|
110
|
+
instance=request.path,
|
|
111
|
+
status=exc.status,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
async def validation_handler(request: Request, exc: BaseException) -> Response:
|
|
116
|
+
assert isinstance(exc, RequestValidationError)
|
|
117
|
+
logger.info("request.invalid", path=request.path, fields=len(exc.errors))
|
|
118
|
+
return problem_response(
|
|
119
|
+
ErrorCode.VALIDATION_ERROR,
|
|
120
|
+
detail=f"{len(exc.errors)} field(s) failed validation",
|
|
121
|
+
errors=exc.errors,
|
|
122
|
+
instance=request.path,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
async def unhandled_handler(request: Request, exc: BaseException) -> Response:
|
|
127
|
+
ctx = current()
|
|
128
|
+
logger.error(
|
|
129
|
+
"request.unhandled",
|
|
130
|
+
path=request.path,
|
|
131
|
+
method=request.method,
|
|
132
|
+
trace_id=ctx.trace_id if ctx else None,
|
|
133
|
+
exc_info=exc,
|
|
134
|
+
)
|
|
135
|
+
return problem_response(
|
|
136
|
+
ErrorCode.INTERNAL_ERROR,
|
|
137
|
+
detail="An unexpected error occurred",
|
|
138
|
+
instance=request.path,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class _ExceptionHandlerHost(Protocol):
|
|
143
|
+
def add_exception_handler(self, exc_type: type[BaseException], handler: Any) -> None: ...
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def register_exception_handlers(app: _ExceptionHandlerHost) -> None:
|
|
147
|
+
"""注册顺序即匹配顺序:越具体的类型越靠前,Exception 兜底最后。"""
|
|
148
|
+
app.add_exception_handler(RequestValidationError, validation_handler)
|
|
149
|
+
app.add_exception_handler(AppError, app_error_handler)
|
|
150
|
+
# 顺序敏感:isinstance 按注册顺序匹配,IntegrityError 必须先于 DBAPIError
|
|
151
|
+
app.add_exception_handler(_IntegrityError, integrity_error_handler)
|
|
152
|
+
app.add_exception_handler(_DatabaseError, database_error_handler)
|
|
153
|
+
# asyncpg 在"连不上"时直接抛 ConnectionRefusedError(不是 DBAPIError)
|
|
154
|
+
app.add_exception_handler(ConnectionError, database_error_handler)
|
|
155
|
+
app.add_exception_handler(Exception, unhandled_handler)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""RFC 9457 Problem Details 模型。
|
|
2
|
+
|
|
3
|
+
对外契约:所有错误响应都是 `application/problem+json`,且结构一致。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
11
|
+
|
|
12
|
+
from swiftapi.core.errors.codes import ErrorCode, spec_for
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FieldError(BaseModel):
|
|
16
|
+
"""字段级校验错误:loc 是路径,msg 是给人看的,type 是给程序看的。"""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(frozen=True)
|
|
19
|
+
|
|
20
|
+
loc: list[str | int]
|
|
21
|
+
msg: str
|
|
22
|
+
type: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ProblemDetail(BaseModel):
|
|
26
|
+
model_config = ConfigDict(frozen=True)
|
|
27
|
+
|
|
28
|
+
type: str = Field(description="问题类型的文档 URI")
|
|
29
|
+
title: str = Field(description="稳定的短标题,不随实例变化")
|
|
30
|
+
status: int
|
|
31
|
+
code: str = Field(description="错误码,来自 ErrorCode 枚举")
|
|
32
|
+
detail: str = Field(description="本实例的具体说明")
|
|
33
|
+
instance: str | None = Field(default=None, description="请求路径")
|
|
34
|
+
trace_id: str | None = None
|
|
35
|
+
errors: list[FieldError] | None = Field(default=None, description="仅 422 出现")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_problem(
|
|
39
|
+
code: ErrorCode,
|
|
40
|
+
*,
|
|
41
|
+
detail: str | None = None,
|
|
42
|
+
instance: str | None = None,
|
|
43
|
+
trace_id: str | None = None,
|
|
44
|
+
errors: list[FieldError] | None = None,
|
|
45
|
+
status: int | None = None,
|
|
46
|
+
) -> dict[str, Any]:
|
|
47
|
+
spec = spec_for(code)
|
|
48
|
+
payload = ProblemDetail(
|
|
49
|
+
type=spec.type_uri,
|
|
50
|
+
title=spec.title,
|
|
51
|
+
status=status or spec.status,
|
|
52
|
+
code=str(code),
|
|
53
|
+
detail=detail or spec.title,
|
|
54
|
+
instance=instance,
|
|
55
|
+
trace_id=trace_id,
|
|
56
|
+
errors=errors,
|
|
57
|
+
)
|
|
58
|
+
return payload.model_dump(exclude_none=True)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""请求校验异常:参数绑定失败时抛出,由 App 统一转成 422 problem+json。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from swiftapi.core.errors.problem import FieldError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class RequestValidationError(Exception):
|
|
9
|
+
def __init__(self, errors: list[FieldError]) -> None:
|
|
10
|
+
self.errors = errors
|
|
11
|
+
super().__init__(f"{len(errors)} validation error(s)")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""内核自带表:outbox / processed_event / admin_audit / admin_user / idempotency_key / login_throttle。
|
|
2
|
+
|
|
3
|
+
迁移生成时必须一并纳入——否则 `emit()` 会报 `no such table: outbox`
|
|
4
|
+
(cleanroom 验证发现的第三个 P0)。注意这里**不包含**示例模块 users。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from swiftapi.core.admin.accounts import AdminUser, LoginThrottle
|
|
10
|
+
from swiftapi.core.admin.audit import AdminAudit
|
|
11
|
+
from swiftapi.core.http.idempotency import IdempotencyKey
|
|
12
|
+
from swiftapi.core.messaging.idempotency import ProcessedEvent
|
|
13
|
+
from swiftapi.core.messaging.outbox import OutboxMessage
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"AdminAudit",
|
|
17
|
+
"AdminUser",
|
|
18
|
+
"IdempotencyKey",
|
|
19
|
+
"LoginThrottle",
|
|
20
|
+
"OutboxMessage",
|
|
21
|
+
"ProcessedEvent",
|
|
22
|
+
]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""自研 ASGI 微框架(零 Web 框架依赖)。
|
|
2
|
+
|
|
3
|
+
业务只依赖这五个名字:`App` / `Router` / `Request` / `Response` / `JSONResponse`,
|
|
4
|
+
以及参数标记 `Path` / `Query` / `Header` / `Body` / `Depends`。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from swiftapi.core.http.app import App
|
|
10
|
+
from swiftapi.core.http.cors import CORSMiddleware
|
|
11
|
+
from swiftapi.core.http.params import Body, Depends, Header, Path, Query
|
|
12
|
+
from swiftapi.core.http.request import Request
|
|
13
|
+
from swiftapi.core.http.responses import (
|
|
14
|
+
HTMLResponse,
|
|
15
|
+
JSONResponse,
|
|
16
|
+
NoContentResponse,
|
|
17
|
+
PlainTextResponse,
|
|
18
|
+
Response,
|
|
19
|
+
StreamingResponse,
|
|
20
|
+
)
|
|
21
|
+
from swiftapi.core.http.routing import Route, Router
|
|
22
|
+
from swiftapi.core.http.types import ASGIApp, Headers, Message, Receive, Scope, Send
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"ASGIApp",
|
|
26
|
+
"App",
|
|
27
|
+
"Body",
|
|
28
|
+
"CORSMiddleware",
|
|
29
|
+
"Depends",
|
|
30
|
+
"HTMLResponse",
|
|
31
|
+
"Header",
|
|
32
|
+
"Headers",
|
|
33
|
+
"JSONResponse",
|
|
34
|
+
"Message",
|
|
35
|
+
"NoContentResponse",
|
|
36
|
+
"Path",
|
|
37
|
+
"PlainTextResponse",
|
|
38
|
+
"Query",
|
|
39
|
+
"Receive",
|
|
40
|
+
"Request",
|
|
41
|
+
"Response",
|
|
42
|
+
"Route",
|
|
43
|
+
"Router",
|
|
44
|
+
"Scope",
|
|
45
|
+
"Send",
|
|
46
|
+
"StreamingResponse",
|
|
47
|
+
]
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""ASGI 应用:装配、中间件链、异常分发、请求作用域、超时、优雅停机。
|
|
2
|
+
|
|
3
|
+
调用链(与架构文档 §9.2 一致):
|
|
4
|
+
ASGI server → 用户中间件(后加者在外层)→ 路由匹配 → 参数绑定 → handler → 响应
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from collections.abc import Awaitable, Callable
|
|
11
|
+
from contextlib import AbstractAsyncContextManager
|
|
12
|
+
from types import SimpleNamespace
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel
|
|
16
|
+
|
|
17
|
+
from swiftapi.core.container import Container, ContainerError, RequestScope
|
|
18
|
+
from swiftapi.core.errors.codes import ErrorCode
|
|
19
|
+
from swiftapi.core.errors.handlers import problem_response
|
|
20
|
+
from swiftapi.core.http.openapi import build_openapi
|
|
21
|
+
from swiftapi.core.http.params import resolve
|
|
22
|
+
from swiftapi.core.http.request import Request
|
|
23
|
+
from swiftapi.core.http.responses import JSONResponse, Response
|
|
24
|
+
from swiftapi.core.http.routing import Handler, Route, Router
|
|
25
|
+
from swiftapi.core.http.types import ASGIApp, Message, Receive, Scope, Send
|
|
26
|
+
|
|
27
|
+
ErrorHandler = Callable[[Request, BaseException], Awaitable[Response]]
|
|
28
|
+
Lifespan = Callable[["App"], AbstractAsyncContextManager[None]]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class App:
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
*,
|
|
35
|
+
title: str = "SwiftAPI",
|
|
36
|
+
version: str = "0.0.0",
|
|
37
|
+
description: str = "",
|
|
38
|
+
openapi_url: str = "/openapi.json",
|
|
39
|
+
lifespan: Lifespan | None = None,
|
|
40
|
+
container: Container | None = None,
|
|
41
|
+
request_timeout_s: float = 5.0,
|
|
42
|
+
graceful_shutdown_timeout_s: float = 25.0,
|
|
43
|
+
) -> None:
|
|
44
|
+
self.title = title
|
|
45
|
+
self.version = version
|
|
46
|
+
self.description = description
|
|
47
|
+
self.openapi_url = openapi_url
|
|
48
|
+
# 不内置 UI:文档页由 docs_ui 接管(P4),契约本身始终可用
|
|
49
|
+
self.docs_url: str | None = None
|
|
50
|
+
self.redoc_url: str | None = None
|
|
51
|
+
self.debug = False
|
|
52
|
+
self.state = SimpleNamespace(ready=False)
|
|
53
|
+
self.container = container
|
|
54
|
+
self.request_timeout_s = request_timeout_s
|
|
55
|
+
self.graceful_shutdown_timeout_s = graceful_shutdown_timeout_s
|
|
56
|
+
self.router = Router()
|
|
57
|
+
self.user_middleware: list[tuple[type[Any], dict[str, Any]]] = []
|
|
58
|
+
self.exception_handlers: dict[type[BaseException], ErrorHandler] = {}
|
|
59
|
+
self._lifespan = lifespan
|
|
60
|
+
self._lifespan_cm: AbstractAsyncContextManager[None] | None = None
|
|
61
|
+
self._stack: ASGIApp | None = None
|
|
62
|
+
self._active = 0
|
|
63
|
+
self._draining = False
|
|
64
|
+
self._idle = asyncio.Event()
|
|
65
|
+
self._idle.set()
|
|
66
|
+
if openapi_url:
|
|
67
|
+
self.router.add_route(openapi_url, self._openapi_endpoint, include_in_schema=False)
|
|
68
|
+
|
|
69
|
+
# 默认错误契约:裸 App 也返回 problem+json(否则 404/422 会变成 500)
|
|
70
|
+
from swiftapi.core.errors.handlers import register_exception_handlers
|
|
71
|
+
|
|
72
|
+
register_exception_handlers(self)
|
|
73
|
+
|
|
74
|
+
# ---------------- 装配 ----------------
|
|
75
|
+
|
|
76
|
+
def add_middleware(self, middleware_class: type[Any], **options: Any) -> None:
|
|
77
|
+
if self._stack is not None:
|
|
78
|
+
raise RuntimeError("中间件必须在首次请求之前注册")
|
|
79
|
+
self.user_middleware.append((middleware_class, options))
|
|
80
|
+
|
|
81
|
+
def add_exception_handler(
|
|
82
|
+
self, exc_type: type[BaseException], handler: ErrorHandler
|
|
83
|
+
) -> None:
|
|
84
|
+
self.exception_handlers[exc_type] = handler
|
|
85
|
+
|
|
86
|
+
def include_router(self, router: Router, *, prefix: str = "") -> None:
|
|
87
|
+
self.router.include_router(router, prefix=prefix)
|
|
88
|
+
|
|
89
|
+
def get(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
|
|
90
|
+
return self.router.get(path, **kwargs)
|
|
91
|
+
|
|
92
|
+
def post(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
|
|
93
|
+
return self.router.post(path, **kwargs)
|
|
94
|
+
|
|
95
|
+
def put(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
|
|
96
|
+
return self.router.put(path, **kwargs)
|
|
97
|
+
|
|
98
|
+
def patch(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
|
|
99
|
+
return self.router.patch(path, **kwargs)
|
|
100
|
+
|
|
101
|
+
def delete(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
|
|
102
|
+
return self.router.delete(path, **kwargs)
|
|
103
|
+
|
|
104
|
+
def openapi(self) -> dict[str, Any]:
|
|
105
|
+
return build_openapi(self)
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def lifespan_context(self) -> AbstractAsyncContextManager[None] | None:
|
|
109
|
+
return self._lifespan(self) if self._lifespan else None
|
|
110
|
+
|
|
111
|
+
# ---------------- 优雅停机 ----------------
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def active_requests(self) -> int:
|
|
115
|
+
return self._active
|
|
116
|
+
|
|
117
|
+
def begin_drain(self) -> None:
|
|
118
|
+
"""停止接收新请求:新请求直接 503 SERVICE_DRAINING。"""
|
|
119
|
+
self._draining = True
|
|
120
|
+
|
|
121
|
+
async def wait_idle(self, timeout_s: float) -> bool:
|
|
122
|
+
"""等待在飞请求结束;返回是否在超时前清空。"""
|
|
123
|
+
if self._active == 0:
|
|
124
|
+
return True
|
|
125
|
+
try:
|
|
126
|
+
async with asyncio.timeout(timeout_s):
|
|
127
|
+
await self._idle.wait()
|
|
128
|
+
except TimeoutError:
|
|
129
|
+
return False
|
|
130
|
+
return True
|
|
131
|
+
|
|
132
|
+
# ---------------- ASGI ----------------
|
|
133
|
+
|
|
134
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
135
|
+
if scope["type"] == "lifespan":
|
|
136
|
+
await self._handle_lifespan(receive, send)
|
|
137
|
+
return
|
|
138
|
+
if self._stack is None:
|
|
139
|
+
self._stack = self._build_stack()
|
|
140
|
+
await self._stack(scope, receive, send)
|
|
141
|
+
|
|
142
|
+
def _build_stack(self) -> ASGIApp:
|
|
143
|
+
app: ASGIApp = self._handle_http
|
|
144
|
+
for middleware_class, options in self.user_middleware:
|
|
145
|
+
app = middleware_class(app, **options)
|
|
146
|
+
return app
|
|
147
|
+
|
|
148
|
+
async def _handle_lifespan(self, receive: Receive, send: Send) -> None:
|
|
149
|
+
while True:
|
|
150
|
+
message: Message = await receive()
|
|
151
|
+
if message["type"] == "lifespan.startup":
|
|
152
|
+
try:
|
|
153
|
+
if self._lifespan is not None:
|
|
154
|
+
self._lifespan_cm = self._lifespan(self)
|
|
155
|
+
await self._lifespan_cm.__aenter__()
|
|
156
|
+
self.state.ready = True
|
|
157
|
+
except BaseException as exc: # 启动失败必须让服务器知道
|
|
158
|
+
await send({"type": "lifespan.startup.failed", "message": str(exc)})
|
|
159
|
+
else:
|
|
160
|
+
await send({"type": "lifespan.startup.complete"})
|
|
161
|
+
elif message["type"] == "lifespan.shutdown":
|
|
162
|
+
try:
|
|
163
|
+
if self._lifespan_cm is not None:
|
|
164
|
+
await self._lifespan_cm.__aexit__(None, None, None)
|
|
165
|
+
self._lifespan_cm = None
|
|
166
|
+
self.state.ready = False
|
|
167
|
+
except BaseException as exc:
|
|
168
|
+
await send({"type": "lifespan.shutdown.failed", "message": str(exc)})
|
|
169
|
+
else:
|
|
170
|
+
await send({"type": "lifespan.shutdown.complete"})
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
async def _handle_http(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
174
|
+
request = Request(scope, receive)
|
|
175
|
+
|
|
176
|
+
if self._draining:
|
|
177
|
+
response: Response = problem_response(
|
|
178
|
+
ErrorCode.SERVICE_DRAINING,
|
|
179
|
+
detail="实例正在停机,请重试其他实例",
|
|
180
|
+
instance=request.path,
|
|
181
|
+
headers={"Connection": "close"},
|
|
182
|
+
)
|
|
183
|
+
await response(scope, receive, send)
|
|
184
|
+
return
|
|
185
|
+
|
|
186
|
+
self._active += 1
|
|
187
|
+
self._idle.clear()
|
|
188
|
+
request_scope = RequestScope()
|
|
189
|
+
try:
|
|
190
|
+
route, path_params = self.router.resolve(request.method, request.path)
|
|
191
|
+
scope["route"] = route
|
|
192
|
+
request.path_params = path_params
|
|
193
|
+
kwargs = await resolve(
|
|
194
|
+
route.plan,
|
|
195
|
+
request,
|
|
196
|
+
container=self.container,
|
|
197
|
+
request_scope=request_scope,
|
|
198
|
+
)
|
|
199
|
+
result = await self._invoke(route, kwargs)
|
|
200
|
+
response = self._to_response(result, route)
|
|
201
|
+
except TimeoutError:
|
|
202
|
+
response = problem_response(
|
|
203
|
+
ErrorCode.TIMEOUT,
|
|
204
|
+
detail=f"请求超过 {self.request_timeout_s:.1f}s 预算",
|
|
205
|
+
instance=request.path,
|
|
206
|
+
)
|
|
207
|
+
except Exception as exc:
|
|
208
|
+
response = await self._dispatch_error(exc, request)
|
|
209
|
+
finally:
|
|
210
|
+
self._active -= 1
|
|
211
|
+
if self._active == 0:
|
|
212
|
+
self._idle.set()
|
|
213
|
+
await request_scope.close()
|
|
214
|
+
|
|
215
|
+
if request.method == "HEAD":
|
|
216
|
+
response = Response(b"", status_code=response.status_code, headers=response.headers)
|
|
217
|
+
await response(scope, receive, send)
|
|
218
|
+
|
|
219
|
+
async def _invoke(self, route: Route, kwargs: dict[str, Any]) -> Any:
|
|
220
|
+
if self.request_timeout_s <= 0:
|
|
221
|
+
return await route.handler(**kwargs)
|
|
222
|
+
async with asyncio.timeout(self.request_timeout_s):
|
|
223
|
+
return await route.handler(**kwargs)
|
|
224
|
+
|
|
225
|
+
def _to_response(self, result: Any, route: Route) -> Response:
|
|
226
|
+
if isinstance(result, Response):
|
|
227
|
+
return result
|
|
228
|
+
if route.response_model is not None:
|
|
229
|
+
validated = route.response_model.model_validate(result)
|
|
230
|
+
payload: Any = validated.model_dump(mode="json")
|
|
231
|
+
elif isinstance(result, BaseModel):
|
|
232
|
+
payload = result.model_dump(mode="json")
|
|
233
|
+
else:
|
|
234
|
+
payload = result
|
|
235
|
+
return JSONResponse(payload, status_code=route.status_code)
|
|
236
|
+
|
|
237
|
+
async def _dispatch_error(self, exc: BaseException, request: Request) -> Response:
|
|
238
|
+
"""唯一分发入口:只认注册过的处理器,未注册直接抛(由服务器记录)。"""
|
|
239
|
+
for exc_type, handler in self.exception_handlers.items():
|
|
240
|
+
if isinstance(exc, exc_type):
|
|
241
|
+
return await handler(request, exc)
|
|
242
|
+
if isinstance(exc, ContainerError):
|
|
243
|
+
raise exc
|
|
244
|
+
raise exc
|
|
245
|
+
|
|
246
|
+
async def _openapi_endpoint(self, request: Request) -> Response:
|
|
247
|
+
return JSONResponse(self.openapi())
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""CORS 中间件(纯 ASGI,自研)。
|
|
2
|
+
|
|
3
|
+
只做浏览器需要的最小子集:预检 + 实际请求的响应头 + `Vary: Origin`。
|
|
4
|
+
通配 `*` 与 `allow_credentials=True` 互斥(浏览器规范),启动期已由 Settings 拒绝生产通配。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
|
|
11
|
+
from swiftapi.core.http.types import ASGIApp, Message, Receive, Scope, Send
|
|
12
|
+
|
|
13
|
+
_SIMPLE_METHODS = ("GET", "HEAD", "POST")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CORSMiddleware:
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
app: ASGIApp,
|
|
20
|
+
*,
|
|
21
|
+
allow_origins: Sequence[str] = (),
|
|
22
|
+
allow_credentials: bool = False,
|
|
23
|
+
allow_methods: Sequence[str] = ("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"),
|
|
24
|
+
allow_headers: Sequence[str] = ("authorization", "content-type", "x-request-id", "x-tenant-id"),
|
|
25
|
+
max_age: int = 600,
|
|
26
|
+
) -> None:
|
|
27
|
+
self.app = app
|
|
28
|
+
self.allow_origins = tuple(allow_origins)
|
|
29
|
+
self.allow_credentials = allow_credentials
|
|
30
|
+
self.allow_methods = tuple(allow_methods)
|
|
31
|
+
self.allow_headers = tuple(header.lower() for header in allow_headers)
|
|
32
|
+
self.max_age = max_age
|
|
33
|
+
|
|
34
|
+
def _origin_allowed(self, origin: str | None) -> bool:
|
|
35
|
+
if not origin:
|
|
36
|
+
return False
|
|
37
|
+
return "*" in self.allow_origins or origin in self.allow_origins
|
|
38
|
+
|
|
39
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
40
|
+
if scope["type"] != "http" or not self.allow_origins:
|
|
41
|
+
await self.app(scope, receive, send)
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
headers = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
|
|
45
|
+
origin = headers.get("origin")
|
|
46
|
+
if not self._origin_allowed(origin):
|
|
47
|
+
await self.app(scope, receive, send)
|
|
48
|
+
return
|
|
49
|
+
assert origin is not None
|
|
50
|
+
|
|
51
|
+
is_preflight = (
|
|
52
|
+
scope["method"] == "OPTIONS"
|
|
53
|
+
and "access-control-request-method" in headers
|
|
54
|
+
)
|
|
55
|
+
if is_preflight:
|
|
56
|
+
requested = headers.get("access-control-request-headers", "")
|
|
57
|
+
extra = [h.strip() for h in requested.split(",") if h.strip()]
|
|
58
|
+
await self._preflight(origin, headers, extra, scope, receive, send)
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
async def send_with_cors(message: Message) -> None:
|
|
62
|
+
if message["type"] == "http.response.start":
|
|
63
|
+
raw: list[tuple[bytes, bytes]] = message.setdefault("headers", [])
|
|
64
|
+
raw.append((b"access-control-allow-origin", origin.encode()))
|
|
65
|
+
raw.append((b"vary", b"origin"))
|
|
66
|
+
if self.allow_credentials:
|
|
67
|
+
raw.append((b"access-control-allow-credentials", b"true"))
|
|
68
|
+
await send(message)
|
|
69
|
+
|
|
70
|
+
await self.app(scope, receive, send_with_cors)
|
|
71
|
+
|
|
72
|
+
async def _preflight(
|
|
73
|
+
self,
|
|
74
|
+
origin: str,
|
|
75
|
+
headers: dict[str, str],
|
|
76
|
+
extra_headers: list[str],
|
|
77
|
+
scope: Scope,
|
|
78
|
+
receive: Receive,
|
|
79
|
+
send: Send,
|
|
80
|
+
) -> None:
|
|
81
|
+
requested_method = headers.get("access-control-request-method", "")
|
|
82
|
+
allowed = requested_method.upper() in self.allow_methods
|
|
83
|
+
await send(
|
|
84
|
+
{
|
|
85
|
+
"type": "http.response.start",
|
|
86
|
+
"status": 200 if allowed else 403,
|
|
87
|
+
"headers": [
|
|
88
|
+
(b"access-control-allow-origin", origin.encode()),
|
|
89
|
+
(b"access-control-allow-methods", ", ".join(self.allow_methods).encode()),
|
|
90
|
+
(
|
|
91
|
+
b"access-control-allow-headers",
|
|
92
|
+
", ".join([*self.allow_headers, *[h.lower() for h in extra_headers]]).encode(),
|
|
93
|
+
),
|
|
94
|
+
(b"access-control-max-age", str(self.max_age).encode()),
|
|
95
|
+
(b"vary", b"origin"),
|
|
96
|
+
(b"content-length", b"0"),
|
|
97
|
+
],
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
await send({"type": "http.response.body", "body": b""})
|