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,46 @@
|
|
|
1
|
+
"""请求 ID / Trace ID 中间件(纯 ASGI,最外层)。
|
|
2
|
+
|
|
3
|
+
- 透传合法的 `X-Request-Id`,否则生成;
|
|
4
|
+
- 解析 W3C `traceparent`,保证跨服务链路可串联;
|
|
5
|
+
- 响应头回写两个 ID,便于用户报障时直接给出。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
from swiftapi.config.constants import REQUEST_ID_HEADER, TRACE_ID_HEADER, TRACEPARENT_HEADER
|
|
13
|
+
from swiftapi.core.http.types import ASGIApp, Headers, Message, MutableHeaders, Receive, Scope, Send
|
|
14
|
+
from swiftapi.core.observability.context import bind, current, new_request_id, unbind
|
|
15
|
+
|
|
16
|
+
_VALID_REQUEST_ID = re.compile(r"^[A-Za-z0-9._-]{8,64}$")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RequestIDMiddleware:
|
|
20
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
21
|
+
self.app = app
|
|
22
|
+
|
|
23
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
24
|
+
if scope["type"] != "http":
|
|
25
|
+
await self.app(scope, receive, send)
|
|
26
|
+
return
|
|
27
|
+
|
|
28
|
+
headers = Headers.from_scope(scope)
|
|
29
|
+
incoming = headers.get(REQUEST_ID_HEADER)
|
|
30
|
+
request_id = incoming if incoming and _VALID_REQUEST_ID.match(incoming) else new_request_id()
|
|
31
|
+
|
|
32
|
+
token = bind(request_id=request_id, traceparent=headers.get(TRACEPARENT_HEADER))
|
|
33
|
+
ctx = current()
|
|
34
|
+
assert ctx is not None # bind 后必然存在
|
|
35
|
+
|
|
36
|
+
async def send_with_ids(message: Message) -> None:
|
|
37
|
+
if message["type"] == "http.response.start":
|
|
38
|
+
mutable = MutableHeaders(message)
|
|
39
|
+
mutable[REQUEST_ID_HEADER] = ctx.request_id
|
|
40
|
+
mutable[TRACE_ID_HEADER] = ctx.trace_id
|
|
41
|
+
await send(message)
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
await self.app(scope, receive, send_with_ids)
|
|
45
|
+
finally:
|
|
46
|
+
unbind(token)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""安全响应头中间件(纯 ASGI)。
|
|
2
|
+
|
|
3
|
+
即使后续抛错,响应也带上这些头——所以放在最外层附近。
|
|
4
|
+
CSP 默认只允许同源脚本,配合"无 CDN"的文档页设计。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from swiftapi.core.http.types import ASGIApp, Message, Receive, Scope, Send
|
|
10
|
+
|
|
11
|
+
_BASE_HEADERS: dict[str, str] = {
|
|
12
|
+
"X-Content-Type-Options": "nosniff",
|
|
13
|
+
"X-Frame-Options": "DENY",
|
|
14
|
+
"Referrer-Policy": "no-referrer",
|
|
15
|
+
"Cross-Origin-Opener-Policy": "same-origin",
|
|
16
|
+
"Cross-Origin-Resource-Policy": "same-origin",
|
|
17
|
+
"Permissions-Policy": "geolocation=(), microphone=(), camera=()",
|
|
18
|
+
"Content-Security-Policy": (
|
|
19
|
+
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
|
20
|
+
"img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'"
|
|
21
|
+
),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SecurityHeadersMiddleware:
|
|
26
|
+
def __init__(self, app: ASGIApp, *, hsts: bool = False) -> None:
|
|
27
|
+
self.app = app
|
|
28
|
+
self.headers = dict(_BASE_HEADERS)
|
|
29
|
+
if hsts:
|
|
30
|
+
self.headers["Strict-Transport-Security"] = "max-age=15552000; includeSubDomains"
|
|
31
|
+
|
|
32
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
33
|
+
if scope["type"] != "http":
|
|
34
|
+
await self.app(scope, receive, send)
|
|
35
|
+
return
|
|
36
|
+
|
|
37
|
+
async def send_with_headers(message: Message) -> None:
|
|
38
|
+
if message["type"] == "http.response.start":
|
|
39
|
+
headers = message.setdefault("headers", [])
|
|
40
|
+
existing = {key.lower() for key, _ in headers}
|
|
41
|
+
for name, value in self.headers.items():
|
|
42
|
+
if name.lower().encode() not in existing:
|
|
43
|
+
headers.append((name.encode(), value.encode()))
|
|
44
|
+
await send(message)
|
|
45
|
+
|
|
46
|
+
await self.app(scope, receive, send_with_headers)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""租户中间件:解析 → 绑定 contextvar → 响应后清理。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from swiftapi.config.settings import Settings
|
|
6
|
+
from swiftapi.core.errors.codes import ErrorCode
|
|
7
|
+
from swiftapi.core.errors.handlers import problem_response
|
|
8
|
+
from swiftapi.core.http.request import Request
|
|
9
|
+
from swiftapi.core.http.types import ASGIApp, Receive, Scope, Send
|
|
10
|
+
from swiftapi.core.tenant.context import bind_tenant, reset_tenant
|
|
11
|
+
from swiftapi.core.tenant.resolver import TenantResolverService
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TenantMiddleware:
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
app: ASGIApp,
|
|
18
|
+
*,
|
|
19
|
+
settings: Settings,
|
|
20
|
+
resolver: TenantResolverService,
|
|
21
|
+
) -> None:
|
|
22
|
+
self.app = app
|
|
23
|
+
self.settings = settings
|
|
24
|
+
self.resolver = resolver
|
|
25
|
+
|
|
26
|
+
def _public_paths(self) -> frozenset[str]:
|
|
27
|
+
return frozenset(
|
|
28
|
+
{
|
|
29
|
+
"/livez",
|
|
30
|
+
"/readyz",
|
|
31
|
+
"/metrics",
|
|
32
|
+
"/openapi.json",
|
|
33
|
+
self.settings.docs.path,
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
38
|
+
if scope["type"] != "http" or not self.settings.tenant.enabled:
|
|
39
|
+
await self.app(scope, receive, send)
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
request = Request(scope, receive)
|
|
43
|
+
context = self.resolver.resolve(request)
|
|
44
|
+
if context is None:
|
|
45
|
+
# 公开端点(探针/契约/文档)不要求租户
|
|
46
|
+
if request.path in self._public_paths():
|
|
47
|
+
await self.app(scope, receive, send)
|
|
48
|
+
return
|
|
49
|
+
# 未认证请求交给权限依赖决定(401 优先于 400)
|
|
50
|
+
if request.state.get("principal") is None:
|
|
51
|
+
await self.app(scope, receive, send)
|
|
52
|
+
return
|
|
53
|
+
if self.settings.tenant.require_resolved:
|
|
54
|
+
response = problem_response(
|
|
55
|
+
ErrorCode.TENANT_REQUIRED,
|
|
56
|
+
detail=f"缺少租户标识({self.settings.tenant.header_name} 或路径前缀)",
|
|
57
|
+
instance=request.path,
|
|
58
|
+
)
|
|
59
|
+
await response(scope, receive, send)
|
|
60
|
+
return
|
|
61
|
+
await self.app(scope, receive, send)
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
principal = request.state.get("principal")
|
|
65
|
+
if principal is not None:
|
|
66
|
+
allowed: frozenset[str] = getattr(principal, "tenants", frozenset())
|
|
67
|
+
claim = request.state.get("tenant_claim")
|
|
68
|
+
if claim and claim != context.slug:
|
|
69
|
+
response = problem_response(
|
|
70
|
+
ErrorCode.TENANT_MISMATCH,
|
|
71
|
+
detail="令牌租户与请求租户不一致",
|
|
72
|
+
instance=request.path,
|
|
73
|
+
)
|
|
74
|
+
await response(scope, receive, send)
|
|
75
|
+
return
|
|
76
|
+
if allowed and context.slug not in allowed:
|
|
77
|
+
response = problem_response(
|
|
78
|
+
ErrorCode.TENANT_MISMATCH,
|
|
79
|
+
detail="无权访问该租户",
|
|
80
|
+
instance=request.path,
|
|
81
|
+
)
|
|
82
|
+
await response(scope, receive, send)
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
request.state["tenant"] = context
|
|
86
|
+
token = bind_tenant(context)
|
|
87
|
+
try:
|
|
88
|
+
await self.app(scope, receive, send)
|
|
89
|
+
finally:
|
|
90
|
+
reset_tenant(token)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
__all__ = ["TenantMiddleware"]
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""耗时与 RED 指标(纯 ASGI)。
|
|
2
|
+
|
|
3
|
+
route 标签使用**路由模板**(`/api/v1/users/{id}`)而不是实际路径,
|
|
4
|
+
否则 Prometheus 标签基数会被用户 ID 打爆。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
from swiftapi.core.http.types import ASGIApp, Message, Receive, Scope, Send
|
|
12
|
+
from swiftapi.core.observability import metrics
|
|
13
|
+
|
|
14
|
+
_STATE_KEY = "swiftapi_timing"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TimingMiddleware:
|
|
18
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
19
|
+
self.app = app
|
|
20
|
+
|
|
21
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
22
|
+
if scope["type"] != "http":
|
|
23
|
+
await self.app(scope, receive, send)
|
|
24
|
+
return
|
|
25
|
+
|
|
26
|
+
started = time.perf_counter()
|
|
27
|
+
metrics.inc_active()
|
|
28
|
+
status = 500
|
|
29
|
+
|
|
30
|
+
async def send_capture(message: Message) -> None:
|
|
31
|
+
nonlocal status
|
|
32
|
+
if message["type"] == "http.response.start":
|
|
33
|
+
status = int(message["status"])
|
|
34
|
+
await send(message)
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
await self.app(scope, receive, send_capture)
|
|
38
|
+
finally:
|
|
39
|
+
duration = time.perf_counter() - started
|
|
40
|
+
metrics.dec_active()
|
|
41
|
+
route = scope.get("route")
|
|
42
|
+
route_path = getattr(route, "path", None) or scope.get("path", "-")
|
|
43
|
+
method = scope.get("method", "-")
|
|
44
|
+
metrics.observe_request(
|
|
45
|
+
method=method, route=route_path, status=status, duration_s=duration
|
|
46
|
+
)
|
|
47
|
+
scope.setdefault("state", {})[_STATE_KEY] = {
|
|
48
|
+
"duration_ms": round(duration * 1000, 3),
|
|
49
|
+
"status": status,
|
|
50
|
+
"route": route_path,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def read_timing(scope: Scope) -> dict[str, object]:
|
|
55
|
+
state = scope.get("state") or {}
|
|
56
|
+
value = state.get(_STATE_KEY) if isinstance(state, dict) else None
|
|
57
|
+
return value if isinstance(value, dict) else {}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""multipart/form-data 解析(够用且安全的最小实现)。
|
|
2
|
+
|
|
3
|
+
为什么自研:内核不引入 Web 框架,`python-multipart` 是额外依赖;
|
|
4
|
+
而且上传路径必须自己控制 part 数量 / 单 part / 总量三个上限,否则一个请求就能打满内存。
|
|
5
|
+
|
|
6
|
+
限制(默认值):
|
|
7
|
+
- 最多 10 个 part;
|
|
8
|
+
- 单 part 10MB;
|
|
9
|
+
- 总量 20MB;
|
|
10
|
+
超限抛 413,类型不对抛 415。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
from swiftapi.core.errors.base import PayloadTooLarge, UnsupportedMediaType
|
|
19
|
+
from swiftapi.core.http.request import Request
|
|
20
|
+
|
|
21
|
+
_BOUNDARY = re.compile(r'boundary="?([^";]+)"?', re.I)
|
|
22
|
+
_DISPOSITION = re.compile(r'name="([^"]*)"', re.I)
|
|
23
|
+
_FILENAME = re.compile(r'filename="([^"]*)"', re.I)
|
|
24
|
+
|
|
25
|
+
MAX_PARTS = 10
|
|
26
|
+
MAX_PART_BYTES = 10 * 1024 * 1024
|
|
27
|
+
MAX_TOTAL_BYTES = 20 * 1024 * 1024
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class FilePart:
|
|
32
|
+
field: str
|
|
33
|
+
filename: str
|
|
34
|
+
content_type: str
|
|
35
|
+
content: bytes
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _boundary_of(content_type: str) -> str:
|
|
39
|
+
match = _BOUNDARY.search(content_type)
|
|
40
|
+
if not match:
|
|
41
|
+
raise UnsupportedMediaType("multipart 缺少 boundary")
|
|
42
|
+
return match.group(1)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def is_multipart(content_type: str) -> bool:
|
|
46
|
+
return content_type.split(";")[0].strip().lower() == "multipart/form-data"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def parse_multipart(
|
|
50
|
+
body: bytes,
|
|
51
|
+
content_type: str,
|
|
52
|
+
*,
|
|
53
|
+
max_parts: int = MAX_PARTS,
|
|
54
|
+
max_part_bytes: int = MAX_PART_BYTES,
|
|
55
|
+
max_total_bytes: int = MAX_TOTAL_BYTES,
|
|
56
|
+
) -> list[FilePart]:
|
|
57
|
+
if len(body) > max_total_bytes:
|
|
58
|
+
raise PayloadTooLarge(f"multipart 总量超过上限 {max_total_bytes} 字节")
|
|
59
|
+
|
|
60
|
+
delimiter = b"--" + _boundary_of(content_type).encode()
|
|
61
|
+
parts: list[FilePart] = []
|
|
62
|
+
|
|
63
|
+
for chunk in body.split(delimiter)[1:]:
|
|
64
|
+
if chunk.startswith(b"--"): # 结束标记
|
|
65
|
+
break
|
|
66
|
+
chunk = chunk[2:] if chunk.startswith(b"\r\n") else chunk
|
|
67
|
+
head, separator, content = chunk.partition(b"\r\n\r\n")
|
|
68
|
+
if not separator:
|
|
69
|
+
continue
|
|
70
|
+
if content.endswith(b"\r\n"):
|
|
71
|
+
content = content[:-2]
|
|
72
|
+
|
|
73
|
+
if len(content) > max_part_bytes:
|
|
74
|
+
raise PayloadTooLarge(f"单个 part 超过上限 {max_part_bytes} 字节")
|
|
75
|
+
|
|
76
|
+
headers = head.decode("utf-8", errors="replace")
|
|
77
|
+
disposition = next(
|
|
78
|
+
(line for line in headers.splitlines() if line.lower().startswith("content-disposition")),
|
|
79
|
+
"",
|
|
80
|
+
)
|
|
81
|
+
filename_match = _FILENAME.search(disposition)
|
|
82
|
+
if not filename_match:
|
|
83
|
+
continue # 普通表单字段,上传场景忽略
|
|
84
|
+
|
|
85
|
+
if len(parts) >= max_parts:
|
|
86
|
+
raise PayloadTooLarge(f"part 数量超过上限 {max_parts}")
|
|
87
|
+
|
|
88
|
+
name_match = _DISPOSITION.search(disposition)
|
|
89
|
+
content_type_line = next(
|
|
90
|
+
(line for line in headers.splitlines() if line.lower().startswith("content-type")),
|
|
91
|
+
"",
|
|
92
|
+
)
|
|
93
|
+
parts.append(
|
|
94
|
+
FilePart(
|
|
95
|
+
field=name_match.group(1) if name_match else "",
|
|
96
|
+
filename=filename_match.group(1),
|
|
97
|
+
content_type=(
|
|
98
|
+
content_type_line.split(":", 1)[1].strip()
|
|
99
|
+
if content_type_line
|
|
100
|
+
else "application/octet-stream"
|
|
101
|
+
),
|
|
102
|
+
content=content,
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
return parts
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def read_multipart(request: Request, **kwargs: int) -> list[FilePart]:
|
|
110
|
+
content_type = request.headers.get("content-type") or ""
|
|
111
|
+
if not is_multipart(content_type):
|
|
112
|
+
raise UnsupportedMediaType("需要 multipart/form-data")
|
|
113
|
+
return parse_multipart(await request.body(), content_type, **kwargs)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
__all__ = ["FilePart", "is_multipart", "parse_multipart", "read_multipart"]
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""流式 multipart 解析:边收边写,不把文件读进内存。
|
|
2
|
+
|
|
3
|
+
难点是 boundary 可能被切在两个 chunk 之间:这里保留 `len(marker)-1` 的尾巴,
|
|
4
|
+
所以任意 chunk 大小都安全(测试用 1/3/7 字节分片覆盖过)。
|
|
5
|
+
|
|
6
|
+
只处理文件 part(有 filename 的);普通表单字段跳过但计入 part 数量上限。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
from collections.abc import AsyncIterator
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from swiftapi.core.errors.base import PayloadTooLarge, UnsupportedMediaType
|
|
18
|
+
|
|
19
|
+
_MAX_HEADER_BYTES = 64 * 1024
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class StreamedPart:
|
|
24
|
+
field: str
|
|
25
|
+
filename: str
|
|
26
|
+
content_type: str
|
|
27
|
+
path: Path
|
|
28
|
+
size: int
|
|
29
|
+
sha256: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class _PartState:
|
|
34
|
+
skip: bool
|
|
35
|
+
field: str = ""
|
|
36
|
+
filename: str = ""
|
|
37
|
+
content_type: str = "application/octet-stream"
|
|
38
|
+
path: Path | None = None
|
|
39
|
+
handle: Any = None
|
|
40
|
+
hasher: Any = None
|
|
41
|
+
size: int = 0
|
|
42
|
+
|
|
43
|
+
def close_file(self) -> None:
|
|
44
|
+
if self.handle is not None:
|
|
45
|
+
self.handle.close()
|
|
46
|
+
self.handle = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _boundary_bytes(content_type: str) -> bytes:
|
|
50
|
+
from swiftapi.core.http.multipart import _boundary_of
|
|
51
|
+
|
|
52
|
+
return _boundary_of(content_type).encode()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _parse_headers(raw: bytes) -> dict[str, str]:
|
|
56
|
+
headers: dict[str, str] = {}
|
|
57
|
+
for line in raw.decode("utf-8", errors="replace").splitlines():
|
|
58
|
+
if ":" in line:
|
|
59
|
+
key, _, value = line.partition(":")
|
|
60
|
+
headers[key.strip().lower()] = value.strip()
|
|
61
|
+
return headers
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _disposition(headers: dict[str, str]) -> dict[str, str]:
|
|
65
|
+
from swiftapi.core.http.multipart import _DISPOSITION, _FILENAME
|
|
66
|
+
|
|
67
|
+
raw = headers.get("content-disposition", "")
|
|
68
|
+
parsed: dict[str, str] = {}
|
|
69
|
+
name = _DISPOSITION.search(raw)
|
|
70
|
+
filename = _FILENAME.search(raw)
|
|
71
|
+
if name:
|
|
72
|
+
parsed["name"] = name.group(1)
|
|
73
|
+
if filename:
|
|
74
|
+
parsed["filename"] = filename.group(1)
|
|
75
|
+
return parsed
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _discard(state: _PartState | None) -> None:
|
|
79
|
+
if state is None:
|
|
80
|
+
return
|
|
81
|
+
state.close_file()
|
|
82
|
+
if state.path is not None:
|
|
83
|
+
state.path.unlink(missing_ok=True)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _start_part(headers: dict[str, str], directory: Path, want_field: str | None, capture: bool) -> _PartState:
|
|
87
|
+
disposition = _disposition(headers)
|
|
88
|
+
filename = disposition.get("filename")
|
|
89
|
+
if not filename:
|
|
90
|
+
return _PartState(skip=True)
|
|
91
|
+
wanted = want_field is None or disposition.get("name") in {want_field, "file"}
|
|
92
|
+
if not (capture and wanted):
|
|
93
|
+
return _PartState(skip=True)
|
|
94
|
+
|
|
95
|
+
from uuid import uuid4
|
|
96
|
+
|
|
97
|
+
path = directory / f".upload-{uuid4().hex}.part"
|
|
98
|
+
return _PartState(
|
|
99
|
+
skip=False,
|
|
100
|
+
field=disposition.get("name", ""),
|
|
101
|
+
filename=filename,
|
|
102
|
+
content_type=headers.get("content-type", "application/octet-stream"),
|
|
103
|
+
path=path,
|
|
104
|
+
handle=path.open("xb"),
|
|
105
|
+
hasher=hashlib.sha256(),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _write(state: _PartState, data: bytes, max_part_bytes: int) -> None:
|
|
110
|
+
if state.skip or not data:
|
|
111
|
+
return
|
|
112
|
+
state.size += len(data)
|
|
113
|
+
if state.size > max_part_bytes:
|
|
114
|
+
raise PayloadTooLarge(f"单个 part 超过上限 {max_part_bytes} 字节")
|
|
115
|
+
assert state.handle is not None and state.hasher is not None
|
|
116
|
+
state.handle.write(data)
|
|
117
|
+
state.hasher.update(data)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def spool_multipart( # noqa: C901 - 状态机天生多分支
|
|
121
|
+
chunks: AsyncIterator[bytes],
|
|
122
|
+
*,
|
|
123
|
+
content_type: str,
|
|
124
|
+
directory: Path,
|
|
125
|
+
max_part_bytes: int,
|
|
126
|
+
max_parts: int,
|
|
127
|
+
want_field: str | None = None,
|
|
128
|
+
) -> StreamedPart | None:
|
|
129
|
+
"""把第一个匹配的文件 part 写到 `directory` 下的临时文件,返回其信息。"""
|
|
130
|
+
delimiter = b"--" + _boundary_bytes(content_type)
|
|
131
|
+
marker = b"\r\n" + delimiter
|
|
132
|
+
buffer = bytearray()
|
|
133
|
+
state = "preamble"
|
|
134
|
+
parts = 0
|
|
135
|
+
current: _PartState | None = None
|
|
136
|
+
result: StreamedPart | None = None
|
|
137
|
+
|
|
138
|
+
async for chunk in chunks:
|
|
139
|
+
buffer.extend(chunk)
|
|
140
|
+
while True:
|
|
141
|
+
if state == "preamble":
|
|
142
|
+
index = buffer.find(delimiter)
|
|
143
|
+
if index < 0:
|
|
144
|
+
if len(buffer) > len(delimiter):
|
|
145
|
+
del buffer[: len(buffer) - len(delimiter) + 1]
|
|
146
|
+
break
|
|
147
|
+
del buffer[: index + len(delimiter)]
|
|
148
|
+
state = "after_delim"
|
|
149
|
+
|
|
150
|
+
elif state == "after_delim":
|
|
151
|
+
if len(buffer) < 2:
|
|
152
|
+
break
|
|
153
|
+
if buffer.startswith(b"--"):
|
|
154
|
+
state = "done"
|
|
155
|
+
break
|
|
156
|
+
if buffer.startswith(b"\r\n"):
|
|
157
|
+
del buffer[:2]
|
|
158
|
+
state = "headers"
|
|
159
|
+
continue
|
|
160
|
+
raise UnsupportedMediaType("multipart 格式错误(缺少分隔符)")
|
|
161
|
+
|
|
162
|
+
elif state == "headers":
|
|
163
|
+
index = buffer.find(b"\r\n\r\n")
|
|
164
|
+
if index < 0:
|
|
165
|
+
if len(buffer) > _MAX_HEADER_BYTES:
|
|
166
|
+
raise PayloadTooLarge("multipart part 头过大")
|
|
167
|
+
break
|
|
168
|
+
headers = _parse_headers(bytes(buffer[:index]))
|
|
169
|
+
del buffer[: index + 4]
|
|
170
|
+
|
|
171
|
+
parts += 1
|
|
172
|
+
if parts > max_parts:
|
|
173
|
+
raise PayloadTooLarge(f"part 数量超过上限 {max_parts}")
|
|
174
|
+
|
|
175
|
+
current = _start_part(headers, directory, want_field, capture=result is None)
|
|
176
|
+
state = "body"
|
|
177
|
+
|
|
178
|
+
elif state == "body":
|
|
179
|
+
index = buffer.find(marker)
|
|
180
|
+
if index < 0:
|
|
181
|
+
keep = len(marker) - 1
|
|
182
|
+
if len(buffer) > keep:
|
|
183
|
+
if current is not None:
|
|
184
|
+
_write(current, bytes(buffer[: len(buffer) - keep]), max_part_bytes)
|
|
185
|
+
del buffer[: len(buffer) - keep]
|
|
186
|
+
break
|
|
187
|
+
if current is not None:
|
|
188
|
+
_write(current, bytes(buffer[:index]), max_part_bytes)
|
|
189
|
+
del buffer[: index + len(marker)]
|
|
190
|
+
|
|
191
|
+
if current is not None and not current.skip and current.path is not None:
|
|
192
|
+
current.close_file()
|
|
193
|
+
assert current.hasher is not None
|
|
194
|
+
result = StreamedPart(
|
|
195
|
+
field=current.field,
|
|
196
|
+
filename=current.filename,
|
|
197
|
+
content_type=current.content_type,
|
|
198
|
+
path=current.path,
|
|
199
|
+
size=current.size,
|
|
200
|
+
sha256=current.hasher.hexdigest(),
|
|
201
|
+
)
|
|
202
|
+
current = None
|
|
203
|
+
state = "after_delim"
|
|
204
|
+
|
|
205
|
+
elif state == "done":
|
|
206
|
+
break
|
|
207
|
+
|
|
208
|
+
if state != "done":
|
|
209
|
+
_discard(current)
|
|
210
|
+
raise UnsupportedMediaType("multipart 请求被截断")
|
|
211
|
+
|
|
212
|
+
_discard(current)
|
|
213
|
+
return result
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
__all__ = ["StreamedPart", "spool_multipart"]
|