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,657 @@
1
+ """`swiftapi new resource`:生成一条完整的 CRUD 竖切(含可运行测试)。
2
+
3
+ 为什么不是一个"骨架 + TODO":生成器只保证结构正确时,用户仍要手写
4
+ service/测试,第一小时体验断在"骨架能跑但业务是空"这一步。
5
+ 这里直接生成**可运行、可测试**的最小业务:建/查/改/删 + 事件 + 测试。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import shutil
12
+ import string
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import typer
18
+ from rich.console import Console
19
+
20
+ resource_app = typer.Typer(help="生成 CRUD 资源(model/schema/service/router/test)", no_args_is_help=True)
21
+ console = Console()
22
+
23
+
24
+ def _render_variant(content: str, *, idempotency: bool) -> str:
25
+ """保留所需分支,丢弃另一分支与所有标记行。"""
26
+ drop = "plain" if idempotency else "idempotency"
27
+ content = re.sub(rf"[ \t]*# <{drop}>.*?# </{drop}>\n", "", content, flags=re.S)
28
+ return re.sub(r"[ \t]*# </?(idempotency|plain)>[^\n]*\n", "", content)
29
+
30
+
31
+ def _camel(name: str) -> str:
32
+ return "".join(part.capitalize() for part in re.split(r"[_\-\s]+", name) if part)
33
+
34
+
35
+ MODEL = '''"""${title} 模型(由 swiftapi new resource 生成)。"""
36
+
37
+ from __future__ import annotations
38
+
39
+ import uuid
40
+ from typing import Any
41
+ from uuid import UUID
42
+
43
+ from sqlalchemy.orm import Mapped, mapped_column
44
+
45
+ from swiftapi.db import (
46
+ LongText,
47
+ ShortText,
48
+ SoftDeleteMixin,
49
+ TenantScopedModel,
50
+ TimestampMixin,
51
+ UUIDType,
52
+ VersionMixin,
53
+ )
54
+
55
+
56
+ class ${model}(TenantScopedModel, TimestampMixin, SoftDeleteMixin, VersionMixin):
57
+ __tablename__ = "${table}"
58
+ __module_schema__ = "${schema}"
59
+
60
+ id: Mapped[UUID] = mapped_column(UUIDType, primary_key=True, default=uuid.uuid4)
61
+ name: Mapped[str] = mapped_column(ShortText(120), index=True)
62
+ note: Mapped[str | None] = mapped_column(LongText(), nullable=True)
63
+
64
+ def __repr__(self) -> str:
65
+ return f"<${model} {self.id} {self.name}>"
66
+ '''
67
+
68
+ SCHEMAS = '''"""${title} 契约。"""
69
+
70
+ from __future__ import annotations
71
+
72
+ from datetime import datetime
73
+ from typing import Annotated
74
+ from uuid import UUID
75
+
76
+ from pydantic import StringConstraints
77
+
78
+ from swiftapi.core.validation.base import OutModel, StrictModel
79
+
80
+ Name = Annotated[str, StringConstraints(min_length=1, max_length=120)]
81
+ Note = Annotated[str, StringConstraints(max_length=2000)]
82
+
83
+
84
+ class ${model}Create(StrictModel):
85
+ name: Name
86
+ note: Note | None = None
87
+
88
+
89
+ class ${model}Update(StrictModel):
90
+ name: Name | None = None
91
+ note: Note | None = None
92
+
93
+
94
+ class ${model}Out(OutModel):
95
+ id: UUID
96
+ name: str
97
+ note: str | None
98
+ version: int
99
+ created_at: datetime
100
+ '''
101
+
102
+ SERVICE = '''"""${title} 用例:事务边界 + 事件。"""
103
+
104
+ from __future__ import annotations
105
+
106
+ from uuid import UUID
107
+
108
+ from swiftapi.core.db.unit_of_work import UnitOfWork
109
+ from swiftapi.core.errors.base import NotFound
110
+ from swiftapi.core.messaging.outbox import emit
111
+ from swiftapi.db import CRUDBase
112
+ from ${model_module} import ${model}
113
+ from ${schema_module} import ${model}Create, ${model}Update
114
+
115
+ CREATED = "${project}.${name}.created"
116
+ UPDATED = "${project}.${name}.updated"
117
+ DELETED = "${project}.${name}.deleted"
118
+
119
+ ${model}CRUD = CRUDBase(${model})
120
+
121
+
122
+ class ${model}Service:
123
+ def __init__(self, uow: UnitOfWork) -> None:
124
+ self.uow = uow
125
+ self.crud = ${model}CRUD
126
+
127
+ async def create(self, payload: ${model}Create, *, tenant_id: UUID) -> ${model}:
128
+ async with self.uow:
129
+ return await self.create_in_session(self.uow.session, payload, tenant_id=tenant_id)
130
+
131
+ async def create_in_session(self, session, payload: ${model}Create, *, tenant_id: UUID) -> ${model}:
132
+ """与幂等记录同事务写入(外部不要 commit)。"""
133
+ row = await self.crud.create(session, payload.model_dump(), tenant_id=tenant_id)
134
+ await emit(session, CREATED, {"id": str(row.id)}, tenant_id=tenant_id)
135
+ return row
136
+
137
+ async def list(
138
+ self, *, tenant_id: UUID, limit: int = 20, offset: int = 0
139
+ ) -> tuple[list[${model}], int]:
140
+ async with self.uow:
141
+ return await self.crud.list(
142
+ self.uow.session, tenant_id=tenant_id, order_by="-created_at",
143
+ limit=limit, offset=offset,
144
+ )
145
+
146
+ async def get(self, row_id: UUID, *, tenant_id: UUID) -> ${model}:
147
+ async with self.uow:
148
+ row = await self.crud.get(self.uow.session, row_id, tenant_id=tenant_id)
149
+ if row is None:
150
+ raise NotFound(f"${model} {row_id} 不存在")
151
+ return row
152
+
153
+ async def update(self, row_id: UUID, payload: ${model}Update, *, tenant_id: UUID) -> ${model}:
154
+ async with self.uow:
155
+ row = await self.crud.get(self.uow.session, row_id, tenant_id=tenant_id)
156
+ if row is None:
157
+ raise NotFound(f"${model} {row_id} 不存在")
158
+ await self.crud.update(self.uow.session, row, payload)
159
+ await emit(self.uow.session, UPDATED, {"id": str(row_id)}, tenant_id=tenant_id)
160
+ return row
161
+
162
+ async def delete(self, row_id: UUID, *, tenant_id: UUID) -> None:
163
+ async with self.uow:
164
+ row = await self.crud.get(self.uow.session, row_id, tenant_id=tenant_id)
165
+ if row is None:
166
+ raise NotFound(f"${model} {row_id} 不存在")
167
+ await self.crud.delete(self.uow.session, row)
168
+ await emit(self.uow.session, DELETED, {"id": str(row_id)}, tenant_id=tenant_id)
169
+ '''
170
+
171
+ ROUTER = '''"""${title} 接口。"""
172
+
173
+ from __future__ import annotations
174
+
175
+ from typing import Annotated
176
+ from uuid import UUID
177
+
178
+ from typing import Any
179
+
180
+ from swiftapi.core.http import Depends, Query, Router
181
+
182
+ # <idempotency>
183
+ from swiftapi.core.http import Request
184
+ from swiftapi.core.http.idempotency import HEADER as IDEMPOTENCY_HEADER
185
+ from swiftapi.core.http.idempotency import (
186
+ hash_payload,
187
+ load_replay,
188
+ remember,
189
+ replay_response,
190
+ )
191
+ # </idempotency>
192
+ from swiftapi.core.http.pagination import Page, to_page
193
+ from swiftapi.core.security.principal import Principal, require_permission
194
+ from swiftapi.core.tenant.context import current_tenant_id
195
+ from swiftapi.db import UnitOfWork
196
+ from ${schema_module} import ${model}Create, ${model}Out, ${model}Update
197
+ from ${service_module} import ${model}Service
198
+
199
+ router = Router(prefix="/${prefix}", tags=("${prefix}",))
200
+ ENDPOINT = "POST /${prefix}"
201
+
202
+ Uow = Annotated[UnitOfWork, Depends("uow")]
203
+
204
+
205
+ def _service(uow: Uow) -> ${model}Service:
206
+ return ${model}Service(uow)
207
+
208
+
209
+ # <idempotency>
210
+ @router.post("", summary="创建${title}", status_code=201, response_model=${model}Out)
211
+ async def create(
212
+ payload: ${model}Create,
213
+ request: Request,
214
+ uow: Uow,
215
+ principal: Annotated[Principal, Depends(require_permission("${project}:write"))],
216
+ ) -> Any:
217
+ """支持 Idempotency-Key:同 key 同体重放,同 key 异体 409。"""
218
+ tenant_id = current_tenant_id()
219
+ key = request.headers.get(IDEMPOTENCY_HEADER)
220
+ service = _service(uow)
221
+
222
+ async with uow:
223
+ fingerprint = hash_payload(payload) if key else ""
224
+ if key:
225
+ replay = await load_replay(
226
+ uow.session,
227
+ tenant_id=tenant_id,
228
+ key=key,
229
+ endpoint=ENDPOINT,
230
+ request_hash=fingerprint,
231
+ )
232
+ if replay is not None:
233
+ return replay_response(replay)
234
+
235
+ row = await service.create_in_session(uow.session, payload, tenant_id=tenant_id)
236
+ result = ${model}Out.model_validate(row)
237
+
238
+ if key:
239
+ await remember(
240
+ uow.session,
241
+ tenant_id=tenant_id,
242
+ key=key,
243
+ endpoint=ENDPOINT,
244
+ request_hash=fingerprint,
245
+ status_code=201,
246
+ body=result.model_dump(mode="json"),
247
+ )
248
+
249
+ return result
250
+ # </idempotency>
251
+
252
+ # <plain>
253
+ @router.post("", summary="创建${title}", status_code=201, response_model=${model}Out)
254
+ async def create(
255
+ payload: ${model}Create,
256
+ uow: Uow,
257
+ principal: Annotated[Principal, Depends(require_permission("${project}:write"))],
258
+ ) -> ${model}Out:
259
+ async with uow:
260
+ row = await _service(uow).create_in_session(
261
+ uow.session, payload, tenant_id=current_tenant_id()
262
+ )
263
+ result = ${model}Out.model_validate(row)
264
+ return result
265
+ # </plain>
266
+
267
+
268
+ @router.get("", summary="${title}列表", response_model=Page[${model}Out])
269
+ async def list_rows(
270
+ uow: Uow,
271
+ principal: Annotated[Principal, Depends(require_permission("${project}:read"))],
272
+ limit: Annotated[int, Query(20)] = 20,
273
+ offset: Annotated[int, Query(0)] = 0,
274
+ ) -> Page[${model}Out]:
275
+ rows, total = await _service(uow).list(
276
+ tenant_id=current_tenant_id(), limit=limit, offset=offset
277
+ )
278
+ return to_page(rows, total, limit=limit, offset=offset, schema=${model}Out)
279
+
280
+
281
+ @router.get("/{row_id}", summary="${title}详情", response_model=${model}Out)
282
+ async def get_row(
283
+ row_id: UUID,
284
+ uow: Uow,
285
+ principal: Annotated[Principal, Depends(require_permission("${project}:read"))],
286
+ ) -> ${model}Out:
287
+ row = await _service(uow).get(row_id, tenant_id=current_tenant_id())
288
+ return ${model}Out.model_validate(row)
289
+
290
+
291
+ @router.patch("/{row_id}", summary="更新${title}", response_model=${model}Out)
292
+ async def update_row(
293
+ row_id: UUID,
294
+ payload: ${model}Update,
295
+ uow: Uow,
296
+ principal: Annotated[Principal, Depends(require_permission("${project}:write"))],
297
+ ) -> ${model}Out:
298
+ row = await _service(uow).update(row_id, payload, tenant_id=current_tenant_id())
299
+ return ${model}Out.model_validate(row)
300
+
301
+
302
+ @router.delete("/{row_id}", summary="删除${title}", status_code=204)
303
+ async def delete_row(
304
+ row_id: UUID,
305
+ uow: Uow,
306
+ principal: Annotated[Principal, Depends(require_permission("${project}:write"))],
307
+ ) -> None:
308
+ await _service(uow).delete(row_id, tenant_id=current_tenant_id())
309
+ '''
310
+
311
+ TEST = '''"""$title 接口测试(由 swiftapi new resource 生成,可直接运行)。
312
+
313
+ pytest $test_path -q
314
+ """
315
+
316
+ from __future__ import annotations
317
+
318
+ import asyncio
319
+ import sys
320
+ import uuid
321
+ from datetime import UTC, datetime, timedelta
322
+ from pathlib import Path
323
+
324
+ import httpx
325
+ import jwt
326
+ import pytest
327
+
328
+ sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
329
+
330
+ from swiftapi.config.settings import Settings # noqa: E402
331
+ from swiftapi.core.db.engine import create_database # noqa: E402
332
+ from swiftapi.core.security.principal import register_role # noqa: E402
333
+ from swiftapi.db import BaseModel # noqa: E402
334
+ from $project.app import create_app # noqa: E402
335
+
336
+ SECRET = "$project-dev-secret-please-rotate-32"
337
+ BASE = "$base_path"
338
+
339
+
340
+ def _settings(tmp_path: Path) -> Settings:
341
+ return Settings(
342
+ app={"env": "test"},
343
+ database={"url": f"sqlite+aiosqlite:///{tmp_path}/api.db"},
344
+ tenant={"enabled": True, "resolver": ["jwt"], "default_slug": "acme"},
345
+ security={"jwt_algorithm": "HS256", "jwt_private_key": SECRET, "allow_insecure": True},
346
+ admin={"enabled": False},
347
+ docs={"enabled": False},
348
+ observability={"log_level": "WARNING", "log_format": "console"},
349
+ )
350
+
351
+
352
+ def _token(role: str = "agent", tenant: str = "acme") -> str:
353
+ return jwt.encode(
354
+ {
355
+ "sub": str(uuid.uuid4()),
356
+ "roles": [role],
357
+ "tid": tenant,
358
+ "iss": "swiftapi",
359
+ "aud": "swiftapi",
360
+ "exp": datetime.now(UTC) + timedelta(minutes=5),
361
+ },
362
+ SECRET,
363
+ algorithm="HS256",
364
+ )
365
+
366
+
367
+ async def _prepare(tmp_path: Path):
368
+ """一个测试内共享一个库(不要每次请求都重建,否则数据不落库)。"""
369
+ register_role("agent", frozenset({"$project:read", "$project:write"}))
370
+ settings = _settings(tmp_path)
371
+ database = create_database(settings)
372
+ async with database.engine.begin() as connection:
373
+ await connection.run_sync(BaseModel.metadata.drop_all)
374
+ await connection.run_sync(BaseModel.metadata.create_all)
375
+ await database.aclose()
376
+
377
+ app = create_app(settings)
378
+ app.state.tenant_catalog.register("acme")
379
+ app.state.tenant_catalog.register("beta")
380
+ return app
381
+
382
+
383
+ async def _request(
384
+ app,
385
+ method: str,
386
+ path: str,
387
+ *,
388
+ json_body=None,
389
+ role: str = "agent",
390
+ tenant: str = "acme",
391
+ extra_headers: dict[str, str] | None = None,
392
+ ):
393
+ headers = {"authorization": f"Bearer {_token(role, tenant)}"}
394
+ headers.update(extra_headers or {})
395
+ async with httpx.AsyncClient(
396
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
397
+ ) as client:
398
+ return await client.request(method, path, json=json_body, headers=headers)
399
+
400
+
401
+ def test_crud_roundtrip(tmp_path: Path) -> None:
402
+ async def scenario() -> None:
403
+ app = await _prepare(tmp_path)
404
+
405
+ created = await _request(app, "POST", BASE, json_body={"name": "demo"})
406
+ assert created.status_code == 201, created.text
407
+ row_id = created.json()["id"]
408
+
409
+ listed = await _request(app, "GET", BASE)
410
+ assert listed.status_code == 200
411
+ assert listed.json()["total"] == 1
412
+
413
+ fetched = await _request(app, "GET", f"{BASE}/{row_id}")
414
+ assert fetched.status_code == 200
415
+
416
+ patched = await _request(app, "PATCH", f"{BASE}/{row_id}", json_body={"name": "renamed"})
417
+ assert patched.json()["name"] == "renamed"
418
+
419
+ deleted = await _request(app, "DELETE", f"{BASE}/{row_id}")
420
+ assert deleted.status_code == 204
421
+
422
+ asyncio.run(scenario())
423
+
424
+
425
+ # <idempotency>
426
+ def test_idempotent_replay(tmp_path: Path) -> None:
427
+ async def scenario() -> None:
428
+ app = await _prepare(tmp_path)
429
+ headers = {"idempotency-key": "order-once-1"}
430
+
431
+ first = await _request(app, "POST", BASE, json_body={"name": "once"}, extra_headers=headers)
432
+ assert first.status_code == 201
433
+
434
+ second = await _request(app, "POST", BASE, json_body={"name": "once"}, extra_headers=headers)
435
+ assert second.status_code == 201
436
+ assert second.headers.get("idempotent-replayed") == "true"
437
+ assert second.json()["id"] == first.json()["id"]
438
+
439
+ conflict = await _request(
440
+ app, "POST", BASE, json_body={"name": "different"}, extra_headers=headers
441
+ )
442
+ assert conflict.status_code == 409
443
+ assert conflict.json()["code"] == "IDEMPOTENCY_KEY_REUSED"
444
+
445
+ listed = await _request(app, "GET", BASE)
446
+ assert listed.json()["total"] == 1, "重复提交不得产生第二条记录"
447
+
448
+ asyncio.run(scenario())
449
+ # </idempotency>
450
+
451
+
452
+ def test_cross_tenant_is_404(tmp_path: Path) -> None:
453
+ async def scenario() -> None:
454
+ app = await _prepare(tmp_path)
455
+ created = await _request(app, "POST", BASE, json_body={"name": "tenant-a"})
456
+ row_id = created.json()["id"]
457
+ other = await _request(app, "GET", f"{BASE}/{row_id}", tenant="beta")
458
+ assert other.status_code == 404
459
+
460
+ asyncio.run(scenario())
461
+ '''
462
+
463
+ INIT = '''"""${title} 资源(由 swiftapi new resource 生成)。"""
464
+ '''
465
+
466
+ FILES = {
467
+ "__init__.py": INIT,
468
+ "model.py": MODEL,
469
+ "schemas.py": SCHEMAS,
470
+ "service.py": SERVICE,
471
+ "router.py": ROUTER,
472
+ "test_api.py": TEST,
473
+ }
474
+
475
+
476
+ def _base_context(project: str, name: str, url_prefix: str) -> dict[str, str]:
477
+ return {
478
+ "title": name.replace("_", " "),
479
+ "model": _camel(name),
480
+ "name": name,
481
+ "project": project,
482
+ "prefix": url_prefix,
483
+ }
484
+
485
+
486
+ def _app_layout(
487
+ project_dir: Path,
488
+ project: str,
489
+ name: str,
490
+ app: str,
491
+ app_dir: str,
492
+ url_prefix: str,
493
+ ) -> tuple[dict[str, Path], dict[str, str], str, Path]:
494
+ app_root = project_dir / app_dir / app
495
+ if not app_root.is_dir():
496
+ raise FileNotFoundError(str(app_root))
497
+ import_path = f"{project}.{app_dir}.{app}"
498
+ targets = {
499
+ "model.py": app_root / "model" / f"{name}.py",
500
+ "schemas.py": app_root / "schema" / f"{name}.py",
501
+ "service.py": app_root / "service" / f"{name}.py",
502
+ "router.py": app_root / "api" / f"{name}.py",
503
+ "test_api.py": app_root / f"test_{name}.py",
504
+ }
505
+ context = {
506
+ **_base_context(project, name, url_prefix),
507
+ "table": f"{app}_{name}",
508
+ "schema": app,
509
+ "model_module": f"{import_path}.model.{name}",
510
+ "schema_module": f"{import_path}.schema.{name}",
511
+ "service_module": f"{import_path}.service.{name}",
512
+ "base_path": f"/api/v1/{app}/{url_prefix}",
513
+ "test_path": f"{app_dir}/{app}/test_{name}.py",
514
+ }
515
+ return targets, context, import_path, app_root
516
+
517
+
518
+ def _flat_layout(
519
+ project_dir: Path,
520
+ project: str,
521
+ name: str,
522
+ url_prefix: str,
523
+ ) -> tuple[dict[str, Path], dict[str, str], str, Path]:
524
+ package_dir = project_dir / "resources" / name
525
+ if package_dir.exists():
526
+ raise FileExistsError(str(package_dir))
527
+ import_path = f"{project}.resources.{name}"
528
+ targets = {filename: package_dir / filename for filename in FILES}
529
+ context = {
530
+ **_base_context(project, name, url_prefix),
531
+ "table": name,
532
+ "schema": project,
533
+ "model_module": f"{import_path}.model",
534
+ "schema_module": f"{import_path}.schemas",
535
+ "service_module": f"{import_path}.service",
536
+ "base_path": f"/api/v1/{url_prefix}",
537
+ "test_path": f"resources/{name}/test_api.py",
538
+ }
539
+ return targets, context, import_path, package_dir
540
+
541
+
542
+ def _register_app_model(
543
+ project_dir: Path, import_path: str, name: str, model: str
544
+ ) -> None:
545
+ """Django 布局:模型必须被 models.py 导入,迁移才看得到。"""
546
+ models_file = project_dir / "models.py"
547
+ import_line = f"from {import_path}.model.{name} import {model}"
548
+ if not models_file.is_file():
549
+ console.print("[yellow]提示:项目没有 models.py,请自行登记到迁移入口[/yellow]")
550
+ return
551
+ text = models_file.read_text(encoding="utf-8")
552
+ if import_line in text:
553
+ return
554
+ models_file.write_text(
555
+ text.rstrip("\n") + f"\n{import_line} # noqa: F401\n",
556
+ encoding="utf-8",
557
+ )
558
+
559
+
560
+ def _resolve_layout(
561
+ project_dir: Path,
562
+ project: str,
563
+ name: str,
564
+ app: str | None,
565
+ app_dir: str,
566
+ url_prefix: str,
567
+ ) -> tuple[dict[str, Path], dict[str, str], str, Path] | None:
568
+ try:
569
+ if app is not None:
570
+ return _app_layout(project_dir, project, name, app, app_dir, url_prefix)
571
+ return _flat_layout(project_dir, project, name, url_prefix)
572
+ except FileNotFoundError as exc:
573
+ console.print(f"[red]找不到应用目录: {exc}[/red]")
574
+ console.print(f" 先用 swift-api startapp {app} 生成应用")
575
+ return None
576
+ except FileExistsError as exc:
577
+ console.print(f"[red]资源已存在: {exc}[/red]")
578
+ return None
579
+
580
+
581
+ def _write_targets(
582
+ targets: dict[str, Path], context: dict[str, str], *, idempotency: bool
583
+ ) -> None:
584
+ for filename, template in FILES.items():
585
+ target = targets.get(filename)
586
+ if target is None:
587
+ continue
588
+ target.parent.mkdir(parents=True, exist_ok=True)
589
+ content = string.Template(template).substitute(**context)
590
+ content = _render_variant(content, idempotency=idempotency)
591
+ target.write_text(content, encoding="utf-8")
592
+
593
+
594
+ @resource_app.command("resource")
595
+ def create_resource(
596
+ name: str = typer.Argument(..., help="资源名(蛇形单数,如 order)"),
597
+ project: str = typer.Option(..., "--project", help="项目包名"),
598
+ path: Path = typer.Option(Path("."), "--path", "-p", help="项目所在父目录"),
599
+ prefix: str = typer.Option("", "--prefix", help="URL 前缀,默认 <name>s"),
600
+ app: str | None = typer.Option(
601
+ None, "--app", help="生成到 Django 风格的 <app-dir>/<app>/ 分层目录"
602
+ ),
603
+ app_dir: str = typer.Option("apps", "--app-dir", help="应用目录(配合 --app)"),
604
+ dry_run: bool = typer.Option(False, "--dry-run", help="只打印文件名"),
605
+ idempotency: bool = typer.Option(
606
+ True, "--idempotency/--no-idempotency", help="POST 是否支持 Idempotency-Key"
607
+ ),
608
+ ) -> None:
609
+ """生成 model / schemas / service / router / test_api 五件套。"""
610
+ project_dir = Path(path) / project
611
+ if not project_dir.is_dir():
612
+ console.print(f"[red]找不到项目目录: {project_dir}[/red]")
613
+ raise typer.Exit(code=1)
614
+
615
+ layout = _resolve_layout(
616
+ project_dir, project, name, app, app_dir, prefix or f"{name}s"
617
+ )
618
+ if layout is None:
619
+ raise typer.Exit(code=1)
620
+ targets, context, import_path, compile_root = layout
621
+
622
+ existing = [target for target in targets.values() if target.exists()]
623
+ if existing:
624
+ console.print("[red]目标文件已存在:[/red]")
625
+ for target in existing:
626
+ console.print(f" - {target}")
627
+ raise typer.Exit(code=1)
628
+
629
+ if dry_run:
630
+ for target in targets.values():
631
+ console.print(target.relative_to(project_dir))
632
+ return
633
+
634
+ _write_targets(targets, context, idempotency=idempotency)
635
+
636
+ if app is not None:
637
+ _register_app_model(project_dir, import_path, name, context["model"])
638
+
639
+ check = subprocess.run(
640
+ [sys.executable, "-m", "compileall", "-q", str(compile_root)],
641
+ capture_output=True,
642
+ text=True,
643
+ )
644
+ if check.returncode != 0:
645
+ console.print(f"[red]生成物编译失败:{check.stderr}[/red]")
646
+ raise typer.Exit(code=1)
647
+ for cache in compile_root.rglob("__pycache__"):
648
+ shutil.rmtree(cache, ignore_errors=True)
649
+
650
+ console.print(f"[green]已生成[/green] {len(targets)} 个文件")
651
+ for target in targets.values():
652
+ console.print(f" - {target.relative_to(project_dir)}")
653
+ console.print(
654
+ f"下一步:\n"
655
+ f" 1) 迁移:swiftapi db revision --models {project}.models -m 'add {name}'\n"
656
+ f" 2) 测试:pytest {context['test_path']} -q"
657
+ )