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,65 @@
1
+ """工作单元:一次用例一个事务(架构文档 §10.5)。
2
+
3
+ 语义:
4
+ - 最外层 `async with uow:` 开启事务,正常退出 commit,异常 rollback;
5
+ - 嵌套进入不单独提交(复用外层事务),避免"用例中途提交"导致的半个事务;
6
+ - `uow.session` 是唯一入口,repository/crud 不持有提交权。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from types import TracebackType
12
+ from typing import Self
13
+
14
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
15
+
16
+
17
+ class UnitOfWork:
18
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
19
+ self._factory = session_factory
20
+ self._session: AsyncSession | None = None
21
+ self._depth = 0
22
+
23
+ @property
24
+ def session(self) -> AsyncSession:
25
+ if self._session is None:
26
+ raise RuntimeError("UnitOfWork 未进入:请使用 `async with uow:`")
27
+ return self._session
28
+
29
+ @property
30
+ def active(self) -> bool:
31
+ return self._session is not None
32
+
33
+ async def __aenter__(self) -> Self:
34
+ self._depth += 1
35
+ if self._session is None:
36
+ self._session = self._factory()
37
+ await self._session.begin()
38
+ return self
39
+
40
+ async def __aexit__(
41
+ self,
42
+ exc_type: type[BaseException] | None,
43
+ exc: BaseException | None,
44
+ tb: TracebackType | None,
45
+ ) -> None:
46
+ assert self._session is not None
47
+ self._depth -= 1
48
+ if self._depth > 0:
49
+ # 嵌套:不提交也不回滚,交给最外层决定(避免内层吞掉异常导致的半提交)
50
+ return
51
+ try:
52
+ # 只读事务不发 COMMIT:PG 上每次提交都是一次 fsync,
53
+ # 读接口会因此多出 5~10ms 延迟(稳定性测试发现)。
54
+ # close() 隐式回滚,且不会让已加载对象过期。
55
+ pending = bool(
56
+ self._session.new or self._session.dirty or self._session.deleted
57
+ )
58
+ wrote = bool(self._session.info.get("swiftapi_wrote")) or pending
59
+ if exc_type is not None or not wrote:
60
+ await self._session.rollback() if exc_type is not None else await self._session.close()
61
+ else:
62
+ await self._session.commit()
63
+ finally:
64
+ await self._session.close()
65
+ self._session = None
File without changes
@@ -0,0 +1,26 @@
1
+ """文档页路由:`/docs`(HTML)+ 指向 `/openapi.json` 的契约入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from swiftapi.config.settings import DocsSettings
9
+ from swiftapi.core.docs.ui import render_docs
10
+ from swiftapi.core.http.responses import HTMLResponse, Response
11
+ from swiftapi.core.http.routing import Router
12
+
13
+
14
+ def build_docs_router(
15
+ settings: DocsSettings, openapi_provider: Callable[[], dict[str, Any]]
16
+ ) -> Router:
17
+ router = Router(tags=("docs",))
18
+
19
+ @router.get(settings.path, include_in_schema=False)
20
+ async def docs_page() -> Response:
21
+ return HTMLResponse(render_docs(openapi_provider(), title=settings.title))
22
+
23
+ return router
24
+
25
+
26
+ __all__ = ["build_docs_router"]
@@ -0,0 +1,93 @@
1
+ """从 OpenAPI 生成 TypeScript 类型:契约单一源头的最后一环。
2
+
3
+ 只依赖 `/openapi.json`,不读 Python 代码——保证"文档写的就是前端拿到的"。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ _TS_TYPES = {
11
+ "string": "string",
12
+ "integer": "number",
13
+ "number": "number",
14
+ "boolean": "boolean",
15
+ "null": "null",
16
+ }
17
+
18
+
19
+ def _ts_type(schema: dict[str, Any]) -> str:
20
+ if not schema:
21
+ return "unknown"
22
+ if "$ref" in schema:
23
+ return str(schema["$ref"]).split("/")[-1]
24
+ if "anyOf" in schema:
25
+ return " | ".join(_ts_type(item) for item in schema["anyOf"])
26
+ if schema.get("enum"):
27
+ return " | ".join(f'"{value}"' for value in schema["enum"])
28
+ schema_type = schema.get("type")
29
+ if schema_type == "array":
30
+ item = _ts_type(schema.get("items", {}))
31
+ return f"({item})[]" if " | " in item else f"{item}[]"
32
+ if schema_type == "object" or "properties" in schema:
33
+ properties = schema.get("properties") or {}
34
+ if not properties:
35
+ return "Record<string, unknown>"
36
+ body = "; ".join(
37
+ f"{name}{'?' if name not in schema.get('required', []) else ''}: {_ts_type(value)}"
38
+ for name, value in properties.items()
39
+ )
40
+ return "{ " + body + " }"
41
+ return _TS_TYPES.get(str(schema_type), "unknown")
42
+
43
+
44
+ def _interface(name: str, schema: dict[str, Any]) -> str:
45
+ required = set(schema.get("required", []))
46
+ lines = [f"export interface {name} {{"]
47
+ for prop, prop_schema in (schema.get("properties") or {}).items():
48
+ optional = "" if prop in required else "?"
49
+ lines.append(f" {prop}{optional}: {_ts_type(prop_schema)};")
50
+ lines.append("}")
51
+ return "\n".join(lines)
52
+
53
+
54
+ def generate_typescript(spec: dict[str, Any]) -> str:
55
+ chunks: list[str] = [
56
+ "// AUTO-GENERATED from /openapi.json — do not edit by hand.",
57
+ f"// API: {spec.get('info', {}).get('title', '')} v{spec.get('info', {}).get('version', '')}",
58
+ "",
59
+ ]
60
+
61
+ schemas = (spec.get("components") or {}).get("schemas") or {}
62
+ for name, schema in sorted(schemas.items()):
63
+ chunks.append(_interface(name, schema))
64
+ chunks.append("")
65
+
66
+ chunks.append("export interface ApiOperations {")
67
+ for path, operations in sorted((spec.get("paths") or {}).items()):
68
+ for method, operation in sorted(operations.items()):
69
+ operation_id = operation.get("operationId") or f"{method}_{path}"
70
+ body_schema = (
71
+ operation.get("requestBody", {})
72
+ .get("content", {})
73
+ .get("application/json", {})
74
+ .get("schema")
75
+ )
76
+ response_schema = (
77
+ (operation.get("responses", {}).get("200") or operation.get("responses", {}).get("201"))
78
+ or {}
79
+ ).get("content", {}).get("application/json", {}).get("schema")
80
+ chunks.append(f' "{operation_id}": {{')
81
+ chunks.append(f' method: "{method.upper()}";')
82
+ chunks.append(f' path: "{path}";')
83
+ if body_schema:
84
+ chunks.append(f" body: {_ts_type(body_schema)};")
85
+ if response_schema:
86
+ chunks.append(f" response: {_ts_type(response_schema)};")
87
+ chunks.append(" };")
88
+ chunks.append("}")
89
+ chunks.append("")
90
+ return "\n".join(chunks)
91
+
92
+
93
+ __all__ = ["generate_typescript"]
@@ -0,0 +1,132 @@
1
+ """文档页:服务端渲染 OpenAPI(零 CDN、零构建、无 JS 依赖)。
2
+
3
+ 设计取舍:P5 不引入 Vite/React——文档页的价值是"准确 + 离线可用",
4
+ 不是交互炫技。服务端渲染 100% 由 `/openapi.json` 驱动,契约变了页面自动变。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from html import escape
10
+ from typing import Any
11
+
12
+ _CSS = """
13
+ :root { color-scheme: light dark; --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --code:#f6f8fa; --accent:#0969da; }
14
+ @media (prefers-color-scheme: dark) { :root { --fg:#e6edf3; --muted:#9198a1; --line:#3d444d; --bg:#0d1117; --code:#161b22; --accent:#4493f8; } }
15
+ * { box-sizing: border-box; }
16
+ body { margin:0; font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,"PingFang SC","Microsoft YaHei",sans-serif; color:var(--fg); background:var(--bg); }
17
+ header { padding:28px 32px; border-bottom:1px solid var(--line); }
18
+ h1 { margin:0 0 6px; font-size:24px; }
19
+ h2 { margin:36px 0 12px; font-size:19px; border-bottom:1px solid var(--line); padding-bottom:8px; }
20
+ main { max-width: 1080px; padding: 8px 32px 80px; }
21
+ .muted { color: var(--muted); }
22
+ .op { border:1px solid var(--line); border-radius:8px; padding:14px 16px; margin:12px 0; }
23
+ .method { display:inline-block; font:600 12px/1 ui-monospace,monospace; padding:5px 8px; border-radius:5px; color:#fff; margin-right:8px; }
24
+ .get{background:#1f883d}.post{background:#0969da}.put{background:#9a6700}.patch{background:#8250df}.delete{background:#cf222e}
25
+ .path { font:600 14px ui-monospace,monospace; }
26
+ code { background:var(--code); padding:2px 5px; border-radius:4px; font:13px ui-monospace,monospace; }
27
+ table { border-collapse: collapse; width:100%; margin:8px 0 4px; font-size:14px; }
28
+ th,td { text-align:left; padding:6px 10px; border-bottom:1px solid var(--line); vertical-align:top; }
29
+ th { color:var(--muted); font-weight:600; }
30
+ .tag { display:inline-block; font-size:12px; color:var(--muted); border:1px solid var(--line); border-radius:999px; padding:1px 8px; margin-left:6px; }
31
+ footer { padding:24px 32px; border-top:1px solid var(--line); color:var(--muted); font-size:13px; }
32
+ """
33
+
34
+
35
+ def _schema_label(schema: dict[str, Any]) -> str:
36
+ if not schema:
37
+ return "—"
38
+ ref = schema.get("$ref")
39
+ if ref:
40
+ return f"`{ref.split('/')[-1]}`"
41
+ if "type" in schema:
42
+ extra = ""
43
+ if schema.get("format"):
44
+ extra = f" ({schema['format']})"
45
+ return f"{schema['type']}{extra}"
46
+ return "—"
47
+
48
+
49
+ def _params_table(operation: dict[str, Any]) -> str:
50
+ params = operation.get("parameters") or []
51
+ if not params:
52
+ return ""
53
+ rows = "".join(
54
+ f"<tr><td><code>{escape(str(item.get('name', '')))}</code></td>"
55
+ f"<td>{escape(str(item.get('in', '')))}</td>"
56
+ f"<td>{'是' if item.get('required') else '否'}</td>"
57
+ f"<td><code>{escape(str(item.get('schema', {}).get('type', '—')))}</code></td></tr>"
58
+ for item in params
59
+ )
60
+ return (
61
+ "<table><thead><tr><th>参数</th><th>位置</th><th>必填</th><th>类型</th></tr></thead>"
62
+ f"<tbody>{rows}</tbody></table>"
63
+ )
64
+
65
+
66
+ def _body_block(operation: dict[str, Any]) -> str:
67
+ body = operation.get("requestBody")
68
+ if not body:
69
+ return ""
70
+ schema = body.get("content", {}).get("application/json", {}).get("schema", {})
71
+ return f"<p class='muted'>请求体:{_schema_label(schema)}</p>"
72
+
73
+
74
+ def _responses(operation: dict[str, Any]) -> str:
75
+ responses = operation.get("responses") or {}
76
+ return "<p class='muted'>响应:" + " · ".join(escape(code) for code in responses) + "</p>"
77
+
78
+
79
+ def render_docs(spec: dict[str, Any], *, title: str | None = None) -> str:
80
+ info = spec.get("info", {})
81
+ page_title = title or info.get("title", "API")
82
+ version = escape(str(info.get("version", "")))
83
+
84
+ groups: dict[str, list[tuple[str, str, dict[str, Any]]]] = {}
85
+ for path, operations in sorted(spec.get("paths", {}).items()):
86
+ for method, operation in sorted(operations.items()):
87
+ tags = operation.get("tags") or ["default"]
88
+ for tag in tags:
89
+ groups.setdefault(str(tag), []).append((method, path, operation))
90
+
91
+ sections: list[str] = []
92
+ for tag, items in groups.items():
93
+ blocks: list[str] = [f"<h2>{escape(tag)}</h2>"]
94
+ for method, path, operation in items:
95
+ summary = escape(str(operation.get("summary") or operation.get("operationId") or ""))
96
+ operation_id = escape(str(operation.get("operationId") or ""))
97
+ description = escape(str(operation.get("description") or "")).split("\n")[0]
98
+ blocks.append(
99
+ "<div class='op'>"
100
+ f"<div><span class='method {escape(method)}'>{escape(method.upper())}</span>"
101
+ f"<span class='path'>{escape(path)}</span></div>"
102
+ f"<p><strong>{summary}</strong>"
103
+ + (f"<br><span class='muted'>{description}</span>" if description else "")
104
+ + (f"<br><span class='muted'>operationId: <code>{operation_id}</code></span>" if operation_id else "")
105
+ + "</p>"
106
+ + _params_table(operation)
107
+ + _body_block(operation)
108
+ + _responses(operation)
109
+ + "</div>"
110
+ )
111
+ sections.append("".join(blocks))
112
+
113
+ schema_names = sorted((spec.get("components", {}).get("schemas") or {}).keys())
114
+ schema_html = ""
115
+ if schema_names:
116
+ schema_items = "".join(f"<li><code>{escape(name)}</code></li>" for name in schema_names)
117
+ schema_html = f"<h2>数据模型</h2><ul>{schema_items}</ul>"
118
+
119
+ return f"""<!doctype html>
120
+ <html lang="zh-CN"><head><meta charset="utf-8">
121
+ <meta name="viewport" content="width=device-width, initial-scale=1">
122
+ <title>{escape(page_title)} · API 文档</title>
123
+ <style>{_CSS}</style></head>
124
+ <body>
125
+ <header><h1>{escape(page_title)} <span class="tag">v{version}</span></h1>
126
+ <p class="muted">由 <code>/openapi.json</code> 服务端渲染 · 无 CDN · 可离线浏览</p></header>
127
+ <main>{''.join(sections)}{schema_html}</main>
128
+ <footer>契约版本 {version} · <a href="/openapi.json">/openapi.json</a></footer>
129
+ </body></html>"""
130
+
131
+
132
+ __all__ = ["render_docs"]
File without changes
@@ -0,0 +1,168 @@
1
+ """异常体系:领域错误与 HTTP 解耦。
2
+
3
+ 规则(架构文档 §9.4):
4
+ - service 抛 `AppError` 子类或 `DomainError`,**禁止**抛 `HTTPException`;
5
+ - 只有到 handlers 层才翻译成 HTTP 状态码;
6
+ - `expose=False` 时对外只给固定文案,真实信息只进日志。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from typing import Any, ClassVar
13
+
14
+ from swiftapi.core.errors.codes import ErrorCode, spec_for
15
+
16
+
17
+ class AppError(Exception):
18
+ """所有可预期错误的基类。"""
19
+
20
+ default_code: ClassVar[ErrorCode] = ErrorCode.INTERNAL_ERROR
21
+ default_expose: ClassVar[bool] = True
22
+
23
+ def __init__(
24
+ self,
25
+ detail: str | None = None,
26
+ *,
27
+ code: ErrorCode | None = None,
28
+ headers: Mapping[str, str] | None = None,
29
+ extra: Mapping[str, Any] | None = None,
30
+ expose: bool | None = None,
31
+ ) -> None:
32
+ self.code: ErrorCode = code or self.default_code
33
+ self.detail: str = detail or spec_for(self.code).title
34
+ self.headers: dict[str, str] = dict(headers or {})
35
+ self.extra: dict[str, Any] = dict(extra or {})
36
+ self.expose: bool = self.default_expose if expose is None else expose
37
+ super().__init__(self.detail)
38
+
39
+ @property
40
+ def status(self) -> int:
41
+ return spec_for(self.code).status
42
+
43
+ @property
44
+ def title(self) -> str:
45
+ return spec_for(self.code).title
46
+
47
+ def __str__(self) -> str:
48
+ return f"[{self.code}] {self.detail}"
49
+
50
+
51
+ class DomainError(AppError):
52
+ """业务模块自定义错误:必须显式给出 code。"""
53
+
54
+ def __init__(self, code: ErrorCode, detail: str | None = None, **kwargs: Any) -> None:
55
+ super().__init__(detail, code=code, **kwargs)
56
+
57
+
58
+ class NotFound(AppError):
59
+ default_code = ErrorCode.NOT_FOUND
60
+
61
+
62
+ class MethodNotAllowed(AppError):
63
+ default_code = ErrorCode.METHOD_NOT_ALLOWED
64
+
65
+ def __init__(self, allowed: list[str] | None = None, detail: str | None = None) -> None:
66
+ headers = {"Allow": ", ".join(allowed or [])} if allowed else None
67
+ super().__init__(detail, headers=headers)
68
+
69
+
70
+ class Conflict(AppError):
71
+ default_code = ErrorCode.CONFLICT
72
+
73
+
74
+ class VersionConflict(AppError):
75
+ default_code = ErrorCode.VERSION_CONFLICT
76
+
77
+
78
+ class PermissionDenied(AppError):
79
+ default_code = ErrorCode.PERMISSION_DENIED
80
+
81
+
82
+ class Unauthenticated(AppError):
83
+ default_code = ErrorCode.UNAUTHENTICATED
84
+
85
+
86
+ class TokenExpired(AppError):
87
+ default_code = ErrorCode.TOKEN_EXPIRED
88
+
89
+
90
+ class PayloadTooLarge(AppError):
91
+ default_code = ErrorCode.PAYLOAD_TOO_LARGE
92
+
93
+
94
+ class UnsupportedMediaType(AppError):
95
+ default_code = ErrorCode.UNSUPPORTED_MEDIA_TYPE
96
+
97
+
98
+ class RateLimited(AppError):
99
+ default_code = ErrorCode.RATE_LIMITED
100
+
101
+ def __init__(self, detail: str | None = None, *, retry_after: int = 1, **kwargs: Any) -> None:
102
+ headers = dict(kwargs.pop("headers", {}) or {})
103
+ headers.setdefault("Retry-After", str(max(1, retry_after)))
104
+ super().__init__(detail, headers=headers, **kwargs)
105
+
106
+
107
+ class DependencyUnavailable(AppError):
108
+ default_code = ErrorCode.DEPENDENCY_UNAVAILABLE
109
+
110
+
111
+ class CircuitOpen(AppError):
112
+ default_code = ErrorCode.CIRCUIT_OPEN
113
+
114
+
115
+ class ServiceDraining(AppError):
116
+ default_code = ErrorCode.SERVICE_DRAINING
117
+
118
+ def __init__(self, detail: str | None = None, **kwargs: Any) -> None:
119
+ headers = dict(kwargs.pop("headers", {}) or {})
120
+ headers.setdefault("Connection", "close")
121
+ super().__init__(detail, headers=headers, **kwargs)
122
+
123
+
124
+ class RequestTimeout(AppError):
125
+ default_code = ErrorCode.TIMEOUT
126
+
127
+
128
+ class UploadRejected(AppError):
129
+ """扫描钩子判定文件不合格(病毒/敏感内容)。"""
130
+
131
+ default_code = ErrorCode.UPLOAD_REJECTED
132
+
133
+
134
+ class InvalidArgument(AppError):
135
+ """客户端参数不合法(如排序字段不存在)——422,不是 500。"""
136
+
137
+ default_code = ErrorCode.VALIDATION_ERROR
138
+
139
+
140
+ class FeatureNotImplemented(AppError):
141
+ """显式占位:接口已注册但业务未实现(501,而不是假装 200)。"""
142
+
143
+ default_code = ErrorCode.NOT_IMPLEMENTED
144
+
145
+
146
+ class InternalError(AppError):
147
+ default_code = ErrorCode.INTERNAL_ERROR
148
+ default_expose = False
149
+
150
+
151
+ class TenantError(AppError):
152
+ """多租户错误族的基类,子类指定具体 code。"""
153
+
154
+
155
+ class TenantNotFound(TenantError):
156
+ default_code = ErrorCode.TENANT_NOT_FOUND
157
+
158
+
159
+ class TenantMismatch(TenantError):
160
+ default_code = ErrorCode.TENANT_MISMATCH
161
+
162
+
163
+ class TenantSuspended(TenantError):
164
+ default_code = ErrorCode.TENANT_SUSPENDED
165
+
166
+
167
+ class TenantRequired(TenantError):
168
+ default_code = ErrorCode.TENANT_REQUIRED
@@ -0,0 +1,117 @@
1
+ """错误码注册表:全项目唯一的 code 来源。
2
+
3
+ 规则(架构文档 §23):
4
+ 1. 命名 `<DOMAIN>_<REASON>`,大写下划线;
5
+ 2. 每个 code 绑定 HTTP 状态、标题、错误文档 slug;
6
+ 3. 业务模块只能引用这里的枚举,禁止硬编码字符串。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from enum import StrEnum
13
+ from typing import Final
14
+
15
+ from swiftapi.config.constants import PROBLEM_TYPE_BASE
16
+
17
+
18
+ class ErrorCode(StrEnum):
19
+ # ---- 平台通用 ----
20
+ VALIDATION_ERROR = "VALIDATION_ERROR"
21
+ UNAUTHENTICATED = "UNAUTHENTICATED"
22
+ TOKEN_EXPIRED = "TOKEN_EXPIRED"
23
+ PERMISSION_DENIED = "PERMISSION_DENIED"
24
+ NOT_FOUND = "NOT_FOUND"
25
+ METHOD_NOT_ALLOWED = "METHOD_NOT_ALLOWED"
26
+ CONFLICT = "CONFLICT"
27
+ VERSION_CONFLICT = "VERSION_CONFLICT"
28
+ IDEMPOTENCY_KEY_REUSED = "IDEMPOTENCY_KEY_REUSED"
29
+ IDEMPOTENCY_IN_PROGRESS = "IDEMPOTENCY_IN_PROGRESS"
30
+ UPLOAD_REJECTED = "UPLOAD_REJECTED"
31
+ PAYLOAD_TOO_LARGE = "PAYLOAD_TOO_LARGE"
32
+ UNSUPPORTED_MEDIA_TYPE = "UNSUPPORTED_MEDIA_TYPE"
33
+ RATE_LIMITED = "RATE_LIMITED"
34
+ INTERNAL_ERROR = "INTERNAL_ERROR"
35
+ NOT_IMPLEMENTED = "NOT_IMPLEMENTED"
36
+ DEPENDENCY_UNAVAILABLE = "DEPENDENCY_UNAVAILABLE"
37
+ CIRCUIT_OPEN = "CIRCUIT_OPEN"
38
+ SERVICE_DRAINING = "SERVICE_DRAINING"
39
+ TIMEOUT = "TIMEOUT"
40
+ BACKEND_UNAVAILABLE = "BACKEND_UNAVAILABLE"
41
+ SCHEMA_OUT_OF_DATE = "SCHEMA_OUT_OF_DATE"
42
+
43
+ # ---- 多租户 ----
44
+ TENANT_REQUIRED = "TENANT_REQUIRED"
45
+ TENANT_NOT_FOUND = "TENANT_NOT_FOUND"
46
+ TENANT_MISMATCH = "TENANT_MISMATCH"
47
+ TENANT_SUSPENDED = "TENANT_SUSPENDED"
48
+ TENANT_NOT_READY = "TENANT_NOT_READY"
49
+ TENANT_QUOTA_EXCEEDED = "TENANT_QUOTA_EXCEEDED"
50
+ TENANT_CROSS_ACCESS = "TENANT_CROSS_ACCESS"
51
+
52
+ # ---- 用户域(示例模块) ----
53
+ USER_NOT_FOUND = "USER_NOT_FOUND"
54
+ USER_EMAIL_TAKEN = "USER_EMAIL_TAKEN"
55
+ USER_DISABLED = "USER_DISABLED"
56
+ USER_WEAK_PASSWORD = "USER_WEAK_PASSWORD"
57
+ USER_CANNOT_DELETE_SELF = "USER_CANNOT_DELETE_SELF"
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class ProblemSpec:
62
+ status: int
63
+ title: str
64
+ slug: str
65
+
66
+ @property
67
+ def type_uri(self) -> str:
68
+ return f"{PROBLEM_TYPE_BASE}/{self.slug}"
69
+
70
+
71
+ _SPECS: Final[tuple[tuple[ErrorCode, int, str, str], ...]] = (
72
+ (ErrorCode.VALIDATION_ERROR, 422, "Request validation failed", "validation"),
73
+ (ErrorCode.UNAUTHENTICATED, 401, "Authentication required", "unauthenticated"),
74
+ (ErrorCode.TOKEN_EXPIRED, 401, "Token expired", "token-expired"),
75
+ (ErrorCode.PERMISSION_DENIED, 403, "Permission denied", "permission-denied"),
76
+ (ErrorCode.NOT_FOUND, 404, "Resource not found", "not-found"),
77
+ (ErrorCode.METHOD_NOT_ALLOWED, 405, "Method not allowed", "method-not-allowed"),
78
+ (ErrorCode.CONFLICT, 409, "Conflict", "conflict"),
79
+ (ErrorCode.VERSION_CONFLICT, 409, "Version conflict", "version-conflict"),
80
+ (ErrorCode.UPLOAD_REJECTED, 422, "Upload rejected", "upload-rejected"),
81
+ (ErrorCode.IDEMPOTENCY_IN_PROGRESS, 409, "Idempotency key in progress", "idempotency-in-progress"),
82
+ (ErrorCode.IDEMPOTENCY_KEY_REUSED, 409, "Idempotency key reused", "idempotency-key-reused"),
83
+ (ErrorCode.PAYLOAD_TOO_LARGE, 413, "Payload too large", "payload-too-large"),
84
+ (ErrorCode.UNSUPPORTED_MEDIA_TYPE, 415, "Unsupported media type", "unsupported-media-type"),
85
+ (ErrorCode.RATE_LIMITED, 429, "Rate limit exceeded", "rate-limited"),
86
+ (ErrorCode.INTERNAL_ERROR, 500, "Internal server error", "internal-error"),
87
+ (ErrorCode.NOT_IMPLEMENTED, 501, "Not implemented", "not-implemented"),
88
+ (ErrorCode.DEPENDENCY_UNAVAILABLE, 503, "Dependency unavailable", "dependency-unavailable"),
89
+ (ErrorCode.CIRCUIT_OPEN, 503, "Circuit breaker open", "circuit-open"),
90
+ (ErrorCode.SERVICE_DRAINING, 503, "Service is draining", "service-draining"),
91
+ (ErrorCode.TIMEOUT, 504, "Request timed out", "timeout"),
92
+ (ErrorCode.BACKEND_UNAVAILABLE, 503, "Backend unavailable", "backend-unavailable"),
93
+ (ErrorCode.SCHEMA_OUT_OF_DATE, 503, "Database schema out of date", "schema-out-of-date"),
94
+ (ErrorCode.TENANT_REQUIRED, 400, "Tenant required", "tenant-required"),
95
+ (ErrorCode.TENANT_NOT_FOUND, 404, "Tenant not found", "tenant-not-found"),
96
+ (ErrorCode.TENANT_MISMATCH, 403, "Tenant mismatch", "tenant-mismatch"),
97
+ (ErrorCode.TENANT_SUSPENDED, 403, "Tenant suspended", "tenant-suspended"),
98
+ (ErrorCode.TENANT_NOT_READY, 503, "Tenant not ready", "tenant-not-ready"),
99
+ (ErrorCode.TENANT_QUOTA_EXCEEDED, 429, "Tenant quota exceeded", "tenant-quota-exceeded"),
100
+ (ErrorCode.TENANT_CROSS_ACCESS, 404, "Resource not found", "not-found"),
101
+ (ErrorCode.USER_NOT_FOUND, 404, "User not found", "user-not-found"),
102
+ (ErrorCode.USER_EMAIL_TAKEN, 409, "Email already registered", "user-email-taken"),
103
+ (ErrorCode.USER_DISABLED, 403, "User disabled", "user-disabled"),
104
+ (ErrorCode.USER_WEAK_PASSWORD, 422, "Weak password", "user-weak-password"),
105
+ (ErrorCode.USER_CANNOT_DELETE_SELF, 409, "Cannot delete self", "user-cannot-delete-self"),
106
+ )
107
+
108
+ SPECS: Final[dict[ErrorCode, ProblemSpec]] = {
109
+ code: ProblemSpec(status=status, title=title, slug=slug)
110
+ for code, status, title, slug in _SPECS
111
+ }
112
+
113
+ assert set(SPECS) == set(ErrorCode), "每个 ErrorCode 必须注册 ProblemSpec"
114
+
115
+
116
+ def spec_for(code: ErrorCode) -> ProblemSpec:
117
+ return SPECS.get(code, SPECS[ErrorCode.INTERNAL_ERROR])