swiftapi-kernel 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of swiftapi-kernel might be problematic. Click here for more details.
- swiftapi/__init__.py +22 -0
- swiftapi/app/__init__.py +0 -0
- swiftapi/app/factory.py +200 -0
- swiftapi/app/lifespan.py +167 -0
- swiftapi/app/routers.py +58 -0
- swiftapi/cli/__init__.py +0 -0
- swiftapi/cli/admin.py +198 -0
- swiftapi/cli/appref.py +51 -0
- swiftapi/cli/audit.py +45 -0
- swiftapi/cli/db.py +185 -0
- swiftapi/cli/endpoint.py +169 -0
- swiftapi/cli/logs.py +100 -0
- swiftapi/cli/main.py +238 -0
- swiftapi/cli/new.py +113 -0
- swiftapi/cli/openapi.py +69 -0
- swiftapi/cli/resource.py +657 -0
- swiftapi/cli/scaffold.py +168 -0
- swiftapi/config/__init__.py +0 -0
- swiftapi/config/constants.py +51 -0
- swiftapi/config/environments.py +38 -0
- swiftapi/config/settings.py +764 -0
- swiftapi/core/__init__.py +0 -0
- swiftapi/core/admin/__init__.py +0 -0
- swiftapi/core/admin/accounts.py +385 -0
- swiftapi/core/admin/audit.py +203 -0
- swiftapi/core/admin/maintenance.py +53 -0
- swiftapi/core/admin/registry.py +53 -0
- swiftapi/core/admin/security.py +94 -0
- swiftapi/core/admin/session.py +154 -0
- swiftapi/core/admin/views.py +2428 -0
- swiftapi/core/cache/__init__.py +0 -0
- swiftapi/core/cache/base.py +29 -0
- swiftapi/core/cache/decorators.py +51 -0
- swiftapi/core/cache/factory.py +30 -0
- swiftapi/core/cache/keys.py +24 -0
- swiftapi/core/cache/memory.py +60 -0
- swiftapi/core/cache/null.py +28 -0
- swiftapi/core/cache/redis.py +50 -0
- swiftapi/core/container.py +209 -0
- swiftapi/core/db/__init__.py +0 -0
- swiftapi/core/db/base_model.py +122 -0
- swiftapi/core/db/crud.py +242 -0
- swiftapi/core/db/dialects/__init__.py +8 -0
- swiftapi/core/db/dialects/base.py +106 -0
- swiftapi/core/db/dialects/mysql.py +47 -0
- swiftapi/core/db/dialects/pg.py +51 -0
- swiftapi/core/db/dialects/registry.py +30 -0
- swiftapi/core/db/dialects/sqlite.py +47 -0
- swiftapi/core/db/engine.py +209 -0
- swiftapi/core/db/health.py +84 -0
- swiftapi/core/db/migrate/__init__.py +1 -0
- swiftapi/core/db/migrate/ddl.py +162 -0
- swiftapi/core/db/migrate/render.py +84 -0
- swiftapi/core/db/migrate/runner.py +159 -0
- swiftapi/core/db/migrate/schema.py +248 -0
- swiftapi/core/db/mixins.py +53 -0
- swiftapi/core/db/session.py +54 -0
- swiftapi/core/db/snapshot.py +33 -0
- swiftapi/core/db/tenant_model.py +43 -0
- swiftapi/core/db/tenant_router.py +114 -0
- swiftapi/core/db/types.py +109 -0
- swiftapi/core/db/unit_of_work.py +65 -0
- swiftapi/core/docs/__init__.py +0 -0
- swiftapi/core/docs/router.py +26 -0
- swiftapi/core/docs/tsgen.py +93 -0
- swiftapi/core/docs/ui.py +132 -0
- swiftapi/core/errors/__init__.py +0 -0
- swiftapi/core/errors/base.py +168 -0
- swiftapi/core/errors/codes.py +117 -0
- swiftapi/core/errors/handlers.py +155 -0
- swiftapi/core/errors/problem.py +58 -0
- swiftapi/core/errors/validation.py +11 -0
- swiftapi/core/framework_models.py +22 -0
- swiftapi/core/http/__init__.py +47 -0
- swiftapi/core/http/app.py +247 -0
- swiftapi/core/http/cors.py +100 -0
- swiftapi/core/http/idempotency.py +148 -0
- swiftapi/core/http/middleware/__init__.py +82 -0
- swiftapi/core/http/middleware/access_log.py +57 -0
- swiftapi/core/http/middleware/auth.py +105 -0
- swiftapi/core/http/middleware/body_limit.py +76 -0
- swiftapi/core/http/middleware/rate_limit.py +103 -0
- swiftapi/core/http/middleware/request_body.py +122 -0
- swiftapi/core/http/middleware/request_id.py +46 -0
- swiftapi/core/http/middleware/security_headers.py +46 -0
- swiftapi/core/http/middleware/tenant.py +93 -0
- swiftapi/core/http/middleware/timing.py +57 -0
- swiftapi/core/http/multipart.py +116 -0
- swiftapi/core/http/multipart_stream.py +216 -0
- swiftapi/core/http/openapi.py +148 -0
- swiftapi/core/http/pagination.py +55 -0
- swiftapi/core/http/params.py +302 -0
- swiftapi/core/http/request.py +145 -0
- swiftapi/core/http/responses.py +127 -0
- swiftapi/core/http/routing.py +200 -0
- swiftapi/core/http/types.py +86 -0
- swiftapi/core/http/uploads.py +222 -0
- swiftapi/core/messaging/__init__.py +0 -0
- swiftapi/core/messaging/base.py +33 -0
- swiftapi/core/messaging/consumer.py +57 -0
- swiftapi/core/messaging/factory.py +30 -0
- swiftapi/core/messaging/idempotency.py +61 -0
- swiftapi/core/messaging/inprocess.py +30 -0
- swiftapi/core/messaging/outbox.py +106 -0
- swiftapi/core/messaging/rabbitmq.py +186 -0
- swiftapi/core/messaging/relay.py +151 -0
- swiftapi/core/messaging/streams.py +141 -0
- swiftapi/core/observability/__init__.py +0 -0
- swiftapi/core/observability/archive.py +136 -0
- swiftapi/core/observability/context.py +102 -0
- swiftapi/core/observability/logging.py +192 -0
- swiftapi/core/observability/masking.py +74 -0
- swiftapi/core/observability/metrics.py +101 -0
- swiftapi/core/observability/volume.py +67 -0
- swiftapi/core/resilience/__init__.py +0 -0
- swiftapi/core/resilience/bulkhead.py +50 -0
- swiftapi/core/resilience/circuit_breaker.py +97 -0
- swiftapi/core/resilience/client.py +179 -0
- swiftapi/core/resilience/retry.py +59 -0
- swiftapi/core/security/__init__.py +0 -0
- swiftapi/core/security/jwt.py +78 -0
- swiftapi/core/security/principal.py +78 -0
- swiftapi/core/tenant/__init__.py +1 -0
- swiftapi/core/tenant/catalog.py +89 -0
- swiftapi/core/tenant/context.py +75 -0
- swiftapi/core/tenant/isolation.py +48 -0
- swiftapi/core/tenant/resolver.py +48 -0
- swiftapi/core/validation/__init__.py +0 -0
- swiftapi/core/validation/base.py +32 -0
- swiftapi/db.py +50 -0
- swiftapi/modules/__init__.py +0 -0
- swiftapi/modules/users/__init__.py +11 -0
- swiftapi/modules/users/api/__init__.py +0 -0
- swiftapi/modules/users/api/users.py +110 -0
- swiftapi/modules/users/crud/__init__.py +0 -0
- swiftapi/modules/users/crud/user.py +23 -0
- swiftapi/modules/users/errors.py +24 -0
- swiftapi/modules/users/mappers.py +19 -0
- swiftapi/modules/users/model/__init__.py +0 -0
- swiftapi/modules/users/model/user.py +37 -0
- swiftapi/modules/users/policies.py +19 -0
- swiftapi/modules/users/schema/__init__.py +0 -0
- swiftapi/modules/users/schema/user.py +40 -0
- swiftapi/modules/users/service/__init__.py +0 -0
- swiftapi/modules/users/service/user.py +107 -0
- swiftapi/py.typed +0 -0
- swiftapi/templates/__init__.py +0 -0
- swiftapi/templates/app_skeleton/README.md +17 -0
- swiftapi/templates/app_skeleton/__init__.py +1 -0
- swiftapi/templates/app_skeleton/api/__init__.py +23 -0
- swiftapi/templates/app_skeleton/api/health.py +12 -0
- swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
- swiftapi/templates/app_skeleton/model/__init__.py +1 -0
- swiftapi/templates/app_skeleton/router.py +16 -0
- swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
- swiftapi/templates/app_skeleton/service/__init__.py +1 -0
- swiftapi/templates/project/__init__.py +0 -0
- swiftapi/templates/project/api.py +135 -0
- swiftapi/templates/project/app.py +57 -0
- swiftapi/templates/project/endpoints/__init__.py +25 -0
- swiftapi/templates/project/events.py +43 -0
- swiftapi/templates/project/models.py +79 -0
- swiftapi/templates/project/resources/__init__.py +35 -0
- swiftapi/templates/project/schemas.py +45 -0
- swiftapi/templates/project/service.py +125 -0
- swiftapi/templates/project/settings.py +17 -0
- swiftapi/templates/project_skeleton/.env.example +5 -0
- swiftapi/templates/project_skeleton/.gitignore +6 -0
- swiftapi/templates/project_skeleton/README.md +25 -0
- swiftapi/templates/project_skeleton/__init__.py +1 -0
- swiftapi/templates/project_skeleton/app.py +26 -0
- swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
- swiftapi/templates/project_skeleton/common/__init__.py +4 -0
- swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
- swiftapi/templates/project_skeleton/conf/settings.py +73 -0
- swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
- swiftapi/templates/project_skeleton/models.py +12 -0
- swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
- swiftapi/templates/project_skeleton/router.py +46 -0
- swiftapi/templates/project_skeleton/script/start.sh +13 -0
- swiftapi/templates/project_skeleton/start.py +35 -0
- swiftapi/version.py +8 -0
- swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
- swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
- swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
- swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
- swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""结构快照:模型的"可比较表示"。
|
|
2
|
+
|
|
3
|
+
迁移引擎只认这个快照——模型是唯一真相,DDL 由快照 diff 得出。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from dataclasses import asdict, dataclass, field
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import (
|
|
13
|
+
JSON,
|
|
14
|
+
BigInteger,
|
|
15
|
+
Boolean,
|
|
16
|
+
DateTime,
|
|
17
|
+
Integer,
|
|
18
|
+
MetaData,
|
|
19
|
+
Numeric,
|
|
20
|
+
String,
|
|
21
|
+
Text,
|
|
22
|
+
Uuid,
|
|
23
|
+
)
|
|
24
|
+
from sqlalchemy.engine import Connection
|
|
25
|
+
from sqlalchemy.engine.interfaces import Dialect
|
|
26
|
+
from sqlalchemy.inspection import inspect
|
|
27
|
+
|
|
28
|
+
from swiftapi.core.db.dialects.base import DialectAdapter
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class ColumnSpec:
|
|
33
|
+
name: str
|
|
34
|
+
type_sql: str # 生成迁移时那个方言的 SQL(人类阅读 / 旧文件回退用)
|
|
35
|
+
nullable: bool
|
|
36
|
+
primary_key: bool = False
|
|
37
|
+
default: str | None = None
|
|
38
|
+
# 方言无关的类型标识:执行时按目标方言重新编译,保证同一份迁移能跨方言
|
|
39
|
+
type_key: str | None = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class IndexSpec:
|
|
44
|
+
name: str
|
|
45
|
+
columns: tuple[str, ...]
|
|
46
|
+
unique: bool = False
|
|
47
|
+
where: str | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class TableSpec:
|
|
52
|
+
namespace: str
|
|
53
|
+
name: str
|
|
54
|
+
columns: tuple[ColumnSpec, ...] = field(default_factory=tuple)
|
|
55
|
+
indexes: tuple[IndexSpec, ...] = field(default_factory=tuple)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def key(self) -> str:
|
|
59
|
+
return f"{self.namespace}.{self.name}"
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def primary_key(self) -> tuple[str, ...]:
|
|
63
|
+
return tuple(column.name for column in self.columns if column.primary_key)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, slots=True)
|
|
67
|
+
class SchemaSnapshot:
|
|
68
|
+
"""键为逻辑名 `namespace.table`,与方言无关。"""
|
|
69
|
+
|
|
70
|
+
tables: dict[str, TableSpec] = field(default_factory=dict)
|
|
71
|
+
|
|
72
|
+
def to_json(self) -> str:
|
|
73
|
+
return json.dumps(
|
|
74
|
+
{key: asdict(table) for key, table in sorted(self.tables.items())},
|
|
75
|
+
ensure_ascii=False,
|
|
76
|
+
sort_keys=True,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_json(cls, payload: str | dict[str, Any]) -> SchemaSnapshot:
|
|
81
|
+
data = json.loads(payload) if isinstance(payload, str) else payload
|
|
82
|
+
tables: dict[str, TableSpec] = {}
|
|
83
|
+
for key, raw in data.items():
|
|
84
|
+
tables[key] = TableSpec(
|
|
85
|
+
namespace=raw["namespace"],
|
|
86
|
+
name=raw["name"],
|
|
87
|
+
columns=tuple(ColumnSpec(**column) for column in raw.get("columns", [])),
|
|
88
|
+
indexes=tuple(
|
|
89
|
+
IndexSpec(
|
|
90
|
+
name=index["name"],
|
|
91
|
+
columns=tuple(index["columns"]),
|
|
92
|
+
unique=index.get("unique", False),
|
|
93
|
+
where=index.get("where"),
|
|
94
|
+
)
|
|
95
|
+
for index in raw.get("indexes", [])
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
return cls(tables=tables)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def type_key(type_: Any) -> str:
|
|
102
|
+
"""抽象类型 → 方言无关标识(迁移文件里只存这个)。"""
|
|
103
|
+
impl = getattr(type_, "impl", type_)
|
|
104
|
+
if isinstance(type_, Uuid) or isinstance(impl, Uuid):
|
|
105
|
+
return "uuid"
|
|
106
|
+
if isinstance(type_, DateTime) or isinstance(impl, DateTime):
|
|
107
|
+
timezone = bool(getattr(type_, "timezone", False) or getattr(impl, "timezone", False))
|
|
108
|
+
return "timestamp_tz" if timezone else "timestamp"
|
|
109
|
+
if isinstance(type_, Text) or isinstance(impl, Text):
|
|
110
|
+
return "text"
|
|
111
|
+
if isinstance(type_, JSON) or isinstance(impl, JSON):
|
|
112
|
+
return "json"
|
|
113
|
+
if isinstance(type_, Boolean) or isinstance(impl, Boolean):
|
|
114
|
+
return "boolean"
|
|
115
|
+
if isinstance(type_, BigInteger) or isinstance(impl, BigInteger):
|
|
116
|
+
return "bigint"
|
|
117
|
+
if isinstance(type_, Integer) or isinstance(impl, Integer):
|
|
118
|
+
return "integer"
|
|
119
|
+
if isinstance(type_, Numeric) or isinstance(impl, Numeric):
|
|
120
|
+
numeric = type_ if isinstance(type_, Numeric) else impl
|
|
121
|
+
return f"numeric({numeric.precision},{numeric.scale})"
|
|
122
|
+
if isinstance(type_, String) or isinstance(impl, String):
|
|
123
|
+
string = type_ if isinstance(type_, String) else impl
|
|
124
|
+
return f"varchar({string.length})" if string.length else "text"
|
|
125
|
+
return f"raw:{type_}"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_SIMPLE_TYPES: dict[str, Any] = {
|
|
129
|
+
"uuid": lambda: Uuid(as_uuid=True),
|
|
130
|
+
"timestamp_tz": lambda: DateTime(timezone=True),
|
|
131
|
+
"timestamp": lambda: DateTime(),
|
|
132
|
+
"text": lambda: Text(),
|
|
133
|
+
"json": lambda: JSON(),
|
|
134
|
+
"boolean": lambda: Boolean(),
|
|
135
|
+
"bigint": lambda: BigInteger(),
|
|
136
|
+
"integer": lambda: Integer(),
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _type_from_key(key: str) -> Any | None:
|
|
141
|
+
if key.startswith("varchar("):
|
|
142
|
+
return String(int(key[8:-1]))
|
|
143
|
+
if key.startswith("numeric("):
|
|
144
|
+
precision, _, scale = key[8:-1].partition(",")
|
|
145
|
+
return Numeric(int(precision), int(scale))
|
|
146
|
+
factory = _SIMPLE_TYPES.get(key)
|
|
147
|
+
return factory() if factory is not None else None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def type_sql_for(column: ColumnSpec, dialect: Dialect) -> str:
|
|
151
|
+
"""按目标方言编译列类型;旧迁移没有 type_key 时回退到保存的 SQL。"""
|
|
152
|
+
key = column.type_key
|
|
153
|
+
if not key:
|
|
154
|
+
return column.type_sql
|
|
155
|
+
if key.startswith("raw:"):
|
|
156
|
+
return key[4:]
|
|
157
|
+
if key == "timestamp_tz" and dialect.name == "mysql":
|
|
158
|
+
from sqlalchemy.dialects.mysql import DATETIME
|
|
159
|
+
|
|
160
|
+
return str(DATETIME(fsp=6).compile(dialect=dialect))
|
|
161
|
+
type_ = _type_from_key(key)
|
|
162
|
+
if type_ is None:
|
|
163
|
+
return column.type_sql
|
|
164
|
+
return str(type_.compile(dialect=dialect))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def introspect(metadata: MetaData, adapter: DialectAdapter) -> SchemaSnapshot:
|
|
168
|
+
"""模型 → 快照(不连数据库)。类型按目标方言编译。"""
|
|
169
|
+
tables: dict[str, TableSpec] = {}
|
|
170
|
+
for table in metadata.sorted_tables:
|
|
171
|
+
namespace = str(table.schema or table.info.get("module_schema") or "public")
|
|
172
|
+
columns = tuple(
|
|
173
|
+
ColumnSpec(
|
|
174
|
+
name=column.name,
|
|
175
|
+
type_sql=column.type.compile(dialect=adapter.dialect_cls()),
|
|
176
|
+
nullable=bool(column.nullable),
|
|
177
|
+
primary_key=bool(column.primary_key),
|
|
178
|
+
default=_server_default(column),
|
|
179
|
+
type_key=type_key(column.type),
|
|
180
|
+
)
|
|
181
|
+
for column in table.columns
|
|
182
|
+
)
|
|
183
|
+
indexes = tuple(
|
|
184
|
+
IndexSpec(
|
|
185
|
+
name=str(index.name),
|
|
186
|
+
columns=tuple(column.name for column in index.columns),
|
|
187
|
+
unique=bool(index.unique),
|
|
188
|
+
where=_index_where(index),
|
|
189
|
+
)
|
|
190
|
+
for index in sorted(table.indexes, key=lambda item: str(item.name))
|
|
191
|
+
)
|
|
192
|
+
spec = TableSpec(
|
|
193
|
+
namespace=namespace,
|
|
194
|
+
name=table.name,
|
|
195
|
+
columns=columns,
|
|
196
|
+
indexes=indexes,
|
|
197
|
+
)
|
|
198
|
+
tables[spec.key] = spec
|
|
199
|
+
return SchemaSnapshot(tables=tables)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _index_where(index: Any) -> str | None:
|
|
203
|
+
"""部分索引的 WHERE 子句(仅 PG 声明;其他方言由适配器决定是否支持)。"""
|
|
204
|
+
options = cast(dict[str, Any], index.dialect_options)
|
|
205
|
+
pg_options = cast(dict[str, Any], options.get("postgresql") or {})
|
|
206
|
+
where = pg_options.get("where")
|
|
207
|
+
return None if where is None else str(where)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _server_default(column: Any) -> str | None:
|
|
211
|
+
default = getattr(column, "server_default", None)
|
|
212
|
+
if default is None:
|
|
213
|
+
return None
|
|
214
|
+
arg = getattr(default, "arg", None)
|
|
215
|
+
if arg is None:
|
|
216
|
+
return None
|
|
217
|
+
return str(getattr(arg, "text", arg))
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def reflect(connection: Connection, adapter: DialectAdapter, expected: SchemaSnapshot) -> SchemaSnapshot:
|
|
221
|
+
"""数据库 → 快照;只反射 target 里出现过的表(忽略无关表)。"""
|
|
222
|
+
inspector = inspect(connection)
|
|
223
|
+
tables: dict[str, TableSpec] = {}
|
|
224
|
+
for table in expected.tables.values():
|
|
225
|
+
physical, schema_name = adapter.physical_location(table.namespace, table.name)
|
|
226
|
+
if not inspector.has_table(physical, schema=schema_name):
|
|
227
|
+
continue
|
|
228
|
+
columns = tuple(
|
|
229
|
+
ColumnSpec(
|
|
230
|
+
name=column["name"],
|
|
231
|
+
type_sql=str(column["type"]).lower(),
|
|
232
|
+
nullable=bool(column.get("nullable", True)),
|
|
233
|
+
primary_key=bool(column.get("primary_key", False)),
|
|
234
|
+
)
|
|
235
|
+
for column in inspector.get_columns(physical, schema=schema_name)
|
|
236
|
+
)
|
|
237
|
+
indexes = tuple(
|
|
238
|
+
IndexSpec(
|
|
239
|
+
name=str(index["name"]),
|
|
240
|
+
columns=tuple(str(column) for column in index.get("column_names") or ()),
|
|
241
|
+
unique=bool(index.get("unique", False)),
|
|
242
|
+
)
|
|
243
|
+
for index in inspector.get_indexes(physical, schema=schema_name)
|
|
244
|
+
if index.get("name")
|
|
245
|
+
)
|
|
246
|
+
spec = TableSpec(namespace=table.namespace, name=table.name, columns=columns, indexes=indexes)
|
|
247
|
+
tables[spec.key] = spec
|
|
248
|
+
return SchemaSnapshot(tables=tables)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""可组合的模型 Mixin(架构文档 §17.5.5)。
|
|
2
|
+
|
|
3
|
+
都是"加列 + 约定",不含业务逻辑;组合方式:
|
|
4
|
+
class Order(TenantScopedModel, SoftDeleteMixin, VersionMixin): ...
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from uuid import UUID
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import func
|
|
13
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
14
|
+
|
|
15
|
+
from swiftapi.core.db.types import TZDateTime, UUIDType
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TimestampMixin:
|
|
19
|
+
"""创建/更新时间:由数据库生成,避免应用时钟漂移导致排序错乱。"""
|
|
20
|
+
|
|
21
|
+
created_at: Mapped[datetime] = mapped_column(
|
|
22
|
+
TZDateTime,
|
|
23
|
+
nullable=False,
|
|
24
|
+
default=lambda: datetime.now(UTC),
|
|
25
|
+
server_default=func.now(),
|
|
26
|
+
index=True,
|
|
27
|
+
)
|
|
28
|
+
updated_at: Mapped[datetime] = mapped_column(
|
|
29
|
+
TZDateTime,
|
|
30
|
+
nullable=False,
|
|
31
|
+
default=lambda: datetime.now(UTC),
|
|
32
|
+
server_default=func.now(),
|
|
33
|
+
onupdate=lambda: datetime.now(UTC),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class SoftDeleteMixin:
|
|
38
|
+
"""软删:查询需显式过滤 `deleted_at IS NULL`(由 CRUD 基类统一处理)。"""
|
|
39
|
+
|
|
40
|
+
deleted_at: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True, default=None)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class VersionMixin:
|
|
44
|
+
"""乐观锁:更新时 `WHERE id = ? AND version = ?`,影响 0 行即 409。"""
|
|
45
|
+
|
|
46
|
+
version: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AuditMixin:
|
|
50
|
+
"""操作人:写入时由 service 填充,禁止从请求体接收。"""
|
|
51
|
+
|
|
52
|
+
created_by: Mapped[UUID | None] = mapped_column(UUIDType, nullable=True, default=None)
|
|
53
|
+
updated_by: Mapped[UUID | None] = mapped_column(UUIDType, nullable=True, default=None)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""会话辅助:只读会话与"写后读主库"标记。
|
|
2
|
+
|
|
3
|
+
`read()` 返回副本会话(未配置副本时回落主库);写后 1s 内的读由调用方用
|
|
4
|
+
`primary=True` 强制走主库,避免复制延迟导致"写完读不到"。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import AsyncIterator, Iterator
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
|
|
13
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
14
|
+
|
|
15
|
+
from swiftapi.core.db.engine import Database
|
|
16
|
+
|
|
17
|
+
_READ_YOUR_WRITES_TTL_S = 1.0
|
|
18
|
+
_recent_writes: dict[str, float] = {}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def mark_write(key: str) -> None:
|
|
22
|
+
"""写操作成功后调用,标记该主体在 1s 内需要读主库。"""
|
|
23
|
+
_recent_writes[key] = time.monotonic()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def needs_primary(key: str) -> bool:
|
|
27
|
+
written_at = _recent_writes.get(key)
|
|
28
|
+
if written_at is None:
|
|
29
|
+
return False
|
|
30
|
+
if time.monotonic() - written_at > _READ_YOUR_WRITES_TTL_S:
|
|
31
|
+
_recent_writes.pop(key, None)
|
|
32
|
+
return False
|
|
33
|
+
return True
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def read_session(database: Database, *, key: str | None = None) -> AsyncIterator[AsyncSession]:
|
|
37
|
+
use_primary = key is None or needs_primary(key)
|
|
38
|
+
engine = database.engine if use_primary else database.read_engine()
|
|
39
|
+
factory = database.session_factory
|
|
40
|
+
session = factory(bind=engine)
|
|
41
|
+
try:
|
|
42
|
+
yield session
|
|
43
|
+
finally:
|
|
44
|
+
await session.close()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@contextmanager
|
|
48
|
+
def write_guard(key: str) -> Iterator[None]:
|
|
49
|
+
"""写入成功后自动标记 read-your-writes。"""
|
|
50
|
+
yield
|
|
51
|
+
mark_write(key)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
__all__ = ["mark_write", "needs_primary", "read_session", "write_guard"]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""结构快照:模型层的"可比较表示"。
|
|
2
|
+
|
|
3
|
+
迁移引擎(P2)消费它做 diff;现在先提供最小可用的内省能力,
|
|
4
|
+
供 `db check` 与测试断言使用。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True, slots=True)
|
|
13
|
+
class ColumnSnapshot:
|
|
14
|
+
name: str
|
|
15
|
+
type: str
|
|
16
|
+
nullable: bool
|
|
17
|
+
primary_key: bool
|
|
18
|
+
has_default: bool
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class TableSnapshot:
|
|
23
|
+
namespace: str
|
|
24
|
+
name: str
|
|
25
|
+
qualified_name: str
|
|
26
|
+
tenant_scoped: bool
|
|
27
|
+
columns: tuple[ColumnSnapshot, ...] = ()
|
|
28
|
+
indexes: tuple[str, ...] = field(default_factory=tuple)
|
|
29
|
+
unique_constraints: tuple[str, ...] = field(default_factory=tuple)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def column_names(self) -> tuple[str, ...]:
|
|
33
|
+
return tuple(c.name for c in self.columns)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""`TenantScopedModel`:租户隔离基类(架构文档 §17.5)。
|
|
2
|
+
|
|
3
|
+
= `BaseModel` + `tenant_id` + 查询自动过滤 + 约束改写。
|
|
4
|
+
|
|
5
|
+
使用方式:
|
|
6
|
+
from swiftapi.db import TenantScopedModel
|
|
7
|
+
|
|
8
|
+
class Invoice(TenantScopedModel):
|
|
9
|
+
__tablename__ = "invoice"
|
|
10
|
+
|
|
11
|
+
**不要手写 tenant_id** —— 基类已提供,重复声明会直接报错。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import ClassVar
|
|
17
|
+
from uuid import UUID
|
|
18
|
+
|
|
19
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
20
|
+
|
|
21
|
+
from swiftapi.config.constants import DEFAULT_TENANT_ID
|
|
22
|
+
from swiftapi.core.db.base_model import BaseModel
|
|
23
|
+
from swiftapi.core.db.types import UUIDType
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TenantScopedModel(BaseModel):
|
|
27
|
+
"""所有"属于某个租户"的业务表的基类。"""
|
|
28
|
+
|
|
29
|
+
__abstract__ = True
|
|
30
|
+
__tenant_scoped__: ClassVar[bool] = True
|
|
31
|
+
|
|
32
|
+
tenant_id: Mapped[UUID] = mapped_column(
|
|
33
|
+
UUIDType,
|
|
34
|
+
nullable=False,
|
|
35
|
+
default=DEFAULT_TENANT_ID,
|
|
36
|
+
index=True,
|
|
37
|
+
doc="租户标识;由 before_insert 事件按当前上下文填充,业务代码不得显式赋值",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def qualified_name(cls) -> str:
|
|
42
|
+
"""租户表的逻辑名额外带租户维度,便于迁移引擎按策略 fan-out。"""
|
|
43
|
+
return f"{cls.namespace()}.{cls.table_name()}"
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""租户物理隔离:按租户 context 选择数据库引擎/会话工厂。
|
|
2
|
+
|
|
3
|
+
支持三种策略:
|
|
4
|
+
- `row`:所有租户共用数据库(默认,查询自动带 tenant_id);
|
|
5
|
+
- `schema`:PostgreSQL 每租户一个 schema,连接 `search_path` 指向该 schema;
|
|
6
|
+
- `database`:每租户一个数据库,连接串来自租户目录。
|
|
7
|
+
|
|
8
|
+
注意:`schema`/`database` 的租户库/schema 必须先用迁移命令建好:
|
|
9
|
+
swiftapi db upgrade --dir migrations --database-url <tenant-url>
|
|
10
|
+
swiftapi db upgrade --dir migrations --tenant-schema <schema>
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
|
|
18
|
+
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
|
|
19
|
+
|
|
20
|
+
from swiftapi.config.settings import Settings
|
|
21
|
+
from swiftapi.core.db.engine import Database, create_engine_for
|
|
22
|
+
from swiftapi.core.tenant.context import TenantContext
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TenantRoutingError(RuntimeError):
|
|
26
|
+
"""租户物理位置缺失/方言不一致。"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TenantDatabaseRouter:
|
|
30
|
+
def __init__(self, database: Database, settings: Settings) -> None:
|
|
31
|
+
self.database = database
|
|
32
|
+
self.settings = settings
|
|
33
|
+
self._engines: dict[str, AsyncEngine] = {}
|
|
34
|
+
self._factories: dict[str, async_sessionmaker[AsyncSession]] = {}
|
|
35
|
+
self._lock = asyncio.Lock()
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def main_factory(self) -> async_sessionmaker[AsyncSession]:
|
|
39
|
+
return self.database.session_factory
|
|
40
|
+
|
|
41
|
+
async def session_factory(
|
|
42
|
+
self, context: TenantContext | None
|
|
43
|
+
) -> async_sessionmaker[AsyncSession]:
|
|
44
|
+
if context is None or context.is_row:
|
|
45
|
+
return self.main_factory
|
|
46
|
+
|
|
47
|
+
if context.is_schema:
|
|
48
|
+
if not context.schema:
|
|
49
|
+
raise TenantRoutingError(f"租户 {context.slug} 缺少 schema")
|
|
50
|
+
key = f"schema:{context.schema}"
|
|
51
|
+
return await self._factory(
|
|
52
|
+
key,
|
|
53
|
+
lambda: create_engine_for(
|
|
54
|
+
str(self.settings.database.url.get_secret_value()),
|
|
55
|
+
self.settings,
|
|
56
|
+
connect_args={"server_settings": {"search_path": f'"{context.schema}",public'}},
|
|
57
|
+
pool_size=self.settings.tenant.pool_size_per_tenant,
|
|
58
|
+
),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
if context.is_database:
|
|
62
|
+
if not context.database_url:
|
|
63
|
+
raise TenantRoutingError(f"租户 {context.slug} 缺少 database_url")
|
|
64
|
+
if not context.database_url.startswith(f"{self.settings.database.dialect}+"):
|
|
65
|
+
raise TenantRoutingError(
|
|
66
|
+
f"租户 {context.slug} 的库方言与主库不一致:{context.database_url.split(':', 1)[0]}"
|
|
67
|
+
)
|
|
68
|
+
key = f"database:{context.database_url}"
|
|
69
|
+
return await self._factory(
|
|
70
|
+
key,
|
|
71
|
+
lambda: create_engine_for(
|
|
72
|
+
context.database_url or "",
|
|
73
|
+
self.settings,
|
|
74
|
+
pool_size=self.settings.tenant.pool_size_per_tenant,
|
|
75
|
+
),
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
raise TenantRoutingError(f"未知租户策略: {context.strategy}")
|
|
79
|
+
|
|
80
|
+
async def _factory(
|
|
81
|
+
self, key: str, engine_factory: Callable[[], AsyncEngine]
|
|
82
|
+
) -> async_sessionmaker[AsyncSession]:
|
|
83
|
+
async with self._lock:
|
|
84
|
+
cached = self._factories.get(key)
|
|
85
|
+
if cached is not None:
|
|
86
|
+
return cached
|
|
87
|
+
if len(self._engines) >= self.settings.tenant.max_pools:
|
|
88
|
+
raise TenantRoutingError(
|
|
89
|
+
f"租户连接池数量超过 tenant.max_pools={self.settings.tenant.max_pools};"
|
|
90
|
+
"请调大上限或缩短租户目录缓存"
|
|
91
|
+
)
|
|
92
|
+
engine = engine_factory()
|
|
93
|
+
factory = async_sessionmaker(
|
|
94
|
+
bind=engine,
|
|
95
|
+
class_=AsyncSession,
|
|
96
|
+
expire_on_commit=False,
|
|
97
|
+
autoflush=False,
|
|
98
|
+
info={"swiftapi_wrote": False},
|
|
99
|
+
)
|
|
100
|
+
self._engines[key] = engine
|
|
101
|
+
self._factories[key] = factory
|
|
102
|
+
return factory
|
|
103
|
+
|
|
104
|
+
async def aclose(self) -> None:
|
|
105
|
+
for engine in self._engines.values():
|
|
106
|
+
await engine.dispose()
|
|
107
|
+
self._engines.clear()
|
|
108
|
+
self._factories.clear()
|
|
109
|
+
|
|
110
|
+
def describe(self) -> dict[str, int]:
|
|
111
|
+
return {"tenant_engines": len(self._engines)}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
__all__ = ["TenantDatabaseRouter", "TenantRoutingError"]
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""方言感知的列类型(架构文档 §16.4)。
|
|
2
|
+
|
|
3
|
+
业务模型只声明抽象类型,具体 DDL 由 SQLAlchemy 的方言 compiler 决定:
|
|
4
|
+
- `UUIDType` → PG `uuid` / MySQL `BINARY(16)` / SQLite `CHAR(32)`
|
|
5
|
+
- `JSONType` → PG `jsonb` / MySQL `json` / SQLite `TEXT`(json1)
|
|
6
|
+
- `TZDateTime`→ PG `timestamptz` / MySQL `DATETIME(6)` / SQLite `TEXT`
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from typing import Any
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, Numeric, String, Text, Uuid
|
|
16
|
+
from sqlalchemy.engine import Dialect
|
|
17
|
+
from sqlalchemy.types import TypeDecorator, TypeEngine
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UUIDType(TypeDecorator[Any]):
|
|
21
|
+
"""UUID 列:方言感知(PG uuid / MySQL BINARY(16) / SQLite CHAR(32))。
|
|
22
|
+
|
|
23
|
+
额外做一件 SQLAlchemy 默认不做的事:**接受 str 并自动转 UUID**。
|
|
24
|
+
否则 `Model.id == "..."` 会抛 "'str' object has no attribute 'hex'",
|
|
25
|
+
这个报错对使用者毫无指向性(真实踩过:事件消费者传了 str)。
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
impl = Uuid(as_uuid=True)
|
|
29
|
+
cache_ok = True
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def python_type(self) -> type[Any]:
|
|
33
|
+
# TypeDecorator 默认不透传,后台按主键类型转换时需要它(String PK 靠这个分支区分)
|
|
34
|
+
return UUID
|
|
35
|
+
|
|
36
|
+
def process_bind_param(self, value: Any, dialect: Dialect) -> Any:
|
|
37
|
+
if value is None or isinstance(value, UUID):
|
|
38
|
+
return value
|
|
39
|
+
if isinstance(value, str):
|
|
40
|
+
try:
|
|
41
|
+
return UUID(value)
|
|
42
|
+
except ValueError as exc:
|
|
43
|
+
raise ValueError(f"非法 UUID 字符串: {value!r}") from exc
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
def process_result_value(self, value: Any, dialect: Dialect) -> Any:
|
|
47
|
+
if value is None or isinstance(value, UUID):
|
|
48
|
+
return value
|
|
49
|
+
return UUID(str(value))
|
|
50
|
+
|
|
51
|
+
# JSON:PG 上是 jsonb,MySQL 是 json,SQLite 落到 TEXT
|
|
52
|
+
JSONType: TypeEngine[Any] = JSON()
|
|
53
|
+
|
|
54
|
+
class UTCDateTime(TypeDecorator[datetime]):
|
|
55
|
+
"""统一 UTC:写入时归一化,读出时补回 tzinfo。
|
|
56
|
+
|
|
57
|
+
MySQL/SQLite 的 DATETIME 不保存时区,直接写 aware 值会被驱动按本地时间落库,
|
|
58
|
+
导致 `next_retry_at <= now` 这类比较偏移 8 小时(真实踩过的坑)。
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
impl = DateTime(timezone=True)
|
|
62
|
+
cache_ok = True
|
|
63
|
+
|
|
64
|
+
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
|
65
|
+
# MySQL 默认 DATETIME 精度为秒,微秒会被四舍五入到未来一秒,
|
|
66
|
+
# 导致 outbox 的 next_retry_at <= now 刚写入就查不到。
|
|
67
|
+
if dialect.name == "mysql":
|
|
68
|
+
from sqlalchemy.dialects.mysql import DATETIME
|
|
69
|
+
|
|
70
|
+
return dialect.type_descriptor(DATETIME(fsp=6))
|
|
71
|
+
return dialect.type_descriptor(DateTime(timezone=True))
|
|
72
|
+
|
|
73
|
+
def process_bind_param(self, value: datetime | None, dialect: Dialect) -> datetime | None:
|
|
74
|
+
if value is None:
|
|
75
|
+
return None
|
|
76
|
+
normalized = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)
|
|
77
|
+
# PG 有 timestamptz;MySQL/SQLite 只是 DATETIME,落库前去掉 tzinfo
|
|
78
|
+
return normalized if dialect.name == "postgresql" else normalized.replace(tzinfo=None)
|
|
79
|
+
|
|
80
|
+
def process_result_value(self, value: datetime | None, dialect: Dialect) -> datetime | None:
|
|
81
|
+
if value is not None and value.tzinfo is None:
|
|
82
|
+
return value.replace(tzinfo=UTC)
|
|
83
|
+
return value
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# 带时区的时间:统一以 UTC 写入(方言差异由 TypeDecorator 抹平)
|
|
87
|
+
TZDateTime: TypeEngine[Any] = UTCDateTime()
|
|
88
|
+
|
|
89
|
+
BigIntType: TypeEngine[Any] = BigInteger()
|
|
90
|
+
BoolType: TypeEngine[Any] = Boolean()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def ShortText(length: int) -> TypeEngine[Any]:
|
|
94
|
+
"""有长度上限的字符串。长度必须显式给出——避免 MySQL 行溢出与索引超限。"""
|
|
95
|
+
if length <= 0:
|
|
96
|
+
raise ValueError("ShortText 长度必须为正")
|
|
97
|
+
return String(length)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def LongText() -> TypeEngine[Any]:
|
|
101
|
+
"""长文本:PG text / MySQL longtext / SQLite text。"""
|
|
102
|
+
return Text()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def Money(precision: int = 18, scale: int = 2) -> TypeEngine[Any]:
|
|
106
|
+
"""金额:禁止用 float。"""
|
|
107
|
+
if precision <= scale:
|
|
108
|
+
raise ValueError("Money 精度必须大于小数位")
|
|
109
|
+
return Numeric(precision, scale, asdecimal=True)
|