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,141 @@
|
|
|
1
|
+
"""Redis Streams 消息总线:消费组 + ACK + 超时重领(架构文档 §17.6)。
|
|
2
|
+
|
|
3
|
+
语义:**至少一次投递**。消费端必须用 `mark_processed` 去重;
|
|
4
|
+
未 ACK 的消息留在 pending 列表,由 `claim_stale()` 重新投递。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from collections.abc import Awaitable, Callable
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import Any
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
from swiftapi.core.messaging.base import EventEnvelope
|
|
16
|
+
|
|
17
|
+
Handler = Callable[[EventEnvelope], Awaitable[None]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _encode(envelope: EventEnvelope) -> dict[str, str]:
|
|
21
|
+
return {
|
|
22
|
+
"event_id": str(envelope.event_id),
|
|
23
|
+
"event_type": envelope.event_type,
|
|
24
|
+
"event_version": str(envelope.event_version),
|
|
25
|
+
"occurred_at": envelope.occurred_at.isoformat(),
|
|
26
|
+
"trace_id": envelope.trace_id or "",
|
|
27
|
+
"tenant_id": str(envelope.tenant_id) if envelope.tenant_id else "",
|
|
28
|
+
"payload": json.dumps(envelope.payload, ensure_ascii=False),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _decode(fields: dict[str, str]) -> EventEnvelope:
|
|
33
|
+
return EventEnvelope(
|
|
34
|
+
event_id=UUID(fields["event_id"]),
|
|
35
|
+
event_type=fields["event_type"],
|
|
36
|
+
event_version=int(fields["event_version"]),
|
|
37
|
+
occurred_at=datetime.fromisoformat(fields["occurred_at"]),
|
|
38
|
+
trace_id=fields["trace_id"] or None,
|
|
39
|
+
tenant_id=UUID(fields["tenant_id"]) if fields["tenant_id"] else None,
|
|
40
|
+
payload=json.loads(fields["payload"] or "{}"),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class RedisStreamsBus:
|
|
45
|
+
"""生产端 + 消费端共用一条连接(各自可独立实例化)。"""
|
|
46
|
+
|
|
47
|
+
name = "redis_streams"
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
url: str,
|
|
52
|
+
*,
|
|
53
|
+
stream: str = "swiftapi:events",
|
|
54
|
+
group: str = "swiftapi",
|
|
55
|
+
consumer: str = "worker-1",
|
|
56
|
+
max_len: int = 100_000,
|
|
57
|
+
) -> None:
|
|
58
|
+
try:
|
|
59
|
+
from redis.asyncio import Redis
|
|
60
|
+
except ImportError as exc: # pragma: no cover - 可选依赖
|
|
61
|
+
raise RuntimeError(
|
|
62
|
+
"messaging.backend=redis_streams 需要安装 redis:uv pip install 'swiftapi[cache]'"
|
|
63
|
+
) from exc
|
|
64
|
+
self._client: Any = Redis.from_url(url, decode_responses=True)
|
|
65
|
+
self.stream = stream
|
|
66
|
+
self.group = group
|
|
67
|
+
self.consumer = consumer
|
|
68
|
+
self.max_len = max_len
|
|
69
|
+
self._handlers: dict[str, list[Handler]] = {}
|
|
70
|
+
|
|
71
|
+
# ---------------- 生产 ----------------
|
|
72
|
+
|
|
73
|
+
async def publish(self, envelope: EventEnvelope) -> None:
|
|
74
|
+
await self._client.xadd(
|
|
75
|
+
self.stream,
|
|
76
|
+
_encode(envelope),
|
|
77
|
+
maxlen=self.max_len,
|
|
78
|
+
approximate=True,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# ---------------- 消费 ----------------
|
|
82
|
+
|
|
83
|
+
def subscribe(self, event_type: str, handler: Handler) -> None:
|
|
84
|
+
self._handlers.setdefault(event_type, []).append(handler)
|
|
85
|
+
|
|
86
|
+
async def ensure_group(self) -> None:
|
|
87
|
+
try:
|
|
88
|
+
await self._client.xgroup_create(self.stream, self.group, id="0", mkstream=True)
|
|
89
|
+
except Exception as exc: # BUSYGROUP:组已存在
|
|
90
|
+
if "BUSYGROUP" not in str(exc):
|
|
91
|
+
raise
|
|
92
|
+
|
|
93
|
+
async def run_once(self, *, count: int = 10) -> int:
|
|
94
|
+
"""读一批 → 分发 → ACK。处理失败则留在 pending(下次 claim)。"""
|
|
95
|
+
await self.ensure_group()
|
|
96
|
+
response = await self._client.xreadgroup(
|
|
97
|
+
self.group, self.consumer, {self.stream: ">"}, count=count
|
|
98
|
+
)
|
|
99
|
+
processed = 0
|
|
100
|
+
for _stream, messages in response or []:
|
|
101
|
+
for message_id, fields in messages:
|
|
102
|
+
envelope = _decode(fields)
|
|
103
|
+
for handler in self._handlers.get(envelope.event_type, ()):
|
|
104
|
+
await handler(envelope)
|
|
105
|
+
await self._client.xack(self.stream, self.group, message_id)
|
|
106
|
+
processed += 1
|
|
107
|
+
return processed
|
|
108
|
+
|
|
109
|
+
async def claim_stale(self, *, min_idle_ms: int = 30_000, count: int = 10) -> int:
|
|
110
|
+
"""把超时未 ACK 的消息重新分给当前消费者(失败重投)。"""
|
|
111
|
+
pending = await self._client.xpending_range(
|
|
112
|
+
self.stream, self.group, min="-", max="+", count=count
|
|
113
|
+
)
|
|
114
|
+
stale = [
|
|
115
|
+
item["message_id"]
|
|
116
|
+
for item in pending
|
|
117
|
+
if min_idle_ms <= 0 or item.get("time_since_delivered", 0) >= min_idle_ms
|
|
118
|
+
]
|
|
119
|
+
if not stale:
|
|
120
|
+
return 0
|
|
121
|
+
claimed = await self._client.xclaim(
|
|
122
|
+
self.stream, self.group, self.consumer, min_idle_time=min_idle_ms, message_ids=stale
|
|
123
|
+
)
|
|
124
|
+
processed = 0
|
|
125
|
+
for message_id, fields in claimed:
|
|
126
|
+
envelope = _decode(fields)
|
|
127
|
+
for handler in self._handlers.get(envelope.event_type, ()):
|
|
128
|
+
await handler(envelope)
|
|
129
|
+
await self._client.xack(self.stream, self.group, message_id)
|
|
130
|
+
processed += 1
|
|
131
|
+
return processed
|
|
132
|
+
|
|
133
|
+
async def close(self) -> None:
|
|
134
|
+
await self._client.aclose()
|
|
135
|
+
|
|
136
|
+
async def reset(self) -> None:
|
|
137
|
+
"""测试辅助:清空流与消费组(生产不要调用)。"""
|
|
138
|
+
await self._client.delete(self.stream)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
__all__ = ["RedisStreamsBus"]
|
|
File without changes
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""日志归档:按周期把 logs/ 下的日志压成 zip,存到指定目录。
|
|
2
|
+
|
|
3
|
+
关键约束:**不能 unlink 正在写的日志文件**。
|
|
4
|
+
`RotatingFileHandler` 持有打开的 inode,删掉路径后 handler 会继续写一个
|
|
5
|
+
"已删除"的文件——`tail -f logs/app.log` 永远看不到新日志(真实踩过:
|
|
6
|
+
服务启动即归档,之后所有日志凭空消失)。
|
|
7
|
+
因此对顶层 `*.log` 采用**原地截断**(保留 inode),只删除轮转出来的
|
|
8
|
+
`*.log.N` 备份;空文件不参与归档。
|
|
9
|
+
|
|
10
|
+
约定:
|
|
11
|
+
- 压缩包名 `YYYYmmddHHMMSS.zip`(本地时区,便于人工检索);
|
|
12
|
+
- 只处理 `log_dir` **顶层**的 `*.log*`(不会把 archive 目录自身打进去);
|
|
13
|
+
- 周期由 `log_archive_interval_days` 控制,最后归档时间记在 `log_dir/.last_archive`;
|
|
14
|
+
- 归档失败只记日志,不抛给调用方。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import zipfile
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from datetime import UTC, datetime, timedelta
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from swiftapi.config.settings import Settings
|
|
25
|
+
from swiftapi.core.observability.logging import get_logger
|
|
26
|
+
|
|
27
|
+
_STATE_FILE = ".last_archive"
|
|
28
|
+
logger = get_logger("swiftapi.logs")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class ArchiveResult:
|
|
33
|
+
path: Path
|
|
34
|
+
files: tuple[str, ...]
|
|
35
|
+
bytes_written: int
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def empty(self) -> bool:
|
|
39
|
+
return not self.files
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class LogArchiver:
|
|
43
|
+
def __init__(self, settings: Settings, *, now: datetime | None = None) -> None:
|
|
44
|
+
obs = settings.observability
|
|
45
|
+
self.log_dir = Path(obs.log_dir)
|
|
46
|
+
self.archive_dir = Path(obs.log_archive_dir)
|
|
47
|
+
self.interval = timedelta(days=obs.log_archive_interval_days)
|
|
48
|
+
self._now = now
|
|
49
|
+
|
|
50
|
+
# ---------------- 判定 ----------------
|
|
51
|
+
|
|
52
|
+
def now(self) -> datetime:
|
|
53
|
+
return self._now or datetime.now().astimezone()
|
|
54
|
+
|
|
55
|
+
def _state_file(self) -> Path:
|
|
56
|
+
return self.log_dir / _STATE_FILE
|
|
57
|
+
|
|
58
|
+
def last_archived_at(self) -> datetime | None:
|
|
59
|
+
state = self._state_file()
|
|
60
|
+
if not state.is_file():
|
|
61
|
+
return None
|
|
62
|
+
try:
|
|
63
|
+
return datetime.fromisoformat(state.read_text(encoding="utf-8").strip())
|
|
64
|
+
except ValueError:
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
def collect(self) -> list[Path]:
|
|
68
|
+
if not self.log_dir.is_dir():
|
|
69
|
+
return []
|
|
70
|
+
return sorted(
|
|
71
|
+
path
|
|
72
|
+
for path in self.log_dir.iterdir()
|
|
73
|
+
if path.is_file()
|
|
74
|
+
and (path.name.endswith(".log") or ".log." in path.name)
|
|
75
|
+
and path.stat().st_size > 0
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def is_due(self) -> bool:
|
|
79
|
+
files = self.collect()
|
|
80
|
+
if not files:
|
|
81
|
+
return False
|
|
82
|
+
last = self.last_archived_at()
|
|
83
|
+
if last is None:
|
|
84
|
+
return True
|
|
85
|
+
return self.now() - last >= self.interval
|
|
86
|
+
|
|
87
|
+
# ---------------- 执行 ----------------
|
|
88
|
+
|
|
89
|
+
def archive(self) -> ArchiveResult:
|
|
90
|
+
files = self.collect()
|
|
91
|
+
if not files:
|
|
92
|
+
return ArchiveResult(path=self.archive_dir, files=(), bytes_written=0)
|
|
93
|
+
|
|
94
|
+
self.archive_dir.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
stamp = self.now().strftime("%Y%m%d%H%M%S")
|
|
96
|
+
target = self.archive_dir / f"{stamp}.zip"
|
|
97
|
+
suffix = 1
|
|
98
|
+
while target.exists(): # 同秒并发/重跑
|
|
99
|
+
target = self.archive_dir / f"{stamp}-{suffix}.zip"
|
|
100
|
+
suffix += 1
|
|
101
|
+
|
|
102
|
+
with zipfile.ZipFile(target, "w", compression=zipfile.ZIP_DEFLATED) as bundle:
|
|
103
|
+
for path in files:
|
|
104
|
+
bundle.write(path, arcname=path.name)
|
|
105
|
+
|
|
106
|
+
for path in files:
|
|
107
|
+
if ".log." in path.name:
|
|
108
|
+
path.unlink(missing_ok=True) # 轮转备份:没有 handler 持有
|
|
109
|
+
else:
|
|
110
|
+
path.write_bytes(b"") # 活动日志:原地截断,保住 inode
|
|
111
|
+
|
|
112
|
+
self._state_file().write_text(self.now().isoformat(), encoding="utf-8")
|
|
113
|
+
written = target.stat().st_size
|
|
114
|
+
logger.info(
|
|
115
|
+
"log.archived",
|
|
116
|
+
archive=str(target),
|
|
117
|
+
files=len(files),
|
|
118
|
+
bytes=written,
|
|
119
|
+
)
|
|
120
|
+
return ArchiveResult(path=target, files=tuple(p.name for p in files), bytes_written=written)
|
|
121
|
+
|
|
122
|
+
def archive_if_due(self) -> ArchiveResult | None:
|
|
123
|
+
try:
|
|
124
|
+
if not self.is_due():
|
|
125
|
+
return None
|
|
126
|
+
return self.archive()
|
|
127
|
+
except OSError as exc: # 归档失败不能影响服务
|
|
128
|
+
logger.warning("log.archive_failed", error=str(exc))
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def utc_now() -> datetime:
|
|
133
|
+
return datetime.now(UTC)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
__all__ = ["ArchiveResult", "LogArchiver", "utc_now"]
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""请求级上下文:request_id / trace_id / 租户 / 用户。
|
|
2
|
+
|
|
3
|
+
用不可变 dataclass + 单个 ContextVar,避免多个 ContextVar 之间不一致。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
import uuid
|
|
10
|
+
from contextvars import ContextVar, Token
|
|
11
|
+
from dataclasses import dataclass, replace
|
|
12
|
+
|
|
13
|
+
_TRACEPARENT_RE = re.compile(r"^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class RequestContext:
|
|
18
|
+
request_id: str
|
|
19
|
+
trace_id: str
|
|
20
|
+
span_id: str
|
|
21
|
+
tenant_id: str | None = None
|
|
22
|
+
user_id: str | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
_ctx: ContextVar[RequestContext | None] = ContextVar("swiftapi_request_context", default=None)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def new_request_id() -> str:
|
|
29
|
+
return uuid.uuid4().hex
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def new_trace_id() -> str:
|
|
33
|
+
return uuid.uuid4().hex
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def new_span_id() -> str:
|
|
37
|
+
return uuid.uuid4().hex[:16]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_traceparent(value: str | None) -> tuple[str, str] | None:
|
|
41
|
+
"""解析 W3C traceparent,非法则返回 None(不抛错,避免坏 header 打挂请求)。"""
|
|
42
|
+
if not value:
|
|
43
|
+
return None
|
|
44
|
+
match = _TRACEPARENT_RE.match(value.strip().lower())
|
|
45
|
+
if not match:
|
|
46
|
+
return None
|
|
47
|
+
trace_id, parent_span = match.group(1), match.group(2)
|
|
48
|
+
if trace_id == "0" * 32 or parent_span == "0" * 16:
|
|
49
|
+
return None
|
|
50
|
+
return trace_id, parent_span
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def bind(
|
|
54
|
+
*,
|
|
55
|
+
request_id: str | None = None,
|
|
56
|
+
traceparent: str | None = None,
|
|
57
|
+
) -> Token[RequestContext | None]:
|
|
58
|
+
"""绑定请求上下文;已有 trace 时沿用上游 trace_id(链路串联)。"""
|
|
59
|
+
parsed = parse_traceparent(traceparent)
|
|
60
|
+
ctx = RequestContext(
|
|
61
|
+
request_id=request_id or new_request_id(),
|
|
62
|
+
trace_id=parsed[0] if parsed else new_trace_id(),
|
|
63
|
+
span_id=new_span_id(),
|
|
64
|
+
)
|
|
65
|
+
return _ctx.set(ctx)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def unbind(token: Token[RequestContext | None]) -> None:
|
|
69
|
+
_ctx.reset(token)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def current() -> RequestContext | None:
|
|
73
|
+
return _ctx.get()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def trace_id() -> str | None:
|
|
77
|
+
ctx = _ctx.get()
|
|
78
|
+
return ctx.trace_id if ctx else None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def request_id() -> str | None:
|
|
82
|
+
ctx = _ctx.get()
|
|
83
|
+
return ctx.request_id if ctx else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def tenant_id() -> str | None:
|
|
87
|
+
ctx = _ctx.get()
|
|
88
|
+
return ctx.tenant_id if ctx else None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def with_tenant(value: str | None) -> Token[RequestContext | None] | None:
|
|
92
|
+
ctx = _ctx.get()
|
|
93
|
+
if ctx is None:
|
|
94
|
+
return None
|
|
95
|
+
return _ctx.set(replace(ctx, tenant_id=value))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def with_user(value: str | None) -> Token[RequestContext | None] | None:
|
|
99
|
+
ctx = _ctx.get()
|
|
100
|
+
if ctx is None:
|
|
101
|
+
return None
|
|
102
|
+
return _ctx.set(replace(ctx, user_id=value))
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""结构化日志:控制台 + 落盘(app / access / crud / error 四路分文件)。
|
|
2
|
+
|
|
3
|
+
设计:
|
|
4
|
+
- structlog 只做"结构化 + 上下文字段",输出交给标准库 logging;
|
|
5
|
+
- 标准库 Handler 负责分流:靠 logger 名(`swiftapi.access` / `swiftapi.crud`)和级别;
|
|
6
|
+
- 落盘用 RotatingFileHandler,按大小滚动(`log_max_bytes` / `log_backup_count`)。
|
|
7
|
+
|
|
8
|
+
为什么分四个文件:排障时"看请求"和"看数据写入"是两种动作,
|
|
9
|
+
混在一个文件里会被 INFO 淹没。error.log 单独存在是为了 `tail -f` 时不被噪声打断。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import logging
|
|
16
|
+
import logging.handlers
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import orjson
|
|
22
|
+
import structlog
|
|
23
|
+
|
|
24
|
+
from swiftapi.config.settings import LogFormat, Settings
|
|
25
|
+
|
|
26
|
+
ACCESS_LOGGER = "swiftapi.access"
|
|
27
|
+
CRUD_LOGGER = "swiftapi.crud"
|
|
28
|
+
SQL_LOGGER = "swiftapi.sql"
|
|
29
|
+
|
|
30
|
+
_APP_FILE = "app.log"
|
|
31
|
+
_ACCESS_FILE = "access.log"
|
|
32
|
+
_CRUD_FILE = "crud.log"
|
|
33
|
+
_ERROR_FILE = "error.log"
|
|
34
|
+
_SQL_FILE = "sql.log"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _MinLevel(logging.Filter):
|
|
38
|
+
def __init__(self, level: int) -> None:
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.level = level
|
|
41
|
+
|
|
42
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
43
|
+
return record.levelno >= self.level
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _NamePrefix(logging.Filter):
|
|
47
|
+
"""只放行指定 logger(含子 logger),可选择排除。"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, prefix: str, *, exclude: bool = False) -> None:
|
|
50
|
+
super().__init__()
|
|
51
|
+
self.prefix = prefix
|
|
52
|
+
self.exclude = exclude
|
|
53
|
+
|
|
54
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
55
|
+
matched = record.name == self.prefix or record.name.startswith(f"{self.prefix}.")
|
|
56
|
+
return not matched if self.exclude else matched
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _orjson_dumps(value: Any, **_kwargs: Any) -> str:
|
|
60
|
+
return orjson.dumps(value, option=orjson.OPT_NON_STR_KEYS).decode()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _inject_request_context(
|
|
64
|
+
_logger: Any, _method: str, event_dict: dict[str, Any]
|
|
65
|
+
) -> dict[str, Any]:
|
|
66
|
+
from swiftapi.core.observability.context import current
|
|
67
|
+
|
|
68
|
+
ctx = current()
|
|
69
|
+
if ctx is not None:
|
|
70
|
+
event_dict.setdefault("trace_id", ctx.trace_id)
|
|
71
|
+
event_dict.setdefault("request_id", ctx.request_id)
|
|
72
|
+
event_dict.setdefault("span_id", ctx.span_id)
|
|
73
|
+
if ctx.tenant_id:
|
|
74
|
+
event_dict.setdefault("tenant_id", ctx.tenant_id)
|
|
75
|
+
if ctx.user_id:
|
|
76
|
+
event_dict.setdefault("user_id", ctx.user_id)
|
|
77
|
+
return event_dict
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _shared_processors() -> list[Any]:
|
|
81
|
+
return [
|
|
82
|
+
structlog.contextvars.merge_contextvars,
|
|
83
|
+
_inject_request_context,
|
|
84
|
+
structlog.processors.add_log_level,
|
|
85
|
+
structlog.processors.TimeStamper(fmt="iso", utc=True),
|
|
86
|
+
structlog.processors.StackInfoRenderer(),
|
|
87
|
+
structlog.processors.format_exc_info,
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _formatter(settings: Settings, *, force_json: bool = False) -> structlog.stdlib.ProcessorFormatter:
|
|
92
|
+
shared = _shared_processors()
|
|
93
|
+
use_json = force_json or settings.observability.log_format is LogFormat.JSON
|
|
94
|
+
if use_json:
|
|
95
|
+
renderer: Any = structlog.processors.JSONRenderer(serializer=_orjson_dumps)
|
|
96
|
+
else:
|
|
97
|
+
renderer = structlog.dev.ConsoleRenderer(colors=sys.stdout.isatty())
|
|
98
|
+
return structlog.stdlib.ProcessorFormatter(processor=renderer, foreign_pre_chain=shared)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _rotating_handler(path: Path, settings: Settings, filters: list[logging.Filter]) -> logging.Handler:
|
|
102
|
+
handler = logging.handlers.RotatingFileHandler(
|
|
103
|
+
path,
|
|
104
|
+
maxBytes=settings.observability.log_max_bytes,
|
|
105
|
+
backupCount=settings.observability.log_backup_count,
|
|
106
|
+
encoding="utf-8",
|
|
107
|
+
)
|
|
108
|
+
for item in filters:
|
|
109
|
+
handler.addFilter(item)
|
|
110
|
+
return handler
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def configure_logging(settings: Settings) -> None:
|
|
114
|
+
obs = settings.observability
|
|
115
|
+
level = getattr(logging, obs.log_level)
|
|
116
|
+
console_formatter = _formatter(settings)
|
|
117
|
+
file_formatter = _formatter(settings, force_json=True)
|
|
118
|
+
|
|
119
|
+
structlog.configure(
|
|
120
|
+
processors=[*_shared_processors(), structlog.stdlib.ProcessorFormatter.wrap_for_formatter],
|
|
121
|
+
logger_factory=structlog.stdlib.LoggerFactory(),
|
|
122
|
+
wrapper_class=structlog.make_filtering_bound_logger(level),
|
|
123
|
+
# 不缓存 bound logger:重新 configure 后不会残留旧的过滤级别
|
|
124
|
+
cache_logger_on_first_use=False,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
root = logging.getLogger()
|
|
128
|
+
for handler in list(root.handlers):
|
|
129
|
+
root.removeHandler(handler)
|
|
130
|
+
# 显式关闭:反复 configure(测试、热重载、多 app)不能靠 GC 收 FD
|
|
131
|
+
with contextlib.suppress(Exception):
|
|
132
|
+
handler.close()
|
|
133
|
+
root.setLevel(level)
|
|
134
|
+
|
|
135
|
+
if obs.log_console:
|
|
136
|
+
console = logging.StreamHandler(sys.stdout)
|
|
137
|
+
console.setFormatter(console_formatter)
|
|
138
|
+
root.addHandler(console)
|
|
139
|
+
|
|
140
|
+
if obs.log_to_file:
|
|
141
|
+
directory = Path(obs.log_dir)
|
|
142
|
+
try:
|
|
143
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
except OSError as exc: # 目录不可写 → 只保留控制台,不因日志挂掉服务
|
|
145
|
+
logging.getLogger(__name__).warning(
|
|
146
|
+
"log.dir_unavailable", extra={"dir": str(directory), "error": str(exc)}
|
|
147
|
+
)
|
|
148
|
+
return
|
|
149
|
+
|
|
150
|
+
# app.log:常规日志(排除 access/crud/uvicorn,它们各有去处)
|
|
151
|
+
app_handler = _rotating_handler(
|
|
152
|
+
directory / _APP_FILE,
|
|
153
|
+
settings,
|
|
154
|
+
[
|
|
155
|
+
_MinLevel(logging.INFO),
|
|
156
|
+
_NamePrefix(ACCESS_LOGGER, exclude=True),
|
|
157
|
+
_NamePrefix(CRUD_LOGGER, exclude=True),
|
|
158
|
+
_NamePrefix(SQL_LOGGER, exclude=True),
|
|
159
|
+
_NamePrefix("uvicorn", exclude=True),
|
|
160
|
+
],
|
|
161
|
+
)
|
|
162
|
+
app_handler.setFormatter(file_formatter)
|
|
163
|
+
|
|
164
|
+
error_handler = _rotating_handler(directory / _ERROR_FILE, settings, [_MinLevel(logging.ERROR)])
|
|
165
|
+
error_handler.setFormatter(file_formatter)
|
|
166
|
+
|
|
167
|
+
access_handler = _rotating_handler(directory / _ACCESS_FILE, settings, [_NamePrefix(ACCESS_LOGGER)])
|
|
168
|
+
access_handler.setFormatter(file_formatter)
|
|
169
|
+
|
|
170
|
+
crud_handler = _rotating_handler(directory / _CRUD_FILE, settings, [_NamePrefix(CRUD_LOGGER)])
|
|
171
|
+
crud_handler.setFormatter(file_formatter)
|
|
172
|
+
|
|
173
|
+
sql_handler = _rotating_handler(directory / _SQL_FILE, settings, [_NamePrefix(SQL_LOGGER)])
|
|
174
|
+
sql_handler.setFormatter(file_formatter)
|
|
175
|
+
|
|
176
|
+
for handler in (app_handler, error_handler, access_handler, crud_handler, sql_handler):
|
|
177
|
+
root.addHandler(handler)
|
|
178
|
+
|
|
179
|
+
logging.getLogger("uvicorn.access").disabled = True
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def get_logger(name: str) -> Any:
|
|
183
|
+
return structlog.get_logger(name)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
__all__ = [
|
|
187
|
+
"ACCESS_LOGGER",
|
|
188
|
+
"CRUD_LOGGER",
|
|
189
|
+
"SQL_LOGGER",
|
|
190
|
+
"configure_logging",
|
|
191
|
+
"get_logger",
|
|
192
|
+
]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""日志脱敏:字段名优先,正则兜底。
|
|
2
|
+
|
|
3
|
+
原则:**宁可多脱敏,不可漏**。日志一旦落盘,就等于数据外泄。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
SENSITIVE_KEYS = frozenset(
|
|
12
|
+
{
|
|
13
|
+
"password",
|
|
14
|
+
"passwd",
|
|
15
|
+
"pwd",
|
|
16
|
+
"secret",
|
|
17
|
+
"token",
|
|
18
|
+
"access_token",
|
|
19
|
+
"refresh_token",
|
|
20
|
+
"authorization",
|
|
21
|
+
"api_key",
|
|
22
|
+
"apikey",
|
|
23
|
+
"private_key",
|
|
24
|
+
"id_card",
|
|
25
|
+
"idcard",
|
|
26
|
+
"bank_card",
|
|
27
|
+
"card_no",
|
|
28
|
+
"cvv",
|
|
29
|
+
"phone",
|
|
30
|
+
"mobile",
|
|
31
|
+
"email",
|
|
32
|
+
}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
|
|
36
|
+
(re.compile(r"\b1[3-9]\d{9}\b"), "1**********"), # 中国大陆手机号
|
|
37
|
+
(re.compile(r"\b\d{17}[\dXx]\b"), "******************"), # 18 位身份证
|
|
38
|
+
(re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"), "***@***"), # 邮箱
|
|
39
|
+
(re.compile(r"\bBearer\s+[A-Za-z0-9._\-]+", re.I), "Bearer ***"), # token
|
|
40
|
+
(re.compile(r"\b\d{16,19}\b"), "****"), # 银行卡号
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
MASK = "***"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def mask_text(value: str) -> str:
|
|
47
|
+
for pattern, replacement in _PATTERNS:
|
|
48
|
+
value = pattern.sub(replacement, value)
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def mask_value(
|
|
53
|
+
value: Any,
|
|
54
|
+
*,
|
|
55
|
+
depth: int = 0,
|
|
56
|
+
extra_keys: frozenset[str] = frozenset(),
|
|
57
|
+
) -> Any:
|
|
58
|
+
"""递归脱敏:dict 看 key(内置 + 业务自定义),list 逐项,str 走正则。"""
|
|
59
|
+
if depth > 8: # 防御深层嵌套
|
|
60
|
+
return "***"
|
|
61
|
+
if isinstance(value, dict):
|
|
62
|
+
sensitive = SENSITIVE_KEYS | extra_keys
|
|
63
|
+
return {
|
|
64
|
+
key: (MASK if str(key).lower() in sensitive else mask_value(item, depth=depth + 1, extra_keys=extra_keys))
|
|
65
|
+
for key, item in value.items()
|
|
66
|
+
}
|
|
67
|
+
if isinstance(value, (list, tuple)):
|
|
68
|
+
return [mask_value(item, depth=depth + 1, extra_keys=extra_keys) for item in value]
|
|
69
|
+
if isinstance(value, str):
|
|
70
|
+
return mask_text(value)
|
|
71
|
+
return value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
__all__ = ["MASK", "SENSITIVE_KEYS", "mask_text", "mask_value"]
|