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.
- swiftpy/.gitignore +0 -0
- swiftpy/__init__.py +572 -0
- swiftpy/admin/__init__.py +50 -0
- swiftpy/admin/auth.py +522 -0
- swiftpy/admin/registry.py +567 -0
- swiftpy/admin/views.py +1583 -0
- swiftpy/ai/__init__.py +199 -0
- swiftpy/ai/_deterministic.py +40 -0
- swiftpy/ai/_fake.py +604 -0
- swiftpy/ai/agents/__init__.py +30 -0
- swiftpy/ai/agents/base_agent.py +506 -0
- swiftpy/ai/agents/memory.py +864 -0
- swiftpy/ai/client.py +1011 -0
- swiftpy/ai/conversation.py +171 -0
- swiftpy/ai/embeddings.py +321 -0
- swiftpy/ai/exceptions.py +75 -0
- swiftpy/ai/history_strategies.py +157 -0
- swiftpy/ai/middleware.py +918 -0
- swiftpy/ai/observability/__init__.py +28 -0
- swiftpy/ai/observability/drivers.py +763 -0
- swiftpy/ai/observability/observer.py +364 -0
- swiftpy/ai/pool.py +102 -0
- swiftpy/ai/pricing.py +101 -0
- swiftpy/ai/prompts/__init__.py +6 -0
- swiftpy/ai/prompts/loader.py +343 -0
- swiftpy/ai/providers/__init__.py +22 -0
- swiftpy/ai/providers/anthropic_provider.py +353 -0
- swiftpy/ai/providers/base.py +273 -0
- swiftpy/ai/providers/openai_provider.py +275 -0
- swiftpy/ai/rag/__init__.py +53 -0
- swiftpy/ai/rag/context_formatter.py +263 -0
- swiftpy/ai/rag/pipeline_builder.py +544 -0
- swiftpy/ai/rag/reranker.py +484 -0
- swiftpy/ai/rag/result.py +78 -0
- swiftpy/ai/rag/retriever.py +315 -0
- swiftpy/ai/redis_store.py +227 -0
- swiftpy/ai/streaming.py +115 -0
- swiftpy/ai/tools/__init__.py +22 -0
- swiftpy/ai/tools/base_tool.py +489 -0
- swiftpy/ai/tools/first_party.py +384 -0
- swiftpy/ai/tools/tool_loop.py +417 -0
- swiftpy/ai/vectorstore/__init__.py +46 -0
- swiftpy/ai/vectorstore/base.py +542 -0
- swiftpy/ai/vectorstore/chroma_adapter.py +435 -0
- swiftpy/ai/vectorstore/in_memory_adapter.py +321 -0
- swiftpy/ai/vectorstore/lancedb_adapter.py +370 -0
- swiftpy/ai/vectorstore/pgvector_adapter.py +496 -0
- swiftpy/ai/vectorstore/pinecone_adapter.py +445 -0
- swiftpy/ai/vectorstore/qdrant_adapter.py +418 -0
- swiftpy/auth/__init__.py +50 -0
- swiftpy/auth/api_key_guard.py +544 -0
- swiftpy/auth/auth_manager.py +259 -0
- swiftpy/auth/exceptions.py +71 -0
- swiftpy/auth/jwt_guard.py +230 -0
- swiftpy/auth/jwt_issuer.py +658 -0
- swiftpy/auth/token_blacklist.py +300 -0
- swiftpy/cache/__init__.py +14 -0
- swiftpy/cache/cache.py +251 -0
- swiftpy/cache/driver.py +216 -0
- swiftpy/cache/drivers/memory.py +199 -0
- swiftpy/cache/drivers/redis.py +421 -0
- swiftpy/console/__init__.py +0 -0
- swiftpy/console/cli.py +68 -0
- swiftpy/console/commands/__init__.py +0 -0
- swiftpy/console/commands/cache.py +164 -0
- swiftpy/console/commands/make.py +935 -0
- swiftpy/console/commands/migrate.py +280 -0
- swiftpy/console/commands/new.py +1806 -0
- swiftpy/console/commands/queue.py +306 -0
- swiftpy/console/commands/seed.py +252 -0
- swiftpy/console/commands/start.py +171 -0
- swiftpy/console/commands/storage.py +104 -0
- swiftpy/console/loader.py +21 -0
- swiftpy/console/stubs/__init__.py +26 -0
- swiftpy/console/stubs/controller.stub +14 -0
- swiftpy/console/stubs/event.stub +14 -0
- swiftpy/console/stubs/job.stub +22 -0
- swiftpy/console/stubs/listener.stub +14 -0
- swiftpy/console/stubs/mail.stub +20 -0
- swiftpy/console/stubs/middleware.stub +16 -0
- swiftpy/console/stubs/migration.alter.stub +17 -0
- swiftpy/console/stubs/migration.api_keys.stub +22 -0
- swiftpy/console/stubs/migration.blank.stub +11 -0
- swiftpy/console/stubs/migration.create.stub +15 -0
- swiftpy/console/stubs/migration.stub +11 -0
- swiftpy/console/stubs/migration.update.stub +17 -0
- swiftpy/console/stubs/model.stub +17 -0
- swiftpy/console/stubs/provider.stub +18 -0
- swiftpy/console/stubs/repository.stub +10 -0
- swiftpy/console/stubs/request.stub +16 -0
- swiftpy/console/stubs/resource.stub +21 -0
- swiftpy/console/stubs/schema.stub +12 -0
- swiftpy/console/stubs/seeder.stub +14 -0
- swiftpy/console/stubs/service.stub +10 -0
- swiftpy/core/__init__.py +0 -0
- swiftpy/core/application.py +1306 -0
- swiftpy/core/bootstrap.py +30 -0
- swiftpy/core/config.py +432 -0
- swiftpy/core/container.py +596 -0
- swiftpy/core/container_exceptions.py +18 -0
- swiftpy/core/context.py +148 -0
- swiftpy/core/exceptions.py +352 -0
- swiftpy/core/providers/base.py +35 -0
- swiftpy/database/__init__.py +41 -0
- swiftpy/database/exceptions.py +42 -0
- swiftpy/database/identifiers.py +105 -0
- swiftpy/database/migrations/__init__.py +36 -0
- swiftpy/database/migrations/blueprint.py +431 -0
- swiftpy/database/migrations/lock.py +104 -0
- swiftpy/database/migrations/migration.py +22 -0
- swiftpy/database/migrations/migrator.py +507 -0
- swiftpy/database/migrations/schema.py +435 -0
- swiftpy/database/orm/__init__.py +33 -0
- swiftpy/database/orm/fields.py +92 -0
- swiftpy/database/orm/model.py +2034 -0
- swiftpy/database/orm/registry.py +33 -0
- swiftpy/database/orm/relationships.py +836 -0
- swiftpy/database/pagination/__init__.py +16 -0
- swiftpy/database/pagination/contracts.py +60 -0
- swiftpy/database/pagination/paginator.py +112 -0
- swiftpy/database/pagination/simple_paginator.py +97 -0
- swiftpy/database/pool.py +218 -0
- swiftpy/database/query_builder.py +1803 -0
- swiftpy/database/seeder.py +39 -0
- swiftpy/database/transaction.py +276 -0
- swiftpy/events/__init__.py +10 -0
- swiftpy/events/dispatcher.py +308 -0
- swiftpy/events/redis_bus.py +552 -0
- swiftpy/filesystem/__init__.py +227 -0
- swiftpy/filesystem/disk.py +378 -0
- swiftpy/filesystem/drivers/__init__.py +11 -0
- swiftpy/filesystem/drivers/base.py +156 -0
- swiftpy/filesystem/drivers/local.py +559 -0
- swiftpy/filesystem/drivers/s3.py +655 -0
- swiftpy/filesystem/events.py +37 -0
- swiftpy/filesystem/exceptions.py +127 -0
- swiftpy/filesystem/manager.py +138 -0
- swiftpy/filesystem/metadata.py +22 -0
- swiftpy/filesystem/paths.py +99 -0
- swiftpy/filesystem/service_provider.py +17 -0
- swiftpy/filesystem/uploads/__init__.py +13 -0
- swiftpy/filesystem/uploads/handlers.py +362 -0
- swiftpy/filesystem/uploads/uploaded_file.py +222 -0
- swiftpy/filesystem/uploads/validators.py +186 -0
- swiftpy/filesystem/visibility.py +22 -0
- swiftpy/helpers/__init__.py +42 -0
- swiftpy/helpers/helper.py +180 -0
- swiftpy/http/exceptions.py +41 -0
- swiftpy/http/middleware.py +307 -0
- swiftpy/http/request.py +375 -0
- swiftpy/http/response.py +442 -0
- swiftpy/http/router.py +1050 -0
- swiftpy/mail/__init__.py +58 -0
- swiftpy/mail/attachments.py +255 -0
- swiftpy/mail/config.py +71 -0
- swiftpy/mail/envelope.py +183 -0
- swiftpy/mail/exceptions.py +90 -0
- swiftpy/mail/facade.py +312 -0
- swiftpy/mail/mailable.py +53 -0
- swiftpy/mail/manager.py +240 -0
- swiftpy/mail/message.py +186 -0
- swiftpy/mail/models.py +19 -0
- swiftpy/mail/queue/__init__.py +5 -0
- swiftpy/mail/queue/job.py +279 -0
- swiftpy/mail/service_provider.py +19 -0
- swiftpy/mail/templates/__init__.py +5 -0
- swiftpy/mail/templates/renderer.py +173 -0
- swiftpy/mail/transports/__init__.py +21 -0
- swiftpy/mail/transports/api/__init__.py +13 -0
- swiftpy/mail/transports/api/base.py +194 -0
- swiftpy/mail/transports/api/mailgun.py +158 -0
- swiftpy/mail/transports/api/resend.py +156 -0
- swiftpy/mail/transports/api/sendgrid.py +172 -0
- swiftpy/mail/transports/base.py +24 -0
- swiftpy/mail/transports/console.py +91 -0
- swiftpy/mail/transports/sendmail.py +128 -0
- swiftpy/mail/transports/smtp.py +466 -0
- swiftpy/queue/__init__.py +13 -0
- swiftpy/queue/dispatcher.py +813 -0
- swiftpy/queue/job.py +541 -0
- swiftpy/queue/worker.py +556 -0
- swiftpy/support/__init__.py +12 -0
- swiftpy/support/keys.py +108 -0
- swiftpy/support/redis_config.py +223 -0
- swiftpy/support/strings.py +114 -0
- swiftpy/testing/__init__.py +20 -0
- swiftpy/testing/fakes/__init__.py +11 -0
- swiftpy/testing/fakes/ai_fake.py +21 -0
- swiftpy/testing/fakes/vectorstore_fake.py +194 -0
- swiftpy/testing/fixtures.py +124 -0
- swiftpy/testing/http_client.py +730 -0
- swiftpy/testing/test_case.py +126 -0
- swiftpy/validation/__init__.py +97 -0
- swiftpy/validation/exceptions.py +26 -0
- swiftpy/validation/form_request.py +302 -0
- swiftpy/validation/protocols.py +33 -0
- swiftpy/validation/rules/__init__.py +89 -0
- swiftpy/validation/rules/builtin.py +391 -0
- swiftpy/validation/rules/exists.py +86 -0
- swiftpy/validation/rules/registry.py +290 -0
- swiftpy/validation/rules/required.py +55 -0
- swiftpy/validation/rules/unique.py +138 -0
- swiftpy/validation/validator.py +612 -0
- swiftpy/websockets/__init__.py +19 -0
- swiftpy/websockets/connection.py +317 -0
- swiftpy/websockets/manager.py +271 -0
- swiftpy_framework-0.1.0.dist-info/METADATA +603 -0
- swiftpy_framework-0.1.0.dist-info/RECORD +211 -0
- swiftpy_framework-0.1.0.dist-info/WHEEL +4 -0
- swiftpy_framework-0.1.0.dist-info/entry_points.txt +2 -0
- 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,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
|
+
]
|