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
swiftapi/cli/appref.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""项目应用定位:CLI 的 run / openapi 都要找"用户的应用",不是内核默认应用。
|
|
2
|
+
|
|
3
|
+
生成的项目结构是 `<parent>/<package>/app.py`,包目录的父级才是导入根;
|
|
4
|
+
`discover_settings_module()` 已经能定位项目根,这里复用它并把父级补进 sys.path。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib
|
|
10
|
+
import inspect
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Any, cast
|
|
14
|
+
|
|
15
|
+
from swiftapi.config.settings import discover_settings_module
|
|
16
|
+
|
|
17
|
+
KERNEL_APP = "swiftapi.app.factory:create_app"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def discover_app_reference(explicit: str | None = None) -> str:
|
|
21
|
+
"""返回 `模块:工厂`;显式优先,其次项目 `<包名>.app:create_app`,最后内核默认。"""
|
|
22
|
+
if explicit:
|
|
23
|
+
return explicit
|
|
24
|
+
found = discover_settings_module()
|
|
25
|
+
if found is None:
|
|
26
|
+
return KERNEL_APP
|
|
27
|
+
_, root = found
|
|
28
|
+
parent = str(root.parent)
|
|
29
|
+
if parent not in sys.path:
|
|
30
|
+
sys.path.insert(0, parent)
|
|
31
|
+
# 只判断文件,不 import:发现阶段不产生副作用,也不会命中 sys.modules 里的
|
|
32
|
+
# 同名旧包(测试里同一个 tmp 包名会缓存)。真正的导入交给调用方。
|
|
33
|
+
if not (root / "app.py").is_file():
|
|
34
|
+
return KERNEL_APP
|
|
35
|
+
return f"{root.name}.app:create_app"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def call_factory(factory: Callable[..., Any], settings: Any) -> Any:
|
|
39
|
+
"""兼容 `create_app(settings)` 与 `create_app()` 两种签名。"""
|
|
40
|
+
if inspect.signature(factory).parameters:
|
|
41
|
+
return factory(settings)
|
|
42
|
+
return factory()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def import_factory(reference: str) -> Callable[..., Any]:
|
|
46
|
+
module_path, _, attribute = reference.partition(":")
|
|
47
|
+
module = importlib.import_module(module_path)
|
|
48
|
+
factory = getattr(module, attribute or "create_app", None)
|
|
49
|
+
if not callable(factory):
|
|
50
|
+
raise AttributeError(f"{reference!r} 不是可调用的应用工厂")
|
|
51
|
+
return cast(Callable[..., Any], factory)
|
swiftapi/cli/audit.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""`swiftapi audit verify`:校验后台审计哈希链是否完整。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
|
|
10
|
+
from swiftapi.config.settings import Settings, SettingsError, load_settings
|
|
11
|
+
from swiftapi.core.admin.audit import verify_chain
|
|
12
|
+
from swiftapi.core.db.engine import create_database
|
|
13
|
+
|
|
14
|
+
audit_app = typer.Typer(help="审计日志", no_args_is_help=True)
|
|
15
|
+
console = Console()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@audit_app.command("verify")
|
|
19
|
+
def verify(
|
|
20
|
+
settings: str | None = typer.Option(None, "--settings", "-s", help="settings 模块路径"),
|
|
21
|
+
) -> None:
|
|
22
|
+
"""逐行重算哈希链;被篡改或被删除都能定位到具体记录。"""
|
|
23
|
+
try:
|
|
24
|
+
resolved: Settings = load_settings(settings)
|
|
25
|
+
except SettingsError as exc:
|
|
26
|
+
console.print(f"[red]{exc}[/red]")
|
|
27
|
+
raise typer.Exit(code=1) from exc
|
|
28
|
+
|
|
29
|
+
async def run() -> int:
|
|
30
|
+
database = create_database(resolved)
|
|
31
|
+
try:
|
|
32
|
+
async with database.session_factory() as session:
|
|
33
|
+
result = await verify_chain(session)
|
|
34
|
+
finally:
|
|
35
|
+
await database.aclose()
|
|
36
|
+
|
|
37
|
+
if result.ok:
|
|
38
|
+
console.print(f"[green]审计链完整[/green]({result.checked} 条)")
|
|
39
|
+
return 0
|
|
40
|
+
console.print(
|
|
41
|
+
f"[red]审计链断裂[/red]:第 {result.checked} 条({result.broken_at})—— {result.reason}"
|
|
42
|
+
)
|
|
43
|
+
return 1
|
|
44
|
+
|
|
45
|
+
raise typer.Exit(code=asyncio.run(run()))
|
swiftapi/cli/db.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""`swiftapi db`:生成迁移、执行迁移、查看历史。
|
|
2
|
+
|
|
3
|
+
迁移文件只存"目标结构快照",执行时按当前库 diff 生成 DDL——
|
|
4
|
+
同一份迁移因此能在 PG / MySQL / SQLite 上跑。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import importlib
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import typer
|
|
15
|
+
from pydantic import SecretStr
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
from sqlalchemy import text
|
|
18
|
+
|
|
19
|
+
from swiftapi.config.settings import Settings, SettingsError, load_settings
|
|
20
|
+
from swiftapi.core.db.dialects import get_adapter
|
|
21
|
+
from swiftapi.core.db.engine import Database, create_database
|
|
22
|
+
from swiftapi.core.db.migrate.render import load_chain, write_revision
|
|
23
|
+
from swiftapi.core.db.migrate.runner import MigrationRunner, describe
|
|
24
|
+
from swiftapi.core.db.migrate.schema import introspect
|
|
25
|
+
from swiftapi.db import BaseModel
|
|
26
|
+
|
|
27
|
+
db_app = typer.Typer(help="数据库迁移(model → 迁移文件 → 执行)", no_args_is_help=True)
|
|
28
|
+
console = Console()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _settings(settings_module: str | None) -> Settings:
|
|
32
|
+
try:
|
|
33
|
+
return load_settings(settings_module)
|
|
34
|
+
except SettingsError as exc:
|
|
35
|
+
console.print(f"[red]{exc}[/red]")
|
|
36
|
+
raise typer.Exit(code=1) from exc
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _database(settings: Settings) -> Database:
|
|
40
|
+
return create_database(settings)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _database_at(settings: Settings, *, url: str | None = None, connect_args: dict[str, object] | None = None) -> Database:
|
|
44
|
+
return create_database(settings, url=url, connect_args=connect_args)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _settings_with_url(settings: Settings, url: str) -> Settings:
|
|
48
|
+
database = settings.database.model_copy(update={"url": SecretStr(url)})
|
|
49
|
+
return settings.model_copy(update={"database": database})
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _announce(resolved: object) -> None:
|
|
53
|
+
"""每次 db 命令都先说清楚:读的哪个配置、连的哪个库。"""
|
|
54
|
+
from swiftapi.config.settings import active_settings_source, describe_database
|
|
55
|
+
|
|
56
|
+
source = active_settings_source()
|
|
57
|
+
module = source.get("module") or "内核默认值"
|
|
58
|
+
how = "(自动发现)" if source.get("discovered") else ""
|
|
59
|
+
console.print(
|
|
60
|
+
f"[dim]配置: {module}{how} → {describe_database(resolved)}[/dim]" # type: ignore[arg-type]
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _import_models(modules: list[str]) -> None:
|
|
65
|
+
for module in modules:
|
|
66
|
+
try:
|
|
67
|
+
importlib.import_module(module)
|
|
68
|
+
except ImportError as exc:
|
|
69
|
+
console.print(f"[red]无法导入模型模块 {module!r}: {exc}[/red]")
|
|
70
|
+
raise typer.Exit(code=1) from exc
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@db_app.command("revision")
|
|
74
|
+
def revision(
|
|
75
|
+
message: str = typer.Option(..., "-m", "--message", help="迁移说明"),
|
|
76
|
+
models: list[str] = typer.Option(
|
|
77
|
+
..., "--models", help="模型模块(可多次指定,如 myproject.models)"
|
|
78
|
+
),
|
|
79
|
+
directory: Path = typer.Option(Path("migrations"), "--dir", help="迁移文件目录"),
|
|
80
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
81
|
+
) -> None:
|
|
82
|
+
"""按当前模型生成一份迁移文件(不执行)。"""
|
|
83
|
+
resolved = _settings(settings)
|
|
84
|
+
_announce(resolved)
|
|
85
|
+
_import_models(models)
|
|
86
|
+
# 内核自带表(outbox / processed_event / admin_audit)必须一起进迁移
|
|
87
|
+
import swiftapi.core.framework_models # noqa: F401
|
|
88
|
+
|
|
89
|
+
adapter = get_adapter(resolved.database.dialect)
|
|
90
|
+
snapshot = introspect(BaseModel.metadata, adapter)
|
|
91
|
+
chain = load_chain(directory)
|
|
92
|
+
previous = chain[-1].revision if chain else None
|
|
93
|
+
path = write_revision(directory, message=message, previous=previous, target=snapshot)
|
|
94
|
+
console.print(f"[green]已生成[/green] {path}({len(snapshot.tables)} 张表)")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@db_app.command("upgrade")
|
|
98
|
+
def upgrade(
|
|
99
|
+
directory: Path = typer.Option(Path("migrations"), "--dir"),
|
|
100
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
101
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="只打印 DDL,不执行"),
|
|
102
|
+
allow_destructive: bool = typer.Option(False, "--allow-destructive"),
|
|
103
|
+
database_url: str | None = typer.Option(
|
|
104
|
+
None, "--database-url", help="租户独立库:在该库执行迁移(database 级租户)"
|
|
105
|
+
),
|
|
106
|
+
tenant_schema: str | None = typer.Option(
|
|
107
|
+
None, "--tenant-schema", help="租户 schema:在 PostgreSQL schema 内执行迁移"
|
|
108
|
+
),
|
|
109
|
+
) -> None:
|
|
110
|
+
"""执行尚未应用的迁移。
|
|
111
|
+
|
|
112
|
+
`--database-url` / `--tenant-schema` 用于物理隔离租户的库/schema 初始化;
|
|
113
|
+
与 `tenant.database_url_template` / `schema_prefix` 对应。
|
|
114
|
+
"""
|
|
115
|
+
if database_url is not None and tenant_schema is not None:
|
|
116
|
+
console.print("[red]--database-url 与 --tenant-schema 不能同时使用[/red]")
|
|
117
|
+
raise typer.Exit(code=1)
|
|
118
|
+
|
|
119
|
+
resolved = _settings(settings)
|
|
120
|
+
if tenant_schema is not None and resolved.database.dialect != "postgresql":
|
|
121
|
+
console.print("[red]--tenant-schema 只支持 PostgreSQL[/red]")
|
|
122
|
+
raise typer.Exit(code=1)
|
|
123
|
+
if tenant_schema is not None and not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", tenant_schema):
|
|
124
|
+
console.print("[red]--tenant-schema 必须是合法 SQL 标识符(字母/数字/下划线)[/red]")
|
|
125
|
+
raise typer.Exit(code=1)
|
|
126
|
+
if database_url is not None:
|
|
127
|
+
resolved = _settings_with_url(resolved, database_url)
|
|
128
|
+
|
|
129
|
+
_announce(resolved)
|
|
130
|
+
chain = load_chain(directory)
|
|
131
|
+
if not chain:
|
|
132
|
+
console.print(f"[yellow]没有迁移文件[/yellow](目录:{directory})")
|
|
133
|
+
console.print("先用 `swiftapi db revision --models <模块>` 生成")
|
|
134
|
+
return
|
|
135
|
+
|
|
136
|
+
async def _run() -> int:
|
|
137
|
+
database = _database(resolved)
|
|
138
|
+
if tenant_schema is not None:
|
|
139
|
+
adapter = get_adapter(resolved.database.dialect)
|
|
140
|
+
async with database.engine.begin() as connection:
|
|
141
|
+
await connection.execute(
|
|
142
|
+
text(f"CREATE SCHEMA IF NOT EXISTS {adapter.quote(tenant_schema)}")
|
|
143
|
+
)
|
|
144
|
+
await database.aclose()
|
|
145
|
+
database = _database_at(
|
|
146
|
+
resolved,
|
|
147
|
+
connect_args={"server_settings": {"search_path": f'"{tenant_schema}",public'}},
|
|
148
|
+
)
|
|
149
|
+
try:
|
|
150
|
+
runner = MigrationRunner(database, get_adapter(resolved.database.dialect))
|
|
151
|
+
statements = await runner.upgrade(
|
|
152
|
+
chain, allow_destructive=allow_destructive, dry_run=dry_run
|
|
153
|
+
)
|
|
154
|
+
if statements:
|
|
155
|
+
console.print(describe(statements))
|
|
156
|
+
return len(statements)
|
|
157
|
+
finally:
|
|
158
|
+
await database.aclose()
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
count = asyncio.run(_run())
|
|
162
|
+
except Exception as exc:
|
|
163
|
+
console.print(f"[red]{exc}[/red]")
|
|
164
|
+
raise typer.Exit(code=1) from exc
|
|
165
|
+
console.print(f"[green]{'预演' if dry_run else '已执行'}[/green] {count} 条语句")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@db_app.command("history")
|
|
169
|
+
def history(
|
|
170
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
171
|
+
) -> None:
|
|
172
|
+
"""查看已应用的迁移。"""
|
|
173
|
+
resolved = _settings(settings)
|
|
174
|
+
|
|
175
|
+
async def _run() -> list[tuple[str, str, str]]:
|
|
176
|
+
database = _database(resolved)
|
|
177
|
+
try:
|
|
178
|
+
runner = MigrationRunner(database, get_adapter(resolved.database.dialect))
|
|
179
|
+
await runner.ensure_history()
|
|
180
|
+
return [(item.revision, item.checksum, item.applied_at) for item in await runner.applied()]
|
|
181
|
+
finally:
|
|
182
|
+
await database.aclose()
|
|
183
|
+
|
|
184
|
+
for revision_id, checksum, applied_at in asyncio.run(_run()):
|
|
185
|
+
console.print(f"{revision_id} {checksum} {applied_at}")
|
swiftapi/cli/endpoint.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""`swiftapi new endpoint`:在已有项目里加一个接口(DX C6)。
|
|
2
|
+
|
|
3
|
+
生成物是**自包含**的:schema、router、handler 全在一个文件里,
|
|
4
|
+
所以不需要改任何既有文件——`endpoints/__init__.py` 的 `load_routers()`
|
|
5
|
+
会在启动时自动装配。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import typer
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
|
|
18
|
+
endpoint_app = typer.Typer(help="在项目里新增端点", no_args_is_help=True)
|
|
19
|
+
console = Console()
|
|
20
|
+
|
|
21
|
+
_TEMPLATE = '''"""{title}(由 swiftapi new endpoint 生成)。"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from typing import Annotated
|
|
26
|
+
from uuid import UUID
|
|
27
|
+
|
|
28
|
+
from pydantic import Field
|
|
29
|
+
|
|
30
|
+
from swiftapi.core.errors.base import FeatureNotImplemented
|
|
31
|
+
from swiftapi.core.http import Depends, Router
|
|
32
|
+
from swiftapi.core.security.principal import Principal, require_permission
|
|
33
|
+
from swiftapi.core.validation.base import StrictModel
|
|
34
|
+
from swiftapi.db import UnitOfWork
|
|
35
|
+
|
|
36
|
+
router = Router(prefix="{prefix}", tags=("{tag}",))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class {model}Request(StrictModel):
|
|
40
|
+
"""TODO: 按业务补字段。"""
|
|
41
|
+
|
|
42
|
+
example: str = Field(min_length=1, max_length=64)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class {model}Response(StrictModel):
|
|
46
|
+
ok: bool
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@router.{method}(
|
|
50
|
+
"{path}",
|
|
51
|
+
summary="{title}",
|
|
52
|
+
status_code={status},
|
|
53
|
+
response_model={model}Response,
|
|
54
|
+
)
|
|
55
|
+
async def {func}(
|
|
56
|
+
payload: {model}Request,
|
|
57
|
+
uow: Annotated[UnitOfWork, Depends("uow")],
|
|
58
|
+
principal: Annotated[Principal, Depends(require_permission("{permission}"))],
|
|
59
|
+
) -> {model}Response:
|
|
60
|
+
"""TODO: 实现 {func}(当前显式返回 501,而不是假装成功)。"""
|
|
61
|
+
raise FeatureNotImplemented("{func} 尚未实现")
|
|
62
|
+
'''
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _camel(name: str) -> str:
|
|
66
|
+
return "".join(part.capitalize() for part in re.split(r"[_\-\s]+", name) if part)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@endpoint_app.command("endpoint")
|
|
70
|
+
def create_endpoint(
|
|
71
|
+
name: str = typer.Argument(..., help="端点名(蛇形,如 assign_ticket)"),
|
|
72
|
+
project: str = typer.Option(..., "--project", help="项目包名(如 demo)"),
|
|
73
|
+
path: Path = typer.Option(Path("."), "--path", "-p", help="项目所在父目录"),
|
|
74
|
+
method: str = typer.Option("POST", "--method", help="GET/POST/PUT/PATCH/DELETE"),
|
|
75
|
+
route: str = typer.Option("", "--route", help="路由模板,默认 /<name>"),
|
|
76
|
+
prefix: str = typer.Option("", "--prefix", help="路由前缀,默认 /<name 的复数猜测>"),
|
|
77
|
+
permission: str = typer.Option("", "--permission", help="所需权限,默认 <project>:write"),
|
|
78
|
+
app: str | None = typer.Option(
|
|
79
|
+
None, "--app", help="生成到 <app-dir>/<app>/api/(Django 风格三级路由)"
|
|
80
|
+
),
|
|
81
|
+
app_dir: str = typer.Option("apps", "--app-dir", help="应用目录(配合 --app)"),
|
|
82
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="只打印,不写文件"),
|
|
83
|
+
) -> None:
|
|
84
|
+
"""生成一个自包含端点文件(默认 <project>/endpoints/,`--app` 落到应用内)。"""
|
|
85
|
+
project_dir = Path(path) / project
|
|
86
|
+
if not project_dir.is_dir():
|
|
87
|
+
console.print(f"[red]找不到项目目录: {project_dir}[/red]")
|
|
88
|
+
raise typer.Exit(code=1)
|
|
89
|
+
|
|
90
|
+
method_upper = method.upper()
|
|
91
|
+
if method_upper not in {"GET", "POST", "PUT", "PATCH", "DELETE"}:
|
|
92
|
+
console.print(f"[red]不支持的方法: {method}[/red]")
|
|
93
|
+
raise typer.Exit(code=1)
|
|
94
|
+
|
|
95
|
+
# Django 风格:app 的 api/__init__.py 会自动扫描本目录,无需改任何既有文件
|
|
96
|
+
if app is not None:
|
|
97
|
+
app_path = project_dir / app_dir / app
|
|
98
|
+
if not app_path.is_dir():
|
|
99
|
+
console.print(f"[red]找不到应用目录: {app_path}[/red]")
|
|
100
|
+
console.print(f" 先用 swift-api startapp {app} 生成应用")
|
|
101
|
+
raise typer.Exit(code=1)
|
|
102
|
+
endpoints_dir = app_path / "api"
|
|
103
|
+
else:
|
|
104
|
+
endpoints_dir = project_dir / "endpoints"
|
|
105
|
+
endpoints_dir.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
|
|
107
|
+
file_name = re.sub(r"[^a-z0-9_]", "_", name.lower()) + ".py"
|
|
108
|
+
target = endpoints_dir / file_name
|
|
109
|
+
if target.exists():
|
|
110
|
+
console.print(f"[red]已存在: {target}(换个名字或先删除)[/red]")
|
|
111
|
+
raise typer.Exit(code=1)
|
|
112
|
+
|
|
113
|
+
full_route = route or f"/{name.replace('_', '-')}"
|
|
114
|
+
if not full_route.startswith("/"):
|
|
115
|
+
full_route = "/" + full_route
|
|
116
|
+
|
|
117
|
+
# `--route` 是完整路径;`--prefix` 只是 Router 前缀。
|
|
118
|
+
# 两者都写全时自动去重,避免生成 /orders/orders/{id}/refund。
|
|
119
|
+
if app is not None:
|
|
120
|
+
# app 内路由相对于 /api/v1/<app>,默认不再猜前缀
|
|
121
|
+
normalized_prefix = f"/{prefix.strip('/')}" if prefix.strip("/") else ""
|
|
122
|
+
tag = app
|
|
123
|
+
elif prefix:
|
|
124
|
+
normalized_prefix = "/" + prefix.strip("/")
|
|
125
|
+
tag = name.split("_")[0]
|
|
126
|
+
else:
|
|
127
|
+
parts = full_route.split("/", 2)
|
|
128
|
+
normalized_prefix = f"/{parts[1]}" if len(parts) > 1 and parts[1] else ""
|
|
129
|
+
tag = name.split("_")[0]
|
|
130
|
+
|
|
131
|
+
handler_path = full_route
|
|
132
|
+
if normalized_prefix and handler_path.startswith(normalized_prefix):
|
|
133
|
+
handler_path = handler_path[len(normalized_prefix) :]
|
|
134
|
+
route_path = handler_path or "/"
|
|
135
|
+
prefix = normalized_prefix
|
|
136
|
+
model = _camel(name)
|
|
137
|
+
content = _TEMPLATE.format(
|
|
138
|
+
title=name.replace("_", " "),
|
|
139
|
+
prefix=prefix,
|
|
140
|
+
tag=tag,
|
|
141
|
+
path=route_path,
|
|
142
|
+
method=method_upper.lower(),
|
|
143
|
+
status=201 if method_upper == "POST" else 200,
|
|
144
|
+
model=model,
|
|
145
|
+
func=name,
|
|
146
|
+
permission=permission or f"{project}:write",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if dry_run:
|
|
150
|
+
console.print(content)
|
|
151
|
+
return
|
|
152
|
+
|
|
153
|
+
target.write_text(content, encoding="utf-8")
|
|
154
|
+
check = subprocess.run(
|
|
155
|
+
[sys.executable, "-m", "compileall", "-q", str(target)],
|
|
156
|
+
capture_output=True,
|
|
157
|
+
text=True,
|
|
158
|
+
)
|
|
159
|
+
if check.returncode != 0:
|
|
160
|
+
target.unlink(missing_ok=True)
|
|
161
|
+
console.print(f"[red]生成物编译失败:{check.stderr}[/red]")
|
|
162
|
+
raise typer.Exit(code=1)
|
|
163
|
+
|
|
164
|
+
mount = f"/api/v1/{app}" if app is not None else ""
|
|
165
|
+
console.print(f"[green]已生成[/green] {target}")
|
|
166
|
+
console.print(
|
|
167
|
+
f"启动后即生效(自动装配):{mount}{prefix}{route_path};"
|
|
168
|
+
f"当前返回 501,请实现 {name}()。"
|
|
169
|
+
)
|
swiftapi/cli/logs.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""`swiftapi logs`:查看与手动触发日志归档。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
|
|
8
|
+
from swiftapi.config.settings import Settings, SettingsError, load_settings
|
|
9
|
+
from swiftapi.core.observability.archive import LogArchiver
|
|
10
|
+
from swiftapi.core.observability.volume import estimate_volume
|
|
11
|
+
|
|
12
|
+
logs_app = typer.Typer(help="日志:归档 / 状态", no_args_is_help=True)
|
|
13
|
+
console = Console()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _settings(module: str | None) -> Settings:
|
|
17
|
+
try:
|
|
18
|
+
return load_settings(module)
|
|
19
|
+
except SettingsError as exc:
|
|
20
|
+
console.print(f"[red]{exc}[/red]")
|
|
21
|
+
raise typer.Exit(code=1) from exc
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@logs_app.command("archive")
|
|
25
|
+
def archive(
|
|
26
|
+
settings: str | None = typer.Option(None, "--settings", "-s", help="settings 模块路径"),
|
|
27
|
+
force: bool = typer.Option(False, "--force", help="忽略周期,立即归档"),
|
|
28
|
+
) -> None:
|
|
29
|
+
"""把 logs/ 下的日志压成 zip 存到 log_archive_dir,然后删除原文件。"""
|
|
30
|
+
resolved = _settings(settings)
|
|
31
|
+
archiver = LogArchiver(resolved)
|
|
32
|
+
|
|
33
|
+
if not force and not archiver.is_due():
|
|
34
|
+
last = archiver.last_archived_at()
|
|
35
|
+
console.print(
|
|
36
|
+
f"[yellow]未到归档周期[/yellow](每 {resolved.observability.log_archive_interval_days} 天,"
|
|
37
|
+
f"上次:{last.isoformat() if last else '从未'});加 --force 立即归档"
|
|
38
|
+
)
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
result = archiver.archive()
|
|
42
|
+
if result.empty:
|
|
43
|
+
console.print("没有可归档的日志")
|
|
44
|
+
return
|
|
45
|
+
console.print(
|
|
46
|
+
f"[green]已归档[/green] {result.path}({len(result.files)} 个文件,{result.bytes_written} 字节)"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@logs_app.command("status")
|
|
51
|
+
def status(
|
|
52
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
53
|
+
) -> None:
|
|
54
|
+
"""查看日志目录、归档目录与下次归档判定。"""
|
|
55
|
+
resolved = _settings(settings)
|
|
56
|
+
archiver = LogArchiver(resolved)
|
|
57
|
+
files = archiver.collect()
|
|
58
|
+
console.print(f"log_dir : {archiver.log_dir}")
|
|
59
|
+
console.print(f"archive_dir : {archiver.archive_dir}")
|
|
60
|
+
console.print(f"待归档文件 : {len(files)}")
|
|
61
|
+
console.print(f"上次归档 : {archiver.last_archived_at() or '从未'}")
|
|
62
|
+
console.print(f"周期 : {resolved.observability.log_archive_interval_days} 天")
|
|
63
|
+
console.print(f"现在是否到期 : {archiver.is_due()}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@logs_app.command("estimate")
|
|
67
|
+
def estimate(
|
|
68
|
+
qps: float = typer.Option(1000, "--qps", help="峰值 QPS"),
|
|
69
|
+
ratio: float | None = typer.Option(None, "--ratio", help="采样比例,默认取配置"),
|
|
70
|
+
avg_bytes: int = typer.Option(400, "--avg-bytes", help="单条日志估算字节"),
|
|
71
|
+
replicas: int | None = typer.Option(None, "--replicas", help="副本数,默认取配置"),
|
|
72
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
73
|
+
) -> None:
|
|
74
|
+
"""估算请求体日志的写入量,以及是否会撞到每分钟预算。"""
|
|
75
|
+
resolved = _settings(settings)
|
|
76
|
+
obs = resolved.observability
|
|
77
|
+
used_ratio = obs.log_request_body_sample_ratio if ratio is None else ratio
|
|
78
|
+
volume = estimate_volume(
|
|
79
|
+
qps=qps,
|
|
80
|
+
ratio=used_ratio,
|
|
81
|
+
avg_bytes=avg_bytes,
|
|
82
|
+
max_per_minute=obs.log_request_body_max_per_minute,
|
|
83
|
+
replicas=obs.log_request_body_replicas if replicas is None else replicas,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
console.print(f"峰值 QPS : {volume.qps}")
|
|
87
|
+
console.print(f"采样比例 : {volume.ratio:.2%}")
|
|
88
|
+
console.print(f"理论条/秒 : {volume.sampled_per_second}")
|
|
89
|
+
console.print(f"副本数 : {volume.replicas}")
|
|
90
|
+
console.print(f"预算条/秒 : {volume.budget_per_second or '不限'}(集群)")
|
|
91
|
+
console.print(f"每副本条/秒 : {volume.per_replica_budget or '不限'}")
|
|
92
|
+
console.print(f"实际条/秒 : {volume.effective_per_second}")
|
|
93
|
+
console.print(f"实际条/天 : {volume.effective_per_day:,}")
|
|
94
|
+
console.print(f"估算体积/天 : {volume.bytes_per_day / 1024 / 1024:.1f} MB")
|
|
95
|
+
|
|
96
|
+
if volume.budget_limited:
|
|
97
|
+
console.print(
|
|
98
|
+
"[yellow]注意:理论采样量超过每分钟预算,实际会按预算截断;"
|
|
99
|
+
"要么调大 log_request_body_max_per_minute,要么降低采样比例。[/yellow]"
|
|
100
|
+
)
|