swiftapi-kernel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of swiftapi-kernel might be problematic. Click here for more details.

Files changed (187) hide show
  1. swiftapi/__init__.py +22 -0
  2. swiftapi/app/__init__.py +0 -0
  3. swiftapi/app/factory.py +200 -0
  4. swiftapi/app/lifespan.py +167 -0
  5. swiftapi/app/routers.py +58 -0
  6. swiftapi/cli/__init__.py +0 -0
  7. swiftapi/cli/admin.py +198 -0
  8. swiftapi/cli/appref.py +51 -0
  9. swiftapi/cli/audit.py +45 -0
  10. swiftapi/cli/db.py +185 -0
  11. swiftapi/cli/endpoint.py +169 -0
  12. swiftapi/cli/logs.py +100 -0
  13. swiftapi/cli/main.py +238 -0
  14. swiftapi/cli/new.py +113 -0
  15. swiftapi/cli/openapi.py +69 -0
  16. swiftapi/cli/resource.py +657 -0
  17. swiftapi/cli/scaffold.py +168 -0
  18. swiftapi/config/__init__.py +0 -0
  19. swiftapi/config/constants.py +51 -0
  20. swiftapi/config/environments.py +38 -0
  21. swiftapi/config/settings.py +764 -0
  22. swiftapi/core/__init__.py +0 -0
  23. swiftapi/core/admin/__init__.py +0 -0
  24. swiftapi/core/admin/accounts.py +385 -0
  25. swiftapi/core/admin/audit.py +203 -0
  26. swiftapi/core/admin/maintenance.py +53 -0
  27. swiftapi/core/admin/registry.py +53 -0
  28. swiftapi/core/admin/security.py +94 -0
  29. swiftapi/core/admin/session.py +154 -0
  30. swiftapi/core/admin/views.py +2428 -0
  31. swiftapi/core/cache/__init__.py +0 -0
  32. swiftapi/core/cache/base.py +29 -0
  33. swiftapi/core/cache/decorators.py +51 -0
  34. swiftapi/core/cache/factory.py +30 -0
  35. swiftapi/core/cache/keys.py +24 -0
  36. swiftapi/core/cache/memory.py +60 -0
  37. swiftapi/core/cache/null.py +28 -0
  38. swiftapi/core/cache/redis.py +50 -0
  39. swiftapi/core/container.py +209 -0
  40. swiftapi/core/db/__init__.py +0 -0
  41. swiftapi/core/db/base_model.py +122 -0
  42. swiftapi/core/db/crud.py +242 -0
  43. swiftapi/core/db/dialects/__init__.py +8 -0
  44. swiftapi/core/db/dialects/base.py +106 -0
  45. swiftapi/core/db/dialects/mysql.py +47 -0
  46. swiftapi/core/db/dialects/pg.py +51 -0
  47. swiftapi/core/db/dialects/registry.py +30 -0
  48. swiftapi/core/db/dialects/sqlite.py +47 -0
  49. swiftapi/core/db/engine.py +209 -0
  50. swiftapi/core/db/health.py +84 -0
  51. swiftapi/core/db/migrate/__init__.py +1 -0
  52. swiftapi/core/db/migrate/ddl.py +162 -0
  53. swiftapi/core/db/migrate/render.py +84 -0
  54. swiftapi/core/db/migrate/runner.py +159 -0
  55. swiftapi/core/db/migrate/schema.py +248 -0
  56. swiftapi/core/db/mixins.py +53 -0
  57. swiftapi/core/db/session.py +54 -0
  58. swiftapi/core/db/snapshot.py +33 -0
  59. swiftapi/core/db/tenant_model.py +43 -0
  60. swiftapi/core/db/tenant_router.py +114 -0
  61. swiftapi/core/db/types.py +109 -0
  62. swiftapi/core/db/unit_of_work.py +65 -0
  63. swiftapi/core/docs/__init__.py +0 -0
  64. swiftapi/core/docs/router.py +26 -0
  65. swiftapi/core/docs/tsgen.py +93 -0
  66. swiftapi/core/docs/ui.py +132 -0
  67. swiftapi/core/errors/__init__.py +0 -0
  68. swiftapi/core/errors/base.py +168 -0
  69. swiftapi/core/errors/codes.py +117 -0
  70. swiftapi/core/errors/handlers.py +155 -0
  71. swiftapi/core/errors/problem.py +58 -0
  72. swiftapi/core/errors/validation.py +11 -0
  73. swiftapi/core/framework_models.py +22 -0
  74. swiftapi/core/http/__init__.py +47 -0
  75. swiftapi/core/http/app.py +247 -0
  76. swiftapi/core/http/cors.py +100 -0
  77. swiftapi/core/http/idempotency.py +148 -0
  78. swiftapi/core/http/middleware/__init__.py +82 -0
  79. swiftapi/core/http/middleware/access_log.py +57 -0
  80. swiftapi/core/http/middleware/auth.py +105 -0
  81. swiftapi/core/http/middleware/body_limit.py +76 -0
  82. swiftapi/core/http/middleware/rate_limit.py +103 -0
  83. swiftapi/core/http/middleware/request_body.py +122 -0
  84. swiftapi/core/http/middleware/request_id.py +46 -0
  85. swiftapi/core/http/middleware/security_headers.py +46 -0
  86. swiftapi/core/http/middleware/tenant.py +93 -0
  87. swiftapi/core/http/middleware/timing.py +57 -0
  88. swiftapi/core/http/multipart.py +116 -0
  89. swiftapi/core/http/multipart_stream.py +216 -0
  90. swiftapi/core/http/openapi.py +148 -0
  91. swiftapi/core/http/pagination.py +55 -0
  92. swiftapi/core/http/params.py +302 -0
  93. swiftapi/core/http/request.py +145 -0
  94. swiftapi/core/http/responses.py +127 -0
  95. swiftapi/core/http/routing.py +200 -0
  96. swiftapi/core/http/types.py +86 -0
  97. swiftapi/core/http/uploads.py +222 -0
  98. swiftapi/core/messaging/__init__.py +0 -0
  99. swiftapi/core/messaging/base.py +33 -0
  100. swiftapi/core/messaging/consumer.py +57 -0
  101. swiftapi/core/messaging/factory.py +30 -0
  102. swiftapi/core/messaging/idempotency.py +61 -0
  103. swiftapi/core/messaging/inprocess.py +30 -0
  104. swiftapi/core/messaging/outbox.py +106 -0
  105. swiftapi/core/messaging/rabbitmq.py +186 -0
  106. swiftapi/core/messaging/relay.py +151 -0
  107. swiftapi/core/messaging/streams.py +141 -0
  108. swiftapi/core/observability/__init__.py +0 -0
  109. swiftapi/core/observability/archive.py +136 -0
  110. swiftapi/core/observability/context.py +102 -0
  111. swiftapi/core/observability/logging.py +192 -0
  112. swiftapi/core/observability/masking.py +74 -0
  113. swiftapi/core/observability/metrics.py +101 -0
  114. swiftapi/core/observability/volume.py +67 -0
  115. swiftapi/core/resilience/__init__.py +0 -0
  116. swiftapi/core/resilience/bulkhead.py +50 -0
  117. swiftapi/core/resilience/circuit_breaker.py +97 -0
  118. swiftapi/core/resilience/client.py +179 -0
  119. swiftapi/core/resilience/retry.py +59 -0
  120. swiftapi/core/security/__init__.py +0 -0
  121. swiftapi/core/security/jwt.py +78 -0
  122. swiftapi/core/security/principal.py +78 -0
  123. swiftapi/core/tenant/__init__.py +1 -0
  124. swiftapi/core/tenant/catalog.py +89 -0
  125. swiftapi/core/tenant/context.py +75 -0
  126. swiftapi/core/tenant/isolation.py +48 -0
  127. swiftapi/core/tenant/resolver.py +48 -0
  128. swiftapi/core/validation/__init__.py +0 -0
  129. swiftapi/core/validation/base.py +32 -0
  130. swiftapi/db.py +50 -0
  131. swiftapi/modules/__init__.py +0 -0
  132. swiftapi/modules/users/__init__.py +11 -0
  133. swiftapi/modules/users/api/__init__.py +0 -0
  134. swiftapi/modules/users/api/users.py +110 -0
  135. swiftapi/modules/users/crud/__init__.py +0 -0
  136. swiftapi/modules/users/crud/user.py +23 -0
  137. swiftapi/modules/users/errors.py +24 -0
  138. swiftapi/modules/users/mappers.py +19 -0
  139. swiftapi/modules/users/model/__init__.py +0 -0
  140. swiftapi/modules/users/model/user.py +37 -0
  141. swiftapi/modules/users/policies.py +19 -0
  142. swiftapi/modules/users/schema/__init__.py +0 -0
  143. swiftapi/modules/users/schema/user.py +40 -0
  144. swiftapi/modules/users/service/__init__.py +0 -0
  145. swiftapi/modules/users/service/user.py +107 -0
  146. swiftapi/py.typed +0 -0
  147. swiftapi/templates/__init__.py +0 -0
  148. swiftapi/templates/app_skeleton/README.md +17 -0
  149. swiftapi/templates/app_skeleton/__init__.py +1 -0
  150. swiftapi/templates/app_skeleton/api/__init__.py +23 -0
  151. swiftapi/templates/app_skeleton/api/health.py +12 -0
  152. swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
  153. swiftapi/templates/app_skeleton/model/__init__.py +1 -0
  154. swiftapi/templates/app_skeleton/router.py +16 -0
  155. swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
  156. swiftapi/templates/app_skeleton/service/__init__.py +1 -0
  157. swiftapi/templates/project/__init__.py +0 -0
  158. swiftapi/templates/project/api.py +135 -0
  159. swiftapi/templates/project/app.py +57 -0
  160. swiftapi/templates/project/endpoints/__init__.py +25 -0
  161. swiftapi/templates/project/events.py +43 -0
  162. swiftapi/templates/project/models.py +79 -0
  163. swiftapi/templates/project/resources/__init__.py +35 -0
  164. swiftapi/templates/project/schemas.py +45 -0
  165. swiftapi/templates/project/service.py +125 -0
  166. swiftapi/templates/project/settings.py +17 -0
  167. swiftapi/templates/project_skeleton/.env.example +5 -0
  168. swiftapi/templates/project_skeleton/.gitignore +6 -0
  169. swiftapi/templates/project_skeleton/README.md +25 -0
  170. swiftapi/templates/project_skeleton/__init__.py +1 -0
  171. swiftapi/templates/project_skeleton/app.py +26 -0
  172. swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
  173. swiftapi/templates/project_skeleton/common/__init__.py +4 -0
  174. swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
  175. swiftapi/templates/project_skeleton/conf/settings.py +73 -0
  176. swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
  177. swiftapi/templates/project_skeleton/models.py +12 -0
  178. swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
  179. swiftapi/templates/project_skeleton/router.py +46 -0
  180. swiftapi/templates/project_skeleton/script/start.sh +13 -0
  181. swiftapi/templates/project_skeleton/start.py +35 -0
  182. swiftapi/version.py +8 -0
  183. swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
  184. swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
  185. swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
  186. swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
  187. swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,57 @@
1
+ """消费者:把"拿 session + 去重 + 调 handler"封装起来(DX G4)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable
6
+
7
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
8
+
9
+ from swiftapi.core.messaging.base import EventEnvelope, MessageBus
10
+ from swiftapi.core.messaging.idempotency import mark_processed
11
+
12
+ Handler = Callable[[AsyncSession, EventEnvelope], Awaitable[None]]
13
+
14
+
15
+ class Consumer:
16
+ """用法:
17
+
18
+ consumer = Consumer(bus, database.session_factory, group="audit")
19
+ consumer.on("ticket.created", handle_created)
20
+ await consumer.run_once()
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ bus: MessageBus,
26
+ session_factory: async_sessionmaker[AsyncSession],
27
+ *,
28
+ group: str = "consumer",
29
+ idempotent: bool = True,
30
+ ) -> None:
31
+ self.bus = bus
32
+ self.session_factory = session_factory
33
+ self.group = group
34
+ self.idempotent = idempotent
35
+ self._handlers: dict[str, list[Handler]] = {}
36
+
37
+ def on(self, event_type: str) -> Callable[[Handler], Handler]:
38
+ def decorator(handler: Handler) -> Handler:
39
+ self._handlers.setdefault(event_type, []).append(handler)
40
+ self.bus.subscribe(event_type, self._dispatch) # type: ignore[attr-defined]
41
+ return handler
42
+
43
+ return decorator
44
+
45
+ async def _dispatch(self, envelope: EventEnvelope) -> None:
46
+ async with self.session_factory() as session:
47
+ if self.idempotent:
48
+ first = await mark_processed(session, envelope.event_id, self.group)
49
+ if not first:
50
+ await session.rollback()
51
+ return
52
+ for handler in self._handlers.get(envelope.event_type, ()):
53
+ await handler(session, envelope)
54
+ await session.commit()
55
+
56
+
57
+ __all__ = ["Consumer", "Handler"]
@@ -0,0 +1,30 @@
1
+ """按配置选消息总线:工厂是唯一的"选实现"入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from swiftapi.config.settings import MessagingBackend, Settings
6
+ from swiftapi.core.messaging.base import MessageBus
7
+ from swiftapi.core.messaging.inprocess import InProcessBus
8
+
9
+
10
+ def create_bus(settings: Settings) -> MessageBus:
11
+ if not settings.messaging.enabled:
12
+ return InProcessBus()
13
+ backend = settings.messaging.backend
14
+ if backend is MessagingBackend.INPROCESS:
15
+ return InProcessBus()
16
+ if backend is MessagingBackend.REDIS_STREAMS:
17
+ from swiftapi.core.messaging.streams import RedisStreamsBus
18
+
19
+ url = settings.messaging.url or settings.cache.url
20
+ assert url is not None # 启动校验已保证
21
+ return RedisStreamsBus(url.get_secret_value())
22
+ if backend is MessagingBackend.RABBITMQ:
23
+ from swiftapi.core.messaging.rabbitmq import RabbitMQBus
24
+
25
+ assert settings.messaging.url is not None
26
+ return RabbitMQBus(settings.messaging.url.get_secret_value())
27
+ return InProcessBus()
28
+
29
+
30
+ __all__ = ["create_bus"]
@@ -0,0 +1,61 @@
1
+ """消费幂等:同一 (consumer, event_id) 只处理一次。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ from typing import Any, cast
7
+ from uuid import UUID
8
+
9
+ from sqlalchemy import func
10
+ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
11
+ from sqlalchemy.ext.asyncio import AsyncSession
12
+ from sqlalchemy.orm import Mapped, mapped_column
13
+
14
+ from swiftapi.core.db.types import ShortText, TZDateTime, UUIDType
15
+ from swiftapi.db import BaseModel
16
+
17
+
18
+ class ProcessedEvent(BaseModel):
19
+ __tablename__ = "processed_event"
20
+ __module_schema__ = "platform"
21
+
22
+ event_id: Mapped[UUID] = mapped_column(UUIDType, primary_key=True)
23
+ consumer: Mapped[str] = mapped_column(ShortText(64), primary_key=True)
24
+ processed_at: Mapped[datetime] = mapped_column(
25
+ TZDateTime, server_default=func.now(), nullable=False
26
+ )
27
+
28
+
29
+ async def mark_processed(session: AsyncSession, event_id: UUID, consumer: str) -> bool:
30
+ """返回 True 表示"首次处理";False 表示重复投递,应跳过。"""
31
+ dialect = session.bind.dialect.name if session.bind is not None else "sqlite"
32
+ values = {"event_id": event_id, "consumer": consumer, "processed_at": datetime.now(UTC)}
33
+
34
+ if dialect == "sqlite":
35
+ statement = (
36
+ sqlite_insert(ProcessedEvent)
37
+ .values(**values)
38
+ .on_conflict_do_nothing(index_elements=["event_id", "consumer"])
39
+ )
40
+ result = cast(Any, await session.execute(statement))
41
+ return bool(result.rowcount)
42
+ if dialect == "postgresql":
43
+ from sqlalchemy.dialects.postgresql import insert as pg_insert
44
+
45
+ pg_statement = (
46
+ pg_insert(ProcessedEvent)
47
+ .values(**values)
48
+ .on_conflict_do_nothing(index_elements=["event_id", "consumer"])
49
+ )
50
+ result = cast(Any, await session.execute(pg_statement))
51
+ return bool(result.rowcount)
52
+ if dialect == "mysql":
53
+ from sqlalchemy.dialects.mysql import insert as mysql_insert
54
+
55
+ mysql_statement = mysql_insert(ProcessedEvent).values(**values).prefix_with("IGNORE")
56
+ result = cast(Any, await session.execute(mysql_statement))
57
+ return bool(result.rowcount)
58
+ raise NotImplementedError(f"未知方言: {dialect}")
59
+
60
+
61
+ __all__ = ["ProcessedEvent", "mark_processed"]
@@ -0,0 +1,30 @@
1
+ """进程内总线:单模块开发与单测用(生产禁用)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from collections.abc import Awaitable, Callable
7
+
8
+ from swiftapi.core.messaging.base import EventEnvelope
9
+
10
+ Handler = Callable[[EventEnvelope], Awaitable[None]]
11
+
12
+
13
+ class InProcessBus:
14
+ name = "inprocess"
15
+
16
+ def __init__(self) -> None:
17
+ self._handlers: dict[str, list[Handler]] = defaultdict(list)
18
+
19
+ def subscribe(self, event_type: str, handler: Handler) -> None:
20
+ self._handlers[event_type].append(handler)
21
+
22
+ async def publish(self, envelope: EventEnvelope) -> None:
23
+ for handler in self._handlers.get(envelope.event_type, ()):
24
+ await handler(envelope)
25
+
26
+ async def close(self) -> None:
27
+ self._handlers.clear()
28
+
29
+
30
+ __all__ = ["Handler", "InProcessBus"]
@@ -0,0 +1,106 @@
1
+ """Transactional Outbox:业务写入与事件写入同一个事务(架构文档 §17.6)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ from typing import Any
7
+ from uuid import UUID
8
+
9
+ from pydantic import BaseModel as PydanticModel
10
+ from sqlalchemy import func
11
+ from sqlalchemy.ext.asyncio import AsyncSession
12
+ from sqlalchemy.orm import Mapped, mapped_column
13
+
14
+ from swiftapi.core.db.types import JSONType, ShortText, TZDateTime, UUIDType
15
+ from swiftapi.core.messaging.base import EventEnvelope
16
+ from swiftapi.db import BaseModel
17
+
18
+ PENDING = "pending"
19
+ PUBLISHED = "published"
20
+ DEAD = "dead"
21
+
22
+
23
+ class OutboxMessage(BaseModel):
24
+ __tablename__ = "outbox"
25
+ __module_schema__ = "platform"
26
+
27
+ id: Mapped[UUID] = mapped_column(UUIDType, primary_key=True)
28
+ event_type: Mapped[str] = mapped_column(ShortText(128), index=True)
29
+ event_version: Mapped[int] = mapped_column(default=1)
30
+ payload: Mapped[dict[str, Any]] = mapped_column(JSONType)
31
+ status: Mapped[str] = mapped_column(ShortText(16), default=PENDING, index=True)
32
+ attempts: Mapped[int] = mapped_column(default=0)
33
+ next_retry_at: Mapped[datetime] = mapped_column(
34
+ TZDateTime,
35
+ default=lambda: datetime.now(UTC),
36
+ server_default=func.now(),
37
+ index=True,
38
+ )
39
+ created_at: Mapped[datetime] = mapped_column(
40
+ TZDateTime, server_default=func.now(), nullable=False
41
+ )
42
+ published_at: Mapped[datetime | None] = mapped_column(TZDateTime, default=None)
43
+
44
+
45
+ def event_envelope(
46
+ event_type: str,
47
+ payload: PydanticModel | dict[str, Any],
48
+ *,
49
+ tenant_id: UUID | None = None,
50
+ trace_id: str | None = None,
51
+ ) -> EventEnvelope:
52
+ return EventEnvelope(
53
+ event_type=event_type,
54
+ payload=payload.model_dump(mode="json") if isinstance(payload, PydanticModel) else dict(payload),
55
+ tenant_id=tenant_id,
56
+ trace_id=trace_id,
57
+ )
58
+
59
+
60
+ async def emit(
61
+ session: AsyncSession,
62
+ event_type: str,
63
+ payload: PydanticModel | dict[str, Any],
64
+ *,
65
+ tenant_id: UUID | None = None,
66
+ trace_id: str | None = None,
67
+ ) -> OutboxMessage:
68
+ """一行发事件:`await emit(session, "ticket.created", TicketCreated(...), tenant_id=tid)`。"""
69
+ from swiftapi.core.observability.context import trace_id as current_trace_id
70
+
71
+ envelope = event_envelope(
72
+ event_type,
73
+ payload,
74
+ tenant_id=tenant_id,
75
+ trace_id=trace_id or current_trace_id(),
76
+ )
77
+ return await add_event(session, envelope)
78
+
79
+
80
+ def to_outbox_message(envelope: EventEnvelope) -> OutboxMessage:
81
+ return OutboxMessage(
82
+ id=envelope.event_id,
83
+ event_type=envelope.event_type,
84
+ event_version=envelope.event_version,
85
+ payload={**envelope.payload, "_trace_id": envelope.trace_id, "_tenant_id": str(envelope.tenant_id) if envelope.tenant_id else None},
86
+ )
87
+
88
+
89
+ async def add_event(session: AsyncSession, envelope: EventEnvelope) -> OutboxMessage:
90
+ """在调用方的事务里写一条 outbox 记录(不 commit)。"""
91
+ message = to_outbox_message(envelope)
92
+ session.add(message)
93
+ await session.flush()
94
+ return message
95
+
96
+
97
+ __all__ = [
98
+ "DEAD",
99
+ "PENDING",
100
+ "PUBLISHED",
101
+ "OutboxMessage",
102
+ "add_event",
103
+ "emit",
104
+ "event_envelope",
105
+ "to_outbox_message",
106
+ ]
@@ -0,0 +1,186 @@
1
+ """RabbitMQ 后端:生产端(confirms + 持久化)+ 消费端(prefetch + DLX)。
2
+
3
+ 可靠性约定:
4
+ - 队列 durable + 消息 PERSISTENT + publisher confirms;
5
+ - 消费失败 `nack(requeue=False)` → 死信交换机(不无限重试打爆队列);
6
+ - 顺序性:同一 routing key 落同一队列,单消费者内有序。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Awaitable, Callable
13
+ from datetime import datetime
14
+ from typing import Any
15
+ from uuid import UUID
16
+
17
+ from swiftapi.core.messaging.base import EventEnvelope
18
+
19
+ Handler = Callable[[EventEnvelope], Awaitable[None]]
20
+
21
+
22
+ class RabbitMQBus:
23
+ name = "rabbitmq"
24
+
25
+ def __init__(
26
+ self,
27
+ url: str,
28
+ *,
29
+ exchange: str = "swiftapi.events",
30
+ dead_letter_exchange: str = "swiftapi.dlx",
31
+ prefetch: int = 10,
32
+ ) -> None:
33
+ try:
34
+ import aio_pika
35
+ except ImportError as exc: # pragma: no cover - 可选依赖
36
+ raise RuntimeError(
37
+ "messaging.backend=rabbitmq 需要安装 aio-pika:uv pip install 'swiftapi[rabbitmq]'"
38
+ ) from exc
39
+ self._aio_pika = aio_pika
40
+ self.url = url
41
+ self.exchange_name = exchange
42
+ self.dlx_name = dead_letter_exchange
43
+ self.prefetch = prefetch
44
+ self._connection: Any = None
45
+ self._channel: Any = None
46
+ self._exchange: Any = None
47
+ self._dlx: Any = None
48
+ self._main_queue: Any = None
49
+ self._handlers: dict[str, list[Handler]] = {}
50
+
51
+ # ---------------- 连接与拓扑 ----------------
52
+
53
+ async def _ensure(self) -> None:
54
+ if self._exchange is not None:
55
+ return
56
+ self._connection = await self._aio_pika.connect_robust(self.url)
57
+ self._channel = await self._connection.channel(publisher_confirms=True)
58
+ await self._channel.set_qos(prefetch_count=self.prefetch)
59
+ self._exchange = await self._channel.declare_exchange(
60
+ self.exchange_name, self._aio_pika.ExchangeType.TOPIC, durable=True
61
+ )
62
+ self._dlx = await self._channel.declare_exchange(
63
+ self.dlx_name, self._aio_pika.ExchangeType.DIRECT, durable=True
64
+ )
65
+ dead_queue = await self._channel.declare_queue("swiftapi.dead", durable=True)
66
+ await dead_queue.bind(self._dlx, routing_key="dead")
67
+ self._main_queue = await self._channel.declare_queue(
68
+ f"{self.exchange_name}",
69
+ durable=True,
70
+ arguments={
71
+ "x-dead-letter-exchange": self.dlx_name,
72
+ "x-dead-letter-routing-key": "dead",
73
+ },
74
+ )
75
+ await self._main_queue.bind(self._exchange, routing_key="#")
76
+
77
+ async def _queue(self) -> Any:
78
+ """主队列绑定 `#`:**先发布、后启动消费者**也不会丢消息(topic 交换机不存离线消息)。
79
+
80
+ `group` 参数只用于消费者标签,不再参与队列命名——
81
+ 否则每个 group 一个新队列,早于消费者发布的消息会被交换机直接丢弃。
82
+ """
83
+ await self._ensure()
84
+ return self._main_queue
85
+
86
+ # ---------------- 生产 ----------------
87
+
88
+ async def publish(self, envelope: EventEnvelope) -> None:
89
+ await self._ensure()
90
+ message = self._aio_pika.Message(
91
+ body=_encode(envelope),
92
+ content_type="application/json",
93
+ delivery_mode=self._aio_pika.DeliveryMode.PERSISTENT,
94
+ message_id=str(envelope.event_id),
95
+ )
96
+ await self._exchange.publish(message, routing_key=envelope.event_type)
97
+
98
+ # ---------------- 消费 ----------------
99
+
100
+ def subscribe(self, event_type: str, handler: Handler) -> None:
101
+ self._handlers.setdefault(event_type, []).append(handler)
102
+
103
+ async def run_once(self, *, group: str = "swiftapi", timeout_s: float = 1.0) -> int:
104
+ """取一条 → 分发 → ack;处理失败 nack(requeue=False) 进死信。
105
+
106
+ 注意:aio-pika 在队列为空时抛 `QueueEmpty`(而不是返回 None),
107
+ 这里统一翻译成"没有消息"。
108
+ """
109
+ queue = await self._queue()
110
+ try:
111
+ message = await queue.get(no_ack=False, timeout=timeout_s)
112
+ except Exception as exc: # QueueEmpty 在不同版本里是不同类
113
+ if type(exc).__name__ == "QueueEmpty":
114
+ return 0
115
+ raise
116
+ if message is None:
117
+ return 0
118
+ await self._dispatch(message)
119
+ return 1
120
+
121
+ async def start(self, *, group: str = "swiftapi") -> None:
122
+ queue = await self._queue()
123
+ async with queue.iterator() as iterator:
124
+ async for message in iterator:
125
+ await self._dispatch(message)
126
+
127
+ async def _dispatch(self, message: Any) -> None:
128
+ envelope = _decode(message.body)
129
+ try:
130
+ for handler in self._handlers.get(envelope.event_type, ()):
131
+ await handler(envelope)
132
+ except Exception:
133
+ await message.nack(requeue=False)
134
+ raise
135
+ await message.ack()
136
+
137
+ async def dead_letter_count(self) -> int:
138
+ await self._ensure()
139
+ queue = await self._channel.declare_queue("swiftapi.dead", durable=True)
140
+ declared = await queue.declare()
141
+ return int(declared.message_count)
142
+
143
+ async def purge(self) -> None:
144
+ """测试辅助:清空业务队列与死信队列。"""
145
+ await self._ensure()
146
+ for queue in (self._main_queue, await self._channel.declare_queue("swiftapi.dead", durable=True)):
147
+ await queue.purge()
148
+
149
+ async def close(self) -> None:
150
+ if self._connection is not None:
151
+ await self._connection.close()
152
+ self._connection = None
153
+ self._channel = None
154
+ self._exchange = None
155
+ self._dlx = None
156
+
157
+
158
+ def _encode(envelope: EventEnvelope) -> bytes:
159
+ return json.dumps(
160
+ {
161
+ "event_id": str(envelope.event_id),
162
+ "event_type": envelope.event_type,
163
+ "event_version": envelope.event_version,
164
+ "occurred_at": envelope.occurred_at.isoformat(),
165
+ "trace_id": envelope.trace_id,
166
+ "tenant_id": str(envelope.tenant_id) if envelope.tenant_id else None,
167
+ "payload": envelope.payload,
168
+ },
169
+ ensure_ascii=False,
170
+ ).encode()
171
+
172
+
173
+ def _decode(body: bytes) -> EventEnvelope:
174
+ data = json.loads(body)
175
+ return EventEnvelope(
176
+ event_id=UUID(data["event_id"]),
177
+ event_type=data["event_type"],
178
+ event_version=int(data["event_version"]),
179
+ occurred_at=datetime.fromisoformat(data["occurred_at"]),
180
+ trace_id=data.get("trace_id"),
181
+ tenant_id=UUID(data["tenant_id"]) if data.get("tenant_id") else None,
182
+ payload=data.get("payload") or {},
183
+ )
184
+
185
+
186
+ __all__ = ["RabbitMQBus"]
@@ -0,0 +1,151 @@
1
+ """Outbox 中继:轮询 → 投递 → 标记;失败退避,超过上限转死信。
2
+
3
+ 顺序性:同一 aggregate 依赖 `ORDER BY created_at, id` + 单实例中继。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import uuid
9
+ from dataclasses import dataclass
10
+ from datetime import UTC, datetime, timedelta
11
+ from typing import Any, cast
12
+
13
+ from sqlalchemy import select, update
14
+ from sqlalchemy.engine import CursorResult
15
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
16
+
17
+ from swiftapi.core.messaging.base import EventEnvelope, MessageBus
18
+ from swiftapi.core.messaging.outbox import DEAD, PENDING, PUBLISHED, OutboxMessage
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class RelayResult:
23
+ published: int
24
+ failed: int
25
+ dead: int
26
+
27
+
28
+ class OutboxRelay:
29
+ def __init__(
30
+ self,
31
+ session_factory: async_sessionmaker[AsyncSession],
32
+ bus: MessageBus,
33
+ *,
34
+ max_attempts: int = 12,
35
+ batch_size: int = 100,
36
+ base_delay_s: float = 1.0,
37
+ lease_s: float = 60.0,
38
+ ) -> None:
39
+ self.session_factory = session_factory
40
+ self.bus = bus
41
+ self.max_attempts = max_attempts
42
+ self.batch_size = batch_size
43
+ self.base_delay_s = base_delay_s
44
+ # 租约:claim 后 next_retry_at 推到 now+lease_s。进程崩溃时最多等一个租约,
45
+ # 不会永久卡住;正常投递成功会立即标记 published。
46
+ self.lease_s = lease_s
47
+
48
+ async def run_once(self, *, now: datetime | None = None) -> RelayResult:
49
+ moment = now or datetime.now(UTC)
50
+ compare_at = moment # 时区归一化由 UTCDateTime 负责
51
+ published = failed = dead = 0
52
+
53
+ async with self.session_factory() as session:
54
+ statement = (
55
+ select(OutboxMessage)
56
+ .where(
57
+ OutboxMessage.status == PENDING,
58
+ OutboxMessage.next_retry_at <= compare_at,
59
+ )
60
+ .order_by(OutboxMessage.created_at, OutboxMessage.id)
61
+ .limit(self.batch_size)
62
+ )
63
+ # PG / MySQL:锁住本批行,其它副本直接跳过(不排队等锁)。
64
+ # SQLite 不支持 SKIP LOCKED,靠下面的 CAS 租约保证同一行只被 claim 一次。
65
+ dialect = session.bind.dialect.name if session.bind is not None else "sqlite"
66
+ if dialect in {"postgresql", "mysql"}:
67
+ statement = statement.with_for_update(skip_locked=True)
68
+
69
+ rows = (await session.execute(statement)).scalars().all()
70
+ claimed: list[OutboxMessage] = []
71
+ for row in rows:
72
+ result = await session.execute(
73
+ update(OutboxMessage)
74
+ .where(
75
+ OutboxMessage.id == row.id,
76
+ OutboxMessage.status == PENDING,
77
+ OutboxMessage.next_retry_at <= compare_at,
78
+ )
79
+ .values(next_retry_at=moment + timedelta(seconds=self.lease_s))
80
+ )
81
+ if cast(CursorResult[Any], result).rowcount:
82
+ claimed.append(row)
83
+ # 先提交 claim:进程崩溃后其它副本等一个租约即可接手,
84
+ # 不会出现"锁一直挂在未提交事务里"。
85
+ await session.commit()
86
+
87
+ for row in claimed:
88
+ envelope = _to_envelope(row)
89
+ try:
90
+ await self.bus.publish(envelope)
91
+ except Exception:
92
+ attempts = row.attempts + 1
93
+ if attempts >= self.max_attempts:
94
+ await self._finish(row.id, status=DEAD, attempts=attempts, when=moment)
95
+ dead += 1
96
+ else:
97
+ retry_at = moment + timedelta(
98
+ seconds=self.base_delay_s * (2 ** (attempts - 1))
99
+ )
100
+ await self._finish(
101
+ row.id, status=PENDING, attempts=attempts, when=retry_at
102
+ )
103
+ failed += 1
104
+ else:
105
+ await self._finish(
106
+ row.id, status=PUBLISHED, attempts=row.attempts, when=moment, published=True
107
+ )
108
+ published += 1
109
+
110
+ return RelayResult(published=published, failed=failed, dead=dead)
111
+
112
+ async def _finish(
113
+ self,
114
+ message_id: uuid.UUID,
115
+ *,
116
+ status: str,
117
+ attempts: int,
118
+ when: datetime,
119
+ published: bool = False,
120
+ ) -> None:
121
+ async with self.session_factory() as session:
122
+ values: dict[str, object] = {
123
+ "status": status,
124
+ "attempts": attempts,
125
+ "next_retry_at": when,
126
+ }
127
+ if published:
128
+ values["published_at"] = when
129
+ await session.execute(
130
+ update(OutboxMessage).where(OutboxMessage.id == message_id).values(**values)
131
+ )
132
+ await session.commit()
133
+
134
+
135
+ def _to_envelope(row: OutboxMessage) -> EventEnvelope:
136
+ payload = dict(row.payload)
137
+ trace_id = payload.pop("_trace_id", None)
138
+ tenant_raw = payload.pop("_tenant_id", None)
139
+
140
+ return EventEnvelope(
141
+ event_id=row.id,
142
+ event_type=row.event_type,
143
+ event_version=row.event_version,
144
+ occurred_at=row.created_at,
145
+ trace_id=trace_id,
146
+ tenant_id=uuid.UUID(tenant_raw) if tenant_raw else None,
147
+ payload=payload,
148
+ )
149
+
150
+
151
+ __all__ = ["OutboxRelay", "RelayResult"]