resource-engine-sqlalchemy 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.
@@ -0,0 +1,172 @@
1
+ """Transactional outbox table for SQLAlchemy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Sequence
7
+ from datetime import UTC, datetime
8
+ from typing import Any, override
9
+
10
+ from resource_engine.messaging import EventEnvelope
11
+ from resource_engine.ports.messaging import InspectableOutbox, OutboxRecord, OutboxStore
12
+ from sqlalchemy import (
13
+ Boolean,
14
+ Column,
15
+ DateTime,
16
+ Index,
17
+ Integer,
18
+ MetaData,
19
+ String,
20
+ Table,
21
+ Text,
22
+ delete,
23
+ select,
24
+ update,
25
+ )
26
+ from sqlalchemy.ext.asyncio import AsyncSession
27
+
28
+ DEFAULT_TABLE = "resource_engine_outbox"
29
+
30
+
31
+ def outbox_table(metadata: MetaData, name: str = DEFAULT_TABLE) -> Table:
32
+ """Declare the outbox table on your metadata (and create it with your migrations)."""
33
+ return Table(
34
+ name,
35
+ metadata,
36
+ Column("id", String(64), primary_key=True),
37
+ Column("seq", Integer, nullable=False, autoincrement=True, index=True),
38
+ Column("type", String(200), nullable=False),
39
+ Column("resource", String(200), nullable=True),
40
+ Column("message", Text, nullable=False),
41
+ Column("created_at", DateTime(timezone=True), nullable=False),
42
+ Column("published", Boolean, nullable=False, default=False),
43
+ Column("published_at", DateTime(timezone=True), nullable=True),
44
+ Column("attempts", Integer, nullable=False, default=0),
45
+ Column("last_error", Text, nullable=True),
46
+ Index(f"ix_{name}_pending", "published", "seq"),
47
+ )
48
+
49
+
50
+ class SqlAlchemyOutbox(OutboxStore, InspectableOutbox):
51
+ """The outbox in a SQL table, written in the unit of work's session."""
52
+
53
+ def __init__(self, session: AsyncSession, table: Table) -> None:
54
+ self.session = session
55
+ self.table = table
56
+
57
+ @override
58
+ async def add(self, envelopes: Sequence[EventEnvelope]) -> None:
59
+ if not envelopes:
60
+ return
61
+ now = datetime.now(UTC)
62
+ # seq keeps insertion order across a batch even with equal timestamps
63
+ start = await self.session.scalar(
64
+ select(self.table.c.seq).order_by(self.table.c.seq.desc()).limit(1)
65
+ )
66
+ start = (start or 0) + 1
67
+ await self.session.execute(
68
+ self.table.insert(),
69
+ [
70
+ {
71
+ "id": env.id,
72
+ "seq": start + offset,
73
+ "type": env.type,
74
+ "resource": env.resource,
75
+ "message": env.to_json(),
76
+ "created_at": now,
77
+ "published": False,
78
+ "attempts": 0,
79
+ }
80
+ for offset, env in enumerate(envelopes)
81
+ ],
82
+ )
83
+
84
+ @override
85
+ async def pending(self, limit: int) -> list[OutboxRecord]:
86
+ stmt = (
87
+ select(self.table)
88
+ .where(self.table.c.published.is_(False))
89
+ .order_by(self.table.c.seq)
90
+ .limit(limit)
91
+ .with_for_update(skip_locked=True)
92
+ )
93
+ rows = (await self.session.execute(stmt)).mappings().all()
94
+ return [
95
+ OutboxRecord(
96
+ envelope=EventEnvelope.from_dict(json.loads(row["message"])),
97
+ attempts=row["attempts"],
98
+ last_error=row["last_error"],
99
+ created_at=row["created_at"],
100
+ )
101
+ for row in rows
102
+ ]
103
+
104
+ def _record(self, row: Any) -> OutboxRecord:
105
+ return OutboxRecord(
106
+ envelope=EventEnvelope.from_dict(json.loads(row["message"])),
107
+ attempts=row["attempts"],
108
+ last_error=row["last_error"],
109
+ created_at=row["created_at"],
110
+ published=bool(row["published"]),
111
+ published_at=row["published_at"],
112
+ )
113
+
114
+ @override
115
+ async def unpublished(self, limit: int) -> list[OutboxRecord]:
116
+ stmt = (
117
+ select(self.table)
118
+ .where(self.table.c.published.is_(False))
119
+ .order_by(self.table.c.seq)
120
+ .limit(limit)
121
+ )
122
+ return [self._record(r) for r in (await self.session.execute(stmt)).mappings().all()]
123
+
124
+ @override
125
+ async def get(self, message_id: str) -> OutboxRecord | None:
126
+ stmt = select(self.table).where(self.table.c.id == message_id)
127
+ row = (await self.session.execute(stmt)).mappings().first()
128
+ return self._record(row) if row is not None else None
129
+
130
+ @override
131
+ async def requeue(self, ids: Sequence[str]) -> int:
132
+ if not ids:
133
+ return 0
134
+ result = await self.session.execute(
135
+ update(self.table)
136
+ .where(self.table.c.id.in_(list(ids)))
137
+ .values(published=False, published_at=None, attempts=0, last_error=None)
138
+ )
139
+ return int(result.rowcount or 0) # type: ignore[attr-defined]
140
+
141
+ @override
142
+ async def mark_published(self, ids: Sequence[str]) -> None:
143
+ if ids:
144
+ await self.session.execute(
145
+ update(self.table)
146
+ .where(self.table.c.id.in_(list(ids)))
147
+ .values(published=True, published_at=datetime.now(UTC))
148
+ )
149
+
150
+ @override
151
+ async def mark_failed(self, ids: Sequence[str], error: str) -> None:
152
+ if ids:
153
+ await self.session.execute(
154
+ update(self.table)
155
+ .where(self.table.c.id.in_(list(ids)))
156
+ .values(attempts=self.table.c.attempts + 1, last_error=error[:2000])
157
+ )
158
+
159
+ @override
160
+ async def purge_published(self, before: datetime, limit: int) -> int:
161
+ t = self.table
162
+ ids = (
163
+ await self.session.scalars(
164
+ select(t.c.id)
165
+ .where(t.c.published.is_(True), t.c.published_at < before)
166
+ .order_by(t.c.seq)
167
+ .limit(limit)
168
+ )
169
+ ).all()
170
+ if ids:
171
+ await self.session.execute(delete(t).where(t.c.id.in_(list(ids))))
172
+ return len(ids)
@@ -0,0 +1,72 @@
1
+ """Base and subtype resources as joined tables: one base table with the common
2
+ columns and ids, one extension table per subtype with its own columns.
3
+
4
+ ```python
5
+ requests = Table("requests", metadata,
6
+ Column("id", Integer, primary_key=True, autoincrement=True),
7
+ Column("type", String(32), nullable=False, index=True),
8
+ Column("title", String(200), nullable=False), ...)
9
+ vacation_requests = extension_table("vacation_requests", requests,
10
+ Column("days", Integer, nullable=False))
11
+
12
+ map_family(mapper_registry, registry, "requests",
13
+ {"requests": requests, "vacation_requests": vacation_requests, ...})
14
+ ```
15
+
16
+ Reads of the base load every subtype's columns in the same query (one outer
17
+ join per subtype), so base records come back as their subtype's entity.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import Mapping
23
+ from typing import Any
24
+
25
+ from resource_engine import ResourceRegistry
26
+ from resource_engine.errors import ConfigurationError
27
+ from sqlalchemy import Column, ForeignKey, Table
28
+ from sqlalchemy.orm import registry as orm_registry
29
+
30
+
31
+ def extension_table(name: str, base: Table, *columns: Any, id_column: str = "id") -> Table:
32
+ """A subtype's table: its primary key is also a foreign key to the base row."""
33
+ base_id = base.c[id_column]
34
+ return Table(
35
+ name,
36
+ base.metadata,
37
+ Column(id_column, base_id.type, ForeignKey(base_id), primary_key=True),
38
+ *columns,
39
+ )
40
+
41
+
42
+ def map_family(
43
+ mapper_registry: orm_registry,
44
+ registry: ResourceRegistry,
45
+ base: str,
46
+ tables: Mapping[str, Table],
47
+ ) -> None:
48
+ """Map a base resource and its registered subtypes (joined-table inheritance)."""
49
+ definition = registry.get(base)
50
+ if definition.discriminator is None:
51
+ raise ConfigurationError(f"{base} has no discriminator: it is not a base resource")
52
+ subtypes = registry.subtypes(base)
53
+ missing = [n for n in (base, *(d.name for d in subtypes.values())) if n not in tables]
54
+ if missing:
55
+ raise ConfigurationError(f"map_family({base!r}): no table for {missing}")
56
+ base_table = tables[base]
57
+ mapper_registry.map_imperatively(
58
+ definition.model,
59
+ base_table,
60
+ polymorphic_on=base_table.c[definition.discriminator],
61
+ )
62
+ for identity, sub in subtypes.items():
63
+ mapper_registry.map_imperatively(
64
+ sub.model,
65
+ tables[sub.name],
66
+ inherits=definition.model,
67
+ polymorphic_identity=identity,
68
+ polymorphic_load="inline", # base queries load the subtype columns too
69
+ )
70
+
71
+
72
+ __all__ = ["extension_table", "map_family"]
File without changes
@@ -0,0 +1,194 @@
1
+ """Repositories over SQLAlchemy sessions, with row conditions compiled to SQL."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, cast, override
6
+
7
+ from resource_engine import ListQuery, Page
8
+ from resource_engine.errors import ConditionNotSupported, VersionConflict
9
+ from resource_engine.ports.repository import Repository
10
+ from sqlalchemy import and_, delete, false, func, literal, not_, or_, select, true, update
11
+ from sqlalchemy import inspect as sa_inspect
12
+ from sqlalchemy.engine import CursorResult
13
+ from sqlalchemy.ext.asyncio import AsyncSession
14
+
15
+
16
+ class SqlAlchemyRepository[E](Repository[E]):
17
+ """Generic repository for an imperatively mapped domain entity.
18
+
19
+ Applies ``ListQuery.condition`` (row-level permissions) as SQL, and
20
+ compares and sets versions atomically (``UPDATE ... WHERE version = :expected``).
21
+ """
22
+
23
+ supports_conditions = True
24
+ supports_versions = True
25
+
26
+ def __init__(
27
+ self,
28
+ session: AsyncSession,
29
+ entity_cls: type[E],
30
+ id_field: str = "id",
31
+ *,
32
+ version_field: str = "version",
33
+ ) -> None:
34
+ self.session = session
35
+ self.entity_cls = entity_cls
36
+ self.id_field = id_field
37
+ self.version_field = version_field
38
+
39
+ @override
40
+ async def get(self, entity_id: Any) -> E | None:
41
+ return await self.session.get(self.entity_cls, entity_id)
42
+
43
+ def _column(self, name: str, query: ListQuery) -> Any:
44
+ """A column, or for a translatable (JSON) one its text in the query's
45
+ languages: ``COALESCE(name->>'ca-ES', name->>'ca', ...)``."""
46
+ column = getattr(self.entity_cls, name)
47
+ if name not in query.translatable or not query.locales:
48
+ return column
49
+ texts = [column[locale].as_string() for locale in query.locales]
50
+ return func.coalesce(*texts) if len(texts) > 1 else texts[0]
51
+
52
+ @override
53
+ async def list(self, query: ListQuery) -> Page[E]:
54
+ stmt = select(self.entity_cls)
55
+ for field, value in query.filters.items():
56
+ stmt = stmt.where(self._column(field, query) == value)
57
+ if query.condition is not None:
58
+ stmt = stmt.where(compile_condition(query.condition, self.entity_cls))
59
+ total = await self.session.scalar(select(func.count()).select_from(stmt.subquery()))
60
+ for key in query.order_by:
61
+ column = self._column(key.lstrip("-"), query)
62
+ stmt = stmt.order_by(column.desc() if key.startswith("-") else column.asc())
63
+ # the primary key last: a total order, so pages never repeat or skip rows
64
+ # when the sort has ties (PostgreSQL's top-N sort isn't stable)
65
+ sorted_by = {key.lstrip("-") for key in query.order_by}
66
+ for column in sa_inspect(self.entity_cls).primary_key:
67
+ if column.key not in sorted_by:
68
+ stmt = stmt.order_by(column.asc())
69
+ stmt = stmt.offset(query.offset).limit(query.limit)
70
+ items = list((await self.session.scalars(stmt)).all())
71
+ return Page(items, total or 0, query.offset, query.limit)
72
+
73
+ @override
74
+ async def add(self, entity: E) -> E:
75
+ self.session.add(entity)
76
+ await self.session.flush()
77
+ return entity
78
+
79
+ @override
80
+ async def update(self, entity: E, *, expected_version: int | None = None) -> E:
81
+ self.session.add(entity)
82
+ if expected_version is not None:
83
+ await self._claim(entity, expected_version)
84
+ await self.session.flush()
85
+ return entity
86
+
87
+ @override
88
+ async def delete(self, entity: E, *, expected_version: int | None = None) -> None:
89
+ if expected_version is not None:
90
+ await self._claim(entity, expected_version, remove=True)
91
+ if sa_inspect(self.entity_cls).inherits is None and (
92
+ sa_inspect(self.entity_cls).polymorphic_on is None
93
+ ):
94
+ self.session.expunge(entity)
95
+ return
96
+ await self.session.delete(entity)
97
+ await self.session.flush()
98
+
99
+ async def _claim(self, entity: E, expected: int, *, remove: bool = False) -> None:
100
+ """Compare and set: the row must still be at ``expected``. A concurrent
101
+ transaction holding the row makes this wait; once it commits, no row
102
+ matches and the write fails instead of overwriting."""
103
+ entity_id = getattr(entity, self.id_field)
104
+ id_col = getattr(self.entity_cls, self.id_field)
105
+ version_col = getattr(self.entity_cls, self.version_field)
106
+ mapper = sa_inspect(self.entity_cls)
107
+ joined = mapper.inherits is not None or mapper.polymorphic_on is not None
108
+ if joined:
109
+ # base and subtype tables: claim on the table holding the version,
110
+ # then let the ORM delete every row of the record
111
+ [column] = mapper.attrs[self.version_field].columns
112
+ table = column.table
113
+ key = next(c for c in mapper.attrs[self.id_field].columns if c.table is table)
114
+ stmt: Any = (
115
+ update(table)
116
+ .where(key == entity_id, column == expected)
117
+ .values({column.name: expected + 1})
118
+ )
119
+ else:
120
+ match = (id_col == entity_id, version_col == expected)
121
+ stmt = (
122
+ delete(self.entity_cls).where(*match)
123
+ if remove
124
+ else update(self.entity_cls)
125
+ .where(*match)
126
+ .values({self.version_field: expected + 1})
127
+ ).execution_options(synchronize_session=False)
128
+ with self.session.no_autoflush:
129
+ result = await self.session.execute(stmt)
130
+ if cast("CursorResult[Any]", result).rowcount != 1:
131
+ with self.session.no_autoflush:
132
+ current = await self.session.scalar(select(version_col).where(id_col == entity_id))
133
+ raise VersionConflict(
134
+ f"{self.entity_cls.__name__} {entity_id!r} changed: version {current}, "
135
+ f"expected {expected}",
136
+ hint="Reload the record and apply your change again.",
137
+ details={
138
+ "id": entity_id,
139
+ "expected": expected,
140
+ "current": current,
141
+ "reason": "version conflict",
142
+ },
143
+ )
144
+ if not remove:
145
+ setattr(entity, self.version_field, expected + 1)
146
+
147
+
148
+ def compile_condition(node: Any, entity_cls: Any) -> Any:
149
+ """Policy condition over ``resource.*`` → SQLAlchemy expression."""
150
+ if node is True:
151
+ return true()
152
+ if node is False:
153
+ return false()
154
+ ((op, args),) = node.items()
155
+ if op == "and":
156
+ return and_(*(compile_condition(c, entity_cls) for c in args))
157
+ if op == "or":
158
+ return or_(*(compile_condition(c, entity_cls) for c in args))
159
+ if op == "not":
160
+ return not_(compile_condition(args, entity_cls))
161
+
162
+ def operand(value: Any) -> Any:
163
+ if isinstance(value, dict) and set(value) == {"attr"}:
164
+ namespace, _, name = value["attr"].partition(".")
165
+ column = getattr(entity_cls, name, None) if namespace == "resource" else None
166
+ if column is None or "." in name:
167
+ raise ConditionNotSupported(f"Cannot filter on {value['attr']!r} in SQL")
168
+ return column
169
+ return literal(value)
170
+
171
+ if op == "exists":
172
+ return operand(args).is_not(None)
173
+ left, right = args
174
+ if op in ("in", "nin"):
175
+ if not isinstance(right, list):
176
+ raise ConditionNotSupported(f"'{op}' needs a literal list in SQL")
177
+ column = operand(left)
178
+ clause = column.in_(right) if right else false()
179
+ return not_(clause) if op == "nin" else clause
180
+ if op == "contains":
181
+ raise ConditionNotSupported("'contains' on record attributes is not supported in SQL")
182
+ if op == "icontains":
183
+ if not isinstance(right, str):
184
+ raise ConditionNotSupported("'icontains' needs literal text in SQL")
185
+ from resource_engine.integration import like_pattern
186
+
187
+ # ILIKE in PostgreSQL, lower() LIKE lower() elsewhere; % and _ escaped
188
+ return operand(left).ilike(like_pattern(right), escape="\\")
189
+ a, b = operand(left), operand(right)
190
+ if op == "eq":
191
+ return a.is_(None) if right is None else a == b
192
+ if op == "ne":
193
+ return a.is_not(None) if right is None else a != b
194
+ return {"lt": a < b, "le": a <= b, "gt": a > b, "ge": a >= b}[op]
@@ -0,0 +1,156 @@
1
+ """The engine's tables on your ``MetaData``, ready for Alembic autogenerate.
2
+
3
+ ```python
4
+ from sqlalchemy import MetaData
5
+ from sqlalchemy.orm import registry as orm_registry
6
+ from resource_engine_sqlalchemy import NAMING_CONVENTION, engine_tables, map_engine
7
+
8
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
9
+ mapper_registry = orm_registry(metadata=metadata)
10
+ engine = engine_tables(metadata, outbox=True, audit=True, seals=True, authz=True)
11
+ map_engine(mapper_registry, engine)
12
+ uow = unit_of_work_factory(sessions, registry, outbox_table=engine.outbox)
13
+ ```
14
+
15
+ Your own tables and the engine's live on the same ``MetaData``, so
16
+ ``alembic revision --autogenerate`` writes one migration for both. See
17
+ docs/migrations.md.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass
23
+ from typing import Any
24
+
25
+ from sqlalchemy import MetaData, Table
26
+ from sqlalchemy.orm import registry as orm_registry
27
+
28
+ from resource_engine_sqlalchemy.activity import activity_tables
29
+ from resource_engine_sqlalchemy.audit import audit_seal_table, audit_table, map_audit
30
+ from resource_engine_sqlalchemy.authz import (
31
+ AuthzTables,
32
+ api_keys_table,
33
+ authz_tables,
34
+ map_api_keys,
35
+ map_authz,
36
+ )
37
+ from resource_engine_sqlalchemy.documents import documents_table, map_documents
38
+ from resource_engine_sqlalchemy.idempotency import idempotency_table
39
+ from resource_engine_sqlalchemy.inbox import inbox_table
40
+ from resource_engine_sqlalchemy.locks import locks_table
41
+ from resource_engine_sqlalchemy.outbox import outbox_table
42
+ from resource_engine_sqlalchemy.suppressions import suppressions_table
43
+
44
+ #: Constraint and index names that are stable across databases, so later
45
+ #: migrations can drop or rename them. Pass it to your ``MetaData``.
46
+ NAMING_CONVENTION: dict[str, str] = {
47
+ "ix": "ix_%(column_0_label)s",
48
+ "uq": "uq_%(table_name)s_%(column_0_N_name)s",
49
+ "ck": "ck_%(table_name)s_%(constraint_name)s",
50
+ "fk": "fk_%(table_name)s_%(column_0_N_name)s_%(referred_table_name)s",
51
+ "pk": "pk_%(table_name)s",
52
+ }
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class EngineTables:
57
+ """The engine tables declared by ``engine_tables`` (``None`` when not asked for)."""
58
+
59
+ outbox: Table | None = None
60
+ inbox: Table | None = None
61
+ audit: Table | None = None
62
+ seals: Table | None = None
63
+ authz: AuthzTables | None = None
64
+ documents: Table | None = None
65
+ locks: Table | None = None
66
+ idempotency: Table | None = None
67
+ api_keys: Table | None = None
68
+ suppressions: Table | None = None
69
+ activity: Any = None # ActivityTables
70
+
71
+ def all(self) -> list[Table]:
72
+ """Every engine table that was declared."""
73
+ tables = [
74
+ self.suppressions,
75
+ self.outbox,
76
+ self.inbox,
77
+ self.audit,
78
+ self.seals,
79
+ self.documents,
80
+ self.locks,
81
+ self.idempotency,
82
+ self.api_keys,
83
+ ]
84
+ if self.authz is not None:
85
+ tables += [self.authz.policies, self.authz.roles, self.authz.assignments]
86
+ if self.activity is not None:
87
+ tables += self.activity.all()
88
+ return [t for t in tables if t is not None]
89
+
90
+
91
+ def engine_tables(
92
+ metadata: MetaData,
93
+ *,
94
+ outbox: bool = False,
95
+ inbox: bool = False,
96
+ audit: bool = False,
97
+ seals: bool = False,
98
+ authz: bool = False,
99
+ documents: bool = False,
100
+ locks: bool = False,
101
+ idempotency: bool = False,
102
+ api_keys: bool = False,
103
+ suppressions: bool = False,
104
+ activity: bool = False,
105
+ names: dict[str, Any] | None = None,
106
+ ) -> EngineTables:
107
+ """Declare the engine tables an application uses on ``metadata``.
108
+
109
+ Args:
110
+ outbox, inbox: Messaging (``OutboxDelivery``, ``MessageProcessor``).
111
+ audit, seals: The audit trail and its seals (``AuditSealer``); ``seals``
112
+ needs ``audit``.
113
+ authz: Policies, roles and role assignments (``registry.register_authz``).
114
+ documents: Attached documents (``registry.register_documents``).
115
+ locks: Leases for ``JobRunner`` jobs with ``single=True``.
116
+ idempotency: Results of writes sent with an idempotency key.
117
+ api_keys: Keys for machine clients (``registry.register_api_keys``).
118
+ suppressions: Email addresses not to send to (``SqlAlchemySuppressionList``).
119
+ activity: What the worker did, for the explorer (``SqlAlchemyActivityLog``;
120
+ ``names`` takes a prefix).
121
+ names: Custom table names, by the same keys. ``authz`` and ``activity``
122
+ take a prefix instead, without the trailing ``_``.
123
+ """
124
+ if seals and not audit:
125
+ raise ValueError("seals=True needs audit=True: seals cover audit entries")
126
+ names = names or {}
127
+
128
+ def named(key: str, build: Any) -> Any:
129
+ return build(metadata, names[key]) if key in names else build(metadata)
130
+
131
+ return EngineTables(
132
+ outbox=named("outbox", outbox_table) if outbox else None,
133
+ inbox=named("inbox", inbox_table) if inbox else None,
134
+ audit=named("audit", audit_table) if audit else None,
135
+ seals=named("seals", audit_seal_table) if seals else None,
136
+ authz=named("authz", authz_tables) if authz else None,
137
+ documents=named("documents", documents_table) if documents else None,
138
+ locks=named("locks", locks_table) if locks else None,
139
+ idempotency=named("idempotency", idempotency_table) if idempotency else None,
140
+ api_keys=named("api_keys", api_keys_table) if api_keys else None,
141
+ suppressions=named("suppressions", suppressions_table) if suppressions else None,
142
+ activity=named("activity", activity_tables) if activity else None,
143
+ )
144
+
145
+
146
+ def map_engine(mapper_registry: orm_registry, tables: EngineTables) -> None:
147
+ """Map the engine's entities onto the tables that need it (audit, seals,
148
+ authz, documents). Safe to call more than once."""
149
+ if tables.audit is not None:
150
+ map_audit(mapper_registry, tables.audit, tables.seals)
151
+ if tables.authz is not None:
152
+ map_authz(mapper_registry, tables.authz)
153
+ if tables.documents is not None:
154
+ map_documents(mapper_registry, tables.documents)
155
+ if tables.api_keys is not None:
156
+ map_api_keys(mapper_registry, tables.api_keys)
@@ -0,0 +1,75 @@
1
+ """The email suppression list in a table (``SuppressionList``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from datetime import UTC, datetime
7
+ from email.utils import parseaddr
8
+ from typing import override
9
+
10
+ from resource_engine.ports.email import SuppressionList
11
+ from sqlalchemy import Column, DateTime, MetaData, String, Table, delete, insert, select, update
12
+ from sqlalchemy.exc import IntegrityError
13
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
14
+
15
+ DEFAULT_TABLE = "resource_engine_email_suppressions"
16
+
17
+
18
+ def suppressions_table(metadata: MetaData, name: str = DEFAULT_TABLE) -> Table:
19
+ """The table of email addresses that must not be sent to."""
20
+ return Table(
21
+ name,
22
+ metadata,
23
+ Column("address", String(320), primary_key=True),
24
+ Column("reason", String(500), nullable=False, default=""),
25
+ Column("suppressed_at", DateTime(timezone=True), nullable=False),
26
+ )
27
+
28
+
29
+ class SqlAlchemySuppressionList(SuppressionList):
30
+ """``SuppressionList`` shared by every instance, in its own short transactions."""
31
+
32
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession], table: Table) -> None:
33
+ self.session_factory = session_factory
34
+ self.table = table
35
+
36
+ @staticmethod
37
+ def _key(address: str) -> str:
38
+ return (parseaddr(address)[1] or address).lower()
39
+
40
+ @override
41
+ async def suppressed(self, addresses: Sequence[str]) -> set[str]:
42
+ keys = {self._key(a) for a in addresses}
43
+ if not keys:
44
+ return set()
45
+ async with self.session_factory() as session:
46
+ rows = await session.execute(
47
+ select(self.table.c.address).where(self.table.c.address.in_(keys))
48
+ )
49
+ return {row[0] for row in rows}
50
+
51
+ @override
52
+ async def suppress(self, address: str, reason: str) -> None:
53
+ values = {"reason": reason[:500], "suppressed_at": datetime.now(UTC)}
54
+ key = self._key(address)
55
+ async with self.session_factory() as session:
56
+ try:
57
+ await session.execute(insert(self.table).values(address=key, **values))
58
+ await session.commit()
59
+ except IntegrityError: # already there: refresh the reason
60
+ await session.rollback()
61
+ await session.execute(
62
+ update(self.table).where(self.table.c.address == key).values(**values)
63
+ )
64
+ await session.commit()
65
+
66
+ @override
67
+ async def release(self, address: str) -> None:
68
+ async with self.session_factory() as session:
69
+ await session.execute(
70
+ delete(self.table).where(self.table.c.address == self._key(address))
71
+ )
72
+ await session.commit()
73
+
74
+
75
+ __all__ = ["SqlAlchemySuppressionList", "suppressions_table"]