Spaces:
Running

File size: 2,486 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Async engine and session factory with per-transaction tenant binding."""

from __future__ import annotations

import uuid
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from sqlalchemy import event, text
from sqlalchemy.ext.asyncio import (
    AsyncEngine,
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)

from core.config import get_settings
from core.tenancy import context as tenancy


def make_engine(url: str | None = None, **kwargs: object) -> AsyncEngine:
    engine = create_async_engine(url or get_settings().database_url, pool_pre_ping=True, **kwargs)

    @event.listens_for(engine.sync_engine, "begin")
    def _bind_tenant(conn):  # type: ignore[no-untyped-def]
        """Runs at the start of every transaction: scope RLS to the current context."""
        ctx = tenancy.current()
        conn.exec_driver_sql(
            "SELECT set_config('app.tenant_id', %(t)s, true), "
            "set_config('app.user_id', %(u)s, true)",
            {
                "t": str(ctx.tenant_id) if ctx.tenant_id else "",
                "u": str(ctx.user_id) if ctx.user_id else "",
            },
        )

    return engine


class Database:
    """Owns the engine and hands out sessions. One instance per process."""

    def __init__(self, url: str | None = None, **engine_kwargs: object) -> None:
        self.engine = make_engine(url, **engine_kwargs)
        self.sessionmaker = async_sessionmaker(self.engine, expire_on_commit=False)

    @asynccontextmanager
    async def session(

        self, tenant_id: uuid.UUID | None = None, user_id: uuid.UUID | None = None

    ) -> AsyncIterator[AsyncSession]:
        """Open a session; if ``tenant_id`` is given, bind it for the session's lifetime."""
        if tenant_id is None and user_id is None:
            async with self.sessionmaker() as s:
                yield s
            return
        ctx = tenancy.current()
        with tenancy.use_context(
            tenant_id=tenant_id or ctx.tenant_id,
            user_id=user_id or ctx.user_id,
            actor=ctx.actor,
        ):
            async with self.sessionmaker() as s:
                yield s

    async def ping(self) -> bool:
        async with self.engine.connect() as conn:
            await conn.execute(text("SELECT 1"))
        return True

    async def dispose(self) -> None:
        await self.engine.dispose()