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,101 @@
|
|
|
1
|
+
"""Prometheus 指标:每路由 RED + 活跃请求数。
|
|
2
|
+
|
|
3
|
+
指标名遵循 OTel 语义约定,避免与社区面板不兼容。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import time
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from prometheus_client import CONTENT_TYPE_LATEST, Counter, Gauge, Histogram, generate_latest
|
|
12
|
+
|
|
13
|
+
_requests_total = Counter(
|
|
14
|
+
"http_server_requests_total",
|
|
15
|
+
"HTTP 请求总数",
|
|
16
|
+
["method", "route", "status"],
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
_request_duration = Histogram(
|
|
20
|
+
"http_server_request_duration_seconds",
|
|
21
|
+
"HTTP 请求耗时(秒)",
|
|
22
|
+
["method", "route"],
|
|
23
|
+
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_active_requests = Gauge(
|
|
27
|
+
"http_server_active_requests",
|
|
28
|
+
"当前正在处理的请求数",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
_last_trace = Gauge(
|
|
32
|
+
"swiftapi_info",
|
|
33
|
+
"服务信息(恒为 1)",
|
|
34
|
+
["version", "env"],
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def observe_request(*, method: str, route: str, status: int, duration_s: float) -> None:
|
|
39
|
+
_requests_total.labels(method=method, route=route, status=str(status)).inc()
|
|
40
|
+
_request_duration.labels(method=method, route=route).observe(duration_s)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def inc_active() -> None:
|
|
44
|
+
_active_requests.inc()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def dec_active() -> None:
|
|
48
|
+
_active_requests.dec()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def mark_info(*, version: str, env: str) -> None:
|
|
52
|
+
_last_trace.labels(version=version, env=env).set(1)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def render_metrics() -> tuple[bytes, str]:
|
|
56
|
+
return generate_latest(), CONTENT_TYPE_LATEST
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---------------- 后台监控页用:进程内快照 ----------------
|
|
60
|
+
|
|
61
|
+
_STARTED_AT = time.time()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def snapshot(limit_routes: int = 8) -> dict[str, Any]:
|
|
65
|
+
"""给管理后台用的只读快照;不替代 `/metrics`,只是人看的聚合。"""
|
|
66
|
+
total = 0
|
|
67
|
+
by_status: dict[str, int] = {}
|
|
68
|
+
by_route: dict[str, int] = {}
|
|
69
|
+
for metric in _requests_total.collect():
|
|
70
|
+
for sample in metric.samples:
|
|
71
|
+
if not sample.name.endswith("_total"):
|
|
72
|
+
continue
|
|
73
|
+
count = int(sample.value)
|
|
74
|
+
total += count
|
|
75
|
+
status = str(sample.labels.get("status", "?"))
|
|
76
|
+
by_status[status] = by_status.get(status, 0) + count
|
|
77
|
+
route = f"{sample.labels.get('method', '?')} {sample.labels.get('route', '?')}"
|
|
78
|
+
by_route[route] = by_route.get(route, 0) + count
|
|
79
|
+
|
|
80
|
+
latency_count = 0
|
|
81
|
+
latency_sum = 0.0
|
|
82
|
+
for metric in _request_duration.collect():
|
|
83
|
+
for sample in metric.samples:
|
|
84
|
+
if sample.name.endswith("_count"):
|
|
85
|
+
latency_count += int(sample.value)
|
|
86
|
+
elif sample.name.endswith("_sum"):
|
|
87
|
+
latency_sum += float(sample.value)
|
|
88
|
+
|
|
89
|
+
errors = sum(count for status, count in by_status.items() if status.startswith("5"))
|
|
90
|
+
return {
|
|
91
|
+
"started_at": _STARTED_AT,
|
|
92
|
+
"uptime_s": round(time.time() - _STARTED_AT, 1),
|
|
93
|
+
"requests_total": total,
|
|
94
|
+
"errors_total": errors,
|
|
95
|
+
"by_status": dict(sorted(by_status.items())),
|
|
96
|
+
"top_routes": sorted(by_route.items(), key=lambda item: item[1], reverse=True)[
|
|
97
|
+
:limit_routes
|
|
98
|
+
],
|
|
99
|
+
"avg_latency_ms": round(latency_sum / latency_count * 1000, 2) if latency_count else 0.0,
|
|
100
|
+
"active_requests": int(_active_requests._value.get()),
|
|
101
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""请求体采样的容量估算:上线前先算清楚"会写多少日志"。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
SECONDS_PER_DAY = 86_400
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class BodyLogVolume:
|
|
12
|
+
qps: float
|
|
13
|
+
ratio: float
|
|
14
|
+
replicas: int
|
|
15
|
+
sampled_per_second: float # 集群理论值
|
|
16
|
+
effective_per_second: float # 集群实际值(受预算约束)
|
|
17
|
+
effective_per_day: int
|
|
18
|
+
bytes_per_day: int
|
|
19
|
+
budget_per_second: float | None # 集群预算(条/秒)
|
|
20
|
+
per_replica_budget: float | None # 每副本预算(条/秒)
|
|
21
|
+
budget_limited: bool
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def estimate_volume(
|
|
25
|
+
*,
|
|
26
|
+
qps: float,
|
|
27
|
+
ratio: float,
|
|
28
|
+
avg_bytes: int = 400,
|
|
29
|
+
max_per_minute: int = 600,
|
|
30
|
+
replicas: int = 1,
|
|
31
|
+
) -> BodyLogVolume:
|
|
32
|
+
"""按**集群口径**估算。
|
|
33
|
+
|
|
34
|
+
- `qps` 是集群总 QPS,每副本看到 `qps / replicas`;
|
|
35
|
+
- 预算 `max_per_minute` 也是集群口径,每副本分到 `max_per_minute / replicas`;
|
|
36
|
+
- 单副本至少保留 1 条/分钟(与中间件一致)。
|
|
37
|
+
"""
|
|
38
|
+
replicas = max(1, replicas)
|
|
39
|
+
raw = max(0.0, qps) * max(0.0, ratio)
|
|
40
|
+
per_replica_raw = raw / replicas
|
|
41
|
+
|
|
42
|
+
if max_per_minute <= 0:
|
|
43
|
+
cluster_budget_s: float | None = None
|
|
44
|
+
per_replica_budget: float | None = None
|
|
45
|
+
effective = raw
|
|
46
|
+
else:
|
|
47
|
+
per_replica_per_minute = max(1, max_per_minute // replicas)
|
|
48
|
+
per_replica_budget = per_replica_per_minute / 60
|
|
49
|
+
cluster_budget_s = per_replica_budget * replicas
|
|
50
|
+
effective = min(per_replica_raw, per_replica_budget) * replicas
|
|
51
|
+
|
|
52
|
+
per_day = int(effective * SECONDS_PER_DAY)
|
|
53
|
+
return BodyLogVolume(
|
|
54
|
+
qps=qps,
|
|
55
|
+
ratio=ratio,
|
|
56
|
+
replicas=replicas,
|
|
57
|
+
sampled_per_second=round(raw, 2),
|
|
58
|
+
effective_per_second=round(effective, 2),
|
|
59
|
+
effective_per_day=per_day,
|
|
60
|
+
bytes_per_day=per_day * max(avg_bytes, 0),
|
|
61
|
+
budget_per_second=None if cluster_budget_s is None else round(cluster_budget_s, 2),
|
|
62
|
+
per_replica_budget=None if per_replica_budget is None else round(per_replica_budget, 2),
|
|
63
|
+
budget_limited=cluster_budget_s is not None and raw > cluster_budget_s,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
__all__ = ["SECONDS_PER_DAY", "BodyLogVolume", "estimate_volume"]
|
|
File without changes
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""舱壁:限制单依赖的并发数,避免一个下游拖垮整个服务。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from types import TracebackType
|
|
7
|
+
from typing import Self
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BulkheadFull(RuntimeError):
|
|
11
|
+
"""并发与排队都满:快速失败(503),不要无限排队。"""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Bulkhead:
|
|
15
|
+
def __init__(self, *, name: str = "default", limit: int = 50, max_waiting: int = 100) -> None:
|
|
16
|
+
self.name = name
|
|
17
|
+
self.limit = limit
|
|
18
|
+
self.max_waiting = max_waiting
|
|
19
|
+
self._semaphore = asyncio.Semaphore(limit)
|
|
20
|
+
self._waiting = 0
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def active(self) -> int:
|
|
24
|
+
return self.limit - self._semaphore._value
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def waiting(self) -> int:
|
|
28
|
+
return self._waiting
|
|
29
|
+
|
|
30
|
+
async def __aenter__(self) -> Self:
|
|
31
|
+
# 只有"已满且排队位也用尽"才拒绝;未满时直接进入
|
|
32
|
+
if self._semaphore.locked() and self._waiting >= self.max_waiting:
|
|
33
|
+
raise BulkheadFull(f"舱壁已满: {self.name}")
|
|
34
|
+
self._waiting += 1
|
|
35
|
+
try:
|
|
36
|
+
await self._semaphore.acquire()
|
|
37
|
+
finally:
|
|
38
|
+
self._waiting -= 1
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
async def __aexit__(
|
|
42
|
+
self,
|
|
43
|
+
exc_type: type[BaseException] | None,
|
|
44
|
+
exc: BaseException | None,
|
|
45
|
+
tb: TracebackType | None,
|
|
46
|
+
) -> None:
|
|
47
|
+
self._semaphore.release()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
__all__ = ["Bulkhead", "BulkheadFull"]
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""熔断器:滑动窗口 + 半开探测(架构文档 §10.8)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections import deque
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CircuitState(StrEnum):
|
|
12
|
+
CLOSED = "closed"
|
|
13
|
+
OPEN = "open"
|
|
14
|
+
HALF_OPEN = "half_open"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CircuitOpenError(RuntimeError):
|
|
18
|
+
"""熔断中:快速失败,不要排队。"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CircuitBreaker:
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
*,
|
|
25
|
+
name: str = "default",
|
|
26
|
+
window: int = 20,
|
|
27
|
+
failure_threshold: float = 0.5,
|
|
28
|
+
min_calls: int = 5,
|
|
29
|
+
recovery_time_s: float = 10.0,
|
|
30
|
+
half_open_max: int = 3,
|
|
31
|
+
clock: Callable[[], float] = time.monotonic,
|
|
32
|
+
) -> None:
|
|
33
|
+
self.name = name
|
|
34
|
+
self.window = window
|
|
35
|
+
self.failure_threshold = failure_threshold
|
|
36
|
+
self.min_calls = min_calls
|
|
37
|
+
self.recovery_time_s = recovery_time_s
|
|
38
|
+
self.half_open_max = half_open_max
|
|
39
|
+
self._clock = clock
|
|
40
|
+
self._results: deque[bool] = deque(maxlen=window)
|
|
41
|
+
self._state = CircuitState.CLOSED
|
|
42
|
+
self._opened_at = 0.0
|
|
43
|
+
self._half_open_calls = 0
|
|
44
|
+
self._probe_successes = 0
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def state(self) -> CircuitState:
|
|
48
|
+
if (
|
|
49
|
+
self._state is CircuitState.OPEN
|
|
50
|
+
and self._clock() - self._opened_at >= self.recovery_time_s
|
|
51
|
+
):
|
|
52
|
+
self._state = CircuitState.HALF_OPEN
|
|
53
|
+
self._half_open_calls = 0
|
|
54
|
+
self._probe_successes = 0
|
|
55
|
+
return self._state
|
|
56
|
+
|
|
57
|
+
def _open(self) -> None:
|
|
58
|
+
self._state = CircuitState.OPEN
|
|
59
|
+
self._opened_at = self._clock()
|
|
60
|
+
|
|
61
|
+
async def call[T](self, operation: Callable[[], Awaitable[T]]) -> T:
|
|
62
|
+
state = self.state
|
|
63
|
+
if state is CircuitState.OPEN:
|
|
64
|
+
raise CircuitOpenError(f"熔断打开: {self.name}")
|
|
65
|
+
if state is CircuitState.HALF_OPEN:
|
|
66
|
+
if self._half_open_calls >= self.half_open_max:
|
|
67
|
+
raise CircuitOpenError(f"半开探测已达上限: {self.name}")
|
|
68
|
+
self._half_open_calls += 1
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
result = await operation()
|
|
72
|
+
except Exception:
|
|
73
|
+
self._record(False)
|
|
74
|
+
raise
|
|
75
|
+
self._record(True)
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
def _record(self, success: bool) -> None:
|
|
79
|
+
if self._state is CircuitState.HALF_OPEN:
|
|
80
|
+
if success:
|
|
81
|
+
self._probe_successes += 1
|
|
82
|
+
if self._probe_successes >= self.half_open_max:
|
|
83
|
+
self._state = CircuitState.CLOSED
|
|
84
|
+
self._results.clear()
|
|
85
|
+
else:
|
|
86
|
+
self._open()
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
self._results.append(success)
|
|
90
|
+
if len(self._results) < self.min_calls:
|
|
91
|
+
return
|
|
92
|
+
failures = sum(1 for item in self._results if not item)
|
|
93
|
+
if failures / len(self._results) >= self.failure_threshold:
|
|
94
|
+
self._open()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
__all__ = ["CircuitBreaker", "CircuitOpenError", "CircuitState"]
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""出站客户端:把超时/舱壁/熔断/重试按正确顺序串起来(架构文档 §10.8)。
|
|
2
|
+
|
|
3
|
+
组合顺序:`bulkhead → circuit → retry(timeout(request))`
|
|
4
|
+
- 舱壁最外层:先限制并发,避免把下游打爆;
|
|
5
|
+
- 熔断在重试外层:已熔断就不再重试;
|
|
6
|
+
- 超时在最内层:保证每次尝试都在预算内。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import ipaddress
|
|
13
|
+
import socket
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
from swiftapi.core.resilience.bulkhead import Bulkhead
|
|
20
|
+
from swiftapi.core.resilience.circuit_breaker import CircuitBreaker
|
|
21
|
+
from swiftapi.core.resilience.retry import RetryPolicy, retry_async
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from swiftapi.config.settings import Settings
|
|
25
|
+
|
|
26
|
+
IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "PUT", "DELETE", "OPTIONS"})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TransientHttpError(RuntimeError):
|
|
30
|
+
"""5xx:可重试的瞬时失败(4xx 不重试,重试也不会变好)。"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, status_code: int, url: str) -> None:
|
|
33
|
+
self.status_code = status_code
|
|
34
|
+
super().__init__(f"{status_code} from {url}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class BlockedDestination(ValueError):
|
|
38
|
+
"""出站目标命中了 SSRF 防护(内网/元数据/非 http(s))。"""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_BLOCKED_HOSTNAMES = frozenset(
|
|
42
|
+
{"localhost", "localhost.localdomain", "metadata", "metadata.google.internal"}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _is_public_ip(raw: str) -> bool:
|
|
47
|
+
address = ipaddress.ip_address(raw)
|
|
48
|
+
return not (
|
|
49
|
+
address.is_private
|
|
50
|
+
or address.is_loopback
|
|
51
|
+
or address.is_link_local
|
|
52
|
+
or address.is_reserved
|
|
53
|
+
or address.is_multicast
|
|
54
|
+
or address.is_unspecified
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class OutboundClient:
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
base_url: str = "",
|
|
63
|
+
timeout_s: float = 1.0,
|
|
64
|
+
verify_tls: bool = True,
|
|
65
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
66
|
+
retry: RetryPolicy | None = None,
|
|
67
|
+
breaker: CircuitBreaker | None = None,
|
|
68
|
+
bulkhead: Bulkhead | None = None,
|
|
69
|
+
allow_private: bool = False,
|
|
70
|
+
allowed_hosts: tuple[str, ...] | None = None,
|
|
71
|
+
check_dns: bool | None = None,
|
|
72
|
+
) -> None:
|
|
73
|
+
self.timeout_s = timeout_s
|
|
74
|
+
self.retry = retry or RetryPolicy(
|
|
75
|
+
max_attempts=3,
|
|
76
|
+
base_delay_s=0.05,
|
|
77
|
+
max_delay_s=0.5,
|
|
78
|
+
retry_on=(TimeoutError, ConnectionError, TransientHttpError),
|
|
79
|
+
)
|
|
80
|
+
self.breaker = breaker or CircuitBreaker(name="outbound")
|
|
81
|
+
self.bulkhead = bulkhead or Bulkhead(name="outbound")
|
|
82
|
+
self.allow_private = allow_private
|
|
83
|
+
self.allowed_hosts = allowed_hosts
|
|
84
|
+
# 真实网络默认做 DNS 解析校验;注入 transport(测试)时跳过,避免离线解析失败
|
|
85
|
+
self.check_dns = transport is None if check_dns is None else check_dns
|
|
86
|
+
self._client = httpx.AsyncClient(
|
|
87
|
+
base_url=base_url,
|
|
88
|
+
timeout=httpx.Timeout(timeout_s),
|
|
89
|
+
verify=verify_tls,
|
|
90
|
+
transport=transport,
|
|
91
|
+
headers={"user-agent": "swiftapi-outbound/0.1"},
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def from_settings(cls, settings: Settings) -> OutboundClient:
|
|
96
|
+
"""按项目配置构造(`SWIFTAPI__OUTBOUND__*` 或 settings.py 的 outbound 段)。"""
|
|
97
|
+
cfg = settings.outbound
|
|
98
|
+
return cls(
|
|
99
|
+
timeout_s=cfg.timeout_s,
|
|
100
|
+
allow_private=cfg.allow_private,
|
|
101
|
+
allowed_hosts=tuple(cfg.allowed_hosts) or None,
|
|
102
|
+
check_dns=cfg.check_dns,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
async def _candidate_ips(self, host: str, port: int) -> set[str]:
|
|
106
|
+
try:
|
|
107
|
+
return {str(ipaddress.ip_address(host))}
|
|
108
|
+
except ValueError:
|
|
109
|
+
pass
|
|
110
|
+
if not self.check_dns:
|
|
111
|
+
return set()
|
|
112
|
+
loop = asyncio.get_running_loop()
|
|
113
|
+
try:
|
|
114
|
+
infos = await loop.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
115
|
+
except OSError as exc:
|
|
116
|
+
raise BlockedDestination(f"无法解析主机: {host}") from exc
|
|
117
|
+
return {str(info[4][0]) for info in infos}
|
|
118
|
+
|
|
119
|
+
async def _guard(self, url: str) -> None:
|
|
120
|
+
"""SSRF 防护:协议白名单 + 主机黑名单 + 私网 IP 校验(可选 DNS 解析)。"""
|
|
121
|
+
parts = urlsplit(url)
|
|
122
|
+
if parts.scheme not in {"http", "https"}:
|
|
123
|
+
raise BlockedDestination(f"不支持的协议: {parts.scheme or '(none)'}")
|
|
124
|
+
if parts.username or parts.password:
|
|
125
|
+
raise BlockedDestination("URL 不允许携带凭据")
|
|
126
|
+
|
|
127
|
+
host = parts.hostname
|
|
128
|
+
if not host:
|
|
129
|
+
raise BlockedDestination("URL 缺少主机")
|
|
130
|
+
if self.allow_private:
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
normalized = host.lower().rstrip(".")
|
|
134
|
+
if normalized in _BLOCKED_HOSTNAMES:
|
|
135
|
+
raise BlockedDestination(f"禁止访问主机: {host}")
|
|
136
|
+
|
|
137
|
+
if self.allowed_hosts is not None and not any(
|
|
138
|
+
normalized == item.lower() or normalized.endswith(f".{item.lower()}")
|
|
139
|
+
for item in self.allowed_hosts
|
|
140
|
+
):
|
|
141
|
+
raise BlockedDestination(f"主机不在白名单: {host}")
|
|
142
|
+
|
|
143
|
+
port = parts.port or (443 if parts.scheme == "https" else 80)
|
|
144
|
+
for candidate in await self._candidate_ips(host, port):
|
|
145
|
+
if not _is_public_ip(candidate):
|
|
146
|
+
raise BlockedDestination(f"禁止访问内网地址: {host} -> {candidate}")
|
|
147
|
+
|
|
148
|
+
async def request(
|
|
149
|
+
self,
|
|
150
|
+
method: str,
|
|
151
|
+
url: str,
|
|
152
|
+
*,
|
|
153
|
+
idempotent: bool | None = None,
|
|
154
|
+
**kwargs: Any,
|
|
155
|
+
) -> httpx.Response:
|
|
156
|
+
is_idempotent = (
|
|
157
|
+
idempotent if idempotent is not None else method.upper() in IDEMPOTENT_METHODS
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
if not urlsplit(url).scheme and self._client.base_url:
|
|
161
|
+
url = str(self._client.base_url.join(url))
|
|
162
|
+
await self._guard(url)
|
|
163
|
+
|
|
164
|
+
async def once() -> httpx.Response:
|
|
165
|
+
response = await self._client.request(method, url, **kwargs)
|
|
166
|
+
if response.status_code >= 500:
|
|
167
|
+
raise TransientHttpError(response.status_code, url)
|
|
168
|
+
return response
|
|
169
|
+
|
|
170
|
+
async with self.bulkhead:
|
|
171
|
+
return await self.breaker.call(
|
|
172
|
+
lambda: retry_async(once, policy=self.retry, idempotent=is_idempotent)
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
async def aclose(self) -> None:
|
|
176
|
+
await self._client.aclose()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
__all__ = ["IDEMPOTENT_METHODS", "BlockedDestination", "OutboundClient", "TransientHttpError"]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""重试:只重试幂等操作,且不突破总预算(架构文档 §10.8)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import random
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TypeVar
|
|
10
|
+
|
|
11
|
+
T = TypeVar("T")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RetryExhausted(RuntimeError):
|
|
15
|
+
def __init__(self, attempts: int, last: BaseException) -> None:
|
|
16
|
+
self.attempts = attempts
|
|
17
|
+
self.last = last
|
|
18
|
+
super().__init__(f"重试 {attempts} 次仍失败: {last!r}")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class RetryPolicy:
|
|
23
|
+
max_attempts: int = 3
|
|
24
|
+
base_delay_s: float = 0.1
|
|
25
|
+
max_delay_s: float = 2.0
|
|
26
|
+
jitter_ratio: float = 0.2
|
|
27
|
+
retry_on: tuple[type[BaseException], ...] = (TimeoutError, ConnectionError)
|
|
28
|
+
|
|
29
|
+
def delay_for(self, attempt: int) -> float:
|
|
30
|
+
raw = min(self.max_delay_s, self.base_delay_s * (2 ** (attempt - 1)))
|
|
31
|
+
jitter = raw * self.jitter_ratio
|
|
32
|
+
return float(max(0.0, raw + random.uniform(-jitter, jitter)))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def retry_async[T](
|
|
36
|
+
operation: Callable[[], Awaitable[T]],
|
|
37
|
+
*,
|
|
38
|
+
policy: RetryPolicy | None = None,
|
|
39
|
+
idempotent: bool = True,
|
|
40
|
+
) -> T:
|
|
41
|
+
"""`idempotent=False` 时只执行一次——非幂等操作重试会制造重复副作用。"""
|
|
42
|
+
resolved = policy or RetryPolicy()
|
|
43
|
+
if not idempotent:
|
|
44
|
+
return await operation()
|
|
45
|
+
|
|
46
|
+
last: BaseException | None = None
|
|
47
|
+
for attempt in range(1, resolved.max_attempts + 1):
|
|
48
|
+
try:
|
|
49
|
+
return await operation()
|
|
50
|
+
except resolved.retry_on as exc:
|
|
51
|
+
last = exc
|
|
52
|
+
if attempt == resolved.max_attempts:
|
|
53
|
+
break
|
|
54
|
+
await asyncio.sleep(resolved.delay_for(attempt))
|
|
55
|
+
assert last is not None
|
|
56
|
+
raise RetryExhausted(resolved.max_attempts, last) from last
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
__all__ = ["RetryExhausted", "RetryPolicy", "retry_async"]
|
|
File without changes
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""JWT 校验:RS256(生产)/ HS256(仅测试或 allow_insecure)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
import jwt
|
|
10
|
+
|
|
11
|
+
from swiftapi.config.settings import JwtAlgorithm, Settings
|
|
12
|
+
from swiftapi.core.errors.base import TokenExpired, Unauthenticated
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class Claims:
|
|
17
|
+
subject: UUID
|
|
18
|
+
roles: frozenset[str] = field(default_factory=frozenset)
|
|
19
|
+
tenant_slug: str | None = None
|
|
20
|
+
tenant_slugs: frozenset[str] = field(default_factory=frozenset)
|
|
21
|
+
expires_at: datetime | None = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class JwtVerifier:
|
|
25
|
+
def __init__(self, settings: Settings) -> None:
|
|
26
|
+
self.algorithm = settings.security.jwt_algorithm
|
|
27
|
+
self.issuer = settings.security.jwt_issuer
|
|
28
|
+
self.audience = settings.security.jwt_audience
|
|
29
|
+
self.leeway = settings.security.clock_skew_s
|
|
30
|
+
self._key = self._resolve_key(settings)
|
|
31
|
+
|
|
32
|
+
def _resolve_key(self, settings: Settings) -> str:
|
|
33
|
+
security = settings.security
|
|
34
|
+
if self.algorithm is JwtAlgorithm.HS256:
|
|
35
|
+
secret = security.jwt_private_key or security.jwt_public_key
|
|
36
|
+
if secret is None:
|
|
37
|
+
raise Unauthenticated("HS256 需要配置 jwt_private_key")
|
|
38
|
+
return secret.get_secret_value()
|
|
39
|
+
if security.jwt_public_key is None:
|
|
40
|
+
raise Unauthenticated("RS256 需要配置 jwt_public_key")
|
|
41
|
+
return security.jwt_public_key.get_secret_value()
|
|
42
|
+
|
|
43
|
+
def verify(self, token: str) -> Claims:
|
|
44
|
+
try:
|
|
45
|
+
payload = jwt.decode(
|
|
46
|
+
token,
|
|
47
|
+
self._key,
|
|
48
|
+
algorithms=[self.algorithm.value],
|
|
49
|
+
audience=self.audience,
|
|
50
|
+
issuer=self.issuer,
|
|
51
|
+
leeway=self.leeway,
|
|
52
|
+
options={"require": ["exp", "sub"]},
|
|
53
|
+
)
|
|
54
|
+
except jwt.ExpiredSignatureError as exc:
|
|
55
|
+
raise TokenExpired("令牌已过期") from exc
|
|
56
|
+
except jwt.PyJWTError as exc:
|
|
57
|
+
raise Unauthenticated("令牌无效") from exc
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
subject = UUID(str(payload["sub"]))
|
|
61
|
+
except (KeyError, ValueError) as exc:
|
|
62
|
+
raise Unauthenticated("令牌缺少合法 sub") from exc
|
|
63
|
+
|
|
64
|
+
roles = payload.get("roles") or []
|
|
65
|
+
raw_tenants = payload.get("tenants") or []
|
|
66
|
+
slugs = {str(item) for item in raw_tenants} if isinstance(raw_tenants, (list, tuple)) else set()
|
|
67
|
+
tenant_slug = payload.get("tid")
|
|
68
|
+
if tenant_slug:
|
|
69
|
+
slugs.add(str(tenant_slug))
|
|
70
|
+
return Claims(
|
|
71
|
+
subject=subject,
|
|
72
|
+
roles=frozenset(str(role) for role in roles),
|
|
73
|
+
tenant_slug=tenant_slug,
|
|
74
|
+
tenant_slugs=frozenset(slugs),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
__all__ = ["Claims", "JwtVerifier"]
|