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,764 @@
1
+ """统一配置中心:全项目唯一的 Settings。
2
+
3
+ 设计约束(见架构文档 §12):
4
+ 1. 单一来源:只有这里定义配置字段,其他模块通过 DI 拿到实例;
5
+ 2. 启动即校验:类型、范围、跨字段一致性、后端组合合法性;
6
+ 3. 不可变:frozen=True,运行期修改直接抛错;
7
+ 4. 可解释:redacted_summary() 输出生效组合,便于排障。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import importlib
14
+ import os
15
+ import sys
16
+ from enum import StrEnum
17
+ from pathlib import Path
18
+ from typing import Any, Literal, Self
19
+ from urllib.parse import urlsplit
20
+
21
+ from pydantic import (
22
+ BaseModel,
23
+ ConfigDict,
24
+ Field,
25
+ SecretStr,
26
+ ValidationError,
27
+ field_validator,
28
+ model_validator,
29
+ )
30
+ from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
31
+
32
+ from swiftapi.config.constants import SUPPORTED_DB_SCHEMES
33
+
34
+ # 风格的"用户配置文件"入口:SWIFTAPI_SETTINGS_MODULE=myproject.settings
35
+ SETTINGS_MODULE_ENV = "SWIFTAPI_SETTINGS_MODULE"
36
+ _active_module: str | None = None
37
+ #: 最近一次加载的来源信息(CLI 排障用:到底读了哪个配置文件、连的哪个库)
38
+ _last_source: dict[str, Any] = {}
39
+
40
+
41
+ def active_settings_source() -> dict[str, Any]:
42
+ return dict(_last_source)
43
+
44
+
45
+ def describe_database(settings: Settings) -> str:
46
+ """把库目标描述成人能读的一行(sqlite 显示绝对路径)。"""
47
+ url = settings.database.url.get_secret_value()
48
+ if settings.database.dialect == "sqlite":
49
+ raw = url.split("///", 1)[-1].lstrip("/")
50
+ path = Path(raw)
51
+ absolute = path if path.is_absolute() else (Path.cwd() / path)
52
+ return f"sqlite {absolute.resolve()}"
53
+ host = urlsplit(url).hostname or "?"
54
+ return f"{settings.database.dialect} {host}:{urlsplit(url).port or ''}"
55
+
56
+
57
+ class Env(StrEnum):
58
+ DEV = "dev"
59
+ TEST = "test"
60
+ STAGING = "staging"
61
+ PROD = "prod"
62
+
63
+
64
+ class CacheBackend(StrEnum):
65
+ REDIS = "redis"
66
+ MONGODB = "mongodb"
67
+ MEMORY = "memory"
68
+ DISABLED = "disabled"
69
+
70
+
71
+ class MessagingBackend(StrEnum):
72
+ REDIS_STREAMS = "redis_streams"
73
+ RABBITMQ = "rabbitmq"
74
+ INPROCESS = "inprocess"
75
+ DISABLED = "disabled"
76
+
77
+
78
+ class TenantStrategy(StrEnum):
79
+ ROW = "row"
80
+ SCHEMA = "schema"
81
+ DATABASE = "database"
82
+ HYBRID = "hybrid"
83
+
84
+
85
+ class TenantResolver(StrEnum):
86
+ JWT = "jwt"
87
+ HEADER = "header"
88
+ PATH = "path"
89
+ SUBDOMAIN = "subdomain"
90
+
91
+
92
+ class RateLimitBackend(StrEnum):
93
+ AUTO = "auto"
94
+ REDIS = "redis"
95
+ LOCAL = "local"
96
+
97
+
98
+ class LogFormat(StrEnum):
99
+ JSON = "json"
100
+ CONSOLE = "console"
101
+
102
+
103
+ class JwtAlgorithm(StrEnum):
104
+ RS256 = "RS256"
105
+ HS256 = "HS256"
106
+
107
+
108
+ class ConfigGroup(BaseModel):
109
+ """所有配置分组的基类:不可变、禁未知字段。"""
110
+
111
+ model_config = ConfigDict(frozen=True, extra="forbid")
112
+
113
+
114
+ class AppSettings(ConfigGroup):
115
+ name: str = "swiftapi"
116
+ env: Env = Env.DEV
117
+ debug: bool = False
118
+ timezone: str = "UTC"
119
+
120
+
121
+ class ServerSettings(ConfigGroup):
122
+ # 默认只监听本机:要暴露到公网请显式设置 0.0.0.0(生产由 start.sh/网关决定)
123
+ host: str = "127.0.0.1"
124
+ port: int = Field(default=8000, ge=1, le=65535)
125
+ workers: int = Field(default=1, ge=1, le=64)
126
+ root_path: str = ""
127
+ max_request_body_bytes: int = Field(default=1_048_576, ge=1024)
128
+ request_timeout_s: float = Field(default=5.0, gt=0, le=120)
129
+ graceful_shutdown_timeout_s: float = Field(default=25.0, gt=0, le=300)
130
+ access_log: bool = True
131
+
132
+
133
+ class SqliteSettings(ConfigGroup):
134
+ wal: bool = True
135
+ busy_timeout_ms: int = Field(default=5_000, ge=0)
136
+
137
+
138
+ class DatabaseSettings(ConfigGroup):
139
+ """关系型数据层:方言由 URL scheme 推断,不设第二个真相。"""
140
+
141
+ url: SecretStr = SecretStr("sqlite+aiosqlite:///./dev.db")
142
+ echo: bool = False
143
+ pool_size: int = Field(default=9, ge=1, le=100)
144
+ max_overflow: int = Field(default=0, ge=0, le=100)
145
+ pool_timeout_s: float = Field(default=5.0, gt=0)
146
+ pool_recycle_s: int = Field(default=1_800, ge=0)
147
+ # 借连接前 ping:能剔除失效连接,但每请求多一次 roundtrip。
148
+ # 直连 PG / 本机可关掉换延迟(稳定性测试:conc20 p50 约减半)。
149
+ pool_pre_ping: bool = True
150
+ statement_timeout_ms: int = Field(default=2_000, ge=100)
151
+ max_connections: int = Field(default=100, ge=1)
152
+ read_replica_urls: list[SecretStr] = Field(default_factory=list)
153
+ replica_lag_tolerance_ms: int = Field(default=1_000, ge=0)
154
+ sqlite: SqliteSettings = Field(default_factory=SqliteSettings)
155
+ # SQLite 单写者 + 无并发能力:生产默认拒绝;本地/边缘场景可显式打开
156
+ allow_sqlite_in_prod: bool = False
157
+
158
+ @property
159
+ def dialect(self) -> str:
160
+ scheme = str(self.url.get_secret_value()).split("://", 1)[0]
161
+ return scheme.split("+", 1)[0]
162
+
163
+ @property
164
+ def driver(self) -> str:
165
+ scheme = str(self.url.get_secret_value()).split("://", 1)[0]
166
+ return scheme.split("+", 1)[1] if "+" in scheme else ""
167
+
168
+ @model_validator(mode="after")
169
+ def _check_scheme(self) -> Self:
170
+ if self.dialect not in SUPPORTED_DB_SCHEMES:
171
+ raise ValueError(
172
+ f"不支持的数据库 scheme: {self.dialect!r};"
173
+ f"仅支持 {', '.join(SUPPORTED_DB_SCHEMES)}(架构文档 §16.2)"
174
+ )
175
+ return self
176
+
177
+
178
+ class TenantSettings(ConfigGroup):
179
+ enabled: bool = False
180
+ strategy: TenantStrategy = TenantStrategy.ROW
181
+ resolver: list[TenantResolver] = Field(
182
+ default_factory=lambda: [TenantResolver.JWT, TenantResolver.HEADER]
183
+ )
184
+ header_name: str = "x-tenant-id"
185
+ # 只有确认网关会剥离客户端自带的租户头时才可开启(见 docs/security/…);
186
+ # 默认关闭,否则任何调用方都能靠改请求头切租户。
187
+ trust_header: bool = False
188
+ # 生产环境二次确认:确实由网关剥离 header 时才允许打开 trust_header
189
+ allow_trust_header_in_prod: bool = False
190
+ path_prefix: str = "/t/{tenant}"
191
+ root_domain: str | None = None
192
+ require_resolved: bool = True
193
+ max_pools: int = Field(default=20, ge=1, le=500)
194
+ pool_size_per_tenant: int = Field(default=3, ge=1, le=20)
195
+ # schema 级:PostgreSQL schema 前缀;database 级:连接串模板,用 {tenant} 占位
196
+ schema_prefix: str = Field(default="tenant_", min_length=0, max_length=32)
197
+ database_url_template: SecretStr | None = None
198
+ registry_cache_ttl_s: int = Field(default=60, ge=0)
199
+ default_slug: str = "default"
200
+
201
+
202
+ class CacheSettings(ConfigGroup):
203
+ enabled: bool = False
204
+ backend: CacheBackend = CacheBackend.MEMORY
205
+ url: SecretStr | None = None
206
+ namespace: str = "swiftapi"
207
+ default_ttl_s: int = Field(default=300, ge=0)
208
+ ttl_jitter_ratio: float = Field(default=0.1, ge=0, le=0.5)
209
+ max_connections: int = Field(default=20, ge=1, le=500)
210
+
211
+
212
+ class MessagingSettings(ConfigGroup):
213
+ enabled: bool = False
214
+ backend: MessagingBackend = MessagingBackend.INPROCESS
215
+ url: SecretStr | None = None
216
+ prefetch: int = Field(default=10, ge=1, le=1000)
217
+ max_retries: int = Field(default=12, ge=0, le=100)
218
+ visibility_timeout_s: int = Field(default=30, ge=1)
219
+ dead_letter_ttl_s: int = Field(default=604_800, ge=0)
220
+ # Outbox 中继:把业务事务里写下的事件投递到总线。
221
+ # 默认关闭(进程内总线只适合单实例;多副本时由运维职责决定谁来跑)。
222
+ # 多副本部署请只让一个副本开启,或换 redis_streams/rabbitmq。
223
+ outbox_relay_enabled: bool = False
224
+ outbox_relay_interval_s: float = Field(default=1.0, gt=0, le=60)
225
+ outbox_relay_batch_size: int = Field(default=100, ge=1, le=1000)
226
+ outbox_relay_max_attempts: int = Field(default=12, ge=1, le=100)
227
+ # 租约:中继 claim 一行后占用多久。进程崩溃时其它副本最多等这么久接手。
228
+ outbox_relay_lease_s: float = Field(default=60.0, gt=0, le=3600)
229
+
230
+
231
+ class DocumentSettings(ConfigGroup):
232
+ enabled: bool = False
233
+ uri: SecretStr | None = None
234
+ database: str = "swiftapi"
235
+ collection_prefix: str = ""
236
+ default_ttl_s: int = Field(default=0, ge=0)
237
+
238
+
239
+ class RateLimitSettings(ConfigGroup):
240
+ enabled: bool = True
241
+ backend: RateLimitBackend = RateLimitBackend.AUTO
242
+ ip_rps: int = Field(default=100, ge=0)
243
+ user_rps: int = Field(default=50, ge=0)
244
+ tenant_rps: int = Field(default=500, ge=0)
245
+
246
+
247
+ class SecuritySettings(ConfigGroup):
248
+ jwt_algorithm: JwtAlgorithm = JwtAlgorithm.RS256
249
+ jwt_public_key: SecretStr | None = None
250
+ jwt_private_key: SecretStr | None = None
251
+ # CSRF HMAC 密钥;未配置时回退到 jwt_private_key(生产必须二选一)
252
+ csrf_secret: SecretStr | None = None
253
+ jwt_issuer: str = "swiftapi"
254
+ jwt_audience: str = "swiftapi"
255
+ jwks_url: str | None = None
256
+ jwks_cache_ttl_s: int = Field(default=300, ge=0)
257
+ clock_skew_s: int = Field(default=60, ge=0, le=300)
258
+ access_token_ttl_s: int = Field(default=900, ge=60)
259
+ refresh_token_ttl_s: int = Field(default=1_209_600, ge=60)
260
+ cors_allow_origins: list[str] = Field(default_factory=list)
261
+ trusted_hosts: list[str] = Field(default_factory=lambda: ["*"])
262
+ allow_insecure: bool = False
263
+ rate_limit: RateLimitSettings = Field(default_factory=RateLimitSettings)
264
+
265
+
266
+ class ObservabilitySettings(ConfigGroup):
267
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
268
+ log_format: LogFormat = LogFormat.JSON
269
+ # ---- 落盘日志(项目默认开,内核默认关,避免库使用者被动写文件) ----
270
+ log_to_file: bool = False
271
+ log_dir: str = "logs"
272
+ log_console: bool = True
273
+ log_max_bytes: int = Field(default=10 * 1024 * 1024, ge=0)
274
+ log_backup_count: int = Field(default=5, ge=0)
275
+ # SQL 日志(公共能力):把执行过的 SQL + 耗时写进 logs/sql.log
276
+ log_sql: bool = False
277
+ log_sql_max_chars: int = Field(default=2000, ge=100)
278
+ # 归档:每 N 天把 logs/ 下的日志压成一个 zip 存到 log_archive_dir,然后删除原文件
279
+ log_archive_enabled: bool = False
280
+ log_archive_dir: str = "logs/archive"
281
+ log_archive_interval_days: int = Field(default=7, ge=1, le=365)
282
+ # 请求体采样日志(默认关;开启时按比例采样并脱敏)
283
+ log_request_body: bool = False
284
+ log_request_body_sample_ratio: float = Field(default=0.05, ge=0.0, le=1.0)
285
+ log_request_body_max_chars: int = Field(default=2000, ge=100)
286
+ # 采样预算:**集群维度**每分钟最多记多少条请求体(0 = 不限)。
287
+ # 多副本时按 log_request_body_replicas 均摊,避免 N 个副本各写 N 倍。
288
+ log_request_body_max_per_minute: int = Field(default=600, ge=0)
289
+ log_request_body_replicas: int = Field(default=1, ge=1, le=10_000)
290
+ # 业务自定义脱敏字段(叠加在内置列表上,大小写不敏感)
291
+ log_mask_keys: list[str] = Field(default_factory=list)
292
+ otel_enabled: bool = False
293
+ otlp_endpoint: str | None = None
294
+ trace_sample_ratio: float = Field(default=0.1, ge=0.0, le=1.0)
295
+ metrics_enabled: bool = True
296
+ metrics_path: str = "/metrics"
297
+
298
+ @field_validator("log_level", mode="before")
299
+ @classmethod
300
+ def _upper_level(cls, value: object) -> object:
301
+ return value.upper() if isinstance(value, str) else value
302
+
303
+
304
+ class UploadSettings(ConfigGroup):
305
+ """上传策略。`max_bytes` 不能超过 `server.max_request_body_bytes`,否则永远收不到。"""
306
+
307
+ enabled: bool = True
308
+ max_bytes: int = Field(default=10 * 1024 * 1024, ge=0)
309
+ max_parts: int = Field(default=10, ge=1, le=1000)
310
+ allowed_types: list[str] = Field(default_factory=list)
311
+ streaming: bool = True
312
+ scan_timeout_s: float = Field(default=5.0, gt=0, le=120)
313
+
314
+
315
+ class OutboundSettings(ConfigGroup):
316
+ """出站(SSRF 防护)默认策略。业务可构造 OutboundClient 覆盖。"""
317
+
318
+ allow_private: bool = False
319
+ allowed_hosts: list[str] = Field(default_factory=list)
320
+ check_dns: bool = True
321
+ timeout_s: float = Field(default=2.0, gt=0, le=60)
322
+
323
+
324
+ class AdminSettings(ConfigGroup):
325
+ enabled: bool = False
326
+ path: str = "/admin"
327
+ title: str = "管理后台"
328
+ page_size: int = Field(default=50, ge=10, le=200)
329
+ ip_allowlist: list[str] = Field(default_factory=list)
330
+ session_ttl_s: int = Field(default=1_800, ge=60)
331
+ # 登录保护:连续失败 N 次后锁定 M 分钟(按账号计数,落库可跨进程)
332
+ login_max_attempts: int = Field(default=5, ge=1, le=100)
333
+ lockout_s: int = Field(default=900, ge=0, le=86_400)
334
+ # 按来源 IP 的登录节流:防"每个账号试 4 次"的密码喷洒
335
+ login_ip_max_attempts: int = Field(default=20, ge=1, le=10_000)
336
+ login_ip_window_s: int = Field(default=300, ge=1, le=86_400)
337
+ login_ip_block_s: int = Field(default=900, ge=0, le=86_400)
338
+ # 内置定时清理登录节流表(部署时不用再配 cron)
339
+ throttle_prune_enabled: bool = True
340
+ throttle_prune_interval_s: int = Field(default=21_600, ge=60, le=604_800)
341
+ throttle_retention_s: int = Field(default=86_400, ge=3_600, le=2_592_000)
342
+ require_mfa: bool = False
343
+
344
+
345
+ class DocsSettings(ConfigGroup):
346
+ enabled: bool = True
347
+ path: str = "/docs"
348
+ title: str = "SwiftAPI"
349
+ try_it_out: bool = True
350
+ require_auth: bool = False
351
+ theme: str = "auto"
352
+
353
+
354
+ class FeatureSettings(ConfigGroup):
355
+ features: dict[str, bool] = Field(default_factory=dict)
356
+
357
+ def is_on(self, name: str, default: bool = False) -> bool:
358
+ return self.features.get(name, default)
359
+
360
+
361
+ class Settings(BaseSettings):
362
+ """全项目唯一配置对象。构造成功即代表"配置可用"。"""
363
+
364
+ model_config = SettingsConfigDict(
365
+ env_prefix="SWIFTAPI__",
366
+ env_nested_delimiter="__",
367
+ env_file=(".env",),
368
+ env_file_encoding="utf-8",
369
+ case_sensitive=False,
370
+ extra="forbid",
371
+ frozen=True,
372
+ validate_default=True,
373
+ )
374
+
375
+ @classmethod
376
+ def settings_customise_sources(
377
+ cls,
378
+ settings_cls: type[BaseSettings],
379
+ init_settings: PydanticBaseSettingsSource,
380
+ env_settings: PydanticBaseSettingsSource,
381
+ dotenv_settings: PydanticBaseSettingsSource,
382
+ file_secret_settings: PydanticBaseSettingsSource,
383
+ ) -> tuple[PydanticBaseSettingsSource, ...]:
384
+ """优先级:显式传参 > 环境变量 > .env > 用户 settings 模块 > 代码默认值。
385
+
386
+ 与 Django 的差别:Django 里 settings 模块是唯一来源;这里允许环境变量覆盖它,
387
+ 以便同一份 settings 模块在 dev/staging/prod 复用(12-Factor)。
388
+ """
389
+ return (
390
+ init_settings,
391
+ env_settings,
392
+ dotenv_settings,
393
+ ModuleSettingsSource(settings_cls),
394
+ file_secret_settings,
395
+ )
396
+
397
+ app: AppSettings = Field(default_factory=AppSettings)
398
+ server: ServerSettings = Field(default_factory=ServerSettings)
399
+ database: DatabaseSettings = Field(default_factory=DatabaseSettings)
400
+ tenant: TenantSettings = Field(default_factory=TenantSettings)
401
+ cache: CacheSettings = Field(default_factory=CacheSettings)
402
+ messaging: MessagingSettings = Field(default_factory=MessagingSettings)
403
+ document: DocumentSettings = Field(default_factory=DocumentSettings)
404
+ security: SecuritySettings = Field(default_factory=SecuritySettings)
405
+ observability: ObservabilitySettings = Field(default_factory=ObservabilitySettings)
406
+ admin: AdminSettings = Field(default_factory=AdminSettings)
407
+ outbound: OutboundSettings = Field(default_factory=OutboundSettings)
408
+ uploads: UploadSettings = Field(default_factory=UploadSettings)
409
+ docs: DocsSettings = Field(default_factory=DocsSettings)
410
+ features: FeatureSettings = Field(default_factory=FeatureSettings)
411
+
412
+ @property
413
+ def is_prod(self) -> bool:
414
+ return self.app.env is Env.PROD
415
+
416
+ @model_validator(mode="after")
417
+ def _validate_combinations(self) -> Self:
418
+ problems = [
419
+ *self._check_database(),
420
+ *self._check_cache(),
421
+ *self._check_messaging(),
422
+ *self._check_security(),
423
+ *self._check_tenant(),
424
+ *self._check_ops(),
425
+ ]
426
+ if problems:
427
+ raise ValueError("配置组合非法:\n" + "\n".join(f" - {p}" for p in problems))
428
+ return self
429
+
430
+ def _check_database(self) -> list[str]:
431
+ problems: list[str] = []
432
+ if self.database.dialect == "sqlite":
433
+ if self.is_prod and not self.database.allow_sqlite_in_prod:
434
+ problems.append(
435
+ "生产环境禁止 SQLite(单写者、1000 RPS 实测超时);"
436
+ "请改用 PostgreSQL/MySQL,或显式 database.allow_sqlite_in_prod=true"
437
+ )
438
+ if self.server.workers != 1:
439
+ problems.append(
440
+ "SQLite 为单写者,SWIFTAPI__SERVER__WORKERS 必须为 1(架构文档 §16.7)"
441
+ )
442
+ if self.database.read_replica_urls:
443
+ problems.append("SQLite 不支持只读副本,请清空 read_replica_urls")
444
+ total_conns = (self.database.pool_size + self.database.max_overflow) * self.server.workers
445
+ if total_conns > self.database.max_connections:
446
+ problems.append(
447
+ f"连接数超限:workers×pool={total_conns} > "
448
+ f"max_connections={self.database.max_connections}(架构文档 §25.2)"
449
+ )
450
+ if self.server.request_timeout_s <= self.database.statement_timeout_ms / 1000:
451
+ problems.append(
452
+ "超时预算必须递减:request_timeout_s 必须大于 statement_timeout_ms(§11.1)"
453
+ )
454
+ return problems
455
+
456
+ def _check_cache(self) -> list[str]:
457
+ if not self.cache.enabled:
458
+ return []
459
+ problems: list[str] = []
460
+ if self.cache.backend is CacheBackend.REDIS and self.cache.url is None:
461
+ problems.append("cache.backend=redis 时必须提供 cache.url")
462
+ if self.cache.backend is CacheBackend.MONGODB and self.document.uri is None:
463
+ problems.append("cache.backend=mongodb 时必须提供 document.uri")
464
+ if self.cache.backend is CacheBackend.MEMORY and self.is_prod:
465
+ problems.append("生产环境禁止进程内缓存(多副本不一致),请改用 redis/mongodb")
466
+ return problems
467
+
468
+ def _check_messaging(self) -> list[str]:
469
+ if not self.messaging.enabled:
470
+ return []
471
+ problems: list[str] = []
472
+ if self.messaging.backend is MessagingBackend.RABBITMQ and self.messaging.url is None:
473
+ problems.append("messaging.backend=rabbitmq 时必须提供 url")
474
+ if self.messaging.backend is MessagingBackend.REDIS_STREAMS and (
475
+ self.messaging.url is None and self.cache.url is None
476
+ ):
477
+ problems.append("messaging.backend=redis_streams 时必须提供 messaging.url 或 cache.url")
478
+ if self.messaging.backend is MessagingBackend.INPROCESS and self.is_prod:
479
+ problems.append("生产环境禁止进程内消息总线(多副本收不到事件)")
480
+ return problems
481
+
482
+ def _check_security(self) -> list[str]:
483
+ problems: list[str] = []
484
+ if (
485
+ self.security.jwt_algorithm is JwtAlgorithm.HS256
486
+ and self.is_prod
487
+ and not self.security.allow_insecure
488
+ ):
489
+ problems.append("生产环境禁止 HS256,请使用 RS256(或显式 allow_insecure=true)")
490
+ if self.is_prod and "*" in self.security.cors_allow_origins:
491
+ problems.append("生产环境 CORS 不得为 *,请配置白名单")
492
+ return problems
493
+
494
+ def _check_tenant(self) -> list[str]:
495
+ if not self.tenant.enabled:
496
+ return []
497
+ problems: list[str] = []
498
+ if (
499
+ self.tenant.pool_size_per_tenant * self.tenant.max_pools
500
+ > self.database.max_connections
501
+ ):
502
+ problems.append(
503
+ "租户连接池总量超出数据库上限:pool_size_per_tenant × max_pools "
504
+ "> database.max_connections(架构文档 §17.8)"
505
+ )
506
+ if (
507
+ TenantResolver.SUBDOMAIN in self.tenant.resolver
508
+ and self.tenant.root_domain is None
509
+ ):
510
+ problems.append("tenant.resolver 含 subdomain 时必须配置 tenant.root_domain")
511
+ if self.tenant.strategy is TenantStrategy.SCHEMA and self.database.dialect != "postgresql":
512
+ problems.append("schema 级租户隔离只支持 PostgreSQL(其它方言请用 database 级)")
513
+ if self.tenant.strategy is TenantStrategy.HYBRID:
514
+ problems.append("hybrid 租户策略尚未实现(row / schema / database 已实现)")
515
+ if (
516
+ self.tenant.strategy is TenantStrategy.DATABASE
517
+ and self.tenant.database_url_template is None
518
+ ):
519
+ problems.append(
520
+ "database 级租户隔离必须配置 tenant.database_url_template(用 {tenant} 占位)"
521
+ )
522
+ if (
523
+ self.is_prod
524
+ and self.tenant.trust_header
525
+ and not self.tenant.allow_trust_header_in_prod
526
+ ):
527
+ problems.append(
528
+ "生产环境禁止 tenant.trust_header=true(任意调用方可用请求头切租户);"
529
+ "确认网关会剥离客户端头后,显式设置 "
530
+ "tenant.allow_trust_header_in_prod=true"
531
+ )
532
+ return problems
533
+
534
+ def _check_ops(self) -> list[str]:
535
+ problems: list[str] = []
536
+ if self.observability.otel_enabled:
537
+ problems.append(
538
+ "observability.otel_enabled 尚未实现:当前只提供 trace_id 贯穿与结构化日志,"
539
+ "OTel 导出在路线图中"
540
+ )
541
+ if self.admin.enabled and self.is_prod and not self.admin.ip_allowlist:
542
+ problems.append("生产环境启用管理后台必须配置 admin.ip_allowlist(架构文档 §22.9)")
543
+ if self.docs.enabled and self.is_prod and not self.docs.require_auth:
544
+ problems.append("生产环境开启文档页必须 docs.require_auth=true(或 docs.enabled=false)")
545
+ return problems
546
+
547
+ def redacted_summary(self) -> dict[str, Any]:
548
+ """启动摘要:只输出生效组合与指纹,绝不输出密钥明文。"""
549
+
550
+ return {
551
+ "app": {"name": self.app.name, "env": self.app.env.value, "debug": self.app.debug},
552
+ "server": {"workers": self.server.workers, "port": self.server.port},
553
+ "database": {
554
+ "dialect": self.database.dialect,
555
+ "driver": self.database.driver,
556
+ "pool": {"size": self.database.pool_size, "workers": self.server.workers},
557
+ "replica": len(self.database.read_replica_urls),
558
+ "host": _safe_host(self.database.url),
559
+ },
560
+ "tenant": {
561
+ "enabled": self.tenant.enabled,
562
+ "strategy": self.tenant.strategy.value,
563
+ "resolver": [r.value for r in self.tenant.resolver],
564
+ },
565
+ "cache": {
566
+ "enabled": self.cache.enabled,
567
+ "backend": self.cache.backend.value,
568
+ "ttl": self.cache.default_ttl_s,
569
+ },
570
+ "messaging": {
571
+ "enabled": self.messaging.enabled,
572
+ "backend": self.messaging.backend.value,
573
+ "outbox_relay": self.messaging.outbox_relay_enabled,
574
+ },
575
+ "document": {"enabled": self.document.enabled, "database": self.document.database},
576
+ "rate_limit": {
577
+ "enabled": self.security.rate_limit.enabled,
578
+ "backend": self.security.rate_limit.backend.value,
579
+ "ip_rps": self.security.rate_limit.ip_rps,
580
+ },
581
+ "admin": {"enabled": self.admin.enabled, "path": self.admin.path},
582
+ "docs": {"enabled": self.docs.enabled, "path": self.docs.path},
583
+ "jwt": {
584
+ "alg": self.security.jwt_algorithm.value,
585
+ "key_fingerprint": _fingerprint(self.security.jwt_public_key),
586
+ },
587
+ }
588
+
589
+
590
+ class SettingsError(Exception):
591
+ """配置校验失败:message 已是面向人的可读清单。"""
592
+
593
+
594
+ def _fingerprint(secret: SecretStr | None) -> str | None:
595
+ if secret is None:
596
+ return None
597
+ return hashlib.sha256(secret.get_secret_value().encode()).hexdigest()[:8]
598
+
599
+
600
+ def _safe_host(url: SecretStr) -> str:
601
+ """只暴露 host:port,绝不带出用户名密码。"""
602
+ raw = url.get_secret_value()
603
+ try:
604
+ parts = urlsplit(raw)
605
+ except ValueError:
606
+ return "<invalid>"
607
+ if not parts.hostname:
608
+ return "<local>"
609
+ return f"{parts.hostname}:{parts.port}" if parts.port else parts.hostname
610
+
611
+
612
+ def format_validation_error(exc: ValidationError) -> str:
613
+ lines: list[str] = []
614
+ for err in exc.errors():
615
+ loc = ".".join(str(x) for x in err.get("loc", ()))
616
+ lines.append(f" - {loc}: {err.get('msg', 'invalid value')}")
617
+ return "配置校验失败:\n" + "\n".join(lines)
618
+
619
+
620
+ def _extract_settings(obj: Any, module_path: str) -> dict[str, Any]:
621
+ """把用户模块里的配置声明统一成嵌套 dict。"""
622
+ if isinstance(obj, dict):
623
+ return {str(key): value for key, value in obj.items()}
624
+ if isinstance(obj, type):
625
+ data: dict[str, Any] = {}
626
+ for name in dir(obj):
627
+ if name.startswith("_"):
628
+ continue
629
+ value = getattr(obj, name)
630
+ if callable(value):
631
+ continue
632
+ data[name] = value
633
+ return data
634
+ if callable(obj):
635
+ result = obj()
636
+ if isinstance(result, dict):
637
+ return {str(key): value for key, value in result.items()}
638
+ raise SettingsError(
639
+ f"settings 模块 {module_path!r} 里的配置必须是 dict 或类,得到 {type(obj).__name__}"
640
+ )
641
+
642
+
643
+ def _import_settings_module(module_path: str) -> Any:
644
+ """导入 settings 模块;允许在项目根目录用 `<包名>.conf.settings`。
645
+
646
+ 生成的项目结构是 `<parent>/<package>/conf/settings.py`,包目录的**父级**
647
+ 才是导入根。不补这一步时,`cd 项目 && swiftapi check -s mall.conf.settings`
648
+ 会报 ModuleNotFoundError(脚手架 README 正是这么写的)。
649
+ """
650
+ try:
651
+ return importlib.import_module(module_path)
652
+ except ImportError as exc:
653
+ top = module_path.split(".", 1)[0]
654
+ for candidate in (Path.cwd(), Path.cwd().parent):
655
+ if (candidate / top / "__init__.py").is_file():
656
+ root = str(candidate)
657
+ if root not in sys.path:
658
+ sys.path.insert(0, root)
659
+ try:
660
+ return importlib.import_module(module_path)
661
+ except ImportError:
662
+ break
663
+ raise SettingsError(
664
+ f"无法导入 settings 模块 {module_path!r}:{exc}。"
665
+ f"请检查 PYTHONPATH,或设置 {SETTINGS_MODULE_ENV} 为可导入的模块路径"
666
+ ) from exc
667
+
668
+
669
+ def _load_settings_module(module_path: str) -> dict[str, Any]:
670
+ module = _import_settings_module(module_path)
671
+
672
+ for attribute in ("settings", "SETTINGS", "Settings"):
673
+ candidate = getattr(module, attribute, None)
674
+ if candidate is not None:
675
+ return _extract_settings(candidate, module_path)
676
+
677
+ raise SettingsError(
678
+ f"settings 模块 {module_path!r} 需要提供 `settings` dict、`SETTINGS` dict "
679
+ "或 `Settings` 类之一"
680
+ )
681
+
682
+
683
+ class ModuleSettingsSource(PydanticBaseSettingsSource):
684
+ """用户自定义 settings 模块(Django 风格)。
685
+
686
+ 用法:
687
+ # myproject/settings.py
688
+ settings = {
689
+ "app": {"name": "orders", "env": "prod"},
690
+ "database": {"url": "postgresql+asyncpg://..."},
691
+ "cache": {"enabled": True, "backend": "redis", "url": "redis://..."},
692
+ }
693
+
694
+ $ SWIFTAPI_SETTINGS_MODULE=myproject.settings swiftapi check
695
+ """
696
+
697
+ def __init__(self, settings_cls: type[BaseSettings]) -> None:
698
+ super().__init__(settings_cls)
699
+
700
+ def get_field_value(self, field: Any, field_name: str) -> tuple[Any, str, bool]:
701
+ return None, field_name, False
702
+
703
+ def __call__(self) -> dict[str, Any]:
704
+ module_path = _active_module or os.environ.get(SETTINGS_MODULE_ENV)
705
+ if not module_path:
706
+ return {}
707
+ return _load_settings_module(module_path)
708
+
709
+
710
+ def discover_settings_module(start: Path | None = None) -> tuple[str, Path] | None:
711
+ """向上查找项目根(含 `conf/settings.py` 且自身是包),返回 (模块路径, 项目根)。
712
+
713
+ 有了它,在项目根目录直接跑 `swiftapi db upgrade` 不用再写 `-s`。
714
+ """
715
+ current = (start or Path.cwd()).resolve()
716
+ for candidate in (current, *current.parents):
717
+ if not (candidate / "__init__.py").is_file():
718
+ continue
719
+ # Django 布局(startproject):<pkg>/conf/settings.py
720
+ if (candidate / "conf" / "settings.py").is_file():
721
+ return f"{candidate.name}.conf.settings", candidate
722
+ # 平铺布局(new project):<pkg>/settings.py + <pkg>/app.py
723
+ if (candidate / "settings.py").is_file() and (candidate / "app.py").is_file():
724
+ return f"{candidate.name}.settings", candidate
725
+ return None
726
+
727
+
728
+ def load_settings(settings_module: str | None = None, **overrides: Any) -> Settings:
729
+ """加载配置:用户模块 + 环境变量 + 显式覆盖。
730
+
731
+ 未显式指定模块时,自动发现当前目录所属项目的 `conf/settings.py`。
732
+ 失败时抛 SettingsError(由 app factory / CLI 决定如何退出)。
733
+ """
734
+ global _active_module
735
+ previous = _active_module
736
+ auto_discovered = False
737
+ env_module = os.environ.get("SWIFTAPI_SETTINGS_MODULE")
738
+ if settings_module is None and not env_module:
739
+ found = discover_settings_module()
740
+ if found is not None:
741
+ module, root = found
742
+ parent = str(root.parent)
743
+ if parent not in sys.path:
744
+ sys.path.insert(0, parent)
745
+ settings_module = module
746
+ auto_discovered = True
747
+ if settings_module:
748
+ _active_module = settings_module
749
+ source: dict[str, Any] = {
750
+ "module": settings_module or env_module or None,
751
+ "discovered": auto_discovered,
752
+ "from_env": bool(env_module) and not auto_discovered,
753
+ "cwd": str(Path.cwd()),
754
+ }
755
+ try:
756
+ result = Settings(**overrides)
757
+ except ValidationError as exc:
758
+ raise SettingsError(format_validation_error(exc)) from exc
759
+ finally:
760
+ _active_module = previous
761
+ source["database"] = describe_database(result)
762
+ _last_source.clear()
763
+ _last_source.update(source)
764
+ return result