1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
|
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union, cast
from litestar.cli._utils import console # pyright: ignore
from litestar.constants import HTTP_RESPONSE_START
from sqlalchemy import Engine
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session
from advanced_alchemy.base import metadata_registry
from advanced_alchemy.config.sync import SQLAlchemySyncConfig as _SQLAlchemySyncConfig
from advanced_alchemy.extensions.litestar._utils import (
delete_aa_scope_state,
get_aa_scope_state,
set_aa_scope_state,
)
from advanced_alchemy.extensions.litestar.plugins.init.config.common import (
SESSION_SCOPE_KEY,
SESSION_TERMINUS_ASGI_EVENTS,
)
from advanced_alchemy.extensions.litestar.plugins.init.config.engine import EngineConfig
if TYPE_CHECKING:
from collections.abc import AsyncGenerator
from litestar import Litestar
from litestar.datastructures.state import State
from litestar.types import BeforeMessageSendHookHandler, Message, Scope
__all__ = (
"SQLAlchemySyncConfig",
"autocommit_before_send_handler",
"autocommit_handler_maker",
"default_before_send_handler",
"default_handler_maker",
)
def default_handler_maker(
session_scope_key: str = SESSION_SCOPE_KEY,
) -> "Callable[[Message, Scope], None]":
"""Set up the handler to issue a transaction commit or rollback based on specified status codes
Args:
session_scope_key: The key to use within the application state
Returns:
The handler callable
"""
def handler(message: "Message", scope: "Scope") -> None:
"""Handle commit/rollback, closing and cleaning up sessions before sending.
Args:
message: ASGI-``Message``
scope: An ASGI-``Scope``
Returns:
None
"""
session = cast("Optional[Session]", get_aa_scope_state(scope, session_scope_key))
if session and message["type"] in SESSION_TERMINUS_ASGI_EVENTS:
session.close()
delete_aa_scope_state(scope, session_scope_key)
return handler
default_before_send_handler = default_handler_maker()
def autocommit_handler_maker(
commit_on_redirect: bool = False,
extra_commit_statuses: "Optional[set[int]]" = None,
extra_rollback_statuses: "Optional[set[int]]" = None,
session_scope_key: str = SESSION_SCOPE_KEY,
) -> "Callable[[Message, Scope], None]":
"""Set up the handler to issue a transaction commit or rollback based on specified status codes
Args:
commit_on_redirect: Issue a commit when the response status is a redirect (``3XX``)
extra_commit_statuses: A set of additional status codes that trigger a commit
extra_rollback_statuses: A set of additional status codes that trigger a rollback
session_scope_key: The key to use within the application state
Raises:
ValueError: If extra rollback statuses and commit statuses share any status codes
Returns:
The handler callable
"""
if extra_commit_statuses is None:
extra_commit_statuses = set()
if extra_rollback_statuses is None:
extra_rollback_statuses = set()
if len(extra_commit_statuses & extra_rollback_statuses) > 0:
msg = "Extra rollback statuses and commit statuses must not share any status codes"
raise ValueError(msg)
commit_range = range(200, 400 if commit_on_redirect else 300)
def handler(message: "Message", scope: "Scope") -> None:
"""Handle commit/rollback, closing and cleaning up sessions before sending.
Args:
message: ASGI-``Message``
scope: An ASGI-``Scope``
"""
session = cast("Optional[Session]", get_aa_scope_state(scope, session_scope_key))
try:
if session is not None and message["type"] == HTTP_RESPONSE_START:
if (message["status"] in commit_range or message["status"] in extra_commit_statuses) and message[
"status"
] not in extra_rollback_statuses:
session.commit()
else:
session.rollback()
finally:
if session and message["type"] in SESSION_TERMINUS_ASGI_EVENTS:
session.close()
delete_aa_scope_state(scope, session_scope_key)
return handler
autocommit_before_send_handler = autocommit_handler_maker()
@dataclass
class SQLAlchemySyncConfig(_SQLAlchemySyncConfig):
"""Litestar Sync SQLAlchemy Configuration."""
before_send_handler: Optional[
Union["BeforeMessageSendHookHandler", Literal["autocommit", "autocommit_include_redirects"]]
] = None
"""Handler to call before the ASGI message is sent.
The handler should handle closing the session stored in the ASGI scope, if it's still open, and committing and
uncommitted data.
"""
engine_dependency_key: str = "db_engine"
"""Key to use for the dependency injection of database engines."""
session_dependency_key: str = "db_session"
"""Key to use for the dependency injection of database sessions."""
engine_app_state_key: str = "db_engine"
"""Key under which to store the SQLAlchemy engine in the application :class:`State <.datastructures.State>`
instance.
"""
session_maker_app_state_key: str = "session_maker_class"
"""Key under which to store the SQLAlchemy :class:`sessionmaker <sqlalchemy.orm.sessionmaker>` in the application
:class:`State <.datastructures.State>` instance.
"""
session_scope_key: str = SESSION_SCOPE_KEY
"""Key under which to store the SQLAlchemy scope in the application."""
engine_config: EngineConfig = field(default_factory=EngineConfig) # pyright: ignore[reportIncompatibleVariableOverride]
"""Configuration for the SQLAlchemy engine.
The configuration options are documented in the SQLAlchemy documentation.
"""
set_default_exception_handler: bool = True
"""Sets the default exception handler on application start."""
def _ensure_unique(self, registry_name: str, key: str, new_key: Optional[str] = None, _iter: int = 0) -> str:
new_key = new_key if new_key is not None else key
if new_key in getattr(self.__class__, registry_name, {}):
_iter += 1
new_key = self._ensure_unique(registry_name, key, f"{key}_{_iter}", _iter)
return new_key
def __post_init__(self) -> None:
self.session_scope_key = self._ensure_unique("_SESSION_SCOPE_KEY_REGISTRY", self.session_scope_key)
self.engine_app_state_key = self._ensure_unique("_ENGINE_APP_STATE_KEY_REGISTRY", self.engine_app_state_key)
self.session_maker_app_state_key = self._ensure_unique(
"_SESSIONMAKER_APP_STATE_KEY_REGISTRY",
self.session_maker_app_state_key,
)
self.__class__._SESSION_SCOPE_KEY_REGISTRY.add(self.session_scope_key) # noqa: SLF001
self.__class__._ENGINE_APP_STATE_KEY_REGISTRY.add(self.engine_app_state_key) # noqa: SLF001
self.__class__._SESSIONMAKER_APP_STATE_KEY_REGISTRY.add(self.session_maker_app_state_key) # noqa: SLF001
if self.before_send_handler is None:
self.before_send_handler = default_handler_maker(session_scope_key=self.session_scope_key)
if self.before_send_handler == "autocommit":
self.before_send_handler = autocommit_handler_maker(session_scope_key=self.session_scope_key)
if self.before_send_handler == "autocommit_include_redirects":
self.before_send_handler = autocommit_handler_maker(
session_scope_key=self.session_scope_key,
commit_on_redirect=True,
)
super().__post_init__()
def create_session_maker(self) -> "Callable[[], Session]":
"""Get a session maker. If none exists yet, create one.
Returns:
Session factory used by the plugin.
"""
if self.session_maker:
return self.session_maker
session_kws = self.session_config_dict
if session_kws.get("bind") is None:
session_kws["bind"] = self.get_engine()
return self.session_maker_class(**session_kws)
@asynccontextmanager
async def lifespan(
self,
app: "Litestar",
) -> "AsyncGenerator[None, None]":
deps = self.create_app_state_items()
app.state.update(deps)
try:
if self.create_all:
self.create_all_metadata(app)
yield
finally:
if self.engine_dependency_key in deps:
engine = deps[self.engine_dependency_key]
if hasattr(engine, "dispose"):
cast("Engine", engine).dispose()
def provide_engine(self, state: "State") -> "Engine":
"""Create an engine instance.
Args:
state: The ``Litestar.state`` instance.
Returns:
An engine instance.
"""
return cast("Engine", state.get(self.engine_app_state_key))
def provide_session(self, state: "State", scope: "Scope") -> "Session":
"""Create a session instance.
Args:
state: The ``Litestar.state`` instance.
scope: The current connection's scope.
Returns:
A session instance.
"""
# Import locally to avoid potential circular dependency issues at module level
from advanced_alchemy._listeners import set_async_context
session = cast("Optional[Session]", get_aa_scope_state(scope, self.session_scope_key))
if session is None:
session_maker = cast("Callable[[], Session]", state[self.session_maker_app_state_key])
session = session_maker()
set_aa_scope_state(scope, self.session_scope_key, session)
set_async_context(False) # Set context before yielding
return session
@property
def signature_namespace(self) -> "dict[str, Any]":
"""Return the plugin's signature namespace.
Returns:
A string keyed dict of names to be added to the namespace for signature forward reference resolution.
"""
return {"Engine": Engine, "Session": Session}
def create_all_metadata(self, app: "Litestar") -> None:
"""Create all metadata
Args:
app (Litestar): The ``Litestar`` instance
"""
with self.get_engine().begin() as conn:
try:
metadata_registry.get(self.bind_key).create_all(bind=conn)
except OperationalError as exc:
console.print(f"[bold red] * Could not create target metadata. Reason: {exc}")
def create_app_state_items(self) -> "dict[str, Any]":
"""Key/value pairs to be stored in application state.
Returns:
A dictionary of key/value pairs to be stored in application state.
"""
return {
self.engine_app_state_key: self.get_engine(),
self.session_maker_app_state_key: self.create_session_maker(),
}
def update_app_state(self, app: "Litestar") -> None:
"""Set the app state with engine and session.
Args:
app: The ``Litestar`` instance.
"""
app.state.update(self.create_app_state_items())
|