swiftpy-framework 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.
Files changed (211) hide show
  1. swiftpy/.gitignore +0 -0
  2. swiftpy/__init__.py +572 -0
  3. swiftpy/admin/__init__.py +50 -0
  4. swiftpy/admin/auth.py +522 -0
  5. swiftpy/admin/registry.py +567 -0
  6. swiftpy/admin/views.py +1583 -0
  7. swiftpy/ai/__init__.py +199 -0
  8. swiftpy/ai/_deterministic.py +40 -0
  9. swiftpy/ai/_fake.py +604 -0
  10. swiftpy/ai/agents/__init__.py +30 -0
  11. swiftpy/ai/agents/base_agent.py +506 -0
  12. swiftpy/ai/agents/memory.py +864 -0
  13. swiftpy/ai/client.py +1011 -0
  14. swiftpy/ai/conversation.py +171 -0
  15. swiftpy/ai/embeddings.py +321 -0
  16. swiftpy/ai/exceptions.py +75 -0
  17. swiftpy/ai/history_strategies.py +157 -0
  18. swiftpy/ai/middleware.py +918 -0
  19. swiftpy/ai/observability/__init__.py +28 -0
  20. swiftpy/ai/observability/drivers.py +763 -0
  21. swiftpy/ai/observability/observer.py +364 -0
  22. swiftpy/ai/pool.py +102 -0
  23. swiftpy/ai/pricing.py +101 -0
  24. swiftpy/ai/prompts/__init__.py +6 -0
  25. swiftpy/ai/prompts/loader.py +343 -0
  26. swiftpy/ai/providers/__init__.py +22 -0
  27. swiftpy/ai/providers/anthropic_provider.py +353 -0
  28. swiftpy/ai/providers/base.py +273 -0
  29. swiftpy/ai/providers/openai_provider.py +275 -0
  30. swiftpy/ai/rag/__init__.py +53 -0
  31. swiftpy/ai/rag/context_formatter.py +263 -0
  32. swiftpy/ai/rag/pipeline_builder.py +544 -0
  33. swiftpy/ai/rag/reranker.py +484 -0
  34. swiftpy/ai/rag/result.py +78 -0
  35. swiftpy/ai/rag/retriever.py +315 -0
  36. swiftpy/ai/redis_store.py +227 -0
  37. swiftpy/ai/streaming.py +115 -0
  38. swiftpy/ai/tools/__init__.py +22 -0
  39. swiftpy/ai/tools/base_tool.py +489 -0
  40. swiftpy/ai/tools/first_party.py +384 -0
  41. swiftpy/ai/tools/tool_loop.py +417 -0
  42. swiftpy/ai/vectorstore/__init__.py +46 -0
  43. swiftpy/ai/vectorstore/base.py +542 -0
  44. swiftpy/ai/vectorstore/chroma_adapter.py +435 -0
  45. swiftpy/ai/vectorstore/in_memory_adapter.py +321 -0
  46. swiftpy/ai/vectorstore/lancedb_adapter.py +370 -0
  47. swiftpy/ai/vectorstore/pgvector_adapter.py +496 -0
  48. swiftpy/ai/vectorstore/pinecone_adapter.py +445 -0
  49. swiftpy/ai/vectorstore/qdrant_adapter.py +418 -0
  50. swiftpy/auth/__init__.py +50 -0
  51. swiftpy/auth/api_key_guard.py +544 -0
  52. swiftpy/auth/auth_manager.py +259 -0
  53. swiftpy/auth/exceptions.py +71 -0
  54. swiftpy/auth/jwt_guard.py +230 -0
  55. swiftpy/auth/jwt_issuer.py +658 -0
  56. swiftpy/auth/token_blacklist.py +300 -0
  57. swiftpy/cache/__init__.py +14 -0
  58. swiftpy/cache/cache.py +251 -0
  59. swiftpy/cache/driver.py +216 -0
  60. swiftpy/cache/drivers/memory.py +199 -0
  61. swiftpy/cache/drivers/redis.py +421 -0
  62. swiftpy/console/__init__.py +0 -0
  63. swiftpy/console/cli.py +68 -0
  64. swiftpy/console/commands/__init__.py +0 -0
  65. swiftpy/console/commands/cache.py +164 -0
  66. swiftpy/console/commands/make.py +935 -0
  67. swiftpy/console/commands/migrate.py +280 -0
  68. swiftpy/console/commands/new.py +1806 -0
  69. swiftpy/console/commands/queue.py +306 -0
  70. swiftpy/console/commands/seed.py +252 -0
  71. swiftpy/console/commands/start.py +171 -0
  72. swiftpy/console/commands/storage.py +104 -0
  73. swiftpy/console/loader.py +21 -0
  74. swiftpy/console/stubs/__init__.py +26 -0
  75. swiftpy/console/stubs/controller.stub +14 -0
  76. swiftpy/console/stubs/event.stub +14 -0
  77. swiftpy/console/stubs/job.stub +22 -0
  78. swiftpy/console/stubs/listener.stub +14 -0
  79. swiftpy/console/stubs/mail.stub +20 -0
  80. swiftpy/console/stubs/middleware.stub +16 -0
  81. swiftpy/console/stubs/migration.alter.stub +17 -0
  82. swiftpy/console/stubs/migration.api_keys.stub +22 -0
  83. swiftpy/console/stubs/migration.blank.stub +11 -0
  84. swiftpy/console/stubs/migration.create.stub +15 -0
  85. swiftpy/console/stubs/migration.stub +11 -0
  86. swiftpy/console/stubs/migration.update.stub +17 -0
  87. swiftpy/console/stubs/model.stub +17 -0
  88. swiftpy/console/stubs/provider.stub +18 -0
  89. swiftpy/console/stubs/repository.stub +10 -0
  90. swiftpy/console/stubs/request.stub +16 -0
  91. swiftpy/console/stubs/resource.stub +21 -0
  92. swiftpy/console/stubs/schema.stub +12 -0
  93. swiftpy/console/stubs/seeder.stub +14 -0
  94. swiftpy/console/stubs/service.stub +10 -0
  95. swiftpy/core/__init__.py +0 -0
  96. swiftpy/core/application.py +1306 -0
  97. swiftpy/core/bootstrap.py +30 -0
  98. swiftpy/core/config.py +432 -0
  99. swiftpy/core/container.py +596 -0
  100. swiftpy/core/container_exceptions.py +18 -0
  101. swiftpy/core/context.py +148 -0
  102. swiftpy/core/exceptions.py +352 -0
  103. swiftpy/core/providers/base.py +35 -0
  104. swiftpy/database/__init__.py +41 -0
  105. swiftpy/database/exceptions.py +42 -0
  106. swiftpy/database/identifiers.py +105 -0
  107. swiftpy/database/migrations/__init__.py +36 -0
  108. swiftpy/database/migrations/blueprint.py +431 -0
  109. swiftpy/database/migrations/lock.py +104 -0
  110. swiftpy/database/migrations/migration.py +22 -0
  111. swiftpy/database/migrations/migrator.py +507 -0
  112. swiftpy/database/migrations/schema.py +435 -0
  113. swiftpy/database/orm/__init__.py +33 -0
  114. swiftpy/database/orm/fields.py +92 -0
  115. swiftpy/database/orm/model.py +2034 -0
  116. swiftpy/database/orm/registry.py +33 -0
  117. swiftpy/database/orm/relationships.py +836 -0
  118. swiftpy/database/pagination/__init__.py +16 -0
  119. swiftpy/database/pagination/contracts.py +60 -0
  120. swiftpy/database/pagination/paginator.py +112 -0
  121. swiftpy/database/pagination/simple_paginator.py +97 -0
  122. swiftpy/database/pool.py +218 -0
  123. swiftpy/database/query_builder.py +1803 -0
  124. swiftpy/database/seeder.py +39 -0
  125. swiftpy/database/transaction.py +276 -0
  126. swiftpy/events/__init__.py +10 -0
  127. swiftpy/events/dispatcher.py +308 -0
  128. swiftpy/events/redis_bus.py +552 -0
  129. swiftpy/filesystem/__init__.py +227 -0
  130. swiftpy/filesystem/disk.py +378 -0
  131. swiftpy/filesystem/drivers/__init__.py +11 -0
  132. swiftpy/filesystem/drivers/base.py +156 -0
  133. swiftpy/filesystem/drivers/local.py +559 -0
  134. swiftpy/filesystem/drivers/s3.py +655 -0
  135. swiftpy/filesystem/events.py +37 -0
  136. swiftpy/filesystem/exceptions.py +127 -0
  137. swiftpy/filesystem/manager.py +138 -0
  138. swiftpy/filesystem/metadata.py +22 -0
  139. swiftpy/filesystem/paths.py +99 -0
  140. swiftpy/filesystem/service_provider.py +17 -0
  141. swiftpy/filesystem/uploads/__init__.py +13 -0
  142. swiftpy/filesystem/uploads/handlers.py +362 -0
  143. swiftpy/filesystem/uploads/uploaded_file.py +222 -0
  144. swiftpy/filesystem/uploads/validators.py +186 -0
  145. swiftpy/filesystem/visibility.py +22 -0
  146. swiftpy/helpers/__init__.py +42 -0
  147. swiftpy/helpers/helper.py +180 -0
  148. swiftpy/http/exceptions.py +41 -0
  149. swiftpy/http/middleware.py +307 -0
  150. swiftpy/http/request.py +375 -0
  151. swiftpy/http/response.py +442 -0
  152. swiftpy/http/router.py +1050 -0
  153. swiftpy/mail/__init__.py +58 -0
  154. swiftpy/mail/attachments.py +255 -0
  155. swiftpy/mail/config.py +71 -0
  156. swiftpy/mail/envelope.py +183 -0
  157. swiftpy/mail/exceptions.py +90 -0
  158. swiftpy/mail/facade.py +312 -0
  159. swiftpy/mail/mailable.py +53 -0
  160. swiftpy/mail/manager.py +240 -0
  161. swiftpy/mail/message.py +186 -0
  162. swiftpy/mail/models.py +19 -0
  163. swiftpy/mail/queue/__init__.py +5 -0
  164. swiftpy/mail/queue/job.py +279 -0
  165. swiftpy/mail/service_provider.py +19 -0
  166. swiftpy/mail/templates/__init__.py +5 -0
  167. swiftpy/mail/templates/renderer.py +173 -0
  168. swiftpy/mail/transports/__init__.py +21 -0
  169. swiftpy/mail/transports/api/__init__.py +13 -0
  170. swiftpy/mail/transports/api/base.py +194 -0
  171. swiftpy/mail/transports/api/mailgun.py +158 -0
  172. swiftpy/mail/transports/api/resend.py +156 -0
  173. swiftpy/mail/transports/api/sendgrid.py +172 -0
  174. swiftpy/mail/transports/base.py +24 -0
  175. swiftpy/mail/transports/console.py +91 -0
  176. swiftpy/mail/transports/sendmail.py +128 -0
  177. swiftpy/mail/transports/smtp.py +466 -0
  178. swiftpy/queue/__init__.py +13 -0
  179. swiftpy/queue/dispatcher.py +813 -0
  180. swiftpy/queue/job.py +541 -0
  181. swiftpy/queue/worker.py +556 -0
  182. swiftpy/support/__init__.py +12 -0
  183. swiftpy/support/keys.py +108 -0
  184. swiftpy/support/redis_config.py +223 -0
  185. swiftpy/support/strings.py +114 -0
  186. swiftpy/testing/__init__.py +20 -0
  187. swiftpy/testing/fakes/__init__.py +11 -0
  188. swiftpy/testing/fakes/ai_fake.py +21 -0
  189. swiftpy/testing/fakes/vectorstore_fake.py +194 -0
  190. swiftpy/testing/fixtures.py +124 -0
  191. swiftpy/testing/http_client.py +730 -0
  192. swiftpy/testing/test_case.py +126 -0
  193. swiftpy/validation/__init__.py +97 -0
  194. swiftpy/validation/exceptions.py +26 -0
  195. swiftpy/validation/form_request.py +302 -0
  196. swiftpy/validation/protocols.py +33 -0
  197. swiftpy/validation/rules/__init__.py +89 -0
  198. swiftpy/validation/rules/builtin.py +391 -0
  199. swiftpy/validation/rules/exists.py +86 -0
  200. swiftpy/validation/rules/registry.py +290 -0
  201. swiftpy/validation/rules/required.py +55 -0
  202. swiftpy/validation/rules/unique.py +138 -0
  203. swiftpy/validation/validator.py +612 -0
  204. swiftpy/websockets/__init__.py +19 -0
  205. swiftpy/websockets/connection.py +317 -0
  206. swiftpy/websockets/manager.py +271 -0
  207. swiftpy_framework-0.1.0.dist-info/METADATA +603 -0
  208. swiftpy_framework-0.1.0.dist-info/RECORD +211 -0
  209. swiftpy_framework-0.1.0.dist-info/WHEEL +4 -0
  210. swiftpy_framework-0.1.0.dist-info/entry_points.txt +2 -0
  211. swiftpy_framework-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import logging
5
+ from abc import ABC, abstractmethod
6
+
7
+ logger = logging.getLogger("swiftpy.database.seeder")
8
+
9
+
10
+ class Seeder(ABC):
11
+ """
12
+ Abstract base class for all SwiftPY database seeders.
13
+ Subclasses implement the async `run()` method to populate database records.
14
+ """
15
+
16
+ @abstractmethod
17
+ async def run(self) -> None:
18
+ """Execute the database seed operations."""
19
+ raise NotImplementedError
20
+
21
+ async def call(self, *seeder_classes: type[Seeder]) -> None:
22
+ """Execute a sequence of child seeders."""
23
+ for seeder_cls in seeder_classes:
24
+ if (
25
+ not isinstance(seeder_cls, type)
26
+ or not issubclass(seeder_cls, Seeder)
27
+ or inspect.isabstract(seeder_cls)
28
+ ):
29
+ cls_name = getattr(seeder_cls, "__name__", str(seeder_cls))
30
+ raise TypeError(
31
+ f"Invalid seeder class '{cls_name}': Must be a non-abstract subclass of Seeder."
32
+ )
33
+ logger.info("Running seeder: %s", seeder_cls.__name__)
34
+ seeder = seeder_cls()
35
+ await seeder.run()
36
+
37
+
38
+ __all__ = ["Seeder"]
39
+
@@ -0,0 +1,276 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import inspect
5
+ import logging
6
+ from collections.abc import AsyncGenerator, Callable
7
+ from contextlib import asynccontextmanager
8
+ from contextvars import ContextVar
9
+ from typing import Any
10
+
11
+ import asyncpg
12
+
13
+ from swiftpy.core.container import get_container
14
+ from swiftpy.database.pool import DatabasePool
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class TransactionClosedError(RuntimeError):
20
+ """Raised when a transaction connection handle is used after the transaction block has exited."""
21
+
22
+
23
+ class TransactionConnection:
24
+ """
25
+ Safe handle wrapping an active transaction's asyncpg.Connection (P3-D4).
26
+
27
+ Enforces:
28
+ 1. Explicit closed state: once the transaction block exits, the handle is closed
29
+ and any subsequent access (e.g. from child tasks that inherited the ContextVar)
30
+ raises TransactionClosedError instead of touching the released pool connection.
31
+ 2. Per-transaction asyncio.Lock: concurrent operations on the same transaction
32
+ connection are serialized automatically instead of raising asyncpg.InterfaceError.
33
+ Note: Database transactions share a single connection and are not for query parallelism.
34
+ """
35
+
36
+ def __init__(self, conn: asyncpg.Connection) -> None:
37
+ self._conn: asyncpg.Connection | None = conn
38
+ self._lock = asyncio.Lock()
39
+ self.closed: bool = False
40
+ self._tx_depth: int = 0
41
+ self._commit_callbacks: list[list[Callable[[], Any]]] = []
42
+ self._pending_callbacks: list[Callable[[], Any]] = []
43
+
44
+ def on_commit(self, callback: Callable[[], Any]) -> None:
45
+ """Register a callback to be executed after the outermost transaction successfully commits."""
46
+ self._ensure_open()
47
+ if not self._commit_callbacks:
48
+ self._commit_callbacks.append([])
49
+ self._commit_callbacks[-1].append(callback)
50
+
51
+ def drain_commit_callbacks(self) -> list[Callable[[], Any]]:
52
+ """Pop queued callbacks belonging to an already-committed outermost transaction."""
53
+ callbacks = list(self._pending_callbacks)
54
+ self._pending_callbacks.clear()
55
+ return callbacks
56
+
57
+ @staticmethod
58
+ async def run_commit_callbacks(callbacks: list[Callable[[], Any]]) -> None:
59
+ for cb in callbacks:
60
+ try:
61
+ res = cb()
62
+ if inspect.isawaitable(res):
63
+ await res
64
+ except Exception:
65
+ logger.exception("Error executing on_commit callback %r", cb)
66
+
67
+ async def _run_commit_callbacks(self, callbacks: list[Callable[[], Any]]) -> None:
68
+ await self.run_commit_callbacks(callbacks)
69
+
70
+ def _ensure_open(self) -> asyncpg.Connection:
71
+ if self.closed or self._conn is None:
72
+ raise TransactionClosedError(
73
+ "Cannot use transaction connection after the transaction block has exited."
74
+ )
75
+ return self._conn
76
+
77
+ def _close(self) -> None:
78
+ self.closed = True
79
+ self._conn = None
80
+
81
+ def close(self) -> None:
82
+ """Mark this transaction handle closed and release its underlying reference."""
83
+ self._close()
84
+
85
+ async def rollback_transaction(self, tx: Any) -> None:
86
+ """Acquire the serialized handle lock and roll back the given transaction."""
87
+ async with self._lock:
88
+ if self._conn is not None:
89
+ await tx.rollback()
90
+
91
+ async def fetch(
92
+ self, query: str, *args: Any, timeout: float | None = None
93
+ ) -> list[Any]:
94
+ self._ensure_open()
95
+ async with self._lock:
96
+ conn = self._ensure_open()
97
+ rows = await conn.fetch(query, *args, timeout=timeout)
98
+ return list(rows)
99
+
100
+ async def fetchrow(
101
+ self, query: str, *args: Any, timeout: float | None = None
102
+ ) -> Any:
103
+ self._ensure_open()
104
+ async with self._lock:
105
+ conn = self._ensure_open()
106
+ return await conn.fetchrow(query, *args, timeout=timeout)
107
+
108
+ async def fetchval(
109
+ self,
110
+ query: str,
111
+ *args: Any,
112
+ column: int = 0,
113
+ timeout: float | None = None,
114
+ ) -> Any:
115
+ self._ensure_open()
116
+ async with self._lock:
117
+ conn = self._ensure_open()
118
+ return await conn.fetchval(query, *args, column=column, timeout=timeout)
119
+
120
+ async def execute(
121
+ self, query: str, *args: Any, timeout: float | None = None
122
+ ) -> str:
123
+ self._ensure_open()
124
+ async with self._lock:
125
+ conn = self._ensure_open()
126
+ res = await conn.execute(query, *args, timeout=timeout)
127
+ return str(res)
128
+
129
+ async def executemany(
130
+ self, command: str, args: Any, *, timeout: float | None = None
131
+ ) -> None:
132
+ self._ensure_open()
133
+ async with self._lock:
134
+ conn = self._ensure_open()
135
+ await conn.executemany(command, args, timeout=timeout)
136
+
137
+ @asynccontextmanager
138
+ async def transaction(
139
+ self, *, defer_callbacks: bool = False, **kwargs: Any
140
+ ) -> AsyncGenerator[TransactionConnection, None]:
141
+ self._ensure_open()
142
+ async with self._lock:
143
+ conn = self._ensure_open()
144
+ tx = conn.transaction(**kwargs)
145
+ await tx.start()
146
+ self._tx_depth += 1
147
+ self._commit_callbacks.append([])
148
+ try:
149
+ yield self
150
+ except BaseException:
151
+ async with self._lock:
152
+ self._tx_depth -= 1
153
+ if self._commit_callbacks:
154
+ self._commit_callbacks.pop()
155
+ if self._conn is not None:
156
+ await tx.rollback()
157
+ raise
158
+ else:
159
+ callbacks_to_run: list[Callable[[], Any]] = []
160
+ async with self._lock:
161
+ self._tx_depth -= 1
162
+ level_callbacks = (
163
+ self._commit_callbacks.pop() if self._commit_callbacks else []
164
+ )
165
+ if self._tx_depth > 0:
166
+ if self._commit_callbacks:
167
+ self._commit_callbacks[-1].extend(level_callbacks)
168
+ elif defer_callbacks:
169
+ self._pending_callbacks.extend(level_callbacks)
170
+ else:
171
+ callbacks_to_run = level_callbacks
172
+ conn = self._ensure_open()
173
+ await tx.commit()
174
+
175
+ if callbacks_to_run:
176
+ await self.run_commit_callbacks(callbacks_to_run)
177
+
178
+ def __getattr__(self, name: str) -> Any:
179
+ conn = self._ensure_open()
180
+ return getattr(conn, name)
181
+
182
+
183
+ _active_connection: ContextVar[Any] = ContextVar(
184
+ "swiftpy_active_connection",
185
+ default=None,
186
+ )
187
+
188
+
189
+ def get_active_connection() -> Any:
190
+ conn = _active_connection.get()
191
+ if conn is not None and getattr(conn, "closed", False):
192
+ raise TransactionClosedError(
193
+ "Cannot use transaction connection after the transaction block has exited."
194
+ )
195
+ return conn
196
+
197
+
198
+ def on_commit(callback: Callable[[], Any]) -> None:
199
+ """
200
+ Register a callback to run after the active transaction successfully commits.
201
+ If no database transaction is active, the callback is executed immediately.
202
+ """
203
+ conn = get_active_connection()
204
+ if conn is not None and hasattr(conn, "on_commit"):
205
+ conn.on_commit(callback)
206
+ else:
207
+ res = callback()
208
+ if inspect.isawaitable(res):
209
+ try:
210
+ loop = asyncio.get_running_loop()
211
+ fut: asyncio.Future[Any] = asyncio.ensure_future(res, loop=loop)
212
+
213
+ def _log_err(t: asyncio.Future[Any]) -> None:
214
+ if not t.cancelled() and t.exception():
215
+ logger.exception(
216
+ "Async on_commit callback failed", exc_info=t.exception()
217
+ )
218
+
219
+ fut.add_done_callback(_log_err)
220
+ except RuntimeError:
221
+ pass
222
+
223
+
224
+ class Database:
225
+ """
226
+ Database transaction manager.
227
+ Note: Transactions share a single database connection and serialize concurrent
228
+ operations via an internal lock; they are not intended for query parallelism.
229
+ """
230
+
231
+ def on_commit(self, callback: Callable[[], Any]) -> None:
232
+ """Register a callback to run after the active transaction commits, or immediately if none."""
233
+ on_commit(callback)
234
+
235
+ @asynccontextmanager
236
+ async def transaction(self) -> AsyncGenerator[Any, None]:
237
+ existing = get_active_connection()
238
+
239
+ if existing is not None:
240
+ async with existing.transaction():
241
+ yield existing
242
+ return
243
+
244
+ container = get_container()
245
+
246
+ db_pool = container.resolve(DatabasePool)
247
+
248
+ pool = db_pool.get_pool()
249
+
250
+ committed_callbacks: list[Callable[[], Any]] = []
251
+ async with pool.acquire() as conn:
252
+ handle = TransactionConnection(conn)
253
+ token = _active_connection.set(handle)
254
+
255
+ try:
256
+ async with handle.transaction(defer_callbacks=True):
257
+ yield handle
258
+ committed_callbacks = handle.drain_commit_callbacks()
259
+ finally:
260
+ handle.close()
261
+ _active_connection.reset(token)
262
+
263
+ if committed_callbacks:
264
+ await TransactionConnection.run_commit_callbacks(committed_callbacks)
265
+
266
+
267
+ db = Database()
268
+
269
+ __all__ = [
270
+ "Database",
271
+ "TransactionClosedError",
272
+ "TransactionConnection",
273
+ "db",
274
+ "get_active_connection",
275
+ "on_commit",
276
+ ]
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from swiftpy.events.dispatcher import EventDispatcher, EventHandler
4
+ from swiftpy.events.redis_bus import RedisEventBus
5
+
6
+ __all__ = [
7
+ "EventDispatcher",
8
+ "EventHandler",
9
+ "RedisEventBus",
10
+ ]
@@ -0,0 +1,308 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import re
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from typing import Any, ClassVar
8
+
9
+ from swiftpy.core.container import get_container
10
+
11
+ EventHandler = Callable[..., Any]
12
+
13
+
14
+ def _build_invoker(handler: EventHandler) -> Callable[[str, Any], Any]:
15
+ """Inspect and precompile an invocation strategy for the given handler."""
16
+ try:
17
+ sig = inspect.signature(handler)
18
+ except (ValueError, TypeError):
19
+ def _fallback(event: str, payload: Any) -> Any:
20
+ try:
21
+ return handler(payload)
22
+ except TypeError:
23
+ return handler()
24
+
25
+ return _fallback
26
+
27
+ params = list(sig.parameters.values())
28
+
29
+ pos_params = [
30
+ p
31
+ for p in params
32
+ if p.kind
33
+ in (
34
+ inspect.Parameter.POSITIONAL_ONLY,
35
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
36
+ )
37
+ ]
38
+ has_var_pos = any(p.kind == inspect.Parameter.VAR_POSITIONAL for p in params)
39
+ kw_only = [p for p in params if p.kind == inspect.Parameter.KEYWORD_ONLY]
40
+ has_var_kw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params)
41
+
42
+ req_pos = sum(1 for p in pos_params if p.default is inspect.Parameter.empty)
43
+ num_pos = len(pos_params)
44
+
45
+ if req_pos >= 2 or (
46
+ num_pos >= 2
47
+ and pos_params[0].name in ("event", "event_name")
48
+ and pos_params[1].name == "payload"
49
+ ):
50
+ pos_mode = 2
51
+ elif num_pos >= 1 or has_var_pos:
52
+ pos_mode = 1
53
+ else:
54
+ pos_mode = 0
55
+
56
+ kw_names = tuple(p.name for p in kw_only)
57
+ pass_all_kw = has_var_kw and not kw_only and pos_mode == 0 and not has_var_pos
58
+
59
+ def _compiled_invoker(event: str, payload: Any) -> Any:
60
+ pos_args: tuple[Any, ...]
61
+ if pos_mode == 2:
62
+ pos_args = (event, payload)
63
+ elif pos_mode == 1:
64
+ pos_args = (payload,)
65
+ else:
66
+ pos_args = ()
67
+
68
+ if pass_all_kw:
69
+ return handler(*pos_args, event=event, payload=payload)
70
+
71
+ if kw_names:
72
+ kwargs: dict[str, Any] = {}
73
+ for name in kw_names:
74
+ if name == "payload":
75
+ kwargs["payload"] = payload
76
+ elif name == "event":
77
+ kwargs["event"] = event
78
+ return handler(*pos_args, **kwargs)
79
+
80
+ return handler(*pos_args)
81
+
82
+ return _compiled_invoker
83
+
84
+
85
+ @dataclass(slots=True)
86
+ class _ListenerRegistration:
87
+ pattern: str
88
+ regex: re.Pattern[str] | None
89
+ handler: EventHandler
90
+ order: int
91
+ invoker: Callable[[str, Any], Any]
92
+
93
+
94
+ def _normalize_event_name(event: str | type[Any] | Any) -> str:
95
+ if isinstance(event, str):
96
+ return event
97
+ if isinstance(event, type):
98
+ module = getattr(event, "__module__", "")
99
+ qualname = getattr(event, "__qualname__", event.__name__)
100
+ return f"{module}.{qualname}" if module and module != "__main__" else qualname
101
+
102
+ event_type = type(event)
103
+ module = getattr(event_type, "__module__", "")
104
+ qualname = getattr(event_type, "__qualname__", event_type.__name__)
105
+ return f"{module}.{qualname}" if module and module != "__main__" else qualname
106
+
107
+
108
+ class EventDispatcher:
109
+ """
110
+ In-process event dispatcher supporting synchronous and asynchronous listeners,
111
+ exact and segment-scoped wildcard event patterns, global registration-order
112
+ execution, signature caching, and fail-fast exception propagation.
113
+ """
114
+
115
+ _instance: ClassVar[EventDispatcher | None] = None
116
+
117
+ def __init__(self) -> None:
118
+ self._exact_registry: dict[str, list[_ListenerRegistration]] = {}
119
+ self._wildcard_registry: list[_ListenerRegistration] = []
120
+ self._registry: list[_ListenerRegistration] = []
121
+ self._seq: int = 0
122
+
123
+ @classmethod
124
+ def get_instance(cls) -> EventDispatcher:
125
+ """Retrieve the active application's EventDispatcher from the container, or fallback instance."""
126
+ try:
127
+ container = get_container()
128
+ if container.has(cls):
129
+ return container.resolve(cls)
130
+ except RuntimeError:
131
+ pass
132
+
133
+ if cls._instance is None:
134
+ cls._instance = cls()
135
+ return cls._instance
136
+
137
+ @classmethod
138
+ def set_instance(cls, dispatcher: EventDispatcher | None) -> None:
139
+ """Override or reset the EventDispatcher instance in the active container and fallback."""
140
+ cls._instance = dispatcher
141
+ try:
142
+ container = get_container()
143
+ if container.has(cls):
144
+ if dispatcher is not None:
145
+ container.instance(cls, dispatcher)
146
+ else:
147
+ container.singleton(cls, lambda _: cls())
148
+ except RuntimeError:
149
+ pass
150
+
151
+ def _compile_pattern(self, pattern: str) -> re.Pattern[str] | None:
152
+ """
153
+ Compile an event pattern into regex.
154
+ - '*' alone matches all events.
155
+ - Single '*' within a segmented pattern matches exactly one segment ([^.]+).
156
+ - Double '**' within a pattern matches zero or more segments (.*).
157
+ - Patterns without '*' return None for O(1) exact string matching.
158
+ """
159
+ if "*" not in pattern:
160
+ return None
161
+
162
+ if pattern == "*":
163
+ return re.compile(r"^.*$")
164
+
165
+ # Protect double star '**' before escaping
166
+ token = "__SWIFTPY_DOUBLE_STAR__"
167
+ p = pattern.replace("**", token)
168
+ escaped = re.escape(p)
169
+ # Convert single star to one segment
170
+ escaped = escaped.replace(r"\*", r"[^.]+")
171
+ # Restore double star to any characters
172
+ escaped = escaped.replace(token, r".*")
173
+ return re.compile(f"^{escaped}$")
174
+
175
+ def listen(self, event: str | type[Any], handler: EventHandler) -> None:
176
+ """
177
+ Register an event listener for a specific event or wildcard pattern.
178
+ Example patterns: 'user.created', 'user.*', '*.created', 'user.**', '*'
179
+ """
180
+ event_str = _normalize_event_name(event)
181
+ regex = self._compile_pattern(event_str)
182
+ invoker = _build_invoker(handler)
183
+ reg = _ListenerRegistration(
184
+ pattern=event_str,
185
+ regex=regex,
186
+ handler=handler,
187
+ order=self._seq,
188
+ invoker=invoker,
189
+ )
190
+ self._seq += 1
191
+ self._registry.append(reg)
192
+ if regex is None:
193
+ self._exact_registry.setdefault(event_str, []).append(reg)
194
+ else:
195
+ self._wildcard_registry.append(reg)
196
+
197
+ def has_listeners(self, event: str | type[Any]) -> bool:
198
+ """Determine whether any listeners match the given event."""
199
+ event_str = _normalize_event_name(event)
200
+ if self._exact_registry.get(event_str):
201
+ return True
202
+ for reg in self._wildcard_registry:
203
+ if reg.regex is not None and reg.regex.match(event_str):
204
+ return True
205
+ return False
206
+
207
+ def get_matching_registrations(self, event: str | type[Any]) -> list[_ListenerRegistration]:
208
+ """
209
+ Retrieve all matching registrations for an event in global registration order.
210
+ """
211
+ event_str = _normalize_event_name(event)
212
+ matching: list[_ListenerRegistration] = []
213
+ exact = self._exact_registry.get(event_str)
214
+ if exact:
215
+ matching.extend(exact)
216
+ for reg in self._wildcard_registry:
217
+ if reg.regex is not None and reg.regex.match(event_str):
218
+ matching.append(reg)
219
+
220
+ if len(matching) > 1:
221
+ matching.sort(key=lambda r: r.order)
222
+ return matching
223
+
224
+ def get_listeners(self, event: str | type[Any]) -> list[EventHandler]:
225
+ """
226
+ Retrieve all matching handlers for an event in global registration order,
227
+ interleaving exact and wildcard registrations deterministically.
228
+ """
229
+ return [reg.handler for reg in self.get_matching_registrations(event)]
230
+
231
+ async def dispatch(self, event: str | type[Any] | Any, payload: Any = None) -> list[Any]:
232
+ """
233
+ Dispatch an event to all matching registered listeners in registration order.
234
+ Supports both synchronous functions and async coroutine handlers.
235
+
236
+ Policy: Fail-Fast. If any handler raises an exception, dispatch immediately
237
+ halts, subsequent handlers are not invoked, and the exception is propagated
238
+ to the caller without modifying dispatcher registration state.
239
+ """
240
+ if isinstance(event, str):
241
+ event_name = event
242
+ else:
243
+ event_name = _normalize_event_name(event)
244
+ if payload is None and not isinstance(event, type):
245
+ payload = event
246
+
247
+ matching = self.get_matching_registrations(event_name)
248
+ if not matching:
249
+ return []
250
+
251
+ results: list[Any] = []
252
+ for reg in matching:
253
+ res = reg.invoker(event_name, payload)
254
+ if inspect.isawaitable(res):
255
+ res = await res
256
+ results.append(res)
257
+
258
+ return results
259
+
260
+ def _invoke_handler(self, handler: EventHandler, event: str, payload: Any) -> Any:
261
+ """Invoke a handler with appropriate arguments based on its signature."""
262
+ invoker = _build_invoker(handler)
263
+ return invoker(event, payload)
264
+
265
+ def remove_listener(self, event: str | type[Any], handler: EventHandler) -> bool:
266
+ """Alias for unsubscribe."""
267
+ return self.unsubscribe(event, handler)
268
+
269
+ def unsubscribe(self, event: str | type[Any], handler: EventHandler) -> bool:
270
+ """Unsubscribe a specific handler from an event or pattern."""
271
+ event_str = _normalize_event_name(event)
272
+ initial_len = len(self._registry)
273
+ self._registry = [
274
+ reg
275
+ for reg in self._registry
276
+ if not (reg.pattern == event_str and reg.handler == handler)
277
+ ]
278
+ if event_str in self._exact_registry:
279
+ self._exact_registry[event_str] = [
280
+ reg for reg in self._exact_registry[event_str] if reg.handler != handler
281
+ ]
282
+ if not self._exact_registry[event_str]:
283
+ del self._exact_registry[event_str]
284
+ self._wildcard_registry = [
285
+ reg
286
+ for reg in self._wildcard_registry
287
+ if not (reg.pattern == event_str and reg.handler == handler)
288
+ ]
289
+ return len(self._registry) < initial_len
290
+
291
+ def forget(self, event: str | type[Any] | None = None) -> None:
292
+ """
293
+ Forget listeners for a specific event, event class, or wildcard pattern,
294
+ or clear all registered listeners if event is None.
295
+ """
296
+ if event is None:
297
+ self._registry.clear()
298
+ self._exact_registry.clear()
299
+ self._wildcard_registry.clear()
300
+ else:
301
+ event_str = _normalize_event_name(event)
302
+ self._registry = [
303
+ reg for reg in self._registry if reg.pattern != event_str
304
+ ]
305
+ self._exact_registry.pop(event_str, None)
306
+ self._wildcard_registry = [
307
+ reg for reg in self._wildcard_registry if reg.pattern != event_str
308
+ ]