snodra-messaging-sql 0.7.0__tar.gz → 0.8.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: snodra-messaging-sql
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: The PostgreSQL and MySQL message store for the Snodra messaging suite.
5
5
  Project-URL: Homepage, https://snodra.damoreira.com/
6
6
  Project-URL: Repository, https://github.com/snodra/snodra-messaging-python
@@ -9,7 +9,7 @@ License-File: LICENSE
9
9
  Requires-Python: >=3.12
10
10
  Requires-Dist: asyncmy==0.2.18
11
11
  Requires-Dist: asyncpg==0.32.0
12
- Requires-Dist: snodra-messaging==0.7.0
12
+ Requires-Dist: snodra-messaging==0.8.0
13
13
  Description-Content-Type: text/markdown
14
14
 
15
15
  # snodra-messaging-sql
@@ -55,9 +55,9 @@ asyncio.run(main())
55
55
  `postgres://` or `postgresql://` for PostgreSQL, `mysql://` for MySQL. The driver is read from the scheme when
56
56
  the variable is empty.
57
57
 
58
- The store implements the outbox, the processed-event markers, the dead letters and the processor control state; the
59
- level-3 store checks pass on both engines. The external-call and saga ports are part of the interface frozen at
60
- level 2 and report `snodra.MessageStoreUnsupported` for now; the official add-ons implement every port by level 4.
58
+ The store implements every message-store port: the outbox, the processed-event markers, the dead letters, the
59
+ processor control state, the external-call records and the saga records. The level-3 and level-4 store checks pass on
60
+ both engines; level 4 is not claimed publicly until the release that publishes it for every library.
61
61
 
62
62
  ### The transaction is the service's
63
63
 
@@ -41,9 +41,9 @@ asyncio.run(main())
41
41
  `postgres://` or `postgresql://` for PostgreSQL, `mysql://` for MySQL. The driver is read from the scheme when
42
42
  the variable is empty.
43
43
 
44
- The store implements the outbox, the processed-event markers, the dead letters and the processor control state; the
45
- level-3 store checks pass on both engines. The external-call and saga ports are part of the interface frozen at
46
- level 2 and report `snodra.MessageStoreUnsupported` for now; the official add-ons implement every port by level 4.
44
+ The store implements every message-store port: the outbox, the processed-event markers, the dead letters, the
45
+ processor control state, the external-call records and the saga records. The level-3 and level-4 store checks pass on
46
+ both engines; level 4 is not claimed publicly until the release that publishes it for every library.
47
47
 
48
48
  ### The transaction is the service's
49
49
 
@@ -4,14 +4,14 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "snodra-messaging-sql"
7
- version = "0.7.0"
7
+ version = "0.8.0"
8
8
  description = "The PostgreSQL and MySQL message store for the Snodra messaging suite."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
11
11
  license = "Apache-2.0"
12
12
  license-files = ["LICENSE"]
13
13
  dependencies = [
14
- "snodra-messaging==0.7.0",
14
+ "snodra-messaging==0.8.0",
15
15
  "asyncpg==0.32.0",
16
16
  "asyncmy==0.2.18",
17
17
  ]
@@ -1,10 +1,9 @@
1
1
  """The SQL message-store add-on: the core's message-store ports on PostgreSQL and MySQL.
2
2
 
3
3
  Hand :class:`SqlStore` to :class:`snodra.App` as its ``store``; a service that only sends commands and
4
- queries needs none. The store keeps the outbox, the processed-event markers, the dead letters and the
5
- processor control state in the service's own database, on the shared SQL layout version 1 that every
6
- Snodra library reads and writes; the external-call and saga ports belong to the interface frozen at
7
- level 2 and report ``snodra.MessageStoreUnsupported`` until this add-on implements them.
4
+ queries needs none. The store keeps every message-store port in the service's own database: the outbox,
5
+ the processed-event markers, the dead letters, the processor control state, the external-call records and
6
+ the saga records, on the shared SQL layout version 1 that every Snodra library reads and writes.
8
7
 
9
8
  See :mod:`snodra_sql.sql` for the layout and the guarantees, ``DRIVER-SPIKE.md`` for the driver
10
9
  behaviour the add-on relies on, and ``SPEC-GAPS.md`` for the choices the public specification leaves
@@ -1,7 +1,8 @@
1
1
  """The SQL message store: PostgreSQL and MySQL on the shared layout version 1.
2
2
 
3
- The store keeps the outbox, the processed-event markers, the dead letters and the processor control
4
- state in the service's own database. Every operation joins the transaction bound to the current context
3
+ The store keeps the outbox, the processed-event markers, the dead letters, the processor control state,
4
+ the external-call records and the saga records in the service's own database. Every operation joins the
5
+ transaction bound to the current context
5
6
  (``async with store.transaction()``) or runs in a short transaction of its own, at READ COMMITTED;
6
7
  ``store.transaction(conn=conn)`` binds a connection the service already runs a transaction on, and the
7
8
  store never commits or rolls it back.
@@ -22,8 +23,8 @@ nobody; MySQL has no notification and the relay polls.
22
23
 
23
24
  The dead-letter and processor-control stores use the layout's text/binary payload split and its
24
25
  ``replay`` array, and a letter whose expiry passed is gone for every read and write here. The
25
- external-call and saga ports are part of the interface frozen at level 2 and report
26
- :class:`snodra.MessageStoreUnsupported` for now. The official add-ons implement every port by level 4.
26
+ external-call records commit outside the caller's transaction; the saga records, their dispatch entries,
27
+ deadlines, failures and markers join it.
27
28
 
28
29
  See https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/.
29
30
  """
@@ -40,7 +41,7 @@ import logging
40
41
  import os
41
42
  from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
42
43
  from contextlib import AbstractAsyncContextManager, asynccontextmanager
43
- from dataclasses import dataclass, field
44
+ from dataclasses import dataclass, field, replace
44
45
  from datetime import UTC, datetime, timedelta
45
46
  from importlib.resources import files
46
47
  from typing import Any, Final
@@ -53,6 +54,7 @@ from asyncmy.constants import CLIENT
53
54
  from snodra import (
54
55
  RESET_KIND,
55
56
  AppendListener,
57
+ Association,
56
58
  Conflict,
57
59
  ControlOperation,
58
60
  DeadLetter,
@@ -61,13 +63,16 @@ from snodra import (
61
63
  DeadLetterStore,
62
64
  DeadLetterSummary,
63
65
  DeadlineDocument,
66
+ DeadlineStatus,
64
67
  DispatchFailure,
68
+ DispatchKind,
65
69
  ExternalCall,
70
+ ExternalCallStatus,
66
71
  ExternalCallStore,
72
+ FailureReason,
67
73
  InvalidMessage,
68
74
  Locked,
69
75
  MessageStoreFailed,
70
- MessageStoreUnsupported,
71
76
  OutboxEntry,
72
77
  OutboxStore,
73
78
  Parked,
@@ -123,6 +128,8 @@ MAX_NAME: Final = 255
123
128
  MAX_ID: Final = 255
124
129
  FREE_TEXT_BYTES: Final = 16 * 1024
125
130
  PURGE_BATCH: Final = 1000
131
+ SAGA_START_LOCK: Final = 0x534E4452
132
+ """The first key of the transaction-scoped advisory lock that serialises saga starts per start key."""
126
133
 
127
134
  DEFAULT_MIN_SIZE: Final = 1
128
135
  DEFAULT_MAX_SIZE: Final = 10
@@ -344,13 +351,13 @@ class SqlStore:
344
351
  self.processed: ProcessedStore = _SqlProcessed(self)
345
352
  self.dead_letters: DeadLetterStore = _SqlDeadLetters(self)
346
353
  self.control: ProcessorControlStore = _SqlControl(self)
347
- self.external: ExternalCallStore = _UnsupportedExternal()
354
+ self.external: ExternalCallStore = _SqlExternalCalls(self)
348
355
  self.sagas: SagaStores = SagaStores(
349
- sagas=_UnsupportedSagas(),
350
- dispatch=_UnsupportedDispatch(),
351
- deadlines=_UnsupportedDeadlines(),
352
- failures=_UnsupportedFailures(),
353
- markers=_UnsupportedMarkers(),
356
+ sagas=_SqlSagas(self),
357
+ dispatch=_SqlDispatch(self),
358
+ deadlines=_SqlDeadlines(self),
359
+ failures=_SqlFailures(self),
360
+ markers=_SqlMarkers(self),
354
361
  )
355
362
 
356
363
  @property
@@ -1686,148 +1693,891 @@ def _decode_replay(text: Any) -> tuple[ReplayRange, ...]:
1686
1693
  return tuple(ranges)
1687
1694
 
1688
1695
 
1689
- # ---- the ports this level does not implement ------------------------------------------------------
1696
+ # ---- external calls -------------------------------------------------------------------------------
1690
1697
 
1691
1698
 
1692
- def _unsupported(what: str) -> MessageStoreUnsupported:
1693
- return MessageStoreUnsupported(f"{what} in the SQL message store (level 2)")
1699
+ class _SqlExternalCalls:
1700
+ """The external-call records on ``snodra_external_calls``. Every operation is a write of its own, outside the
1701
+ caller's transaction; every write after the insert is conditional on the record read or owned."""
1694
1702
 
1703
+ def __init__(self, store: SqlStore) -> None:
1704
+ self._store = store
1705
+
1706
+ def _columns(self) -> str:
1707
+ return "id, status, reply, error, attempts, updated_at, lease_until, owner"
1695
1708
 
1696
- class _UnsupportedExternal:
1697
1709
  async def insert(self, call: ExternalCall) -> bool:
1698
- raise _unsupported("external calls")
1710
+ _check_text("an external call's key", call.key, -1)
1711
+ _check_text("an external call's reply", call.reply or "", -1)
1712
+ _check_text("an external call's error", call.error or "", -1)
1713
+ store = self._store
1714
+ async with store._own() as conn:
1715
+ try:
1716
+ await store._exec(
1717
+ conn,
1718
+ "INSERT INTO snodra_external_calls "
1719
+ "(id_hash, id, status, reply, error, attempts, updated_at, lease_until, owner) "
1720
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
1721
+ (
1722
+ _sha256(call.key),
1723
+ call.key,
1724
+ call.status.value,
1725
+ call.reply,
1726
+ call.error,
1727
+ call.attempts,
1728
+ store._time(call.updated_at_ms),
1729
+ None if call.lease_until_ms is None else store._time(call.lease_until_ms),
1730
+ call.owner,
1731
+ ),
1732
+ )
1733
+ except Conflict as error:
1734
+ if _duplicate(error):
1735
+ return False
1736
+ raise
1737
+ return True
1699
1738
 
1700
1739
  async def find(self, key: str) -> ExternalCall | None:
1701
- raise _unsupported("external calls")
1740
+ _check_text("an external call's key", key, -1)
1741
+ store = self._store
1742
+ async with store._read() as conn:
1743
+ row = await store._fetchone(
1744
+ conn,
1745
+ f"SELECT {self._columns()} FROM snodra_external_calls WHERE id_hash = ?",
1746
+ (_sha256(key),),
1747
+ )
1748
+ return None if row is None else _external_from_row(row)
1702
1749
 
1703
1750
  async def take_over(self, seen: ExternalCall, owner: str, lease_until_ms: int, now_ms: int) -> ExternalCall | None:
1704
- raise _unsupported("external calls")
1751
+ store = self._store
1752
+ async with store._own() as conn:
1753
+ condition, args = _external_read_condition(seen, store)
1754
+ affected = await store._exec(
1755
+ conn,
1756
+ "UPDATE snodra_external_calls SET lease_until = ?, updated_at = ?, owner = ?, attempts = attempts + 1 "
1757
+ f"WHERE {condition}",
1758
+ (store._time(lease_until_ms), store._time(now_ms), owner, *args),
1759
+ )
1760
+ if affected != 1:
1761
+ return None
1762
+ row = await store._fetchone(
1763
+ conn,
1764
+ f"SELECT {self._columns()} FROM snodra_external_calls WHERE id_hash = ?",
1765
+ (_sha256(seen.key),),
1766
+ )
1767
+ return None if row is None else _external_from_row(row)
1705
1768
 
1706
1769
  async def expire(self, seen: ExternalCall, now_ms: int) -> bool:
1707
- raise _unsupported("external calls")
1770
+ return await self._settle(seen, ExternalCallStatus.UNKNOWN, now_ms, reply=None, error=None)
1708
1771
 
1709
1772
  async def succeed(self, key: str, owner: str, reply: str, now_ms: int) -> bool:
1710
- raise _unsupported("external calls")
1773
+ store = self._store
1774
+ async with store._own() as conn:
1775
+ affected = await store._exec(
1776
+ conn,
1777
+ "UPDATE snodra_external_calls SET status = ?, reply = ?, error = NULL, updated_at = ?, "
1778
+ "lease_until = NULL, owner = NULL "
1779
+ "WHERE id_hash = ? AND status = 'IN_PROGRESS' AND owner = ?",
1780
+ (ExternalCallStatus.SUCCEEDED.value, reply, store._time(now_ms), _sha256(key), owner),
1781
+ )
1782
+ return affected == 1
1711
1783
 
1712
1784
  async def fail(self, key: str, owner: str, error: str, now_ms: int) -> bool:
1713
- raise _unsupported("external calls")
1785
+ store = self._store
1786
+ async with store._own() as conn:
1787
+ affected = await store._exec(
1788
+ conn,
1789
+ "UPDATE snodra_external_calls SET status = ?, error = ?, updated_at = ?, "
1790
+ "lease_until = NULL, owner = NULL "
1791
+ "WHERE id_hash = ? AND status = 'IN_PROGRESS' AND owner = ?",
1792
+ (ExternalCallStatus.FAILED.value, error, store._time(now_ms), _sha256(key), owner),
1793
+ )
1794
+ return affected == 1
1714
1795
 
1715
1796
  async def mark_unknown(self, key: str, owner: str, now_ms: int) -> bool:
1716
- raise _unsupported("external calls")
1797
+ store = self._store
1798
+ async with store._own() as conn:
1799
+ affected = await store._exec(
1800
+ conn,
1801
+ "UPDATE snodra_external_calls SET status = ?, updated_at = ?, lease_until = NULL, owner = NULL "
1802
+ "WHERE id_hash = ? AND status = 'IN_PROGRESS' AND owner = ?",
1803
+ (ExternalCallStatus.UNKNOWN.value, store._time(now_ms), _sha256(key), owner),
1804
+ )
1805
+ return affected == 1
1717
1806
 
1718
1807
  async def reset(self, key: str, owner: str) -> bool:
1719
- raise _unsupported("external calls")
1808
+ store = self._store
1809
+ async with store._own() as conn:
1810
+ affected = await store._exec(
1811
+ conn,
1812
+ "DELETE FROM snodra_external_calls WHERE id_hash = ? AND status = 'IN_PROGRESS' AND owner = ?",
1813
+ (_sha256(key), owner),
1814
+ )
1815
+ return affected == 1
1816
+
1817
+ async def _settle(
1818
+ self,
1819
+ seen: ExternalCall,
1820
+ status: ExternalCallStatus,
1821
+ now_ms: int,
1822
+ *,
1823
+ reply: str | None,
1824
+ error: str | None,
1825
+ ) -> bool:
1826
+ store = self._store
1827
+ async with store._own() as conn:
1828
+ condition, args = _external_read_condition(seen, store)
1829
+ affected = await store._exec(
1830
+ conn,
1831
+ "UPDATE snodra_external_calls SET status = ?, reply = ?, error = ?, updated_at = ?, "
1832
+ f"lease_until = NULL, owner = NULL WHERE {condition}",
1833
+ (status.value, reply, error, store._time(now_ms), *args),
1834
+ )
1835
+ return affected == 1
1836
+
1837
+
1838
+ def _external_read_condition(seen: ExternalCall, store: SqlStore) -> tuple[str, tuple[Any, ...]]:
1839
+ condition = "id_hash = ? AND status = 'IN_PROGRESS' "
1840
+ args: list[Any] = [_sha256(seen.key)]
1841
+ if seen.owner is None:
1842
+ condition += "AND owner IS NULL "
1843
+ else:
1844
+ condition += "AND owner = ? "
1845
+ args.append(seen.owner)
1846
+ if seen.lease_until_ms is None:
1847
+ condition += "AND lease_until IS NULL"
1848
+ else:
1849
+ condition += "AND lease_until = ?"
1850
+ args.append(store._time(seen.lease_until_ms))
1851
+ return condition, tuple(args)
1852
+
1853
+
1854
+ def _external_from_row(row: dict[str, Any]) -> ExternalCall:
1855
+ return ExternalCall(
1856
+ key=str(row["id"]),
1857
+ status=ExternalCallStatus(str(row["status"])),
1858
+ reply=None if row["reply"] is None else str(row["reply"]),
1859
+ error=None if row["error"] is None else str(row["error"]),
1860
+ attempts=int(row["attempts"]),
1861
+ updated_at_ms=_ms_value(row["updated_at"]),
1862
+ lease_until_ms=None if row["lease_until"] is None else _ms_value(row["lease_until"]),
1863
+ owner=None if row["owner"] is None else str(row["owner"]),
1864
+ )
1865
+
1866
+
1867
+ # ---- the sagas ------------------------------------------------------------------------------------
1868
+
1869
+
1870
+ def _association_hash(key: str, value: str) -> str:
1871
+ return hashlib.sha256(key.encode() + b"\x00" + value.encode()).hexdigest()
1872
+
1720
1873
 
1874
+ class _SqlSagas:
1875
+ """The saga instances on ``snodra_sagas`` and their associations; writes join the caller's transaction."""
1876
+
1877
+ def __init__(self, store: SqlStore) -> None:
1878
+ self._store = store
1879
+
1880
+ def _columns(self) -> str:
1881
+ return "id, type, state, start_key, start_key_hash, ended, ended_at, version, created_at, updated_at"
1721
1882
 
1722
- class _UnsupportedSagas:
1723
1883
  async def find_by_id(self, saga_id: str, *, tx: Tx | None = None) -> SagaDocument | None:
1724
- raise _unsupported("sagas")
1884
+ _check_text("a saga's id", saga_id, MAX_ID)
1885
+ store = self._store
1886
+ async with store._scoped(tx) as conn:
1887
+ row = await store._fetchone(conn, f"SELECT {self._columns()} FROM snodra_sagas WHERE id = ?", (saga_id,))
1888
+ if row is None:
1889
+ return None
1890
+ associations = await self._associations(conn, (saga_id,))
1891
+ return _saga_from_row(row, associations.get(saga_id, ()))
1725
1892
 
1726
1893
  async def find_live(self, type_name: str, key: str, value: str, *, tx: Tx | None = None) -> list[SagaDocument]:
1727
- raise _unsupported("sagas")
1894
+ _check_text("a saga's type", type_name, MAX_NAME)
1895
+ _check_text("an association's key", key, -1)
1896
+ _check_text("an association's value", value, -1)
1897
+ store = self._store
1898
+ async with store._scoped(tx) as conn:
1899
+ rows = await store._fetchall(
1900
+ conn,
1901
+ f"SELECT {self._columns()} FROM snodra_sagas s WHERE s.type = ? AND s.ended = FALSE "
1902
+ "AND EXISTS (SELECT 1 FROM snodra_saga_associations a WHERE a.saga_id = s.id "
1903
+ "AND a.assoc_hash = ? AND a.assoc_key = ? AND a.assoc_value = ?) "
1904
+ "ORDER BY s.created_at, s.id",
1905
+ (type_name, _association_hash(key, value), key, value),
1906
+ )
1907
+ associations = await self._associations(conn, [str(row["id"]) for row in rows])
1908
+ return [_saga_from_row(row, associations.get(str(row["id"]), ())) for row in rows]
1728
1909
 
1729
1910
  async def insert(self, saga: SagaDocument, *, tx: Tx | None = None) -> None:
1730
- raise _unsupported("sagas")
1911
+ self._check(saga)
1912
+ store = self._store
1913
+ async with store._scoped(tx) as conn:
1914
+ if saga.start_key is not None and not saga.ended:
1915
+ if store._driver == DRIVER_POSTGRES:
1916
+ got = await store._fetchval(
1917
+ conn,
1918
+ "SELECT pg_try_advisory_xact_lock(?, hashtext(?)) AS got",
1919
+ (SAGA_START_LOCK, _sha256(saga.start_key)),
1920
+ )
1921
+ if not got:
1922
+ raise Conflict("another transaction is starting a saga with the same start key")
1923
+ previous_timeout: Any = None
1924
+ else:
1925
+ previous_timeout = await store._fetchval(conn, "SELECT @@SESSION.innodb_lock_wait_timeout AS t")
1926
+ await store._exec(conn, "SET SESSION innodb_lock_wait_timeout = 1")
1927
+ try:
1928
+ await store._exec(
1929
+ conn,
1930
+ "INSERT INTO snodra_sagas "
1931
+ "(id, type, state, start_key, start_key_hash, ended, ended_at, version, created_at, updated_at) "
1932
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1933
+ (
1934
+ saga.id,
1935
+ saga.type_name,
1936
+ saga.state,
1937
+ saga.start_key,
1938
+ None if saga.start_key is None else _sha256(saga.start_key),
1939
+ saga.ended,
1940
+ None if saga.ended_at_ms is None else store._time(saga.ended_at_ms),
1941
+ saga.version,
1942
+ store._time(saga.created_at_ms),
1943
+ store._time(saga.updated_at_ms),
1944
+ ),
1945
+ )
1946
+ finally:
1947
+ if saga.start_key is not None and not saga.ended and store._driver == DRIVER_MYSQL:
1948
+ with contextlib.suppress(Exception):
1949
+ await store._exec(conn, "SET SESSION innodb_lock_wait_timeout = ?", (int(previous_timeout),))
1950
+ await self._insert_associations(conn, saga)
1731
1951
 
1732
1952
  async def update(self, saga: SagaDocument, expected_version: int, *, tx: Tx | None = None) -> bool:
1733
- raise _unsupported("sagas")
1953
+ self._check(saga)
1954
+ store = self._store
1955
+ async with store._scoped(tx) as conn:
1956
+ version = await store._fetchval(
1957
+ conn,
1958
+ "SELECT version FROM snodra_sagas WHERE id = ? FOR UPDATE NOWAIT",
1959
+ (saga.id,),
1960
+ )
1961
+ if version is None or int(version) != expected_version:
1962
+ return False
1963
+ await store._exec(
1964
+ conn,
1965
+ "UPDATE snodra_sagas SET type = ?, state = ?, start_key = ?, start_key_hash = ?, ended = ?, "
1966
+ "ended_at = ?, version = ?, created_at = ?, updated_at = ? WHERE id = ? AND version = ?",
1967
+ (
1968
+ saga.type_name,
1969
+ saga.state,
1970
+ saga.start_key,
1971
+ None if saga.start_key is None else _sha256(saga.start_key),
1972
+ saga.ended,
1973
+ None if saga.ended_at_ms is None else store._time(saga.ended_at_ms),
1974
+ saga.version,
1975
+ store._time(saga.created_at_ms),
1976
+ store._time(saga.updated_at_ms),
1977
+ saga.id,
1978
+ expected_version,
1979
+ ),
1980
+ )
1981
+ await store._exec(conn, "DELETE FROM snodra_saga_associations WHERE saga_id = ?", (saga.id,))
1982
+ await self._insert_associations(conn, saga)
1983
+ return True
1734
1984
 
1735
1985
  async def count_live_by_type(self) -> dict[str, int]:
1736
- raise _unsupported("sagas")
1986
+ store = self._store
1987
+ async with store._read() as conn:
1988
+ rows = await store._fetchall(
1989
+ conn,
1990
+ "SELECT type, COUNT(*) AS n FROM snodra_sagas WHERE ended = FALSE GROUP BY type",
1991
+ )
1992
+ return {str(row["type"]): int(row["n"]) for row in rows}
1993
+
1994
+ def _check(self, saga: SagaDocument) -> None:
1995
+ _check_text("a saga's id", saga.id, MAX_ID)
1996
+ _check_text("a saga's type", saga.type_name, MAX_NAME)
1997
+ _check_text("a saga's state", saga.state, -1)
1998
+ if saga.start_key is not None:
1999
+ _check_text("a saga's start key", saga.start_key, -1)
2000
+ for association in saga.associations:
2001
+ _check_text("an association's key", association.key, -1)
2002
+ _check_text("an association's value", association.value, -1)
2003
+
2004
+ async def _insert_associations(self, conn: Any, saga: SagaDocument) -> None:
2005
+ for index, association in enumerate(saga.associations):
2006
+ await self._store._exec(
2007
+ conn,
2008
+ "INSERT INTO snodra_saga_associations (saga_id, idx, assoc_key, assoc_value, assoc_hash) "
2009
+ "VALUES (?, ?, ?, ?, ?)",
2010
+ (
2011
+ saga.id,
2012
+ index,
2013
+ association.key,
2014
+ association.value,
2015
+ _association_hash(association.key, association.value),
2016
+ ),
2017
+ )
2018
+
2019
+ async def _associations(self, conn: Any, ids: Sequence[str]) -> dict[str, tuple[Association, ...]]:
2020
+ if not ids:
2021
+ return {}
2022
+ places = ", ".join("?" for _ in ids)
2023
+ rows = await self._store._fetchall(
2024
+ conn,
2025
+ "SELECT saga_id, assoc_key, assoc_value FROM snodra_saga_associations "
2026
+ f"WHERE saga_id IN ({places}) ORDER BY saga_id, idx",
2027
+ tuple(ids),
2028
+ )
2029
+ grouped: dict[str, list[Association]] = {}
2030
+ for row in rows:
2031
+ grouped.setdefault(str(row["saga_id"]), []).append(
2032
+ Association(str(row["assoc_key"]), str(row["assoc_value"]))
2033
+ )
2034
+ return {saga_id: tuple(items) for saga_id, items in grouped.items()}
1737
2035
 
1738
2036
 
1739
- class _UnsupportedDispatch:
2037
+ def _saga_from_row(row: dict[str, Any], associations: Sequence[Association]) -> SagaDocument:
2038
+ return SagaDocument(
2039
+ id=str(row["id"]),
2040
+ type_name=str(row["type"]),
2041
+ state=str(row["state"]),
2042
+ associations=tuple(associations),
2043
+ start_key=None if row["start_key"] is None else str(row["start_key"]),
2044
+ ended=bool(row["ended"]),
2045
+ ended_at_ms=None if row["ended_at"] is None else _ms_value(row["ended_at"]),
2046
+ version=int(row["version"]),
2047
+ created_at_ms=_ms_value(row["created_at"]),
2048
+ updated_at_ms=_ms_value(row["updated_at"]),
2049
+ )
2050
+
2051
+
2052
+ class _SqlDispatch:
2053
+ """The saga-side outbox and its leases."""
2054
+
2055
+ def __init__(self, store: SqlStore) -> None:
2056
+ self._store = store
2057
+
2058
+ def _columns(self) -> str:
2059
+ return (
2060
+ "id, saga_id, seq, kind, type, payload, "
2061
+ f"CAST(headers AS {self._store._text_type()}) AS headers, routing_key, created_at, dispatched_at, "
2062
+ "attempts, next_attempt_at, failed_at, failure_reason, failure_message, notice_pending, "
2063
+ "notice_attempts, notice_next_at"
2064
+ )
2065
+
1740
2066
  async def record(self, entries: Sequence[SagaDispatchDocument], *, tx: Tx | None = None) -> None:
1741
- raise _unsupported("saga dispatch")
2067
+ for entry in entries:
2068
+ _check_text("a saga-dispatch entry's id", entry.id, MAX_ID)
2069
+ _check_text("a saga-dispatch entry's saga id", entry.saga_id, MAX_ID)
2070
+ _check_text("a saga-dispatch entry's type", entry.type_name, MAX_NAME)
2071
+ if entry.kind is DispatchKind.EVENT:
2072
+ check_outbox_payload(entry.type_name, entry.payload.encode())
2073
+ if not entries:
2074
+ return
2075
+ store = self._store
2076
+ async with store._scoped(tx) as conn:
2077
+ for entry in entries:
2078
+ await store._exec(
2079
+ conn,
2080
+ "INSERT INTO snodra_saga_dispatch "
2081
+ "(id, saga_id, seq, kind, type, payload, headers, routing_key, created_at, dispatched_at, "
2082
+ "attempts, next_attempt_at, failed_at, failure_reason, failure_message, notice_pending, "
2083
+ "notice_attempts, notice_next_at) "
2084
+ f"VALUES (?, ?, ?, ?, ?, ?, CAST(? AS {store._json_type()}), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2085
+ (
2086
+ entry.id,
2087
+ entry.saga_id,
2088
+ entry.seq,
2089
+ entry.kind.value,
2090
+ entry.type_name,
2091
+ entry.payload,
2092
+ _headers_json(entry.headers),
2093
+ entry.routing_key,
2094
+ store._time(entry.created_at_ms),
2095
+ None if entry.dispatched_at_ms is None else store._time(entry.dispatched_at_ms),
2096
+ entry.attempts,
2097
+ None if entry.next_attempt_at_ms is None else store._time(entry.next_attempt_at_ms),
2098
+ None if entry.failed_at_ms is None else store._time(entry.failed_at_ms),
2099
+ None if entry.failure_reason is None else entry.failure_reason.value,
2100
+ entry.failure_message,
2101
+ entry.notice_pending,
2102
+ entry.notice_attempts,
2103
+ None if entry.notice_next_at_ms is None else store._time(entry.notice_next_at_ms),
2104
+ ),
2105
+ )
1742
2106
 
1743
2107
  async def due_sagas(self, now_ms: int, except_sagas: Sequence[str], limit: int) -> list[str]:
1744
- raise _unsupported("saga dispatch")
2108
+ if limit <= 0:
2109
+ return []
2110
+ store = self._store
2111
+ excluded = ""
2112
+ args: list[Any] = []
2113
+ if except_sagas:
2114
+ places = ", ".join("?" for _ in except_sagas)
2115
+ excluded = f"AND d.saga_id NOT IN ({places}) "
2116
+ args.extend(except_sagas)
2117
+ args.extend([store._time(now_ms), int(limit)])
2118
+ async with store._read() as conn:
2119
+ rows = await store._fetchall(
2120
+ conn,
2121
+ "SELECT d.saga_id FROM snodra_saga_dispatch d "
2122
+ "WHERE d.dispatched_at IS NULL AND d.failed_at IS NULL "
2123
+ f"{excluded}"
2124
+ "AND d.seq = (SELECT MIN(x.seq) FROM snodra_saga_dispatch x "
2125
+ "WHERE x.saga_id = d.saga_id AND x.dispatched_at IS NULL AND x.failed_at IS NULL) "
2126
+ "AND (d.next_attempt_at IS NULL OR d.next_attempt_at <= ?) "
2127
+ "ORDER BY d.created_at, d.saga_id LIMIT ?",
2128
+ tuple(args),
2129
+ )
2130
+ return [str(row["saga_id"]) for row in rows]
1745
2131
 
1746
2132
  async def next_pending(self, saga_id: str) -> SagaDispatchDocument | None:
1747
- raise _unsupported("saga dispatch")
2133
+ store = self._store
2134
+ async with store._read() as conn:
2135
+ row = await store._fetchone(
2136
+ conn,
2137
+ f"SELECT {self._columns()} FROM snodra_saga_dispatch "
2138
+ "WHERE saga_id = ? AND dispatched_at IS NULL AND failed_at IS NULL ORDER BY seq LIMIT 1",
2139
+ (saga_id,),
2140
+ )
2141
+ return None if row is None else _dispatch_from_row(row)
1748
2142
 
1749
2143
  async def mark_dispatched(self, entry_id: str, now_ms: int, *, tx: Tx | None = None) -> None:
1750
- raise _unsupported("saga dispatch")
2144
+ store = self._store
2145
+ async with store._scoped(tx) as conn:
2146
+ await store._exec(
2147
+ conn,
2148
+ "UPDATE snodra_saga_dispatch SET dispatched_at = ? WHERE id = ?",
2149
+ (store._time(now_ms), entry_id),
2150
+ )
1751
2151
 
1752
2152
  async def schedule_retry(self, entry_id: str, attempts: int, next_attempt_at_ms: int) -> None:
1753
- raise _unsupported("saga dispatch")
2153
+ store = self._store
2154
+ async with store._own() as conn:
2155
+ await store._exec(
2156
+ conn,
2157
+ "UPDATE snodra_saga_dispatch SET attempts = ?, next_attempt_at = ? WHERE id = ?",
2158
+ (attempts, store._time(next_attempt_at_ms), entry_id),
2159
+ )
1754
2160
 
1755
2161
  async def mark_failed(self, entry_id: str, failure: DispatchFailure) -> None:
1756
- raise _unsupported("saga dispatch")
2162
+ store = self._store
2163
+ sets = ["failed_at = ?", "failure_reason = ?", "failure_message = ?"]
2164
+ args: list[Any] = [store._time(failure.failed_at_ms), failure.reason.value, _cut_free_text(failure.message)]
2165
+ if failure.attempts is not None:
2166
+ sets.append("attempts = ?")
2167
+ args.append(failure.attempts)
2168
+ if failure.notice_at_ms is None:
2169
+ sets.extend(["notice_pending = NULL", "notice_attempts = NULL", "notice_next_at = NULL"])
2170
+ else:
2171
+ sets.extend(["notice_pending = TRUE", "notice_attempts = 0", "notice_next_at = ?"])
2172
+ args.append(store._time(failure.notice_at_ms))
2173
+ args.append(entry_id)
2174
+ async with store._own() as conn:
2175
+ await store._exec(conn, f"UPDATE snodra_saga_dispatch SET {', '.join(sets)} WHERE id = ?", tuple(args))
1757
2176
 
1758
2177
  async def claim_due_notice(self, now_ms: int, reserve_until_ms: int) -> SagaDispatchDocument | None:
1759
- raise _unsupported("saga dispatch")
2178
+ store = self._store
2179
+ async with store._own() as conn:
2180
+ row = await store._fetchone(
2181
+ conn,
2182
+ f"SELECT {self._columns()} FROM snodra_saga_dispatch "
2183
+ "WHERE notice_pending = TRUE AND (notice_next_at IS NULL OR notice_next_at <= ?) "
2184
+ "ORDER BY CASE WHEN notice_next_at IS NULL THEN 0 ELSE 1 END, notice_next_at, id "
2185
+ "LIMIT 1 FOR UPDATE SKIP LOCKED",
2186
+ (store._time(now_ms),),
2187
+ )
2188
+ if row is None:
2189
+ return None
2190
+ await store._exec(
2191
+ conn,
2192
+ "UPDATE snodra_saga_dispatch SET notice_next_at = ? WHERE id = ?",
2193
+ (store._time(reserve_until_ms), str(row["id"])),
2194
+ )
2195
+ claimed = _dispatch_from_row(row)
2196
+ return replace(claimed, notice_next_at_ms=reserve_until_ms)
1760
2197
 
1761
2198
  async def clear_notice(self, entry_id: str) -> None:
1762
- raise _unsupported("saga dispatch")
2199
+ store = self._store
2200
+ async with store._own() as conn:
2201
+ await store._exec(
2202
+ conn,
2203
+ "UPDATE snodra_saga_dispatch SET notice_pending = NULL, notice_attempts = NULL, "
2204
+ "notice_next_at = NULL WHERE id = ?",
2205
+ (entry_id,),
2206
+ )
1763
2207
 
1764
2208
  async def schedule_notice_retry(self, entry_id: str, notice_attempts: int, next_at_ms: int) -> None:
1765
- raise _unsupported("saga dispatch")
2209
+ store = self._store
2210
+ async with store._own() as conn:
2211
+ await store._exec(
2212
+ conn,
2213
+ "UPDATE snodra_saga_dispatch SET notice_attempts = ?, notice_next_at = ? WHERE id = ?",
2214
+ (notice_attempts, store._time(next_at_ms), entry_id),
2215
+ )
1766
2216
 
1767
2217
  async def claim_lease(self, saga_id: str, owner: str, now_ms: int, until_ms: int) -> bool:
1768
- raise _unsupported("saga dispatch")
2218
+ _check_text("a saga id", saga_id, MAX_ID)
2219
+ store = self._store
2220
+ try:
2221
+ async with store._own() as conn:
2222
+ if store._driver == DRIVER_POSTGRES:
2223
+ affected = await store._exec(
2224
+ conn,
2225
+ "INSERT INTO snodra_saga_dispatch_leases (saga_id, owner, lease_until) "
2226
+ "VALUES (?, ?, ?) ON CONFLICT (saga_id) DO UPDATE SET owner = EXCLUDED.owner, "
2227
+ "lease_until = EXCLUDED.lease_until "
2228
+ "WHERE snodra_saga_dispatch_leases.lease_until < ?",
2229
+ (saga_id, owner, store._time(until_ms), store._time(now_ms)),
2230
+ )
2231
+ return affected == 1
2232
+ affected = await store._exec(
2233
+ conn,
2234
+ "UPDATE snodra_saga_dispatch_leases SET owner = ?, lease_until = ? "
2235
+ "WHERE saga_id = ? AND lease_until < ?",
2236
+ (owner, store._time(until_ms), saga_id, store._time(now_ms)),
2237
+ )
2238
+ if affected == 1:
2239
+ return True
2240
+ await store._exec(
2241
+ conn,
2242
+ "INSERT INTO snodra_saga_dispatch_leases (saga_id, owner, lease_until) VALUES (?, ?, ?)",
2243
+ (saga_id, owner, store._time(until_ms)),
2244
+ )
2245
+ return True
2246
+ except Conflict as error:
2247
+ if _duplicate(error) or store._driver == DRIVER_MYSQL:
2248
+ return False
2249
+ raise
1769
2250
 
1770
2251
  async def renew_lease(self, saga_id: str, owner: str, until_ms: int) -> bool:
1771
- raise _unsupported("saga dispatch")
2252
+ store = self._store
2253
+ async with store._own() as conn:
2254
+ affected = await store._exec(
2255
+ conn,
2256
+ "UPDATE snodra_saga_dispatch_leases SET lease_until = ? WHERE saga_id = ? AND owner = ?",
2257
+ (store._time(until_ms), saga_id, owner),
2258
+ )
2259
+ return affected == 1
1772
2260
 
1773
2261
  async def release_lease(self, saga_id: str, owner: str) -> None:
1774
- raise _unsupported("saga dispatch")
2262
+ store = self._store
2263
+ async with store._own() as conn:
2264
+ await store._exec(
2265
+ conn,
2266
+ "DELETE FROM snodra_saga_dispatch_leases WHERE saga_id = ? AND owner = ?",
2267
+ (saga_id, owner),
2268
+ )
1775
2269
 
1776
2270
  async def pending(self) -> int:
1777
- raise _unsupported("saga dispatch")
2271
+ store = self._store
2272
+ async with store._read() as conn:
2273
+ value = await store._fetchval(
2274
+ conn,
2275
+ "SELECT COUNT(*) AS n FROM snodra_saga_dispatch WHERE dispatched_at IS NULL AND failed_at IS NULL",
2276
+ )
2277
+ return 0 if value is None else int(value)
2278
+
2279
+
2280
+ def _dispatch_from_row(row: dict[str, Any]) -> SagaDispatchDocument:
2281
+ return SagaDispatchDocument(
2282
+ id=str(row["id"]),
2283
+ saga_id=str(row["saga_id"]),
2284
+ seq=int(row["seq"]),
2285
+ kind=DispatchKind(str(row["kind"])),
2286
+ type_name=str(row["type"]),
2287
+ payload=str(row["payload"]),
2288
+ headers=_headers_from_json(row["headers"]),
2289
+ routing_key=None if row["routing_key"] is None else str(row["routing_key"]),
2290
+ created_at_ms=_ms_value(row["created_at"]),
2291
+ dispatched_at_ms=None if row["dispatched_at"] is None else _ms_value(row["dispatched_at"]),
2292
+ attempts=int(row["attempts"]),
2293
+ next_attempt_at_ms=None if row["next_attempt_at"] is None else _ms_value(row["next_attempt_at"]),
2294
+ failed_at_ms=None if row["failed_at"] is None else _ms_value(row["failed_at"]),
2295
+ failure_reason=None if row["failure_reason"] is None else FailureReason(str(row["failure_reason"])),
2296
+ failure_message=None if row["failure_message"] is None else str(row["failure_message"]),
2297
+ notice_pending=None if row["notice_pending"] is None else bool(row["notice_pending"]),
2298
+ notice_attempts=None if row["notice_attempts"] is None else int(row["notice_attempts"]),
2299
+ notice_next_at_ms=None if row["notice_next_at"] is None else _ms_value(row["notice_next_at"]),
2300
+ )
1778
2301
 
1779
2302
 
1780
- class _UnsupportedDeadlines:
2303
+ class _SqlDeadlines:
2304
+ """The saga deadlines on ``snodra_deadlines``."""
2305
+
2306
+ def __init__(self, store: SqlStore) -> None:
2307
+ self._store = store
2308
+
2309
+ def _columns(self) -> str:
2310
+ return (
2311
+ "id, saga_type, saga_id, name, payload, payload_type, due_at, correlation_id, status, "
2312
+ "claimed_by, claimed_until, finished_at"
2313
+ )
2314
+
1781
2315
  async def insert(self, deadline: DeadlineDocument, *, tx: Tx | None = None) -> None:
1782
- raise _unsupported("deadlines")
2316
+ self._check(deadline)
2317
+ store = self._store
2318
+ async with store._scoped(tx) as conn:
2319
+ await store._exec(
2320
+ conn,
2321
+ "INSERT INTO snodra_deadlines "
2322
+ "(id, saga_type, saga_id, name, payload, payload_type, due_at, correlation_id, status, "
2323
+ "claimed_by, claimed_until, finished_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2324
+ (
2325
+ deadline.id,
2326
+ deadline.saga_type,
2327
+ deadline.saga_id,
2328
+ deadline.name,
2329
+ deadline.payload,
2330
+ deadline.payload_type,
2331
+ store._time(deadline.due_at_ms),
2332
+ deadline.correlation_id or "",
2333
+ deadline.status.value,
2334
+ deadline.claimed_by,
2335
+ None if deadline.claimed_until_ms is None else store._time(deadline.claimed_until_ms),
2336
+ None if deadline.finished_at_ms is None else store._time(deadline.finished_at_ms),
2337
+ ),
2338
+ )
1783
2339
 
1784
2340
  async def find_scheduled(self, deadline_id: str, *, tx: Tx | None = None) -> DeadlineDocument | None:
1785
- raise _unsupported("deadlines")
2341
+ store = self._store
2342
+ async with store._scoped(tx) as conn:
2343
+ row = await store._fetchone(
2344
+ conn,
2345
+ f"SELECT {self._columns()} FROM snodra_deadlines WHERE id = ? AND status = 'SCHEDULED'",
2346
+ (deadline_id,),
2347
+ )
2348
+ return None if row is None else _deadline_from_row(row)
1786
2349
 
1787
2350
  async def cancel(self, saga_id: str, deadline_id: str, now_ms: int, *, tx: Tx | None = None) -> None:
1788
- raise _unsupported("deadlines")
2351
+ await self._cancel("id = ? AND saga_id = ?", (deadline_id, saga_id), now_ms, tx)
1789
2352
 
1790
2353
  async def cancel_by_name(self, saga_id: str, name: str, now_ms: int, *, tx: Tx | None = None) -> None:
1791
- raise _unsupported("deadlines")
2354
+ await self._cancel("saga_id = ? AND name = ?", (saga_id, name), now_ms, tx)
1792
2355
 
1793
2356
  async def cancel_all(self, saga_id: str, now_ms: int, *, tx: Tx | None = None) -> None:
1794
- raise _unsupported("deadlines")
2357
+ await self._cancel("saga_id = ?", (saga_id,), now_ms, tx)
2358
+
2359
+ async def _cancel(self, condition: str, args: tuple[Any, ...], now_ms: int, tx: Tx | None) -> None:
2360
+ store = self._store
2361
+ async with store._scoped(tx) as conn:
2362
+ await store._exec(
2363
+ conn,
2364
+ f"UPDATE snodra_deadlines SET status = 'CANCELLED', finished_at = ? "
2365
+ f"WHERE {condition} AND status = 'SCHEDULED'",
2366
+ (store._time(now_ms), *args),
2367
+ )
1795
2368
 
1796
2369
  async def mark_fired(self, deadline_id: str, now_ms: int, *, tx: Tx | None = None) -> bool:
1797
- raise _unsupported("deadlines")
2370
+ store = self._store
2371
+ async with store._scoped(tx) as conn:
2372
+ affected = await store._exec(
2373
+ conn,
2374
+ "UPDATE snodra_deadlines SET status = 'FIRED', finished_at = ? WHERE id = ? AND status = 'SCHEDULED'",
2375
+ (store._time(now_ms), deadline_id),
2376
+ )
2377
+ return affected == 1
1798
2378
 
1799
2379
  async def claim_due(self, owner: str, now_ms: int, claimed_until_ms: int) -> DeadlineDocument | None:
1800
- raise _unsupported("deadlines")
2380
+ store = self._store
2381
+ async with store._own() as conn:
2382
+ row = await store._fetchone(
2383
+ conn,
2384
+ f"SELECT {self._columns()} FROM snodra_deadlines WHERE status = 'SCHEDULED' "
2385
+ "AND due_at <= ? AND (claimed_until IS NULL OR claimed_until < ?) "
2386
+ "ORDER BY due_at, id LIMIT 1 FOR UPDATE SKIP LOCKED",
2387
+ (store._time(now_ms), store._time(now_ms)),
2388
+ )
2389
+ if row is None:
2390
+ return None
2391
+ await store._exec(
2392
+ conn,
2393
+ "UPDATE snodra_deadlines SET claimed_by = ?, claimed_until = ? WHERE id = ?",
2394
+ (owner, store._time(claimed_until_ms), str(row["id"])),
2395
+ )
2396
+ return replace(
2397
+ _deadline_from_row(row),
2398
+ claimed_by=owner,
2399
+ claimed_until_ms=claimed_until_ms,
2400
+ )
1801
2401
 
1802
2402
  async def count_overdue_by_name(self, now_ms: int) -> dict[str, int]:
1803
- raise _unsupported("deadlines")
2403
+ store = self._store
2404
+ async with store._read() as conn:
2405
+ rows = await store._fetchall(
2406
+ conn,
2407
+ "SELECT name, COUNT(*) AS n FROM snodra_deadlines "
2408
+ "WHERE status = 'SCHEDULED' AND due_at <= ? GROUP BY name",
2409
+ (store._time(now_ms),),
2410
+ )
2411
+ return {str(row["name"]): int(row["n"]) for row in rows}
2412
+
2413
+ def _check(self, deadline: DeadlineDocument) -> None:
2414
+ _check_text("a deadline's id", deadline.id, MAX_ID)
2415
+ _check_text("a deadline's saga id", deadline.saga_id, MAX_ID)
2416
+ _check_text("a deadline's saga type", deadline.saga_type, MAX_NAME)
2417
+ _check_text("a deadline's name", deadline.name, MAX_NAME)
2418
+ if deadline.payload is not None:
2419
+ _check_text("a deadline's payload", deadline.payload, -1)
2420
+ if deadline.payload_type is not None:
2421
+ _check_text("a deadline's payload type", deadline.payload_type, -1)
2422
+ if deadline.correlation_id is not None:
2423
+ _check_text("a deadline's correlation id", deadline.correlation_id, -1)
2424
+
2425
+
2426
+ def _deadline_from_row(row: dict[str, Any]) -> DeadlineDocument:
2427
+ correlation = row["correlation_id"]
2428
+ return DeadlineDocument(
2429
+ id=str(row["id"]),
2430
+ saga_type=str(row["saga_type"]),
2431
+ saga_id=str(row["saga_id"]),
2432
+ name=str(row["name"]),
2433
+ payload=None if row["payload"] is None else str(row["payload"]),
2434
+ payload_type=None if row["payload_type"] is None else str(row["payload_type"]),
2435
+ due_at_ms=_ms_value(row["due_at"]),
2436
+ status=DeadlineStatus(str(row["status"])),
2437
+ claimed_by=None if row["claimed_by"] is None else str(row["claimed_by"]),
2438
+ claimed_until_ms=None if row["claimed_until"] is None else _ms_value(row["claimed_until"]),
2439
+ finished_at_ms=None if row["finished_at"] is None else _ms_value(row["finished_at"]),
2440
+ correlation_id=None if not correlation else str(correlation),
2441
+ )
2442
+
2443
+
2444
+ class _SqlFailures:
2445
+ """The parked saga events on ``snodra_saga_failures``."""
1804
2446
 
2447
+ def __init__(self, store: SqlStore) -> None:
2448
+ self._store = store
2449
+
2450
+ def _columns(self) -> str:
2451
+ return (
2452
+ "id, saga_type, event_id, event_type, payload, "
2453
+ f"CAST(headers AS {self._store._text_type()}) AS headers, error, attempts, first_failed_at, "
2454
+ "last_failed_at"
2455
+ )
1805
2456
 
1806
- class _UnsupportedFailures:
1807
2457
  async def find(self, failure_id: str, *, tx: Tx | None = None) -> SagaFailureDocument | None:
1808
- raise _unsupported("saga failures")
2458
+ store = self._store
2459
+ async with store._scoped(tx) as conn:
2460
+ row = await store._fetchone(
2461
+ conn,
2462
+ f"SELECT {self._columns()} FROM snodra_saga_failures WHERE id_hash = ?",
2463
+ (_sha256(failure_id),),
2464
+ )
2465
+ return None if row is None else _failure_from_row(row)
1809
2466
 
1810
2467
  async def save(self, failure: SagaFailureDocument, *, tx: Tx | None = None) -> None:
1811
- raise _unsupported("saga failures")
2468
+ _check_text("a saga failure's saga type", failure.saga_type, MAX_NAME)
2469
+ _check_text("a saga failure's id", failure.id, -1)
2470
+ _check_text("a saga failure's event id", failure.event_id, -1)
2471
+ _check_text("a saga failure's event type", failure.event_type, -1)
2472
+ _check_text("a saga failure's payload", failure.payload, -1)
2473
+ store = self._store
2474
+ values = (
2475
+ _sha256(failure.id),
2476
+ failure.id,
2477
+ failure.saga_type,
2478
+ failure.event_id,
2479
+ failure.event_type,
2480
+ failure.payload,
2481
+ _headers_json(failure.headers),
2482
+ _cut_free_text(failure.error),
2483
+ failure.attempts,
2484
+ store._time(failure.first_failed_at_ms),
2485
+ store._time(failure.last_failed_at_ms),
2486
+ )
2487
+ insert = (
2488
+ "INSERT INTO snodra_saga_failures "
2489
+ "(id_hash, id, saga_type, event_id, event_type, payload, headers, error, attempts, "
2490
+ "first_failed_at, last_failed_at) "
2491
+ f"VALUES (?, ?, ?, ?, ?, ?, CAST(? AS {store._json_type()}), ?, ?, ?, ?)"
2492
+ )
2493
+ update = (
2494
+ "id = ?, saga_type = ?, event_id = ?, event_type = ?, payload = ?, "
2495
+ f"headers = CAST(? AS {store._json_type()}), error = ?, attempts = ?, first_failed_at = ?, "
2496
+ "last_failed_at = ?"
2497
+ )
2498
+ async with store._scoped(tx) as conn:
2499
+ if store._driver == DRIVER_POSTGRES:
2500
+ await store._exec(conn, f"{insert} ON CONFLICT (id_hash) DO UPDATE SET {update}", values + values[1:])
2501
+ else:
2502
+ sets = (
2503
+ "id = VALUES(id), saga_type = VALUES(saga_type), event_id = VALUES(event_id), "
2504
+ "event_type = VALUES(event_type), payload = VALUES(payload), headers = VALUES(headers), "
2505
+ "error = VALUES(error), attempts = VALUES(attempts), first_failed_at = VALUES(first_failed_at), "
2506
+ "last_failed_at = VALUES(last_failed_at)"
2507
+ )
2508
+ await store._exec(conn, f"{insert} ON DUPLICATE KEY UPDATE {sets}", values)
1812
2509
 
1813
2510
  async def delete(self, failure_id: str, *, tx: Tx | None = None) -> bool:
1814
- raise _unsupported("saga failures")
2511
+ store = self._store
2512
+ async with store._scoped(tx) as conn:
2513
+ affected = await store._exec(
2514
+ conn, "DELETE FROM snodra_saga_failures WHERE id_hash = ?", (_sha256(failure_id),)
2515
+ )
2516
+ return affected == 1
1815
2517
 
1816
2518
  async def failed_again(
1817
2519
  self, failure_id: str, error: str, attempts: int, now_ms: int, *, tx: Tx | None = None
1818
2520
  ) -> bool:
1819
- raise _unsupported("saga failures")
2521
+ store = self._store
2522
+ async with store._scoped(tx) as conn:
2523
+ affected = await store._exec(
2524
+ conn,
2525
+ "UPDATE snodra_saga_failures SET attempts = attempts + ?, error = ?, last_failed_at = ? "
2526
+ "WHERE id_hash = ?",
2527
+ (attempts, _cut_free_text(error), store._time(now_ms), _sha256(failure_id)),
2528
+ )
2529
+ return affected == 1
1820
2530
 
1821
2531
  async def list(self, saga_type: str | None = None, *, tx: Tx | None = None) -> builtins.list[SagaFailureDocument]:
1822
- raise _unsupported("saga failures")
2532
+ store = self._store
2533
+ query = f"SELECT {self._columns()} FROM snodra_saga_failures"
2534
+ args: list[Any] = []
2535
+ if saga_type is not None:
2536
+ query += " WHERE saga_type = ?"
2537
+ args.append(saga_type)
2538
+ query += " ORDER BY last_failed_at, id_hash"
2539
+ async with store._scoped(tx) as conn:
2540
+ rows = await store._fetchall(conn, query, tuple(args))
2541
+ return [_failure_from_row(row) for row in rows]
1823
2542
 
1824
2543
 
1825
- class _UnsupportedMarkers:
2544
+ def _failure_from_row(row: dict[str, Any]) -> SagaFailureDocument:
2545
+ return SagaFailureDocument(
2546
+ id=str(row["id"]),
2547
+ saga_type=str(row["saga_type"]),
2548
+ event_id=str(row["event_id"]),
2549
+ event_type=str(row["event_type"]),
2550
+ payload=str(row["payload"]),
2551
+ headers=_headers_from_json(row["headers"]),
2552
+ error=str(row["error"]),
2553
+ attempts=int(row["attempts"]),
2554
+ first_failed_at_ms=_ms_value(row["first_failed_at"]),
2555
+ last_failed_at_ms=_ms_value(row["last_failed_at"]),
2556
+ )
2557
+
2558
+
2559
+ class _SqlMarkers:
2560
+ """The saga stage's markers in ``snodra_processed_events``."""
2561
+
2562
+ def __init__(self, store: SqlStore) -> None:
2563
+ self._store = store
2564
+
1826
2565
  async def exists(self, marker_id: str, *, tx: Tx | None = None) -> bool:
1827
- raise _unsupported("saga markers")
2566
+ store = self._store
2567
+ async with store._scoped(tx) as conn:
2568
+ value = await store._fetchval(
2569
+ conn, "SELECT COUNT(*) AS n FROM snodra_processed_events WHERE id_hash = ?", (_sha256(marker_id),)
2570
+ )
2571
+ return bool(value)
1828
2572
 
1829
2573
  async def insert(self, marker_id: str, type_name: str, now_ms: int, *, tx: Tx | None = None) -> None:
1830
- raise _unsupported("saga markers")
2574
+ store = self._store
2575
+ async with store._scoped(tx) as conn:
2576
+ await store._exec(
2577
+ conn,
2578
+ "INSERT INTO snodra_processed_events (id_hash, id, type, processed_at) VALUES (?, ?, ?, ?)",
2579
+ (_sha256(marker_id), marker_id, type_name, store._time(now_ms)),
2580
+ )
1831
2581
 
1832
2582
 
1833
2583
  # ---- values, bounds and drivers -------------------------------------------------------------------
@@ -2098,7 +2848,7 @@ def _affected(status: str) -> int:
2098
2848
 
2099
2849
 
2100
2850
  def _failure(error: BaseException) -> BaseException:
2101
- if isinstance(error, MessageStoreUnsupported | InvalidMessage | Conflict | MessageStoreFailed):
2851
+ if isinstance(error, InvalidMessage | Conflict | MessageStoreFailed):
2102
2852
  return error
2103
2853
  if isinstance(error, asyncpg.PostgresError):
2104
2854
  code = getattr(error, "sqlstate", None)
@@ -3,14 +3,19 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import pytest
6
- from snodra.testing import MESSAGE_STORE_CHECKS, MESSAGE_STORE_L3_CHECKS, run_store_conformance
6
+ from snodra.testing import (
7
+ MESSAGE_STORE_CHECKS,
8
+ MESSAGE_STORE_L3_CHECKS,
9
+ MESSAGE_STORE_L4_CHECKS,
10
+ run_store_conformance,
11
+ )
7
12
  from snodra_sql import SqlStore
8
13
 
9
14
  pytestmark = pytest.mark.timeout(300)
10
15
 
11
16
 
12
17
  async def test_the_sql_message_store_passes_the_kit(store: SqlStore) -> None:
13
- await run_store_conformance(lambda: store, level=3)
18
+ await run_store_conformance(lambda: store, level=4)
14
19
 
15
20
 
16
21
  async def test_the_store_reports_its_name_and_has_the_six_ports(store: SqlStore) -> None:
@@ -45,3 +50,16 @@ def test_the_kit_is_the_nine_level_two_checks_and_the_eight_level_three_ones() -
45
50
  "replay_ranges_round_trip",
46
51
  "processor_control_write_inside_rolled_back_transaction_is_kept",
47
52
  )
53
+ assert tuple(check.__name__ for check in MESSAGE_STORE_L4_CHECKS) == (
54
+ "external_call_idempotency_returns_first_result",
55
+ "saga_ports_round_trip",
56
+ "two_transactions_starting_one_saga_key_leave_one_live_saga",
57
+ "two_transactions_updating_one_saga_version_commit_once",
58
+ "saga_dispatch_store_refuses_an_event_the_outbox_would_refuse",
59
+ "due_deadline_is_claimed_once_until_its_lease_passes",
60
+ "an_empty_deadline_correlation_id_reads_as_absent",
61
+ "two_schedulers_claim_each_due_deadline_once",
62
+ "dispatch_hands_out_each_saga_in_seq_order",
63
+ "two_relays_never_hold_one_saga_lease",
64
+ "concurrent_notice_claims_return_each_notice_once",
65
+ )
@@ -10,7 +10,7 @@ from pathlib import Path
10
10
  from typing import Any
11
11
 
12
12
  import pytest
13
- from snodra import MessageStoreFailed, MessageStoreUnsupported
13
+ from snodra import MessageStoreFailed
14
14
  from snodra_sql import (
15
15
  SCHEMA_VERSION,
16
16
  SqlConfig,
@@ -125,14 +125,6 @@ def test_the_store_offers_the_lifecycle() -> None:
125
125
  assert store._now() == 1_800_000_000_000
126
126
 
127
127
 
128
- async def test_the_unimplemented_ports_name_the_level() -> None:
129
- store = SqlStore(SqlConfig(url="postgres://u@h/db"))
130
- with pytest.raises(MessageStoreUnsupported, match="level 2"):
131
- await store.external.find("key")
132
- with pytest.raises(MessageStoreUnsupported, match="level 2"):
133
- await store.sagas.sagas.find_by_id("id")
134
-
135
-
136
128
  @pytest.mark.timeout(300)
137
129
  async def test_an_empty_database_fails_the_schema_check(database: str, make_config: MakeConfig) -> None:
138
130
  store = SqlStore(make_config())