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.

Files changed (187) hide show
  1. swiftapi/__init__.py +22 -0
  2. swiftapi/app/__init__.py +0 -0
  3. swiftapi/app/factory.py +200 -0
  4. swiftapi/app/lifespan.py +167 -0
  5. swiftapi/app/routers.py +58 -0
  6. swiftapi/cli/__init__.py +0 -0
  7. swiftapi/cli/admin.py +198 -0
  8. swiftapi/cli/appref.py +51 -0
  9. swiftapi/cli/audit.py +45 -0
  10. swiftapi/cli/db.py +185 -0
  11. swiftapi/cli/endpoint.py +169 -0
  12. swiftapi/cli/logs.py +100 -0
  13. swiftapi/cli/main.py +238 -0
  14. swiftapi/cli/new.py +113 -0
  15. swiftapi/cli/openapi.py +69 -0
  16. swiftapi/cli/resource.py +657 -0
  17. swiftapi/cli/scaffold.py +168 -0
  18. swiftapi/config/__init__.py +0 -0
  19. swiftapi/config/constants.py +51 -0
  20. swiftapi/config/environments.py +38 -0
  21. swiftapi/config/settings.py +764 -0
  22. swiftapi/core/__init__.py +0 -0
  23. swiftapi/core/admin/__init__.py +0 -0
  24. swiftapi/core/admin/accounts.py +385 -0
  25. swiftapi/core/admin/audit.py +203 -0
  26. swiftapi/core/admin/maintenance.py +53 -0
  27. swiftapi/core/admin/registry.py +53 -0
  28. swiftapi/core/admin/security.py +94 -0
  29. swiftapi/core/admin/session.py +154 -0
  30. swiftapi/core/admin/views.py +2428 -0
  31. swiftapi/core/cache/__init__.py +0 -0
  32. swiftapi/core/cache/base.py +29 -0
  33. swiftapi/core/cache/decorators.py +51 -0
  34. swiftapi/core/cache/factory.py +30 -0
  35. swiftapi/core/cache/keys.py +24 -0
  36. swiftapi/core/cache/memory.py +60 -0
  37. swiftapi/core/cache/null.py +28 -0
  38. swiftapi/core/cache/redis.py +50 -0
  39. swiftapi/core/container.py +209 -0
  40. swiftapi/core/db/__init__.py +0 -0
  41. swiftapi/core/db/base_model.py +122 -0
  42. swiftapi/core/db/crud.py +242 -0
  43. swiftapi/core/db/dialects/__init__.py +8 -0
  44. swiftapi/core/db/dialects/base.py +106 -0
  45. swiftapi/core/db/dialects/mysql.py +47 -0
  46. swiftapi/core/db/dialects/pg.py +51 -0
  47. swiftapi/core/db/dialects/registry.py +30 -0
  48. swiftapi/core/db/dialects/sqlite.py +47 -0
  49. swiftapi/core/db/engine.py +209 -0
  50. swiftapi/core/db/health.py +84 -0
  51. swiftapi/core/db/migrate/__init__.py +1 -0
  52. swiftapi/core/db/migrate/ddl.py +162 -0
  53. swiftapi/core/db/migrate/render.py +84 -0
  54. swiftapi/core/db/migrate/runner.py +159 -0
  55. swiftapi/core/db/migrate/schema.py +248 -0
  56. swiftapi/core/db/mixins.py +53 -0
  57. swiftapi/core/db/session.py +54 -0
  58. swiftapi/core/db/snapshot.py +33 -0
  59. swiftapi/core/db/tenant_model.py +43 -0
  60. swiftapi/core/db/tenant_router.py +114 -0
  61. swiftapi/core/db/types.py +109 -0
  62. swiftapi/core/db/unit_of_work.py +65 -0
  63. swiftapi/core/docs/__init__.py +0 -0
  64. swiftapi/core/docs/router.py +26 -0
  65. swiftapi/core/docs/tsgen.py +93 -0
  66. swiftapi/core/docs/ui.py +132 -0
  67. swiftapi/core/errors/__init__.py +0 -0
  68. swiftapi/core/errors/base.py +168 -0
  69. swiftapi/core/errors/codes.py +117 -0
  70. swiftapi/core/errors/handlers.py +155 -0
  71. swiftapi/core/errors/problem.py +58 -0
  72. swiftapi/core/errors/validation.py +11 -0
  73. swiftapi/core/framework_models.py +22 -0
  74. swiftapi/core/http/__init__.py +47 -0
  75. swiftapi/core/http/app.py +247 -0
  76. swiftapi/core/http/cors.py +100 -0
  77. swiftapi/core/http/idempotency.py +148 -0
  78. swiftapi/core/http/middleware/__init__.py +82 -0
  79. swiftapi/core/http/middleware/access_log.py +57 -0
  80. swiftapi/core/http/middleware/auth.py +105 -0
  81. swiftapi/core/http/middleware/body_limit.py +76 -0
  82. swiftapi/core/http/middleware/rate_limit.py +103 -0
  83. swiftapi/core/http/middleware/request_body.py +122 -0
  84. swiftapi/core/http/middleware/request_id.py +46 -0
  85. swiftapi/core/http/middleware/security_headers.py +46 -0
  86. swiftapi/core/http/middleware/tenant.py +93 -0
  87. swiftapi/core/http/middleware/timing.py +57 -0
  88. swiftapi/core/http/multipart.py +116 -0
  89. swiftapi/core/http/multipart_stream.py +216 -0
  90. swiftapi/core/http/openapi.py +148 -0
  91. swiftapi/core/http/pagination.py +55 -0
  92. swiftapi/core/http/params.py +302 -0
  93. swiftapi/core/http/request.py +145 -0
  94. swiftapi/core/http/responses.py +127 -0
  95. swiftapi/core/http/routing.py +200 -0
  96. swiftapi/core/http/types.py +86 -0
  97. swiftapi/core/http/uploads.py +222 -0
  98. swiftapi/core/messaging/__init__.py +0 -0
  99. swiftapi/core/messaging/base.py +33 -0
  100. swiftapi/core/messaging/consumer.py +57 -0
  101. swiftapi/core/messaging/factory.py +30 -0
  102. swiftapi/core/messaging/idempotency.py +61 -0
  103. swiftapi/core/messaging/inprocess.py +30 -0
  104. swiftapi/core/messaging/outbox.py +106 -0
  105. swiftapi/core/messaging/rabbitmq.py +186 -0
  106. swiftapi/core/messaging/relay.py +151 -0
  107. swiftapi/core/messaging/streams.py +141 -0
  108. swiftapi/core/observability/__init__.py +0 -0
  109. swiftapi/core/observability/archive.py +136 -0
  110. swiftapi/core/observability/context.py +102 -0
  111. swiftapi/core/observability/logging.py +192 -0
  112. swiftapi/core/observability/masking.py +74 -0
  113. swiftapi/core/observability/metrics.py +101 -0
  114. swiftapi/core/observability/volume.py +67 -0
  115. swiftapi/core/resilience/__init__.py +0 -0
  116. swiftapi/core/resilience/bulkhead.py +50 -0
  117. swiftapi/core/resilience/circuit_breaker.py +97 -0
  118. swiftapi/core/resilience/client.py +179 -0
  119. swiftapi/core/resilience/retry.py +59 -0
  120. swiftapi/core/security/__init__.py +0 -0
  121. swiftapi/core/security/jwt.py +78 -0
  122. swiftapi/core/security/principal.py +78 -0
  123. swiftapi/core/tenant/__init__.py +1 -0
  124. swiftapi/core/tenant/catalog.py +89 -0
  125. swiftapi/core/tenant/context.py +75 -0
  126. swiftapi/core/tenant/isolation.py +48 -0
  127. swiftapi/core/tenant/resolver.py +48 -0
  128. swiftapi/core/validation/__init__.py +0 -0
  129. swiftapi/core/validation/base.py +32 -0
  130. swiftapi/db.py +50 -0
  131. swiftapi/modules/__init__.py +0 -0
  132. swiftapi/modules/users/__init__.py +11 -0
  133. swiftapi/modules/users/api/__init__.py +0 -0
  134. swiftapi/modules/users/api/users.py +110 -0
  135. swiftapi/modules/users/crud/__init__.py +0 -0
  136. swiftapi/modules/users/crud/user.py +23 -0
  137. swiftapi/modules/users/errors.py +24 -0
  138. swiftapi/modules/users/mappers.py +19 -0
  139. swiftapi/modules/users/model/__init__.py +0 -0
  140. swiftapi/modules/users/model/user.py +37 -0
  141. swiftapi/modules/users/policies.py +19 -0
  142. swiftapi/modules/users/schema/__init__.py +0 -0
  143. swiftapi/modules/users/schema/user.py +40 -0
  144. swiftapi/modules/users/service/__init__.py +0 -0
  145. swiftapi/modules/users/service/user.py +107 -0
  146. swiftapi/py.typed +0 -0
  147. swiftapi/templates/__init__.py +0 -0
  148. swiftapi/templates/app_skeleton/README.md +17 -0
  149. swiftapi/templates/app_skeleton/__init__.py +1 -0
  150. swiftapi/templates/app_skeleton/api/__init__.py +23 -0
  151. swiftapi/templates/app_skeleton/api/health.py +12 -0
  152. swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
  153. swiftapi/templates/app_skeleton/model/__init__.py +1 -0
  154. swiftapi/templates/app_skeleton/router.py +16 -0
  155. swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
  156. swiftapi/templates/app_skeleton/service/__init__.py +1 -0
  157. swiftapi/templates/project/__init__.py +0 -0
  158. swiftapi/templates/project/api.py +135 -0
  159. swiftapi/templates/project/app.py +57 -0
  160. swiftapi/templates/project/endpoints/__init__.py +25 -0
  161. swiftapi/templates/project/events.py +43 -0
  162. swiftapi/templates/project/models.py +79 -0
  163. swiftapi/templates/project/resources/__init__.py +35 -0
  164. swiftapi/templates/project/schemas.py +45 -0
  165. swiftapi/templates/project/service.py +125 -0
  166. swiftapi/templates/project/settings.py +17 -0
  167. swiftapi/templates/project_skeleton/.env.example +5 -0
  168. swiftapi/templates/project_skeleton/.gitignore +6 -0
  169. swiftapi/templates/project_skeleton/README.md +25 -0
  170. swiftapi/templates/project_skeleton/__init__.py +1 -0
  171. swiftapi/templates/project_skeleton/app.py +26 -0
  172. swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
  173. swiftapi/templates/project_skeleton/common/__init__.py +4 -0
  174. swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
  175. swiftapi/templates/project_skeleton/conf/settings.py +73 -0
  176. swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
  177. swiftapi/templates/project_skeleton/models.py +12 -0
  178. swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
  179. swiftapi/templates/project_skeleton/router.py +46 -0
  180. swiftapi/templates/project_skeleton/script/start.sh +13 -0
  181. swiftapi/templates/project_skeleton/start.py +35 -0
  182. swiftapi/version.py +8 -0
  183. swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
  184. swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
  185. swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
  186. swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
  187. swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,127 @@
1
+ """响应对象:只实现服务端真正需要的几种(JSON / 文本 / HTML / 空)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator, Mapping
6
+ from typing import Any
7
+
8
+ import orjson
9
+
10
+ from swiftapi.core.http.types import Message, Receive, Scope, Send
11
+
12
+
13
+ class Response:
14
+ media_type: str = "text/plain; charset=utf-8"
15
+
16
+ def __init__(
17
+ self,
18
+ content: bytes | str = b"",
19
+ *,
20
+ status_code: int = 200,
21
+ headers: Mapping[str, str] | None = None,
22
+ media_type: str | None = None,
23
+ ) -> None:
24
+ self.status_code = status_code
25
+ self.body = content.encode("utf-8") if isinstance(content, str) else content
26
+ self._headers = dict(headers or {})
27
+ if media_type is not None:
28
+ self.media_type = media_type
29
+
30
+ @property
31
+ def headers(self) -> dict[str, str]:
32
+ headers = {"content-type": self.media_type, "content-length": str(len(self.body))}
33
+ headers.update({k.lower(): v for k, v in self._headers.items()})
34
+ return headers
35
+
36
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
37
+ start: Message = {
38
+ "type": "http.response.start",
39
+ "status": self.status_code,
40
+ "headers": [(k.encode("latin-1"), v.encode("latin-1")) for k, v in self.headers.items()],
41
+ }
42
+ await send(start)
43
+ await send({"type": "http.response.body", "body": self.body})
44
+
45
+
46
+ class JSONResponse(Response):
47
+ media_type = "application/json"
48
+
49
+ def __init__(
50
+ self,
51
+ content: Any,
52
+ *,
53
+ status_code: int = 200,
54
+ headers: Mapping[str, str] | None = None,
55
+ media_type: str | None = None,
56
+ ) -> None:
57
+ body = orjson.dumps(content, default=str, option=orjson.OPT_NON_STR_KEYS)
58
+ super().__init__(body, status_code=status_code, headers=headers, media_type=media_type)
59
+
60
+
61
+ class PlainTextResponse(Response):
62
+ media_type = "text/plain; charset=utf-8"
63
+
64
+ def __init__(
65
+ self,
66
+ content: str = "",
67
+ *,
68
+ status_code: int = 200,
69
+ headers: Mapping[str, str] | None = None,
70
+ ) -> None:
71
+ super().__init__(content, status_code=status_code, headers=headers)
72
+
73
+
74
+ class HTMLResponse(Response):
75
+ media_type = "text/html; charset=utf-8"
76
+
77
+ def __init__(
78
+ self,
79
+ content: str = "",
80
+ *,
81
+ status_code: int = 200,
82
+ headers: Mapping[str, str] | None = None,
83
+ ) -> None:
84
+ super().__init__(content, status_code=status_code, headers=headers)
85
+
86
+
87
+ class StreamingResponse(Response):
88
+ """流式响应:SSE / 大文件 / 长列表导出。
89
+
90
+ 与 `Response` 的区别:不预计算 content-length,分块 send,支持客户端提前断开。
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ content: AsyncIterator[bytes],
96
+ *,
97
+ status_code: int = 200,
98
+ headers: Mapping[str, str] | None = None,
99
+ media_type: str = "application/octet-stream",
100
+ ) -> None:
101
+ super().__init__(b"", status_code=status_code, headers=headers, media_type=media_type)
102
+ self.body_iterator = content
103
+
104
+ @property
105
+ def headers(self) -> dict[str, str]:
106
+ headers = {"content-type": self.media_type}
107
+ headers.update({k.lower(): v for k, v in self._headers.items()})
108
+ return headers
109
+
110
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
111
+ await send(
112
+ {
113
+ "type": "http.response.start",
114
+ "status": self.status_code,
115
+ "headers": [
116
+ (k.encode("latin-1"), v.encode("latin-1")) for k, v in self.headers.items()
117
+ ],
118
+ }
119
+ )
120
+ async for chunk in self.body_iterator:
121
+ await send({"type": "http.response.body", "body": chunk, "more_body": True})
122
+ await send({"type": "http.response.body", "body": b""})
123
+
124
+
125
+ class NoContentResponse(Response):
126
+ def __init__(self, *, status_code: int = 204) -> None:
127
+ super().__init__(b"", status_code=status_code)
@@ -0,0 +1,200 @@
1
+ """路由:路径模板匹配 + 方法分发(404 / 405 语义与 RFC 一致)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Awaitable, Callable, Iterable, Sequence
7
+ from dataclasses import dataclass, field, replace
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel
11
+
12
+ from swiftapi.core.errors.base import MethodNotAllowed, NotFound
13
+ from swiftapi.core.http.params import Binding, build_plan
14
+
15
+ Handler = Callable[..., Awaitable[Any]]
16
+
17
+
18
+ def join_path(prefix: str, path: str) -> str:
19
+ """拼接前缀与路径;`""` 视为根,`"/"` 不产生重复斜杠。"""
20
+ if not path or path == "/":
21
+ return prefix or "/"
22
+ return f"{prefix}{path}"
23
+
24
+
25
+ class RouteConflictError(ValueError):
26
+ """同一 path + method 重复注册:启动期直接失败,而不是静默覆盖。"""
27
+
28
+
29
+ def compile_path(path: str) -> tuple[re.Pattern[str], tuple[str, ...]]:
30
+ """`/users/{user_id}` → 正则 + 参数名。参数只匹配单段,不允许跨越 `/`。"""
31
+ names: list[str] = []
32
+ pattern = "^"
33
+ for segment in re.split(r"(\{[^}]+\})", path):
34
+ if segment.startswith("{") and segment.endswith("}"):
35
+ name = segment[1:-1]
36
+ names.append(name)
37
+ pattern += f"(?P<{name}>[^/]+)"
38
+ else:
39
+ pattern += re.escape(segment)
40
+ return re.compile(pattern + "$"), tuple(names)
41
+
42
+
43
+ @dataclass
44
+ class Route:
45
+ path: str
46
+ methods: frozenset[str]
47
+ handler: Handler
48
+ plan: list[Binding] = field(default_factory=list)
49
+ name: str = ""
50
+ summary: str | None = None
51
+ description: str | None = None
52
+ tags: tuple[str, ...] = ()
53
+ response_model: type[BaseModel] | None = None
54
+ status_code: int = 200
55
+ include_in_schema: bool = True
56
+ regex: re.Pattern[str] = field(init=False, repr=False)
57
+ param_names: tuple[str, ...] = ()
58
+
59
+ def __post_init__(self) -> None:
60
+ if self.response_model is not None and not (
61
+ isinstance(self.response_model, type)
62
+ and issubclass(self.response_model, BaseModel)
63
+ ):
64
+ # 裸 dict / list 注解在运行期无法校验,只会变成 500。
65
+ # 在注册期就拒绝,错误信息直指问题(真实踩过:response_model=dict[str, int])。
66
+ raise TypeError(
67
+ f"response_model 必须是 Pydantic 模型类(BaseModel 子类),"
68
+ f"收到 {self.response_model!r}(路由 {self.path});"
69
+ "需要字典响应时请定义 OutModel"
70
+ )
71
+ self.regex, self.param_names = compile_path(self.path)
72
+ if not self.name:
73
+ self.name = getattr(self.handler, "__name__", self.path)
74
+ if not self.plan:
75
+ self.plan = build_plan(self.handler)
76
+ # 路径模板里的参数自动视为 Path 来源(lenient:不必强制写 Path())
77
+ if self.param_names:
78
+ self.plan = [
79
+ replace(binding, kind="path", required=True)
80
+ if binding.kind == "query" and binding.name in self.param_names
81
+ else binding
82
+ for binding in self.plan
83
+ ]
84
+
85
+ def match(self, path: str) -> dict[str, str] | None:
86
+ matched = self.regex.match(path)
87
+ return matched.groupdict() if matched else None
88
+
89
+
90
+ class Router:
91
+ def __init__(self, prefix: str = "", tags: Sequence[str] = ()) -> None:
92
+ self.prefix = prefix.rstrip("/")
93
+ self.tags = tuple(tags)
94
+ self.routes: list[Route] = []
95
+
96
+ # ---------------- 注册 ----------------
97
+
98
+ def add_route(
99
+ self,
100
+ path: str,
101
+ handler: Handler,
102
+ *,
103
+ methods: Iterable[str] = ("GET",),
104
+ summary: str | None = None,
105
+ description: str | None = None,
106
+ tags: Sequence[str] = (),
107
+ response_model: type[BaseModel] | None = None,
108
+ status_code: int = 200,
109
+ include_in_schema: bool = True,
110
+ ) -> Route:
111
+ method_set = frozenset({method.upper() for method in methods})
112
+ full_path = join_path(self.prefix, path)
113
+ for existing in self.routes:
114
+ if existing.path == full_path and existing.methods & method_set:
115
+ conflict = sorted(existing.methods & method_set)
116
+ raise RouteConflictError(
117
+ f"路由冲突: {conflict} {existing.path} 已注册(handler: {existing.name})"
118
+ )
119
+
120
+ route = Route(
121
+ path=full_path,
122
+ methods=frozenset({method.upper() for method in methods}),
123
+ handler=handler,
124
+ summary=summary or (handler.__doc__ or "").strip().split("\n")[0] or None,
125
+ description=description or (handler.__doc__ or "").strip() or None,
126
+ tags=tuple({*self.tags, *tags}),
127
+ response_model=response_model,
128
+ status_code=status_code,
129
+ include_in_schema=include_in_schema,
130
+ )
131
+ self.routes.append(route)
132
+ return route
133
+
134
+ def api_route(
135
+ self,
136
+ path: str,
137
+ *,
138
+ methods: Iterable[str] = ("GET",),
139
+ **kwargs: Any,
140
+ ) -> Callable[[Handler], Handler]:
141
+ def decorator(handler: Handler) -> Handler:
142
+ self.add_route(path, handler, methods=methods, **kwargs)
143
+ return handler
144
+
145
+ return decorator
146
+
147
+ def get(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
148
+ return self.api_route(path, methods=("GET",), **kwargs)
149
+
150
+ def post(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
151
+ return self.api_route(path, methods=("POST",), **kwargs)
152
+
153
+ def put(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
154
+ return self.api_route(path, methods=("PUT",), **kwargs)
155
+
156
+ def patch(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
157
+ return self.api_route(path, methods=("PATCH",), **kwargs)
158
+
159
+ def delete(self, path: str, **kwargs: Any) -> Callable[[Handler], Handler]:
160
+ return self.api_route(path, methods=("DELETE",), **kwargs)
161
+
162
+ def include_router(self, router: Router, *, prefix: str = "") -> None:
163
+ base = f"{self.prefix}{prefix}".rstrip("/")
164
+ for route in router.routes:
165
+ self.routes.append(
166
+ Route(
167
+ path=join_path(base, route.path),
168
+ methods=route.methods,
169
+ handler=route.handler,
170
+ plan=route.plan,
171
+ name=route.name,
172
+ summary=route.summary,
173
+ description=route.description,
174
+ tags=tuple({*self.tags, *route.tags}),
175
+ response_model=route.response_model,
176
+ status_code=route.status_code,
177
+ include_in_schema=route.include_in_schema,
178
+ )
179
+ )
180
+
181
+ # ---------------- 匹配 ----------------
182
+
183
+ def resolve(self, method: str, path: str) -> tuple[Route, dict[str, str]]:
184
+ """字面量路由优先于带参数的路由(`/admin/x/export.csv` 不该被 `/{slug}/{id}` 抢走)。"""
185
+ matches: list[tuple[int, Route, dict[str, str]]] = []
186
+ allowed: set[str] = set()
187
+ for route in self.routes:
188
+ params = route.match(path)
189
+ if params is None:
190
+ continue
191
+ allowed |= route.methods
192
+ if method in route.methods or (method == "HEAD" and "GET" in route.methods):
193
+ matches.append((len(route.param_names), route, params))
194
+ if matches:
195
+ matches.sort(key=lambda item: item[0])
196
+ _, route, params = matches[0]
197
+ return route, params
198
+ if allowed:
199
+ raise MethodNotAllowed(allowed=sorted(allowed))
200
+ raise NotFound(f"路径不存在: {path}")
@@ -0,0 +1,86 @@
1
+ """ASGI 基础类型与 Headers 实现(自研,零框架依赖)。
2
+
3
+ 只依赖 ASGI 规范本身:一个应用就是 `(scope, receive, send) -> None` 的可调用对象。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping, MutableMapping
9
+ from typing import Any
10
+
11
+ Scope = MutableMapping[str, Any]
12
+ Message = MutableMapping[str, Any]
13
+ Receive = Callable[[], Awaitable[Message]]
14
+ Send = Callable[[Message], Awaitable[None]]
15
+ ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
16
+
17
+
18
+ class Headers(Mapping[str, str]):
19
+ """大小写不敏感的只读头部集合(HTTP 头按 RFC 7230 不区分大小写)。"""
20
+
21
+ __slots__ = ("_map", "_raw")
22
+
23
+ def __init__(self, raw: Iterable[tuple[bytes, bytes]] = ()) -> None:
24
+ self._raw: list[tuple[bytes, bytes]] = list(raw)
25
+ self._map: dict[str, str] = {
26
+ key.decode("latin-1").lower(): value.decode("latin-1") for key, value in self._raw
27
+ }
28
+
29
+ @classmethod
30
+ def from_scope(cls, scope: Scope) -> Headers:
31
+ return cls(scope.get("headers") or ())
32
+
33
+ def __getitem__(self, key: str) -> str:
34
+ return self._map[key.lower()]
35
+
36
+ def __iter__(self) -> Iterator[str]:
37
+ return iter(self._map)
38
+
39
+ def __len__(self) -> int:
40
+ return len(self._map)
41
+
42
+ def get(self, key: str, default: str | None = None) -> str | None: # type: ignore[override]
43
+ return self._map.get(key.lower(), default)
44
+
45
+ def items(self) -> Iterable[tuple[str, str]]: # type: ignore[override]
46
+ return self._map.items()
47
+
48
+ @property
49
+ def raw(self) -> list[tuple[bytes, bytes]]:
50
+ return list(self._raw)
51
+
52
+
53
+ class MutableHeaders:
54
+ """用于在 `http.response.start` 上增删头部。"""
55
+
56
+ __slots__ = ("_message",)
57
+
58
+ def __init__(self, message: Message) -> None:
59
+ self._message = message
60
+
61
+ @property
62
+ def _headers(self) -> list[tuple[bytes, bytes]]:
63
+ headers: list[tuple[bytes, bytes]] = self._message.setdefault("headers", [])
64
+ return headers
65
+
66
+ def _remove(self, key: bytes) -> None:
67
+ self._headers[:] = [(k, v) for k, v in self._headers if k.lower() != key]
68
+
69
+ def __setitem__(self, key: str, value: str) -> None:
70
+ encoded = key.lower().encode("latin-1")
71
+ self._remove(encoded)
72
+ self._headers.append((encoded, value.encode("latin-1")))
73
+
74
+ def __contains__(self, key: str) -> bool:
75
+ encoded = key.lower().encode("latin-1")
76
+ return any(k.lower() == encoded for k, _ in self._headers)
77
+
78
+ def append(self, key: str, value: str) -> None:
79
+ self._headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))
80
+
81
+ def get(self, key: str, default: str | None = None) -> str | None:
82
+ encoded = key.lower().encode("latin-1")
83
+ for name, value in self._headers:
84
+ if name.lower() == encoded:
85
+ return value.decode("latin-1")
86
+ return default
@@ -0,0 +1,222 @@
1
+ """安全文件上传:流式落盘 + 文件名净化 + 大小/类型限制 + 病毒扫描钩子。
2
+
3
+ 客户的典型写法
4
+
5
+ path = root / tenant / request.headers["x-filename"]
6
+ path.write_bytes(await request.body())
7
+
8
+ 一次踩三个坑:`../` 穿越、全量读进内存、类型随便写。
9
+ 这里默认流式写临时文件,扫描通过后再原子改名——失败不留残file。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import hashlib
16
+ import re
17
+ import uuid
18
+ from collections.abc import Awaitable, Callable
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+
22
+ from swiftapi.core.errors.base import PayloadTooLarge, UnsupportedMediaType, UploadRejected
23
+ from swiftapi.core.http.multipart import is_multipart, read_multipart
24
+ from swiftapi.core.http.multipart_stream import spool_multipart
25
+ from swiftapi.core.http.request import Request
26
+
27
+ _SAFE_NAME = re.compile(r"[^A-Za-z0-9._-]+")
28
+ _RESERVED = {"", ".", "..", "con", "prn", "aux", "nul"}
29
+
30
+ #: 扫描钩子:拿到临时文件路径,抛异常即拒绝(例如检测到病毒)
31
+ ScanHook = Callable[[Path], Awaitable[None]]
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class StoredUpload:
36
+ path: Path
37
+ filename: str # 原始文件名(已净化,仅用于展示)
38
+ size: int
39
+ content_type: str
40
+ sha256: str
41
+
42
+
43
+ def safe_filename(raw: str | None, *, fallback: str = "upload.bin", max_length: int = 100) -> str:
44
+ """只保留 basename + 白名单字符,杜绝 `../`、NUL、换行、超长名。"""
45
+ candidate = (raw or "").replace("\\", "/").split("/")[-1]
46
+ candidate = candidate.replace("\x00", "").replace("\r", "").replace("\n", "")
47
+ candidate = _SAFE_NAME.sub("_", candidate).strip("._")
48
+ if candidate.lower() in _RESERVED:
49
+ return fallback
50
+ if not candidate:
51
+ return fallback
52
+ return candidate[:max_length]
53
+
54
+
55
+ def _resolve_within(root: Path, target: Path) -> Path:
56
+ resolved_root = root.resolve()
57
+ resolved = target.resolve()
58
+ if not resolved.is_relative_to(resolved_root):
59
+ raise ValueError(f"非法存储路径(逃逸出 {resolved_root})")
60
+ return resolved
61
+
62
+
63
+ def _spool_path(directory: Path) -> Path:
64
+ return directory / f".upload-{uuid.uuid4().hex}.part"
65
+
66
+
67
+ async def _finalize(
68
+ spool: Path,
69
+ target: Path,
70
+ digest: str,
71
+ scanner: ScanHook | None,
72
+ scan_timeout_s: float | None,
73
+ ) -> None:
74
+ """扫描 → 原子改名;任何异常都删掉临时文件。"""
75
+ try:
76
+ if scanner is not None:
77
+ if scan_timeout_s is not None:
78
+ try:
79
+ await asyncio.wait_for(scanner(spool), timeout=scan_timeout_s)
80
+ except TimeoutError as exc:
81
+ raise UploadRejected(f"文件扫描超时({scan_timeout_s}s)") from exc
82
+ else:
83
+ await scanner(spool)
84
+ await asyncio.to_thread(spool.replace, target)
85
+ except BaseException:
86
+ await asyncio.to_thread(spool.unlink, missing_ok=True)
87
+ raise
88
+
89
+
90
+ async def _save_multipart_streaming(
91
+ request: Request,
92
+ *,
93
+ raw_type: str,
94
+ directory: Path,
95
+ max_bytes: int,
96
+ max_parts: int,
97
+ allowed_types: frozenset[str] | None,
98
+ randomize_name: bool,
99
+ field_name: str,
100
+ scanner: ScanHook | None,
101
+ scan_timeout_s: float | None,
102
+ ) -> StoredUpload:
103
+ streamed = await spool_multipart(
104
+ request.iter_chunks(max_bytes=max_bytes),
105
+ content_type=raw_type,
106
+ directory=directory,
107
+ max_part_bytes=max_bytes,
108
+ max_parts=max_parts,
109
+ want_field=field_name,
110
+ )
111
+ if streamed is None:
112
+ raise UnsupportedMediaType("multipart 中没有文件字段(用 file 或 x-filename 指定字段名)")
113
+
114
+ content_type = streamed.content_type.split(";")[0].strip().lower()
115
+ if allowed_types is not None and content_type not in allowed_types:
116
+ await asyncio.to_thread(streamed.path.unlink, missing_ok=True)
117
+ raise UnsupportedMediaType(f"不支持的文件类型: {content_type}")
118
+
119
+ original = safe_filename(streamed.filename)
120
+ stored_name = f"{uuid.uuid4().hex}{Path(original).suffix}" if randomize_name else original
121
+ target = _resolve_within(directory, directory / stored_name)
122
+ await _finalize(streamed.path, target, streamed.sha256, scanner, scan_timeout_s)
123
+ return StoredUpload(
124
+ path=target,
125
+ filename=original,
126
+ size=streamed.size,
127
+ content_type=content_type,
128
+ sha256=streamed.sha256,
129
+ )
130
+
131
+
132
+ async def save_upload(
133
+ request: Request,
134
+ *,
135
+ root: Path,
136
+ tenant_slug: str | None = None,
137
+ max_bytes: int = 10 * 1024 * 1024,
138
+ allowed_types: frozenset[str] | None = None,
139
+ randomize_name: bool = True,
140
+ field_name: str = "x-filename",
141
+ streaming: bool = True,
142
+ max_parts: int = 10,
143
+ scanner: ScanHook | None = None,
144
+ scan_timeout_s: float | None = None,
145
+ ) -> StoredUpload:
146
+ """把上传落盘。默认流式写临时文件,`scanner` 通过后原子改名。"""
147
+ raw_type = request.headers.get("content-type") or "application/octet-stream"
148
+ multipart = is_multipart(raw_type)
149
+
150
+ directory = (root / tenant_slug) if tenant_slug else root
151
+ directory.mkdir(parents=True, exist_ok=True)
152
+
153
+ if multipart and streaming:
154
+ return await _save_multipart_streaming(
155
+ request,
156
+ raw_type=raw_type,
157
+ directory=directory,
158
+ max_bytes=max_bytes,
159
+ max_parts=max_parts,
160
+ allowed_types=allowed_types,
161
+ randomize_name=randomize_name,
162
+ field_name=field_name,
163
+ scanner=scanner,
164
+ scan_timeout_s=scan_timeout_s,
165
+ )
166
+
167
+ if multipart:
168
+ parts = await read_multipart(request, max_total_bytes=max_bytes, max_part_bytes=max_bytes)
169
+ selected = [part for part in parts if not field_name or part.field in {field_name, "file"}]
170
+ if not selected:
171
+ raise UnsupportedMediaType("multipart 中没有文件字段(用 file 或 x-filename 指定字段名)")
172
+ part = selected[0]
173
+ content_type = part.content_type.split(";")[0].strip().lower()
174
+ original = safe_filename(part.filename)
175
+ chunks: list[bytes] | None = [part.content]
176
+ else:
177
+ content_type = raw_type.split(";")[0].strip().lower()
178
+ original = safe_filename(request.headers.get(field_name))
179
+ chunks = None
180
+
181
+ if allowed_types is not None and content_type not in allowed_types:
182
+ raise UnsupportedMediaType(f"不支持的文件类型: {content_type}")
183
+
184
+ stored_name = f"{uuid.uuid4().hex}{Path(original).suffix}" if randomize_name else original
185
+ target = _resolve_within(directory, directory / stored_name)
186
+ spool = _spool_path(directory)
187
+
188
+ hasher = hashlib.sha256()
189
+ size = 0
190
+ try:
191
+ with spool.open("xb") as handle:
192
+ if chunks is not None:
193
+ for chunk in chunks:
194
+ size += len(chunk)
195
+ if size > max_bytes:
196
+ raise PayloadTooLarge(f"文件超过上限 {max_bytes} 字节")
197
+ hasher.update(chunk)
198
+ handle.write(chunk)
199
+ elif streaming:
200
+ async for chunk in request.iter_chunks(max_bytes=max_bytes):
201
+ size += len(chunk)
202
+ hasher.update(chunk)
203
+ handle.write(chunk)
204
+ else:
205
+ body = await request.body()
206
+ if len(body) > max_bytes:
207
+ raise PayloadTooLarge(f"文件超过上限 {max_bytes} 字节")
208
+ size = len(body)
209
+ hasher.update(body)
210
+ handle.write(body)
211
+ except BaseException:
212
+ await asyncio.to_thread(spool.unlink, missing_ok=True)
213
+ raise
214
+
215
+ digest = hasher.hexdigest()
216
+ await _finalize(spool, target, digest, scanner, scan_timeout_s)
217
+ return StoredUpload(
218
+ path=target, filename=original, size=size, content_type=content_type, sha256=digest
219
+ )
220
+
221
+
222
+ __all__ = ["ScanHook", "StoredUpload", "safe_filename", "save_upload"]
File without changes
@@ -0,0 +1,33 @@
1
+ """事件信封与总线协议(架构文档 §17.6)。
2
+
3
+ 至少一次投递 + 消费幂等 = 效果一次。不承诺 exactly-once。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from datetime import UTC, datetime
9
+ from typing import Any, Protocol
10
+ from uuid import UUID, uuid4
11
+
12
+ from pydantic import Field
13
+
14
+ from swiftapi.core.validation.base import EventModel
15
+
16
+
17
+ class EventEnvelope(EventModel):
18
+ event_id: UUID = Field(default_factory=uuid4)
19
+ event_type: str = Field(min_length=3, max_length=128)
20
+ event_version: int = Field(default=1, ge=1)
21
+ occurred_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
22
+ trace_id: str | None = None
23
+ tenant_id: UUID | None = None
24
+ payload: dict[str, Any] = Field(default_factory=dict)
25
+
26
+
27
+ class MessageBus(Protocol):
28
+ async def publish(self, envelope: EventEnvelope) -> None: ...
29
+
30
+ async def close(self) -> None: ...
31
+
32
+
33
+ __all__ = ["EventEnvelope", "MessageBus"]