snodra-messaging-sql 0.5.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.
- snodra_messaging_sql-0.5.0.dist-info/METADATA +129 -0
- snodra_messaging_sql-0.5.0.dist-info/RECORD +9 -0
- snodra_messaging_sql-0.5.0.dist-info/WHEEL +4 -0
- snodra_messaging_sql-0.5.0.dist-info/licenses/LICENSE +202 -0
- snodra_sql/__init__.py +37 -0
- snodra_sql/py.typed +0 -0
- snodra_sql/schema/mysql/V1__snodra.sql +212 -0
- snodra_sql/schema/postgresql/V1__snodra.sql +211 -0
- snodra_sql/sql.py +1708 -0
snodra_sql/sql.py
ADDED
|
@@ -0,0 +1,1708 @@
|
|
|
1
|
+
"""The SQL message store: PostgreSQL and MySQL on the shared layout version 1.
|
|
2
|
+
|
|
3
|
+
The store keeps the outbox and the processed-event markers in the service's own database. Every
|
|
4
|
+
operation joins the transaction bound to the current context (``async with store.transaction()``) or
|
|
5
|
+
runs in a short transaction of its own, at READ COMMITTED; ``store.transaction(conn=conn)`` binds a
|
|
6
|
+
connection the service already runs a transaction on, and the store never commits or rolls it back.
|
|
7
|
+
|
|
8
|
+
The layout is the published SQL version 1, byte for byte:
|
|
9
|
+
|
|
10
|
+
- ``schema/postgresql/V1__snodra.sql`` and ``schema/mysql/V1__snodra.sql``, embedded in the
|
|
11
|
+
package and checked against their published SHA-256 values;
|
|
12
|
+
- twelve ``snodra_`` tables, UTC instants at millisecond precision stamped by the application's
|
|
13
|
+
clock, hashes for values with no bound, bounds checked in code before any write;
|
|
14
|
+
- one schema lock for every Snodra library: PostgreSQL's session advisory lock
|
|
15
|
+
``0x534E44525343484D`` and MySQL's named lock ``snodra_schema``.
|
|
16
|
+
|
|
17
|
+
A claim takes ``SELECT ... FOR UPDATE SKIP LOCKED`` in ``(created_at, seq)`` order. On PostgreSQL an
|
|
18
|
+
append's transaction sends ``pg_notify('snodra_outbox', '')`` and :meth:`SqlStore.outbox`'s
|
|
19
|
+
``on_append`` listens on a connection of its own, so a commit wakes the relay and a rollback wakes
|
|
20
|
+
nobody; MySQL has no notification and the relay polls.
|
|
21
|
+
|
|
22
|
+
The dead-letter, processor-control, external-call and saga ports are part of the interface frozen at
|
|
23
|
+
level 2 and report :class:`snodra.MessageStoreUnsupported` for now. The official add-ons implement
|
|
24
|
+
every port by level 4.
|
|
25
|
+
|
|
26
|
+
See https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import asyncio
|
|
32
|
+
import builtins
|
|
33
|
+
import contextlib
|
|
34
|
+
import hashlib
|
|
35
|
+
import inspect
|
|
36
|
+
import json
|
|
37
|
+
import logging
|
|
38
|
+
import os
|
|
39
|
+
from collections.abc import AsyncIterator, Callable, Sequence
|
|
40
|
+
from contextlib import AbstractAsyncContextManager, asynccontextmanager
|
|
41
|
+
from dataclasses import dataclass, field
|
|
42
|
+
from datetime import UTC, datetime, timedelta
|
|
43
|
+
from importlib.resources import files
|
|
44
|
+
from typing import Any, Final
|
|
45
|
+
from urllib.parse import parse_qs, unquote, urlsplit
|
|
46
|
+
|
|
47
|
+
import asyncmy
|
|
48
|
+
import asyncmy.cursors
|
|
49
|
+
import asyncpg
|
|
50
|
+
from snodra import (
|
|
51
|
+
AppendListener,
|
|
52
|
+
Conflict,
|
|
53
|
+
DeadLetter,
|
|
54
|
+
DeadLetterError,
|
|
55
|
+
DeadLetterStore,
|
|
56
|
+
DeadLetterSummary,
|
|
57
|
+
DeadlineDocument,
|
|
58
|
+
DispatchFailure,
|
|
59
|
+
ExternalCall,
|
|
60
|
+
ExternalCallStore,
|
|
61
|
+
InvalidMessage,
|
|
62
|
+
Locked,
|
|
63
|
+
MessageStoreFailed,
|
|
64
|
+
MessageStoreUnsupported,
|
|
65
|
+
OutboxEntry,
|
|
66
|
+
OutboxStore,
|
|
67
|
+
Parked,
|
|
68
|
+
ProcessedMarker,
|
|
69
|
+
ProcessedStore,
|
|
70
|
+
ProcessorControlState,
|
|
71
|
+
ProcessorControlStore,
|
|
72
|
+
ReplayRange,
|
|
73
|
+
SagaDispatchDocument,
|
|
74
|
+
SagaDocument,
|
|
75
|
+
SagaFailureDocument,
|
|
76
|
+
SagaStores,
|
|
77
|
+
StoreLifecycle,
|
|
78
|
+
Tx,
|
|
79
|
+
bind_transaction,
|
|
80
|
+
check_outbox_payload,
|
|
81
|
+
current_transaction,
|
|
82
|
+
now_ms,
|
|
83
|
+
unbind_transaction,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
log = logging.getLogger(__name__)
|
|
87
|
+
|
|
88
|
+
DRIVER_POSTGRES: Final = "postgres"
|
|
89
|
+
DRIVER_MYSQL: Final = "mysql"
|
|
90
|
+
NAME_POSTGRES: Final = "postgres"
|
|
91
|
+
NAME_MYSQL: Final = "mysql"
|
|
92
|
+
|
|
93
|
+
SCHEMA_VERSION: Final = 1
|
|
94
|
+
"""The schema version this add-on reads and writes; versions are additive."""
|
|
95
|
+
|
|
96
|
+
PUBLISHED_POSTGRES_SHA256: Final = "882bff968f8f2e13e021178f5772d124e6352e3efb3ec104f7e8e5fed254a012"
|
|
97
|
+
PUBLISHED_MYSQL_SHA256: Final = "ec77259da977f07ba83abe8ba9104dcf7a9e292760c87ae712639d786671557d"
|
|
98
|
+
|
|
99
|
+
SCHEMA_POSTGRES_PATH: Final = "schema/postgresql/V1__snodra.sql"
|
|
100
|
+
SCHEMA_MYSQL_PATH: Final = "schema/mysql/V1__snodra.sql"
|
|
101
|
+
|
|
102
|
+
SCHEMA_LOCK_POSTGRES: Final = 0x534E44525343484D # "SNDRSCHM", the same in every library
|
|
103
|
+
SCHEMA_LOCK_MYSQL: Final = "snodra_schema"
|
|
104
|
+
SCHEMA_LOCK_WAIT: Final = 60.0
|
|
105
|
+
SCHEMA_LOCK_POLL: Final = 0.2
|
|
106
|
+
NOTIFY_CHANNEL: Final = "snodra_outbox"
|
|
107
|
+
NOTIFY_HEALTH_CHECK: Final = 30.0
|
|
108
|
+
NOTIFY_NETWORK_TIMEOUT: Final = 10.0
|
|
109
|
+
NOTIFY_MIN_BACKOFF: Final = 0.2
|
|
110
|
+
NOTIFY_MAX_BACKOFF: Final = 30.0
|
|
111
|
+
|
|
112
|
+
MAX_PROCESSOR: Final = 64
|
|
113
|
+
MAX_SOURCE: Final = 255
|
|
114
|
+
MAX_SEGMENT: Final = 128
|
|
115
|
+
MAX_POSITION: Final = 128
|
|
116
|
+
MAX_NAME: Final = 255
|
|
117
|
+
MAX_ID: Final = 255
|
|
118
|
+
FREE_TEXT_BYTES: Final = 16 * 1024
|
|
119
|
+
PURGE_BATCH: Final = 1000
|
|
120
|
+
|
|
121
|
+
DEFAULT_MIN_SIZE: Final = 1
|
|
122
|
+
DEFAULT_MAX_SIZE: Final = 10
|
|
123
|
+
DEFAULT_PURGE_INTERVAL: Final = 60.0
|
|
124
|
+
DEFAULT_OUTBOX_RETENTION: Final = 7 * 24 * 3600.0
|
|
125
|
+
DEFAULT_PROCESSED_RETENTION: Final = 30 * 24 * 3600.0
|
|
126
|
+
DEFAULT_EXTERNAL_CALL_RETENTION: Final = 30 * 24 * 3600.0
|
|
127
|
+
DEFAULT_SAGA_ENDED_RETENTION: Final = 30 * 24 * 3600.0
|
|
128
|
+
DEFAULT_SAGA_DISPATCH_RETENTION: Final = 7 * 24 * 3600.0
|
|
129
|
+
DEFAULT_DEADLINE_RETENTION: Final = 7 * 24 * 3600.0
|
|
130
|
+
DEFAULT_FAILED_RETENTION: Final = 30 * 24 * 3600.0
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True, slots=True)
|
|
134
|
+
class SqlConfig:
|
|
135
|
+
"""How the store reaches its database and how long it keeps what the retentions let go.
|
|
136
|
+
|
|
137
|
+
``url`` is required and names the database: ``postgres://`` or ``postgresql://`` for PostgreSQL,
|
|
138
|
+
``mysql://`` for MySQL. ``driver`` is read from the scheme when empty. Pool sizes are in
|
|
139
|
+
connections (at least two: a write that commits on its own inside the service's transaction takes
|
|
140
|
+
a second one). Retentions and the purge interval are in seconds; a negative purge interval turns
|
|
141
|
+
the background purge off.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
url: str = field(repr=False)
|
|
145
|
+
driver: str | None = None
|
|
146
|
+
min_size: int = DEFAULT_MIN_SIZE
|
|
147
|
+
max_size: int = DEFAULT_MAX_SIZE
|
|
148
|
+
notify: bool = True
|
|
149
|
+
purge_interval: float = DEFAULT_PURGE_INTERVAL
|
|
150
|
+
outbox_retention: float = DEFAULT_OUTBOX_RETENTION
|
|
151
|
+
processed_retention: float = DEFAULT_PROCESSED_RETENTION
|
|
152
|
+
external_call_retention: float = DEFAULT_EXTERNAL_CALL_RETENTION
|
|
153
|
+
saga_ended_retention: float = DEFAULT_SAGA_ENDED_RETENTION
|
|
154
|
+
saga_dispatch_retention: float = DEFAULT_SAGA_DISPATCH_RETENTION
|
|
155
|
+
deadline_retention: float = DEFAULT_DEADLINE_RETENTION
|
|
156
|
+
failed_retention: float = DEFAULT_FAILED_RETENTION
|
|
157
|
+
|
|
158
|
+
def __post_init__(self) -> None:
|
|
159
|
+
url = self.url.strip()
|
|
160
|
+
if not url:
|
|
161
|
+
raise ValueError("the SQL message store needs a database URL (SqlConfig.url, SNODRA_STORE_SQL_URL)")
|
|
162
|
+
driver = self.driver or _driver_from_url(url)
|
|
163
|
+
if driver not in (DRIVER_POSTGRES, DRIVER_MYSQL):
|
|
164
|
+
raise ValueError(
|
|
165
|
+
f"the SQL message store has an unknown driver {driver!r}; it supports {DRIVER_POSTGRES!r} and "
|
|
166
|
+
f"{DRIVER_MYSQL!r} (SNODRA_STORE_SQL_DRIVER)"
|
|
167
|
+
)
|
|
168
|
+
if self.max_size < 2:
|
|
169
|
+
raise ValueError(
|
|
170
|
+
"the SQL message store needs a connection pool of at least 2 (max_size has "
|
|
171
|
+
f"{self.max_size}): a write that commits on its own inside the service's transaction takes a second "
|
|
172
|
+
"connection"
|
|
173
|
+
)
|
|
174
|
+
if self.min_size < 0 or self.min_size > self.max_size:
|
|
175
|
+
raise ValueError("the SQL message store needs a min_size between 0 and max_size")
|
|
176
|
+
for name in (
|
|
177
|
+
"outbox_retention",
|
|
178
|
+
"processed_retention",
|
|
179
|
+
"external_call_retention",
|
|
180
|
+
"saga_ended_retention",
|
|
181
|
+
"saga_dispatch_retention",
|
|
182
|
+
"deadline_retention",
|
|
183
|
+
"failed_retention",
|
|
184
|
+
):
|
|
185
|
+
if getattr(self, name) < 0:
|
|
186
|
+
raise ValueError(f"the SQL message store needs a non-negative {name}, has {getattr(self, name)}")
|
|
187
|
+
object.__setattr__(self, "url", url)
|
|
188
|
+
object.__setattr__(self, "driver", driver)
|
|
189
|
+
if self.purge_interval == 0:
|
|
190
|
+
object.__setattr__(self, "purge_interval", DEFAULT_PURGE_INTERVAL)
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def resolved_driver(self) -> str:
|
|
194
|
+
"""The driver the store runs on, read from the URL when the config names none."""
|
|
195
|
+
return self.driver or _driver_from_url(self.url)
|
|
196
|
+
|
|
197
|
+
@classmethod
|
|
198
|
+
def from_env(cls) -> SqlConfig:
|
|
199
|
+
"""The config from the environment: ``SNODRA_STORE_SQL_URL`` (required), ``SNODRA_STORE_SQL_DRIVER``,
|
|
200
|
+
``SNODRA_STORE_SQL_NOTIFY`` (true or false, default true) and ``SNODRA_STORE_SQL_PURGE_INTERVAL_MS``
|
|
201
|
+
(milliseconds, default 60000; 0 turns the purge off)."""
|
|
202
|
+
driver = os.environ.get("SNODRA_STORE_SQL_DRIVER", "").strip().lower() or None
|
|
203
|
+
if driver == "postgresql":
|
|
204
|
+
driver = DRIVER_POSTGRES
|
|
205
|
+
notify = True
|
|
206
|
+
if os.environ.get("SNODRA_STORE_SQL_NOTIFY", "").strip().lower() in ("false", "0", "no"):
|
|
207
|
+
notify = False
|
|
208
|
+
purge = DEFAULT_PURGE_INTERVAL
|
|
209
|
+
value = os.environ.get("SNODRA_STORE_SQL_PURGE_INTERVAL_MS", "").strip()
|
|
210
|
+
if value:
|
|
211
|
+
with contextlib.suppress(ValueError):
|
|
212
|
+
milliseconds = int(value)
|
|
213
|
+
purge = -1.0 if milliseconds <= 0 else milliseconds / 1000.0
|
|
214
|
+
return cls(
|
|
215
|
+
url=os.environ.get("SNODRA_STORE_SQL_URL", "").strip(),
|
|
216
|
+
driver=driver,
|
|
217
|
+
notify=notify,
|
|
218
|
+
purge_interval=purge,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _driver_from_url(url: str) -> str:
|
|
223
|
+
scheme = urlsplit(url).scheme.lower()
|
|
224
|
+
if scheme in ("postgres", "postgresql"):
|
|
225
|
+
return DRIVER_POSTGRES
|
|
226
|
+
if scheme == "mysql":
|
|
227
|
+
return DRIVER_MYSQL
|
|
228
|
+
raise ValueError(
|
|
229
|
+
f"the SQL message store cannot tell the database from the URL's scheme ({scheme or 'none'}); set driver to "
|
|
230
|
+
f"{DRIVER_POSTGRES!r} or {DRIVER_MYSQL!r} (SNODRA_STORE_SQL_DRIVER)"
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@dataclass(slots=True)
|
|
235
|
+
class _SqlTx:
|
|
236
|
+
"""One transaction: the connection it runs on and whether the store began it."""
|
|
237
|
+
|
|
238
|
+
store: SqlStore
|
|
239
|
+
conn: Any
|
|
240
|
+
native: Any = None
|
|
241
|
+
owned: bool = False
|
|
242
|
+
ended: bool = False
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class _BoundScope(AbstractAsyncContextManager[Tx]):
|
|
246
|
+
"""Binds a service's own connection in its transaction to the current context; ends nothing."""
|
|
247
|
+
|
|
248
|
+
def __init__(self, store: SqlStore, conn: Any) -> None:
|
|
249
|
+
self._store = store
|
|
250
|
+
self._conn = conn
|
|
251
|
+
self._tx: Tx | None = None
|
|
252
|
+
self._token: Any = None
|
|
253
|
+
self._joined = False
|
|
254
|
+
|
|
255
|
+
async def __aenter__(self) -> Tx:
|
|
256
|
+
current = current_transaction()
|
|
257
|
+
if (
|
|
258
|
+
current is not None
|
|
259
|
+
and isinstance(current.inner, _SqlTx)
|
|
260
|
+
and current.inner.store is self._store
|
|
261
|
+
and current.inner.conn is self._conn
|
|
262
|
+
and not current.inner.ended
|
|
263
|
+
):
|
|
264
|
+
self._joined = True
|
|
265
|
+
return current
|
|
266
|
+
self._tx = Tx(_SqlTx(self._store, self._conn, owned=False))
|
|
267
|
+
self._token = bind_transaction(self._tx)
|
|
268
|
+
return self._tx
|
|
269
|
+
|
|
270
|
+
async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
|
|
271
|
+
if self._joined:
|
|
272
|
+
return
|
|
273
|
+
token, self._token = self._token, None
|
|
274
|
+
if token is not None:
|
|
275
|
+
unbind_transaction(token)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class _SqlTransactionScope(AbstractAsyncContextManager[Tx]):
|
|
279
|
+
"""The core's transaction context manager, refusing a transaction bound by another message store."""
|
|
280
|
+
|
|
281
|
+
def __init__(self, store: SqlStore) -> None:
|
|
282
|
+
self._store = store
|
|
283
|
+
self._tx: Tx | None = None
|
|
284
|
+
self._token: Any = None
|
|
285
|
+
self._joined = False
|
|
286
|
+
|
|
287
|
+
async def __aenter__(self) -> Tx:
|
|
288
|
+
current = current_transaction()
|
|
289
|
+
if current is not None and self._store._inner(current) is not None:
|
|
290
|
+
self._joined = True
|
|
291
|
+
return current
|
|
292
|
+
tx = await self._store.begin()
|
|
293
|
+
self._tx = tx
|
|
294
|
+
self._token = bind_transaction(tx)
|
|
295
|
+
return tx
|
|
296
|
+
|
|
297
|
+
async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
|
|
298
|
+
if self._joined:
|
|
299
|
+
return
|
|
300
|
+
tx, self._tx = self._tx, None
|
|
301
|
+
if tx is None:
|
|
302
|
+
return
|
|
303
|
+
try:
|
|
304
|
+
if exc_type is None:
|
|
305
|
+
await self._store.commit(tx)
|
|
306
|
+
else:
|
|
307
|
+
await self._store.rollback(tx)
|
|
308
|
+
finally:
|
|
309
|
+
token, self._token = self._token, None
|
|
310
|
+
if token is not None:
|
|
311
|
+
unbind_transaction(token)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class SqlStore:
|
|
315
|
+
"""The PostgreSQL or MySQL message store: see the module docstring.
|
|
316
|
+
|
|
317
|
+
``clock`` is the application's clock in epoch milliseconds (the wall clock by default), for tests
|
|
318
|
+
that need known times; :meth:`use_clock` replaces it.
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
def __init__(self, config: SqlConfig | None = None, *, clock: Callable[[], int] | None = None) -> None:
|
|
322
|
+
self._config = SqlConfig.from_env() if config is None else config
|
|
323
|
+
self._driver = self._config.resolved_driver
|
|
324
|
+
self._dsn = self._config.url
|
|
325
|
+
self._mysql = _MySQLTarget.parse(self._dsn) if self._driver == DRIVER_MYSQL else None
|
|
326
|
+
self._clock: Callable[[], int] = now_ms if clock is None else clock
|
|
327
|
+
self._pool: Any = None
|
|
328
|
+
self._open_lock = asyncio.Lock()
|
|
329
|
+
self._closed = False
|
|
330
|
+
self._listeners: dict[int, Callable[[], None]] = {}
|
|
331
|
+
self._next_listener = 0
|
|
332
|
+
self._listener_task: asyncio.Task[None] | None = None
|
|
333
|
+
self._listener_conn: Any = None
|
|
334
|
+
self._listens = 0
|
|
335
|
+
self.outbox: OutboxStore = _SqlOutbox(self)
|
|
336
|
+
self.processed: ProcessedStore = _SqlProcessed(self)
|
|
337
|
+
self.dead_letters: DeadLetterStore = _UnsupportedDeadLetters()
|
|
338
|
+
self.control: ProcessorControlStore = _UnsupportedControl()
|
|
339
|
+
self.external: ExternalCallStore = _UnsupportedExternal()
|
|
340
|
+
self.sagas: SagaStores = SagaStores(
|
|
341
|
+
sagas=_UnsupportedSagas(),
|
|
342
|
+
dispatch=_UnsupportedDispatch(),
|
|
343
|
+
deadlines=_UnsupportedDeadlines(),
|
|
344
|
+
failures=_UnsupportedFailures(),
|
|
345
|
+
markers=_UnsupportedMarkers(),
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
@property
|
|
349
|
+
def name(self) -> str:
|
|
350
|
+
"""The add-on's name: ``postgres`` or ``mysql``."""
|
|
351
|
+
return self._driver
|
|
352
|
+
|
|
353
|
+
@property
|
|
354
|
+
def config(self) -> SqlConfig:
|
|
355
|
+
"""The config the store was built with."""
|
|
356
|
+
return self._config
|
|
357
|
+
|
|
358
|
+
@property
|
|
359
|
+
def listens(self) -> int:
|
|
360
|
+
"""How many times the PostgreSQL listener established ``LISTEN`` (0 without one)."""
|
|
361
|
+
return self._listens
|
|
362
|
+
|
|
363
|
+
def use_clock(self, clock: Callable[[], int]) -> None:
|
|
364
|
+
"""The application's clock, epoch milliseconds: what the store stamps its own times with."""
|
|
365
|
+
self._clock = now_ms if clock is None else clock
|
|
366
|
+
|
|
367
|
+
async def open(self) -> None:
|
|
368
|
+
"""Opens the connection pool. Every operation opens it on demand; calling it more than once does nothing."""
|
|
369
|
+
if self._pool is not None:
|
|
370
|
+
return
|
|
371
|
+
async with self._open_lock:
|
|
372
|
+
if self._pool is not None:
|
|
373
|
+
return
|
|
374
|
+
if self._closed:
|
|
375
|
+
raise MessageStoreFailed(f"the SQL message store ({self._driver}) is closed")
|
|
376
|
+
try:
|
|
377
|
+
if self._driver == DRIVER_POSTGRES:
|
|
378
|
+
self._pool = await asyncpg.create_pool(
|
|
379
|
+
dsn=self._dsn,
|
|
380
|
+
min_size=self._config.min_size,
|
|
381
|
+
max_size=self._config.max_size,
|
|
382
|
+
)
|
|
383
|
+
else:
|
|
384
|
+
assert self._mysql is not None
|
|
385
|
+
self._pool = await asyncmy.create_pool(
|
|
386
|
+
**self._mysql.kwargs(),
|
|
387
|
+
minsize=self._config.min_size,
|
|
388
|
+
maxsize=self._config.max_size,
|
|
389
|
+
autocommit=True,
|
|
390
|
+
init_command="SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED",
|
|
391
|
+
)
|
|
392
|
+
except Exception as error:
|
|
393
|
+
raise MessageStoreFailed(f"the SQL message store cannot open its pool: {error}") from error
|
|
394
|
+
|
|
395
|
+
async def close(self) -> None:
|
|
396
|
+
"""Closes the pool and the PostgreSQL listener; the store is not usable afterwards. Idempotent."""
|
|
397
|
+
async with self._open_lock:
|
|
398
|
+
if self._closed:
|
|
399
|
+
return
|
|
400
|
+
self._closed = True
|
|
401
|
+
await self._stop_listener()
|
|
402
|
+
pool, self._pool = self._pool, None
|
|
403
|
+
if pool is not None:
|
|
404
|
+
with contextlib.suppress(Exception):
|
|
405
|
+
if self._driver == DRIVER_POSTGRES:
|
|
406
|
+
await pool.close()
|
|
407
|
+
else:
|
|
408
|
+
pool.close()
|
|
409
|
+
await pool.wait_closed()
|
|
410
|
+
|
|
411
|
+
# ---- transactions -------------------------------------------------------------------------
|
|
412
|
+
|
|
413
|
+
def transaction(self, conn: Any | None = None) -> AbstractAsyncContextManager[Tx]:
|
|
414
|
+
"""A transaction bound to the current context, or a new one.
|
|
415
|
+
|
|
416
|
+
Without ``conn`` this is the core's transaction context manager: it joins a transaction already bound (or
|
|
417
|
+
refuses one bound by another message store), begins one of its own otherwise, and commits or rolls it back.
|
|
418
|
+
With ``conn`` it binds a connection the service already runs a transaction on: the store writes on
|
|
419
|
+
that connection and never commits or rolls it back. ``conn`` is an ``asyncpg.Connection`` or an
|
|
420
|
+
``asyncmy`` connection.
|
|
421
|
+
"""
|
|
422
|
+
if conn is None:
|
|
423
|
+
return _SqlTransactionScope(self)
|
|
424
|
+
# TODO(spec-gap): SG-32
|
|
425
|
+
return _BoundScope(self, conn)
|
|
426
|
+
|
|
427
|
+
def plain(self) -> Tx:
|
|
428
|
+
"""No transaction: what reads and writes outside one use."""
|
|
429
|
+
return Tx.none()
|
|
430
|
+
|
|
431
|
+
async def begin(self) -> Tx:
|
|
432
|
+
"""A transaction of the store's own, at READ COMMITTED."""
|
|
433
|
+
await self.open()
|
|
434
|
+
assert self._pool is not None
|
|
435
|
+
conn = await self._pool.acquire()
|
|
436
|
+
native: Any = None
|
|
437
|
+
try:
|
|
438
|
+
if self._driver == DRIVER_POSTGRES:
|
|
439
|
+
native = conn.transaction(isolation="read_committed")
|
|
440
|
+
await native.start()
|
|
441
|
+
else:
|
|
442
|
+
await self._exec(conn, "SET TRANSACTION ISOLATION LEVEL READ COMMITTED")
|
|
443
|
+
await self._exec(conn, "START TRANSACTION")
|
|
444
|
+
except BaseException as error:
|
|
445
|
+
await self._release(conn)
|
|
446
|
+
if native is not None:
|
|
447
|
+
with contextlib.suppress(BaseException):
|
|
448
|
+
await native.rollback()
|
|
449
|
+
if isinstance(error, asyncio.CancelledError):
|
|
450
|
+
raise
|
|
451
|
+
raise _failure(error) from error
|
|
452
|
+
return Tx(_SqlTx(self, conn, native, owned=True))
|
|
453
|
+
|
|
454
|
+
async def commit(self, tx: Tx) -> None:
|
|
455
|
+
"""Commits what ``tx`` wrote; a transaction it does not own (a service's connection) is left alone."""
|
|
456
|
+
inner = self._inner(tx)
|
|
457
|
+
if inner is None or not inner.owned or inner.ended:
|
|
458
|
+
return
|
|
459
|
+
inner.ended = True
|
|
460
|
+
try:
|
|
461
|
+
if self._driver == DRIVER_POSTGRES:
|
|
462
|
+
await inner.native.commit()
|
|
463
|
+
else:
|
|
464
|
+
await inner.conn.commit()
|
|
465
|
+
except Exception as error:
|
|
466
|
+
raise _failure(error) from error
|
|
467
|
+
finally:
|
|
468
|
+
await self._release(inner.conn)
|
|
469
|
+
|
|
470
|
+
async def rollback(self, tx: Tx) -> None:
|
|
471
|
+
"""Abandons ``tx``'s writes; never fails."""
|
|
472
|
+
inner = self._inner(tx)
|
|
473
|
+
if inner is None or not inner.owned or inner.ended:
|
|
474
|
+
return
|
|
475
|
+
inner.ended = True
|
|
476
|
+
try:
|
|
477
|
+
if self._driver == DRIVER_POSTGRES:
|
|
478
|
+
await inner.native.rollback()
|
|
479
|
+
else:
|
|
480
|
+
await inner.conn.rollback()
|
|
481
|
+
except Exception:
|
|
482
|
+
pass
|
|
483
|
+
finally:
|
|
484
|
+
await self._release(inner.conn)
|
|
485
|
+
|
|
486
|
+
@asynccontextmanager
|
|
487
|
+
async def _scoped(self, tx: Tx | None = None) -> AsyncIterator[Any]:
|
|
488
|
+
"""The connection an append or a marker runs on: the bound or given transaction, or a short one of the
|
|
489
|
+
store's own committed afterwards."""
|
|
490
|
+
inner = self._inner(tx)
|
|
491
|
+
if inner is not None:
|
|
492
|
+
yield inner.conn
|
|
493
|
+
return
|
|
494
|
+
own = await self.begin()
|
|
495
|
+
inner = self._inner(own)
|
|
496
|
+
assert inner is not None
|
|
497
|
+
try:
|
|
498
|
+
yield inner.conn
|
|
499
|
+
except BaseException:
|
|
500
|
+
await self.rollback(own)
|
|
501
|
+
raise
|
|
502
|
+
else:
|
|
503
|
+
await self.commit(own)
|
|
504
|
+
|
|
505
|
+
@asynccontextmanager
|
|
506
|
+
async def _own(self) -> AsyncIterator[Any]:
|
|
507
|
+
"""A connection in a transaction of the store's own at READ COMMITTED, committed afterwards, whatever
|
|
508
|
+
transaction is bound to the caller's context."""
|
|
509
|
+
own = await self.begin()
|
|
510
|
+
inner = self._inner(own)
|
|
511
|
+
assert inner is not None
|
|
512
|
+
try:
|
|
513
|
+
yield inner.conn
|
|
514
|
+
except BaseException:
|
|
515
|
+
await self.rollback(own)
|
|
516
|
+
raise
|
|
517
|
+
else:
|
|
518
|
+
await self.commit(own)
|
|
519
|
+
|
|
520
|
+
@asynccontextmanager
|
|
521
|
+
async def _read(self) -> AsyncIterator[Any]:
|
|
522
|
+
"""A pooled connection for a read outside any transaction (autocommit)."""
|
|
523
|
+
await self.open()
|
|
524
|
+
assert self._pool is not None
|
|
525
|
+
conn = await self._pool.acquire()
|
|
526
|
+
try:
|
|
527
|
+
yield conn
|
|
528
|
+
finally:
|
|
529
|
+
await self._release(conn)
|
|
530
|
+
|
|
531
|
+
def _inner(self, tx: Tx | None) -> _SqlTx | None:
|
|
532
|
+
"""This store's open transaction in ``tx`` (or the bound one when ``tx`` is None); None outside one."""
|
|
533
|
+
chosen = current_transaction() if tx is None else tx
|
|
534
|
+
if chosen is None or chosen.inner is None:
|
|
535
|
+
return None
|
|
536
|
+
inner = chosen.inner
|
|
537
|
+
if not isinstance(inner, _SqlTx) or inner.store is not self:
|
|
538
|
+
raise MessageStoreFailed(
|
|
539
|
+
f"the SQL message store ({self._driver}) was given another message store's transaction"
|
|
540
|
+
)
|
|
541
|
+
return None if inner.ended else inner
|
|
542
|
+
|
|
543
|
+
async def _release(self, conn: Any) -> None:
|
|
544
|
+
if self._pool is None:
|
|
545
|
+
with contextlib.suppress(Exception):
|
|
546
|
+
close = getattr(conn, "close", None)
|
|
547
|
+
if close is not None:
|
|
548
|
+
result = close()
|
|
549
|
+
if inspect.isawaitable(result):
|
|
550
|
+
await result
|
|
551
|
+
return
|
|
552
|
+
result = self._pool.release(conn)
|
|
553
|
+
if inspect.isawaitable(result):
|
|
554
|
+
await result
|
|
555
|
+
|
|
556
|
+
# ---- statements ---------------------------------------------------------------------------
|
|
557
|
+
|
|
558
|
+
def _bind(self, query: str) -> str:
|
|
559
|
+
"""Turns the ``?`` placeholders into the driver's own: ``$n`` for asyncpg, ``%s`` for asyncmy."""
|
|
560
|
+
if self._driver == DRIVER_POSTGRES:
|
|
561
|
+
pieces = query.split("?")
|
|
562
|
+
if len(pieces) == 1:
|
|
563
|
+
return query
|
|
564
|
+
bound: list[str] = [pieces[0]]
|
|
565
|
+
for number, piece in enumerate(pieces[1:], start=1):
|
|
566
|
+
bound.append(f"${number}")
|
|
567
|
+
bound.append(piece)
|
|
568
|
+
return "".join(bound)
|
|
569
|
+
return query.replace("?", "%s") if "?" in query else query
|
|
570
|
+
|
|
571
|
+
async def _exec(self, conn: Any, query: str, args: Sequence[Any] = ()) -> int:
|
|
572
|
+
"""Runs a statement and returns the rows it changed (0 for a statement that changes none)."""
|
|
573
|
+
bound = self._bind(query)
|
|
574
|
+
try:
|
|
575
|
+
if self._driver == DRIVER_POSTGRES:
|
|
576
|
+
status = await conn.execute(bound, *args) if args else await conn.execute(bound)
|
|
577
|
+
return _affected(status)
|
|
578
|
+
async with conn.cursor() as cursor:
|
|
579
|
+
if args:
|
|
580
|
+
await cursor.execute(bound, tuple(args))
|
|
581
|
+
else:
|
|
582
|
+
await cursor.execute(bound)
|
|
583
|
+
return max(0, int(cursor.rowcount))
|
|
584
|
+
except Exception as error:
|
|
585
|
+
raise _failure(error) from error
|
|
586
|
+
|
|
587
|
+
async def _exec_many(self, conn: Any, statements: Sequence[str]) -> None:
|
|
588
|
+
for statement in statements:
|
|
589
|
+
await self._exec(conn, statement)
|
|
590
|
+
|
|
591
|
+
async def _fetchall(self, conn: Any, query: str, args: Sequence[Any] = ()) -> list[dict[str, Any]]:
|
|
592
|
+
bound = self._bind(query)
|
|
593
|
+
try:
|
|
594
|
+
if self._driver == DRIVER_POSTGRES:
|
|
595
|
+
rows = await conn.fetch(bound, *args) if args else await conn.fetch(bound)
|
|
596
|
+
return [dict(row) for row in rows]
|
|
597
|
+
async with conn.cursor(asyncmy.cursors.DictCursor) as cursor:
|
|
598
|
+
if args:
|
|
599
|
+
await cursor.execute(bound, tuple(args))
|
|
600
|
+
else:
|
|
601
|
+
await cursor.execute(bound)
|
|
602
|
+
rows = await cursor.fetchall()
|
|
603
|
+
return list(rows)
|
|
604
|
+
except Exception as error:
|
|
605
|
+
raise _failure(error) from error
|
|
606
|
+
|
|
607
|
+
async def _fetchone(self, conn: Any, query: str, args: Sequence[Any] = ()) -> dict[str, Any] | None:
|
|
608
|
+
rows = await self._fetchall(conn, query, args)
|
|
609
|
+
return rows[0] if rows else None
|
|
610
|
+
|
|
611
|
+
async def _fetchval(self, conn: Any, query: str, args: Sequence[Any] = ()) -> Any:
|
|
612
|
+
row = await self._fetchone(conn, query, args)
|
|
613
|
+
if row is None:
|
|
614
|
+
return None
|
|
615
|
+
return next(iter(row.values()))
|
|
616
|
+
|
|
617
|
+
def _json_type(self) -> str:
|
|
618
|
+
return "jsonb" if self._driver == DRIVER_POSTGRES else "JSON"
|
|
619
|
+
|
|
620
|
+
def _text_type(self) -> str:
|
|
621
|
+
return "TEXT" if self._driver == DRIVER_POSTGRES else "CHAR"
|
|
622
|
+
|
|
623
|
+
# ---- lifecycle ----------------------------------------------------------------------------
|
|
624
|
+
|
|
625
|
+
# TODO(spec-gap): SG-30
|
|
626
|
+
async def init_schema(self) -> None:
|
|
627
|
+
"""Checks the server and applies schema version 1 unless the database has it or later, under the shared
|
|
628
|
+
database lock so instances starting together apply it once.
|
|
629
|
+
|
|
630
|
+
:meth:`snodra.App.start` calls this (or :meth:`check_schema`) and then :meth:`background`; it is public for a
|
|
631
|
+
store constructed after the app started, or used outside an app.
|
|
632
|
+
"""
|
|
633
|
+
await self.open()
|
|
634
|
+
await self._verify_server()
|
|
635
|
+
if await self._schema_version() >= SCHEMA_VERSION:
|
|
636
|
+
return
|
|
637
|
+
await self._apply_schema()
|
|
638
|
+
|
|
639
|
+
async def check_schema(self) -> None:
|
|
640
|
+
"""Fails unless the database has schema version 1 or later: the startup path of a service that applies the
|
|
641
|
+
schema itself."""
|
|
642
|
+
await self.open()
|
|
643
|
+
await self._verify_server()
|
|
644
|
+
version = await self._schema_version()
|
|
645
|
+
if version < SCHEMA_VERSION:
|
|
646
|
+
path = SCHEMA_POSTGRES_PATH if self._driver == DRIVER_POSTGRES else SCHEMA_MYSQL_PATH
|
|
647
|
+
raise MessageStoreFailed(
|
|
648
|
+
f"the SQL message store's schema is at version {version}, it needs {SCHEMA_VERSION} or later: apply "
|
|
649
|
+
f"{path} (and the versions after it), or call init_schema()"
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
async def background(self) -> None:
|
|
653
|
+
"""Runs the retention purge every ``purge_interval`` seconds until cancelled. A negative interval turns it
|
|
654
|
+
off and it waits for cancellation; an error is logged and the next interval runs."""
|
|
655
|
+
if self._config.purge_interval < 0:
|
|
656
|
+
await asyncio.Event().wait()
|
|
657
|
+
while True:
|
|
658
|
+
await asyncio.sleep(self._config.purge_interval)
|
|
659
|
+
try:
|
|
660
|
+
async with asyncio.timeout(30):
|
|
661
|
+
await self.purge_expired()
|
|
662
|
+
except TimeoutError:
|
|
663
|
+
log.warning("the SQL message store's purge did not finish within 30 s")
|
|
664
|
+
except Exception as error:
|
|
665
|
+
log.warning("the SQL message store's purge failed: %s", error)
|
|
666
|
+
|
|
667
|
+
async def purge_expired(self) -> int:
|
|
668
|
+
"""Deletes what the retentions let go and the expired leases; how many rows went."""
|
|
669
|
+
now = self._now()
|
|
670
|
+
steps: tuple[tuple[str, str, str, int], ...] = (
|
|
671
|
+
("snodra_outbox", "id", "sent_at < ?", now - _ms(self._config.outbox_retention)),
|
|
672
|
+
("snodra_processed_events", "id_hash", "processed_at < ?", now - _ms(self._config.processed_retention)),
|
|
673
|
+
("snodra_external_calls", "id_hash", "updated_at < ?", now - _ms(self._config.external_call_retention)),
|
|
674
|
+
("snodra_sagas", "id", "ended = TRUE AND ended_at < ?", now - _ms(self._config.saga_ended_retention)),
|
|
675
|
+
("snodra_saga_dispatch", "id", "dispatched_at < ?", now - _ms(self._config.saga_dispatch_retention)),
|
|
676
|
+
("snodra_saga_dispatch", "id", "failed_at < ?", now - _ms(self._config.failed_retention)),
|
|
677
|
+
("snodra_saga_dispatch_leases", "saga_id", "lease_until < ?", now),
|
|
678
|
+
("snodra_deadlines", "id", "finished_at < ?", now - _ms(self._config.deadline_retention)),
|
|
679
|
+
("snodra_saga_failures", "id_hash", "last_failed_at < ?", now - _ms(self._config.failed_retention)),
|
|
680
|
+
("snodra_dead_letters", "id", "expire_at <= ?", now),
|
|
681
|
+
)
|
|
682
|
+
total = 0
|
|
683
|
+
for table, key, condition, bound in steps:
|
|
684
|
+
total += await self._purge_table(table, key, condition, bound)
|
|
685
|
+
return total
|
|
686
|
+
|
|
687
|
+
async def _purge_table(self, table: str, key: str, condition: str, bound: int) -> int:
|
|
688
|
+
if self._driver == DRIVER_POSTGRES:
|
|
689
|
+
query = (
|
|
690
|
+
f"DELETE FROM {table} WHERE {key} IN (SELECT {key} FROM {table} WHERE {condition} LIMIT {PURGE_BATCH})"
|
|
691
|
+
)
|
|
692
|
+
else:
|
|
693
|
+
query = f"DELETE FROM {table} WHERE {condition} LIMIT {PURGE_BATCH}"
|
|
694
|
+
total = 0
|
|
695
|
+
while True:
|
|
696
|
+
async with self._own() as conn:
|
|
697
|
+
affected = await self._exec(conn, query, (self._time(bound),))
|
|
698
|
+
total += affected
|
|
699
|
+
if affected < PURGE_BATCH:
|
|
700
|
+
return total
|
|
701
|
+
|
|
702
|
+
async def _verify_server(self) -> None:
|
|
703
|
+
if self._config.max_size < 2:
|
|
704
|
+
raise MessageStoreFailed(
|
|
705
|
+
"the SQL message store needs a connection pool of at least 2: a write that commits on its own inside "
|
|
706
|
+
"the service's transaction takes a second connection"
|
|
707
|
+
)
|
|
708
|
+
if self._driver == DRIVER_POSTGRES:
|
|
709
|
+
async with self._read() as conn:
|
|
710
|
+
row = await self._fetchone(
|
|
711
|
+
conn,
|
|
712
|
+
"SELECT version() AS product, current_setting('server_version_num') AS num, "
|
|
713
|
+
"current_setting('server_version') AS version",
|
|
714
|
+
)
|
|
715
|
+
if row is None:
|
|
716
|
+
raise MessageStoreFailed("the SQL message store cannot check the database server")
|
|
717
|
+
_check_postgres_server(str(row["product"]), str(row["num"]), str(row["version"]))
|
|
718
|
+
return
|
|
719
|
+
async with self._read() as conn:
|
|
720
|
+
row = await self._fetchone(conn, "SELECT VERSION() AS version, @@SESSION.sql_mode AS mode")
|
|
721
|
+
if row is None:
|
|
722
|
+
raise MessageStoreFailed("the SQL message store cannot check the database server")
|
|
723
|
+
_check_mysql_server(str(row["version"]), str(row["mode"] or ""))
|
|
724
|
+
|
|
725
|
+
async def _schema_version(self) -> int:
|
|
726
|
+
async with self._read() as conn:
|
|
727
|
+
return await self._schema_version_on(conn)
|
|
728
|
+
|
|
729
|
+
async def _schema_version_on(self, conn: Any) -> int:
|
|
730
|
+
cast = "BIGINT" if self._driver == DRIVER_POSTGRES else "SIGNED"
|
|
731
|
+
try:
|
|
732
|
+
value = await self._fetchval(conn, f"SELECT CAST(MAX(version) AS {cast}) AS v FROM snodra_schema")
|
|
733
|
+
except Exception as error:
|
|
734
|
+
if _missing_table(error):
|
|
735
|
+
return 0
|
|
736
|
+
raise MessageStoreFailed(f"the SQL message store cannot read the schema version: {error}") from error
|
|
737
|
+
return 0 if value is None else int(value)
|
|
738
|
+
|
|
739
|
+
async def _apply_schema(self) -> None:
|
|
740
|
+
path, script = _schema_file(self._driver)
|
|
741
|
+
statements = split_sql(script)
|
|
742
|
+
if not statements:
|
|
743
|
+
raise MessageStoreFailed(f"the SQL message store's embedded schema {path} holds no statement")
|
|
744
|
+
conn = await self._connect_raw()
|
|
745
|
+
try:
|
|
746
|
+
await self._acquire_schema_lock(conn)
|
|
747
|
+
try:
|
|
748
|
+
if await self._schema_version_on(conn) >= SCHEMA_VERSION:
|
|
749
|
+
return
|
|
750
|
+
try:
|
|
751
|
+
if self._driver == DRIVER_POSTGRES:
|
|
752
|
+
native = conn.transaction()
|
|
753
|
+
await native.start()
|
|
754
|
+
try:
|
|
755
|
+
await self._exec_many(conn, statements)
|
|
756
|
+
except BaseException:
|
|
757
|
+
await native.rollback()
|
|
758
|
+
raise
|
|
759
|
+
await native.commit()
|
|
760
|
+
else:
|
|
761
|
+
# TODO(spec-gap): SG-33
|
|
762
|
+
await self._exec_many(conn, statements)
|
|
763
|
+
except Exception as error:
|
|
764
|
+
raise MessageStoreFailed(
|
|
765
|
+
f"the SQL message store could not apply its schema ({path}): apply that file yourself and "
|
|
766
|
+
"do not call init_schema(), or grant the service's database user the right to create tables. "
|
|
767
|
+
f"Cause: {error}"
|
|
768
|
+
) from error
|
|
769
|
+
finally:
|
|
770
|
+
await self._release_schema_lock(conn)
|
|
771
|
+
finally:
|
|
772
|
+
with contextlib.suppress(Exception):
|
|
773
|
+
result = conn.close()
|
|
774
|
+
if inspect.isawaitable(result):
|
|
775
|
+
await result
|
|
776
|
+
|
|
777
|
+
async def _connect_raw(self) -> Any:
|
|
778
|
+
try:
|
|
779
|
+
if self._driver == DRIVER_POSTGRES:
|
|
780
|
+
return await asyncpg.connect(dsn=self._dsn)
|
|
781
|
+
assert self._mysql is not None
|
|
782
|
+
conn = await asyncmy.connect(**self._mysql.kwargs(), autocommit=True)
|
|
783
|
+
await self._exec(conn, "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
|
|
784
|
+
return conn
|
|
785
|
+
except Exception as error:
|
|
786
|
+
raise MessageStoreFailed(f"the SQL message store cannot open a connection: {error}") from error
|
|
787
|
+
|
|
788
|
+
async def _acquire_schema_lock(self, conn: Any) -> None:
|
|
789
|
+
loop = asyncio.get_running_loop()
|
|
790
|
+
deadline = loop.time() + SCHEMA_LOCK_WAIT
|
|
791
|
+
timed_out = MessageStoreFailed(
|
|
792
|
+
f"the SQL message store timed out after {SCHEMA_LOCK_WAIT:g} s waiting for another instance to apply the "
|
|
793
|
+
"schema"
|
|
794
|
+
)
|
|
795
|
+
if self._driver == DRIVER_MYSQL:
|
|
796
|
+
got = await self._fetchval(conn, "SELECT GET_LOCK(?, ?) AS got", (SCHEMA_LOCK_MYSQL, int(SCHEMA_LOCK_WAIT)))
|
|
797
|
+
if got != 1:
|
|
798
|
+
raise timed_out
|
|
799
|
+
return
|
|
800
|
+
while True:
|
|
801
|
+
got = await self._fetchval(conn, "SELECT pg_try_advisory_lock(?) AS got", (SCHEMA_LOCK_POSTGRES,))
|
|
802
|
+
if got:
|
|
803
|
+
return
|
|
804
|
+
if loop.time() >= deadline:
|
|
805
|
+
raise timed_out
|
|
806
|
+
await asyncio.sleep(SCHEMA_LOCK_POLL)
|
|
807
|
+
|
|
808
|
+
async def _release_schema_lock(self, conn: Any) -> None:
|
|
809
|
+
with contextlib.suppress(Exception):
|
|
810
|
+
if self._driver == DRIVER_MYSQL:
|
|
811
|
+
await self._fetchval(conn, "SELECT RELEASE_LOCK(?) AS released", (SCHEMA_LOCK_MYSQL,))
|
|
812
|
+
else:
|
|
813
|
+
await self._fetchval(conn, "SELECT pg_advisory_unlock(?) AS released", (SCHEMA_LOCK_POSTGRES,))
|
|
814
|
+
|
|
815
|
+
# ---- the clock and the wake-up ----------------------------------------------------------------
|
|
816
|
+
|
|
817
|
+
def _now(self) -> int:
|
|
818
|
+
return int(self._clock())
|
|
819
|
+
|
|
820
|
+
def _time(self, milliseconds: int) -> datetime:
|
|
821
|
+
"""A time as the driver's column takes it: aware UTC on PostgreSQL, naive UTC on MySQL."""
|
|
822
|
+
moment = _datetime_from_ms(milliseconds)
|
|
823
|
+
return moment if self._driver == DRIVER_POSTGRES else moment.replace(tzinfo=None)
|
|
824
|
+
|
|
825
|
+
def on_append(self, wake: Callable[[], None]) -> AppendListener:
|
|
826
|
+
"""Registers ``wake`` for every append that commits. On PostgreSQL with notifications on the store listens
|
|
827
|
+
on ``snodra_outbox``; on MySQL, and with notifications off, it registers nothing and the relay polls."""
|
|
828
|
+
if wake is None or self._driver != DRIVER_POSTGRES or not self._config.notify or self._closed:
|
|
829
|
+
return AppendListener(lambda: None)
|
|
830
|
+
try:
|
|
831
|
+
asyncio.get_running_loop()
|
|
832
|
+
except RuntimeError:
|
|
833
|
+
# No loop: a listener cannot run, and the relay will poll.
|
|
834
|
+
return AppendListener(lambda: None)
|
|
835
|
+
self._next_listener += 1
|
|
836
|
+
listener = self._next_listener
|
|
837
|
+
self._listeners[listener] = wake
|
|
838
|
+
self._ensure_listener()
|
|
839
|
+
|
|
840
|
+
def remove() -> None:
|
|
841
|
+
self._listeners.pop(listener, None)
|
|
842
|
+
if not self._listeners:
|
|
843
|
+
self._stop_listener_soon()
|
|
844
|
+
|
|
845
|
+
return AppendListener(remove)
|
|
846
|
+
|
|
847
|
+
def _ensure_listener(self) -> None:
|
|
848
|
+
if self._listener_task is not None and not self._listener_task.done():
|
|
849
|
+
return
|
|
850
|
+
self._listener_task = asyncio.get_running_loop().create_task(self._listen_loop(), name="snodra:sql:listener")
|
|
851
|
+
|
|
852
|
+
def _stop_listener_soon(self) -> None:
|
|
853
|
+
task = self._listener_task
|
|
854
|
+
if task is not None and not task.done():
|
|
855
|
+
task.cancel()
|
|
856
|
+
|
|
857
|
+
async def _stop_listener(self) -> None:
|
|
858
|
+
task, self._listener_task = self._listener_task, None
|
|
859
|
+
if task is not None and not task.done():
|
|
860
|
+
task.cancel()
|
|
861
|
+
if task is not None:
|
|
862
|
+
with contextlib.suppress(BaseException):
|
|
863
|
+
await task
|
|
864
|
+
conn, self._listener_conn = self._listener_conn, None
|
|
865
|
+
if conn is not None:
|
|
866
|
+
with contextlib.suppress(Exception):
|
|
867
|
+
await conn.remove_listener(NOTIFY_CHANNEL, self._notification)
|
|
868
|
+
await conn.close()
|
|
869
|
+
|
|
870
|
+
def _notification(self, *_: Any) -> None:
|
|
871
|
+
self._wake_all()
|
|
872
|
+
|
|
873
|
+
def _wake_all(self) -> None:
|
|
874
|
+
token = bind_transaction(None)
|
|
875
|
+
try:
|
|
876
|
+
for wake in list(self._listeners.values()):
|
|
877
|
+
with contextlib.suppress(Exception):
|
|
878
|
+
wake()
|
|
879
|
+
finally:
|
|
880
|
+
unbind_transaction(token)
|
|
881
|
+
|
|
882
|
+
async def _listen_loop(self) -> None:
|
|
883
|
+
backoff = NOTIFY_MIN_BACKOFF
|
|
884
|
+
while not self._closed:
|
|
885
|
+
conn: Any = None
|
|
886
|
+
try:
|
|
887
|
+
conn = await asyncpg.connect(dsn=self._dsn)
|
|
888
|
+
await conn.add_listener(NOTIFY_CHANNEL, self._notification)
|
|
889
|
+
self._listener_conn = conn
|
|
890
|
+
self._listens += 1
|
|
891
|
+
# An append may have committed while nobody listened.
|
|
892
|
+
self._wake_all()
|
|
893
|
+
while not self._closed:
|
|
894
|
+
await asyncio.sleep(NOTIFY_HEALTH_CHECK)
|
|
895
|
+
await asyncio.wait_for(conn.fetchval("SELECT 1"), timeout=NOTIFY_NETWORK_TIMEOUT)
|
|
896
|
+
return
|
|
897
|
+
except asyncio.CancelledError:
|
|
898
|
+
raise
|
|
899
|
+
except Exception as error:
|
|
900
|
+
if not self._closed:
|
|
901
|
+
log.warning("the SQL message store's PostgreSQL listener: %s", error)
|
|
902
|
+
finally:
|
|
903
|
+
self._listener_conn = None
|
|
904
|
+
if conn is not None:
|
|
905
|
+
with contextlib.suppress(Exception):
|
|
906
|
+
await conn.remove_listener(NOTIFY_CHANNEL, self._notification)
|
|
907
|
+
with contextlib.suppress(Exception):
|
|
908
|
+
await conn.close()
|
|
909
|
+
if self._closed:
|
|
910
|
+
return
|
|
911
|
+
await asyncio.sleep(backoff)
|
|
912
|
+
backoff = min(backoff * 2, NOTIFY_MAX_BACKOFF)
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
# ---- the outbox -----------------------------------------------------------------------------------
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
class _SqlOutbox:
|
|
919
|
+
"""The outbox on ``snodra_outbox``."""
|
|
920
|
+
|
|
921
|
+
def __init__(self, store: SqlStore) -> None:
|
|
922
|
+
self._store = store
|
|
923
|
+
|
|
924
|
+
async def append(self, entry: OutboxEntry, *, tx: Tx | None = None) -> None:
|
|
925
|
+
await self._append(entry, tx)
|
|
926
|
+
|
|
927
|
+
async def append_now(self, entry: OutboxEntry) -> None:
|
|
928
|
+
await self._append(entry, None, own=True)
|
|
929
|
+
|
|
930
|
+
async def _append(self, entry: OutboxEntry, tx: Tx | None, *, own: bool = False) -> None:
|
|
931
|
+
headers = _check_outbox_entry(entry)
|
|
932
|
+
store = self._store
|
|
933
|
+
scope = store._own() if own else store._scoped(tx)
|
|
934
|
+
async with scope as conn:
|
|
935
|
+
await store._exec(
|
|
936
|
+
conn,
|
|
937
|
+
"INSERT INTO snodra_outbox (id, type, event_key, headers, payload, created_at, seq, attempts) "
|
|
938
|
+
f"VALUES (?, ?, ?, CAST(? AS {store._json_type()}), CAST(? AS {store._json_type()}), ?, ?, ?)",
|
|
939
|
+
(
|
|
940
|
+
entry.id,
|
|
941
|
+
entry.type_name,
|
|
942
|
+
entry.key,
|
|
943
|
+
headers,
|
|
944
|
+
bytes(entry.payload).decode("utf-8"),
|
|
945
|
+
store._time(entry.created_at_ms),
|
|
946
|
+
entry.seq,
|
|
947
|
+
entry.attempts,
|
|
948
|
+
),
|
|
949
|
+
)
|
|
950
|
+
if store._driver == DRIVER_POSTGRES and store._config.notify:
|
|
951
|
+
# In the same transaction: delivered at the commit, dropped by a rollback.
|
|
952
|
+
await store._fetchval(conn, "SELECT pg_notify('snodra_outbox', '') AS sent")
|
|
953
|
+
|
|
954
|
+
async def claim(self, owner: str, lease: float, limit: int) -> list[OutboxEntry]:
|
|
955
|
+
if not owner:
|
|
956
|
+
# TODO(spec-gap): SG-31
|
|
957
|
+
raise InvalidMessage("the SQL message store needs a non-empty claim owner")
|
|
958
|
+
if limit <= 0:
|
|
959
|
+
return []
|
|
960
|
+
store = self._store
|
|
961
|
+
now = store._now()
|
|
962
|
+
until = now + _ms(lease)
|
|
963
|
+
async with store._own() as conn:
|
|
964
|
+
rows = await store._fetchall(
|
|
965
|
+
conn,
|
|
966
|
+
"SELECT id, type, event_key, "
|
|
967
|
+
f"CAST(headers AS {store._text_type()}) AS headers, CAST(payload AS {store._text_type()}) AS payload, "
|
|
968
|
+
"created_at, seq, attempts FROM snodra_outbox "
|
|
969
|
+
"WHERE sent_at IS NULL AND failed_at IS NULL AND (owner IS NULL OR owner = ? OR lease_until <= ?) "
|
|
970
|
+
"ORDER BY created_at, seq, id LIMIT ? FOR UPDATE SKIP LOCKED",
|
|
971
|
+
(owner, store._time(now), int(limit)),
|
|
972
|
+
)
|
|
973
|
+
entries = [_entry_from_row(row) for row in rows]
|
|
974
|
+
if entries:
|
|
975
|
+
places = ", ".join("?" for _ in entries)
|
|
976
|
+
await store._exec(
|
|
977
|
+
conn,
|
|
978
|
+
f"UPDATE snodra_outbox SET owner = ?, lease_until = ? WHERE id IN ({places})",
|
|
979
|
+
(owner, store._time(until), *(entry.id for entry in entries)),
|
|
980
|
+
)
|
|
981
|
+
return entries
|
|
982
|
+
|
|
983
|
+
async def mark_sent(self, ids: Sequence[str]) -> None:
|
|
984
|
+
if not ids:
|
|
985
|
+
return
|
|
986
|
+
store = self._store
|
|
987
|
+
places = ", ".join("?" for _ in ids)
|
|
988
|
+
async with store._own() as conn:
|
|
989
|
+
await store._exec(
|
|
990
|
+
conn,
|
|
991
|
+
f"UPDATE snodra_outbox SET sent_at = ? WHERE id IN ({places})",
|
|
992
|
+
(store._time(store._now()), *ids),
|
|
993
|
+
)
|
|
994
|
+
|
|
995
|
+
async def mark_attempt_failed(self, entry_id: str, error: str) -> None:
|
|
996
|
+
store = self._store
|
|
997
|
+
async with store._own() as conn:
|
|
998
|
+
await store._exec(
|
|
999
|
+
conn,
|
|
1000
|
+
"UPDATE snodra_outbox SET attempts = attempts + 1, last_error = ? WHERE id = ?",
|
|
1001
|
+
(_cut_free_text(error), entry_id),
|
|
1002
|
+
)
|
|
1003
|
+
|
|
1004
|
+
async def mark_failed(self, entry_id: str, error: str) -> None:
|
|
1005
|
+
store = self._store
|
|
1006
|
+
async with store._own() as conn:
|
|
1007
|
+
await store._exec(
|
|
1008
|
+
conn,
|
|
1009
|
+
"UPDATE snodra_outbox SET attempts = attempts + 1, last_error = ?, failed_at = ? WHERE id = ?",
|
|
1010
|
+
(_cut_free_text(error), store._time(store._now()), entry_id),
|
|
1011
|
+
)
|
|
1012
|
+
|
|
1013
|
+
async def purge(self, sent_before_ms: int) -> int:
|
|
1014
|
+
return await self._store._purge_table("snodra_outbox", "id", "sent_at < ?", sent_before_ms)
|
|
1015
|
+
|
|
1016
|
+
async def pending(self) -> int:
|
|
1017
|
+
store = self._store
|
|
1018
|
+
async with store._read() as conn:
|
|
1019
|
+
value = await store._fetchval(
|
|
1020
|
+
conn, "SELECT COUNT(*) AS n FROM snodra_outbox WHERE sent_at IS NULL AND failed_at IS NULL"
|
|
1021
|
+
)
|
|
1022
|
+
return 0 if value is None else int(value)
|
|
1023
|
+
|
|
1024
|
+
def on_append(self, wake: Callable[[], None]) -> AppendListener:
|
|
1025
|
+
return self._store.on_append(wake)
|
|
1026
|
+
|
|
1027
|
+
async def oldest_pending(self) -> int | None:
|
|
1028
|
+
store = self._store
|
|
1029
|
+
async with store._read() as conn:
|
|
1030
|
+
row = await store._fetchone(
|
|
1031
|
+
conn,
|
|
1032
|
+
"SELECT created_at FROM snodra_outbox WHERE sent_at IS NULL AND failed_at IS NULL "
|
|
1033
|
+
"ORDER BY created_at, seq LIMIT 1",
|
|
1034
|
+
)
|
|
1035
|
+
return None if row is None else _ms_value(row["created_at"])
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
def _entry_from_row(row: dict[str, Any]) -> OutboxEntry:
|
|
1039
|
+
key = row["event_key"]
|
|
1040
|
+
return OutboxEntry(
|
|
1041
|
+
id=str(row["id"]),
|
|
1042
|
+
type_name=str(row["type"]),
|
|
1043
|
+
key=None if key is None else str(key),
|
|
1044
|
+
headers=_headers_from_json(row["headers"]),
|
|
1045
|
+
payload=str(row["payload"]).encode(),
|
|
1046
|
+
created_at_ms=_ms_value(row["created_at"]),
|
|
1047
|
+
seq=int(row["seq"]),
|
|
1048
|
+
attempts=int(row["attempts"]),
|
|
1049
|
+
)
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
# ---- the processed events -------------------------------------------------------------------------
|
|
1053
|
+
|
|
1054
|
+
|
|
1055
|
+
class _SqlProcessed:
|
|
1056
|
+
"""The processed-event markers on ``snodra_processed_events``."""
|
|
1057
|
+
|
|
1058
|
+
def __init__(self, store: SqlStore) -> None:
|
|
1059
|
+
self._store = store
|
|
1060
|
+
|
|
1061
|
+
async def record(self, marker: ProcessedMarker, *, tx: Tx | None = None) -> bool:
|
|
1062
|
+
_check_marker(marker)
|
|
1063
|
+
store = self._store
|
|
1064
|
+
async with store._scoped(tx) as conn:
|
|
1065
|
+
query = (
|
|
1066
|
+
"INSERT INTO snodra_processed_events "
|
|
1067
|
+
"(id_hash, id, type, processed_at, processor, source, segment, position, position_num) "
|
|
1068
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
1069
|
+
)
|
|
1070
|
+
if store._driver == DRIVER_POSTGRES:
|
|
1071
|
+
query += " ON CONFLICT (id_hash) DO NOTHING"
|
|
1072
|
+
try:
|
|
1073
|
+
affected = await store._exec(
|
|
1074
|
+
conn,
|
|
1075
|
+
query,
|
|
1076
|
+
(
|
|
1077
|
+
_sha256(marker.id),
|
|
1078
|
+
marker.id,
|
|
1079
|
+
marker.type_name,
|
|
1080
|
+
store._time(marker.processed_at_ms),
|
|
1081
|
+
marker.processor or None,
|
|
1082
|
+
marker.source or None,
|
|
1083
|
+
marker.segment or None,
|
|
1084
|
+
marker.position or None,
|
|
1085
|
+
_position_number(marker.position or ""),
|
|
1086
|
+
),
|
|
1087
|
+
)
|
|
1088
|
+
except Exception as error:
|
|
1089
|
+
if store._driver == DRIVER_MYSQL and _duplicate(error):
|
|
1090
|
+
return False
|
|
1091
|
+
raise
|
|
1092
|
+
return affected == 1
|
|
1093
|
+
|
|
1094
|
+
async def exists(self, marker_id: str) -> bool:
|
|
1095
|
+
store = self._store
|
|
1096
|
+
async with store._read() as conn:
|
|
1097
|
+
value = await store._fetchval(
|
|
1098
|
+
conn,
|
|
1099
|
+
"SELECT COUNT(*) AS n FROM snodra_processed_events WHERE id_hash = ?",
|
|
1100
|
+
(_sha256(marker_id),),
|
|
1101
|
+
)
|
|
1102
|
+
return bool(value)
|
|
1103
|
+
|
|
1104
|
+
async def delete_markers(self, processor: str, ranges: Sequence[ReplayRange]) -> int:
|
|
1105
|
+
if not ranges:
|
|
1106
|
+
return 0
|
|
1107
|
+
_check_optional_text("a reset's processor", processor, MAX_PROCESSOR)
|
|
1108
|
+
store = self._store
|
|
1109
|
+
deleted = 0
|
|
1110
|
+
async with store._own() as conn:
|
|
1111
|
+
for replay in ranges:
|
|
1112
|
+
_check_optional_text("a reset range's source", replay.source, MAX_SOURCE)
|
|
1113
|
+
_check_optional_text("a reset range's segment", replay.segment, MAX_SEGMENT)
|
|
1114
|
+
_check_optional_text("a reset range's from position", replay.start, MAX_POSITION)
|
|
1115
|
+
_check_optional_text("a reset range's until position", replay.until, MAX_POSITION)
|
|
1116
|
+
from_clause, from_arg = _position_bound(">=", replay.start)
|
|
1117
|
+
until_clause, until_arg = _position_bound("<", replay.until)
|
|
1118
|
+
deleted += await store._exec(
|
|
1119
|
+
conn,
|
|
1120
|
+
"DELETE FROM snodra_processed_events WHERE processor = ? AND source = ? AND segment = ? "
|
|
1121
|
+
f"AND {from_clause} AND {until_clause}",
|
|
1122
|
+
(processor, replay.source, replay.segment, from_arg, until_arg),
|
|
1123
|
+
)
|
|
1124
|
+
return deleted
|
|
1125
|
+
|
|
1126
|
+
async def purge(self, before_ms: int) -> int:
|
|
1127
|
+
return await self._store._purge_table("snodra_processed_events", "id_hash", "processed_at < ?", before_ms)
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _position_bound(op: str, position: str) -> tuple[str, Any]:
|
|
1131
|
+
number = _position_number(position)
|
|
1132
|
+
if number is not None:
|
|
1133
|
+
return f"position_num {op} ?", number
|
|
1134
|
+
return f"position_num IS NULL AND position {op} ?", position
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
# ---- the ports this level does not implement ------------------------------------------------------
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def _unsupported(what: str) -> MessageStoreUnsupported:
|
|
1141
|
+
return MessageStoreUnsupported(f"{what} in the SQL message store (level 2)")
|
|
1142
|
+
|
|
1143
|
+
|
|
1144
|
+
class _UnsupportedDeadLetters:
|
|
1145
|
+
async def park(self, letter: DeadLetter) -> Parked:
|
|
1146
|
+
raise _unsupported("dead_letters")
|
|
1147
|
+
|
|
1148
|
+
async def head(self, processor: str, key: str) -> str | None:
|
|
1149
|
+
raise _unsupported("dead_letters")
|
|
1150
|
+
|
|
1151
|
+
async def earlier(self, processor: str, key: str, position: str) -> str | None:
|
|
1152
|
+
raise _unsupported("dead_letters")
|
|
1153
|
+
|
|
1154
|
+
async def parked_keys(self, processor: str, source: str, segments: Sequence[str]) -> set[str]:
|
|
1155
|
+
raise _unsupported("dead_letters")
|
|
1156
|
+
|
|
1157
|
+
async def get(self, letter: str) -> DeadLetter | None:
|
|
1158
|
+
raise _unsupported("dead_letters")
|
|
1159
|
+
|
|
1160
|
+
async def list(self, processor: str | None = None, limit: int | None = None) -> builtins.list[DeadLetter]:
|
|
1161
|
+
raise _unsupported("dead_letters")
|
|
1162
|
+
|
|
1163
|
+
async def summaries(self, processor: str) -> builtins.list[DeadLetterSummary]:
|
|
1164
|
+
raise _unsupported("dead_letters")
|
|
1165
|
+
|
|
1166
|
+
async def count(self, processor: str | None = None) -> int:
|
|
1167
|
+
raise _unsupported("dead_letters")
|
|
1168
|
+
|
|
1169
|
+
async def delete(self, letter: str) -> bool:
|
|
1170
|
+
raise _unsupported("dead_letters")
|
|
1171
|
+
|
|
1172
|
+
async def delete_in(self, letter: str, *, tx: Tx | None = None) -> bool:
|
|
1173
|
+
raise _unsupported("dead_letters")
|
|
1174
|
+
|
|
1175
|
+
async def record_failure(self, letter: str, error: DeadLetterError, now_ms: int) -> bool:
|
|
1176
|
+
raise _unsupported("dead_letters")
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
class _UnsupportedControl:
|
|
1180
|
+
async def get(self, processor: str) -> ProcessorControlState:
|
|
1181
|
+
raise _unsupported("processor control")
|
|
1182
|
+
|
|
1183
|
+
async def set_paused(self, processor: str, paused: bool, by: str, now_ms: int) -> None:
|
|
1184
|
+
raise _unsupported("processor control")
|
|
1185
|
+
|
|
1186
|
+
async def lock(self, processor: str, operation: str, lease_until_ms: int, now_ms: int) -> Locked:
|
|
1187
|
+
raise _unsupported("processor control")
|
|
1188
|
+
|
|
1189
|
+
async def extend(self, processor: str, operation: str, lease_until_ms: int, now_ms: int) -> bool:
|
|
1190
|
+
raise _unsupported("processor control")
|
|
1191
|
+
|
|
1192
|
+
async def release(self, processor: str, operation: str, now_ms: int) -> bool:
|
|
1193
|
+
raise _unsupported("processor control")
|
|
1194
|
+
|
|
1195
|
+
async def expire(self, processor: str, operation: str, now_ms: int) -> bool:
|
|
1196
|
+
raise _unsupported("processor control")
|
|
1197
|
+
|
|
1198
|
+
async def set_replay(self, processor: str, ranges: Sequence[ReplayRange], now_ms: int) -> None:
|
|
1199
|
+
raise _unsupported("processor control")
|
|
1200
|
+
|
|
1201
|
+
async def remove_range(self, processor: str, replay_range: ReplayRange, now_ms: int) -> bool:
|
|
1202
|
+
raise _unsupported("processor control")
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
class _UnsupportedExternal:
|
|
1206
|
+
async def insert(self, call: ExternalCall) -> bool:
|
|
1207
|
+
raise _unsupported("external calls")
|
|
1208
|
+
|
|
1209
|
+
async def find(self, key: str) -> ExternalCall | None:
|
|
1210
|
+
raise _unsupported("external calls")
|
|
1211
|
+
|
|
1212
|
+
async def take_over(self, seen: ExternalCall, owner: str, lease_until_ms: int, now_ms: int) -> ExternalCall | None:
|
|
1213
|
+
raise _unsupported("external calls")
|
|
1214
|
+
|
|
1215
|
+
async def expire(self, seen: ExternalCall, now_ms: int) -> bool:
|
|
1216
|
+
raise _unsupported("external calls")
|
|
1217
|
+
|
|
1218
|
+
async def succeed(self, key: str, owner: str, reply: str, now_ms: int) -> bool:
|
|
1219
|
+
raise _unsupported("external calls")
|
|
1220
|
+
|
|
1221
|
+
async def fail(self, key: str, owner: str, error: str, now_ms: int) -> bool:
|
|
1222
|
+
raise _unsupported("external calls")
|
|
1223
|
+
|
|
1224
|
+
async def mark_unknown(self, key: str, owner: str, now_ms: int) -> bool:
|
|
1225
|
+
raise _unsupported("external calls")
|
|
1226
|
+
|
|
1227
|
+
async def reset(self, key: str, owner: str) -> bool:
|
|
1228
|
+
raise _unsupported("external calls")
|
|
1229
|
+
|
|
1230
|
+
|
|
1231
|
+
class _UnsupportedSagas:
|
|
1232
|
+
async def find_by_id(self, saga_id: str, *, tx: Tx | None = None) -> SagaDocument | None:
|
|
1233
|
+
raise _unsupported("sagas")
|
|
1234
|
+
|
|
1235
|
+
async def find_live(self, type_name: str, key: str, value: str, *, tx: Tx | None = None) -> list[SagaDocument]:
|
|
1236
|
+
raise _unsupported("sagas")
|
|
1237
|
+
|
|
1238
|
+
async def insert(self, saga: SagaDocument, *, tx: Tx | None = None) -> None:
|
|
1239
|
+
raise _unsupported("sagas")
|
|
1240
|
+
|
|
1241
|
+
async def update(self, saga: SagaDocument, expected_version: int, *, tx: Tx | None = None) -> bool:
|
|
1242
|
+
raise _unsupported("sagas")
|
|
1243
|
+
|
|
1244
|
+
async def count_live_by_type(self) -> dict[str, int]:
|
|
1245
|
+
raise _unsupported("sagas")
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
class _UnsupportedDispatch:
|
|
1249
|
+
async def record(self, entries: Sequence[SagaDispatchDocument], *, tx: Tx | None = None) -> None:
|
|
1250
|
+
raise _unsupported("saga dispatch")
|
|
1251
|
+
|
|
1252
|
+
async def due_sagas(self, now_ms: int, except_sagas: Sequence[str], limit: int) -> list[str]:
|
|
1253
|
+
raise _unsupported("saga dispatch")
|
|
1254
|
+
|
|
1255
|
+
async def next_pending(self, saga_id: str) -> SagaDispatchDocument | None:
|
|
1256
|
+
raise _unsupported("saga dispatch")
|
|
1257
|
+
|
|
1258
|
+
async def mark_dispatched(self, entry_id: str, now_ms: int, *, tx: Tx | None = None) -> None:
|
|
1259
|
+
raise _unsupported("saga dispatch")
|
|
1260
|
+
|
|
1261
|
+
async def schedule_retry(self, entry_id: str, attempts: int, next_attempt_at_ms: int) -> None:
|
|
1262
|
+
raise _unsupported("saga dispatch")
|
|
1263
|
+
|
|
1264
|
+
async def mark_failed(self, entry_id: str, failure: DispatchFailure) -> None:
|
|
1265
|
+
raise _unsupported("saga dispatch")
|
|
1266
|
+
|
|
1267
|
+
async def claim_due_notice(self, now_ms: int, reserve_until_ms: int) -> SagaDispatchDocument | None:
|
|
1268
|
+
raise _unsupported("saga dispatch")
|
|
1269
|
+
|
|
1270
|
+
async def clear_notice(self, entry_id: str) -> None:
|
|
1271
|
+
raise _unsupported("saga dispatch")
|
|
1272
|
+
|
|
1273
|
+
async def schedule_notice_retry(self, entry_id: str, notice_attempts: int, next_at_ms: int) -> None:
|
|
1274
|
+
raise _unsupported("saga dispatch")
|
|
1275
|
+
|
|
1276
|
+
async def claim_lease(self, saga_id: str, owner: str, now_ms: int, until_ms: int) -> bool:
|
|
1277
|
+
raise _unsupported("saga dispatch")
|
|
1278
|
+
|
|
1279
|
+
async def renew_lease(self, saga_id: str, owner: str, until_ms: int) -> bool:
|
|
1280
|
+
raise _unsupported("saga dispatch")
|
|
1281
|
+
|
|
1282
|
+
async def release_lease(self, saga_id: str, owner: str) -> None:
|
|
1283
|
+
raise _unsupported("saga dispatch")
|
|
1284
|
+
|
|
1285
|
+
async def pending(self) -> int:
|
|
1286
|
+
raise _unsupported("saga dispatch")
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
class _UnsupportedDeadlines:
|
|
1290
|
+
async def insert(self, deadline: DeadlineDocument, *, tx: Tx | None = None) -> None:
|
|
1291
|
+
raise _unsupported("deadlines")
|
|
1292
|
+
|
|
1293
|
+
async def find_scheduled(self, deadline_id: str, *, tx: Tx | None = None) -> DeadlineDocument | None:
|
|
1294
|
+
raise _unsupported("deadlines")
|
|
1295
|
+
|
|
1296
|
+
async def cancel(self, saga_id: str, deadline_id: str, now_ms: int, *, tx: Tx | None = None) -> None:
|
|
1297
|
+
raise _unsupported("deadlines")
|
|
1298
|
+
|
|
1299
|
+
async def cancel_by_name(self, saga_id: str, name: str, now_ms: int, *, tx: Tx | None = None) -> None:
|
|
1300
|
+
raise _unsupported("deadlines")
|
|
1301
|
+
|
|
1302
|
+
async def cancel_all(self, saga_id: str, now_ms: int, *, tx: Tx | None = None) -> None:
|
|
1303
|
+
raise _unsupported("deadlines")
|
|
1304
|
+
|
|
1305
|
+
async def mark_fired(self, deadline_id: str, now_ms: int, *, tx: Tx | None = None) -> bool:
|
|
1306
|
+
raise _unsupported("deadlines")
|
|
1307
|
+
|
|
1308
|
+
async def claim_due(self, owner: str, now_ms: int, claimed_until_ms: int) -> DeadlineDocument | None:
|
|
1309
|
+
raise _unsupported("deadlines")
|
|
1310
|
+
|
|
1311
|
+
async def count_overdue_by_name(self, now_ms: int) -> dict[str, int]:
|
|
1312
|
+
raise _unsupported("deadlines")
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
class _UnsupportedFailures:
|
|
1316
|
+
async def find(self, failure_id: str, *, tx: Tx | None = None) -> SagaFailureDocument | None:
|
|
1317
|
+
raise _unsupported("saga failures")
|
|
1318
|
+
|
|
1319
|
+
async def save(self, failure: SagaFailureDocument, *, tx: Tx | None = None) -> None:
|
|
1320
|
+
raise _unsupported("saga failures")
|
|
1321
|
+
|
|
1322
|
+
async def delete(self, failure_id: str, *, tx: Tx | None = None) -> bool:
|
|
1323
|
+
raise _unsupported("saga failures")
|
|
1324
|
+
|
|
1325
|
+
async def failed_again(
|
|
1326
|
+
self, failure_id: str, error: str, attempts: int, now_ms: int, *, tx: Tx | None = None
|
|
1327
|
+
) -> bool:
|
|
1328
|
+
raise _unsupported("saga failures")
|
|
1329
|
+
|
|
1330
|
+
async def list(self, saga_type: str | None = None, *, tx: Tx | None = None) -> builtins.list[SagaFailureDocument]:
|
|
1331
|
+
raise _unsupported("saga failures")
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
class _UnsupportedMarkers:
|
|
1335
|
+
async def exists(self, marker_id: str, *, tx: Tx | None = None) -> bool:
|
|
1336
|
+
raise _unsupported("saga markers")
|
|
1337
|
+
|
|
1338
|
+
async def insert(self, marker_id: str, type_name: str, now_ms: int, *, tx: Tx | None = None) -> None:
|
|
1339
|
+
raise _unsupported("saga markers")
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
# ---- values, bounds and drivers -------------------------------------------------------------------
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
@dataclass(frozen=True, slots=True)
|
|
1346
|
+
class _MySQLTarget:
|
|
1347
|
+
"""The parts of a ``mysql://`` URL the driver takes."""
|
|
1348
|
+
|
|
1349
|
+
host: str
|
|
1350
|
+
port: int
|
|
1351
|
+
user: str
|
|
1352
|
+
password: str = field(repr=False)
|
|
1353
|
+
database: str
|
|
1354
|
+
charset: str
|
|
1355
|
+
options: dict[str, Any]
|
|
1356
|
+
|
|
1357
|
+
@classmethod
|
|
1358
|
+
def parse(cls, url: str) -> _MySQLTarget:
|
|
1359
|
+
parsed = urlsplit(url)
|
|
1360
|
+
if parsed.scheme.lower() != "mysql":
|
|
1361
|
+
raise ValueError("the SQL message store reads a MySQL URL as mysql://user:password@host:port/database")
|
|
1362
|
+
database = unquote(parsed.path.lstrip("/"))
|
|
1363
|
+
if not database:
|
|
1364
|
+
raise ValueError("the MySQL URL names no database")
|
|
1365
|
+
query = parse_qs(parsed.query, keep_blank_values=True)
|
|
1366
|
+
options: dict[str, Any] = {}
|
|
1367
|
+
for name, values in query.items():
|
|
1368
|
+
value = values[-1]
|
|
1369
|
+
if name in ("parseTime", "loc", "multiStatements"):
|
|
1370
|
+
continue
|
|
1371
|
+
if name in ("port", "connect_timeout", "read_timeout", "write_timeout"):
|
|
1372
|
+
with contextlib.suppress(ValueError):
|
|
1373
|
+
options[name] = int(value)
|
|
1374
|
+
continue
|
|
1375
|
+
options[name] = value
|
|
1376
|
+
charset = str(options.pop("charset", "utf8mb4"))
|
|
1377
|
+
return cls(
|
|
1378
|
+
host=parsed.hostname or "localhost",
|
|
1379
|
+
port=parsed.port or 3306,
|
|
1380
|
+
user=unquote(parsed.username or ""),
|
|
1381
|
+
password=unquote(parsed.password or ""),
|
|
1382
|
+
database=database,
|
|
1383
|
+
charset=charset,
|
|
1384
|
+
options=options,
|
|
1385
|
+
)
|
|
1386
|
+
|
|
1387
|
+
def kwargs(self) -> dict[str, Any]:
|
|
1388
|
+
"""The keyword arguments ``asyncmy.connect`` and ``asyncmy.create_pool`` take."""
|
|
1389
|
+
return {
|
|
1390
|
+
"host": self.host,
|
|
1391
|
+
"port": self.port,
|
|
1392
|
+
"user": self.user,
|
|
1393
|
+
"password": self.password,
|
|
1394
|
+
"db": self.database,
|
|
1395
|
+
"charset": self.charset,
|
|
1396
|
+
**self.options,
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
|
|
1400
|
+
def _schema_file(driver: str) -> tuple[str, str]:
|
|
1401
|
+
path = SCHEMA_POSTGRES_PATH if driver == DRIVER_POSTGRES else SCHEMA_MYSQL_PATH
|
|
1402
|
+
return path, files("snodra_sql").joinpath(path).read_text(encoding="utf-8")
|
|
1403
|
+
|
|
1404
|
+
|
|
1405
|
+
def split_sql(script: str) -> list[str]:
|
|
1406
|
+
"""Splits a schema script into its statements, dropping comments.
|
|
1407
|
+
|
|
1408
|
+
Single and double quotes (with their doubled-quote escape), MySQL backticks and backslash escapes in
|
|
1409
|
+
quoted strings are understood, so a semicolon inside one does not end a statement.
|
|
1410
|
+
"""
|
|
1411
|
+
statements: list[str] = []
|
|
1412
|
+
statement: list[str] = []
|
|
1413
|
+
index = 0
|
|
1414
|
+
length = len(script)
|
|
1415
|
+
while index < length:
|
|
1416
|
+
char = script[index]
|
|
1417
|
+
if char == "-" and index + 1 < length and script[index + 1] == "-":
|
|
1418
|
+
while index < length and script[index] != "\n":
|
|
1419
|
+
index += 1
|
|
1420
|
+
elif char == "/" and index + 1 < length and script[index + 1] == "*":
|
|
1421
|
+
index += 2
|
|
1422
|
+
while index + 1 < length and (script[index] != "*" or script[index + 1] != "/"):
|
|
1423
|
+
index += 1
|
|
1424
|
+
index = min(length, index + 2)
|
|
1425
|
+
statement.append(" ")
|
|
1426
|
+
elif char in ("'", '"', "`"):
|
|
1427
|
+
quote = char
|
|
1428
|
+
statement.append(char)
|
|
1429
|
+
index += 1
|
|
1430
|
+
while index < length:
|
|
1431
|
+
statement.append(script[index])
|
|
1432
|
+
if script[index] == quote:
|
|
1433
|
+
if index + 1 < length and script[index + 1] == quote:
|
|
1434
|
+
statement.append(script[index + 1])
|
|
1435
|
+
index += 2
|
|
1436
|
+
continue
|
|
1437
|
+
index += 1
|
|
1438
|
+
break
|
|
1439
|
+
if script[index] == "\\" and quote != "`":
|
|
1440
|
+
index += 1
|
|
1441
|
+
if index < length:
|
|
1442
|
+
statement.append(script[index])
|
|
1443
|
+
index += 1
|
|
1444
|
+
continue
|
|
1445
|
+
index += 1
|
|
1446
|
+
elif char == ";":
|
|
1447
|
+
text = "".join(statement).strip()
|
|
1448
|
+
if text:
|
|
1449
|
+
statements.append(text)
|
|
1450
|
+
statement = []
|
|
1451
|
+
index += 1
|
|
1452
|
+
else:
|
|
1453
|
+
statement.append(char)
|
|
1454
|
+
index += 1
|
|
1455
|
+
text = "".join(statement).strip()
|
|
1456
|
+
if text:
|
|
1457
|
+
statements.append(text)
|
|
1458
|
+
return statements
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
def _check_text(field_name: str, value: str, maximum: int) -> None:
|
|
1462
|
+
if not isinstance(value, str):
|
|
1463
|
+
raise InvalidMessage(f"the SQL message store needs {field_name} to be text, got {type(value).__name__}")
|
|
1464
|
+
try:
|
|
1465
|
+
value.encode("utf-8")
|
|
1466
|
+
except UnicodeEncodeError as error:
|
|
1467
|
+
raise InvalidMessage(f"the SQL message store refuses text that is not UTF-8 in {field_name}") from error
|
|
1468
|
+
if "\x00" in value:
|
|
1469
|
+
raise InvalidMessage(f"the SQL message store refuses the character U+0000 in {field_name}")
|
|
1470
|
+
if maximum >= 0 and len(value) > maximum:
|
|
1471
|
+
raise InvalidMessage(
|
|
1472
|
+
f"the SQL message store keeps {field_name} of at most {maximum} characters; this one has {len(value)}"
|
|
1473
|
+
)
|
|
1474
|
+
|
|
1475
|
+
|
|
1476
|
+
def _check_optional_text(field_name: str, value: str, maximum: int) -> None:
|
|
1477
|
+
if value:
|
|
1478
|
+
_check_text(field_name, value, maximum)
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
def _check_outbox_entry(entry: OutboxEntry) -> str:
|
|
1482
|
+
check_outbox_payload(entry.type_name, entry.payload)
|
|
1483
|
+
_check_text("an outbox entry's id", entry.id, MAX_ID)
|
|
1484
|
+
_check_text("an outbox entry's type", entry.type_name, MAX_NAME)
|
|
1485
|
+
if entry.key is not None:
|
|
1486
|
+
_check_text("an outbox entry's key", entry.key, -1)
|
|
1487
|
+
headers = _headers_json(entry.headers)
|
|
1488
|
+
if _payload_has_nul(entry.payload):
|
|
1489
|
+
raise InvalidMessage(
|
|
1490
|
+
f"the SQL message store refuses the character U+0000 in the payload of event {entry.type_name!r}"
|
|
1491
|
+
)
|
|
1492
|
+
return headers
|
|
1493
|
+
|
|
1494
|
+
|
|
1495
|
+
def _check_marker(marker: ProcessedMarker) -> None:
|
|
1496
|
+
_check_text("a marker's id", marker.id, -1)
|
|
1497
|
+
_check_text("a marker's type", marker.type_name, -1)
|
|
1498
|
+
_check_optional_text("a marker's processor", marker.processor or "", MAX_PROCESSOR)
|
|
1499
|
+
_check_optional_text("a marker's source", marker.source or "", MAX_SOURCE)
|
|
1500
|
+
_check_optional_text("a marker's segment", marker.segment or "", MAX_SEGMENT)
|
|
1501
|
+
_check_optional_text("a marker's position", marker.position or "", MAX_POSITION)
|
|
1502
|
+
|
|
1503
|
+
|
|
1504
|
+
def _headers_json(headers: dict[str, str]) -> str:
|
|
1505
|
+
if headers is None:
|
|
1506
|
+
headers = {}
|
|
1507
|
+
for name, value in headers.items():
|
|
1508
|
+
_check_text("a header name", name, -1)
|
|
1509
|
+
_check_text("a header value", value, -1)
|
|
1510
|
+
return json.dumps(headers, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
|
1511
|
+
|
|
1512
|
+
|
|
1513
|
+
def _headers_from_json(text: Any) -> dict[str, str]:
|
|
1514
|
+
if text is None:
|
|
1515
|
+
return {}
|
|
1516
|
+
raw = str(text)
|
|
1517
|
+
if not raw.strip() or raw.strip() == "null":
|
|
1518
|
+
return {}
|
|
1519
|
+
try:
|
|
1520
|
+
fields: Any = json.loads(raw)
|
|
1521
|
+
except ValueError as error:
|
|
1522
|
+
raise MessageStoreFailed(f"the SQL message store cannot read a headers column: {error}") from error
|
|
1523
|
+
if not isinstance(fields, dict):
|
|
1524
|
+
raise MessageStoreFailed("the SQL message store cannot read a headers column: not an object")
|
|
1525
|
+
headers: dict[str, str] = {}
|
|
1526
|
+
for name, value in fields.items():
|
|
1527
|
+
if value is None:
|
|
1528
|
+
headers[str(name)] = "null"
|
|
1529
|
+
elif isinstance(value, str):
|
|
1530
|
+
headers[str(name)] = value
|
|
1531
|
+
else:
|
|
1532
|
+
headers[str(name)] = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
1533
|
+
return headers
|
|
1534
|
+
|
|
1535
|
+
|
|
1536
|
+
def _payload_has_nul(payload: bytes) -> bool:
|
|
1537
|
+
try:
|
|
1538
|
+
value: Any = json.loads(payload)
|
|
1539
|
+
except (ValueError, RecursionError):
|
|
1540
|
+
return False
|
|
1541
|
+
pending = [value]
|
|
1542
|
+
while pending:
|
|
1543
|
+
item = pending.pop()
|
|
1544
|
+
if isinstance(item, str):
|
|
1545
|
+
if "\x00" in item:
|
|
1546
|
+
return True
|
|
1547
|
+
elif isinstance(item, list):
|
|
1548
|
+
pending.extend(item)
|
|
1549
|
+
elif isinstance(item, dict):
|
|
1550
|
+
for name, child in item.items():
|
|
1551
|
+
if "\x00" in name:
|
|
1552
|
+
return True
|
|
1553
|
+
pending.append(child)
|
|
1554
|
+
return False
|
|
1555
|
+
|
|
1556
|
+
|
|
1557
|
+
def _cut_free_text(text: str) -> str:
|
|
1558
|
+
encoded = text.encode("utf-8", "surrogatepass")
|
|
1559
|
+
if len(encoded) <= FREE_TEXT_BYTES:
|
|
1560
|
+
return text
|
|
1561
|
+
return encoded[:FREE_TEXT_BYTES].decode("utf-8", "ignore")
|
|
1562
|
+
|
|
1563
|
+
|
|
1564
|
+
def _sha256(value: str) -> str:
|
|
1565
|
+
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
|
1566
|
+
|
|
1567
|
+
|
|
1568
|
+
def _position_number(position: str) -> int | None:
|
|
1569
|
+
if not position or (not position.isdigit() and not (position.startswith("-") and position[1:].isdigit())):
|
|
1570
|
+
return None
|
|
1571
|
+
with contextlib.suppress(ValueError):
|
|
1572
|
+
number = int(position, 10)
|
|
1573
|
+
if str(number) == position and -(2**63) <= number <= 2**63 - 1:
|
|
1574
|
+
return number
|
|
1575
|
+
return None
|
|
1576
|
+
|
|
1577
|
+
|
|
1578
|
+
def _ms(seconds: float) -> int:
|
|
1579
|
+
try:
|
|
1580
|
+
return int(seconds * 1000)
|
|
1581
|
+
except (OverflowError, ValueError):
|
|
1582
|
+
return 2**63 - 1
|
|
1583
|
+
|
|
1584
|
+
|
|
1585
|
+
def _datetime_from_ms(milliseconds: int) -> datetime:
|
|
1586
|
+
return datetime(1970, 1, 1, tzinfo=UTC) + timedelta(milliseconds=milliseconds)
|
|
1587
|
+
|
|
1588
|
+
|
|
1589
|
+
def _ms_value(value: Any) -> int:
|
|
1590
|
+
if isinstance(value, datetime):
|
|
1591
|
+
moment = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
|
|
1592
|
+
delta = moment - datetime(1970, 1, 1, tzinfo=UTC)
|
|
1593
|
+
return (delta.days * 86_400 + delta.seconds) * 1000 + delta.microseconds // 1000
|
|
1594
|
+
if isinstance(value, int):
|
|
1595
|
+
return value
|
|
1596
|
+
raise MessageStoreFailed(f"the SQL message store cannot read a time: {value!r}")
|
|
1597
|
+
|
|
1598
|
+
|
|
1599
|
+
def _affected(status: str) -> int:
|
|
1600
|
+
try:
|
|
1601
|
+
return max(0, int(status.rsplit(" ", 1)[-1]))
|
|
1602
|
+
except (AttributeError, ValueError):
|
|
1603
|
+
return 0
|
|
1604
|
+
|
|
1605
|
+
|
|
1606
|
+
def _failure(error: BaseException) -> BaseException:
|
|
1607
|
+
if isinstance(error, MessageStoreUnsupported | InvalidMessage | Conflict | MessageStoreFailed):
|
|
1608
|
+
return error
|
|
1609
|
+
if isinstance(error, asyncpg.PostgresError):
|
|
1610
|
+
code = getattr(error, "sqlstate", None)
|
|
1611
|
+
if code in ("23505", "40001", "40P01", "55P03"):
|
|
1612
|
+
return Conflict(str(error))
|
|
1613
|
+
return MessageStoreFailed(f"the PostgreSQL message store: {error}")
|
|
1614
|
+
args = getattr(error, "args", ())
|
|
1615
|
+
if args and args[0] in (1062, 1586, 1213, 1205, 3572):
|
|
1616
|
+
return Conflict(str(error))
|
|
1617
|
+
return MessageStoreFailed(f"the SQL message store: {error}")
|
|
1618
|
+
|
|
1619
|
+
|
|
1620
|
+
def _duplicate(error: BaseException) -> bool:
|
|
1621
|
+
seen: set[int] = set()
|
|
1622
|
+
current: BaseException | None = error
|
|
1623
|
+
while current is not None and id(current) not in seen:
|
|
1624
|
+
seen.add(id(current))
|
|
1625
|
+
if isinstance(current, asyncpg.PostgresError):
|
|
1626
|
+
return getattr(current, "sqlstate", None) == "23505"
|
|
1627
|
+
args = getattr(current, "args", ())
|
|
1628
|
+
if args and args[0] in (1062, 1586):
|
|
1629
|
+
return True
|
|
1630
|
+
current = current.__cause__
|
|
1631
|
+
return False
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
def _missing_table(error: BaseException) -> bool:
|
|
1635
|
+
seen: set[int] = set()
|
|
1636
|
+
current: BaseException | None = error
|
|
1637
|
+
while current is not None and id(current) not in seen:
|
|
1638
|
+
seen.add(id(current))
|
|
1639
|
+
if isinstance(current, asyncpg.PostgresError):
|
|
1640
|
+
return getattr(current, "sqlstate", None) == "42P01"
|
|
1641
|
+
args = getattr(current, "args", ())
|
|
1642
|
+
if args and args[0] == 1146:
|
|
1643
|
+
return True
|
|
1644
|
+
current = current.__cause__
|
|
1645
|
+
return False
|
|
1646
|
+
|
|
1647
|
+
|
|
1648
|
+
def _check_postgres_server(product: str, num: str, version: str) -> None:
|
|
1649
|
+
"""Fails unless the server is PostgreSQL itself, 13 or later, naming what it is."""
|
|
1650
|
+
if not product.startswith("PostgreSQL"):
|
|
1651
|
+
raise MessageStoreFailed(
|
|
1652
|
+
f"the SQL message store supports PostgreSQL 13 or later, MySQL 8.0.17 or later; this server is {product}"
|
|
1653
|
+
)
|
|
1654
|
+
try:
|
|
1655
|
+
number = int(num.strip())
|
|
1656
|
+
except ValueError as error:
|
|
1657
|
+
raise MessageStoreFailed(f"the SQL message store cannot read the PostgreSQL version number: {num!r}") from error
|
|
1658
|
+
if number < 130_000:
|
|
1659
|
+
raise MessageStoreFailed(
|
|
1660
|
+
f"the SQL message store needs PostgreSQL 13.0 or later; this server is PostgreSQL {version}"
|
|
1661
|
+
)
|
|
1662
|
+
|
|
1663
|
+
|
|
1664
|
+
def _check_mysql_server(version: str, mode: str) -> None:
|
|
1665
|
+
"""Fails unless the server is MySQL 8.0.17 or later (not MariaDB) with a strict sql_mode."""
|
|
1666
|
+
if "mariadb" in version.lower():
|
|
1667
|
+
raise MessageStoreFailed(
|
|
1668
|
+
f"the SQL message store does not support MariaDB yet (MySQL {version}): it supports PostgreSQL 13 or "
|
|
1669
|
+
"later, MySQL 8.0.17 or later"
|
|
1670
|
+
)
|
|
1671
|
+
if _version_numbers(version) < (8, 0, 17):
|
|
1672
|
+
raise MessageStoreFailed(f"the SQL message store needs MySQL 8.0.17 or later; this server is MySQL {version}")
|
|
1673
|
+
if "STRICT_TRANS_TABLES" not in mode and "STRICT_ALL_TABLES" not in mode:
|
|
1674
|
+
raise MessageStoreFailed(
|
|
1675
|
+
"the SQL message store needs a strict sql_mode on MySQL (STRICT_TRANS_TABLES or STRICT_ALL_TABLES), so "
|
|
1676
|
+
f"a value too long is refused rather than truncated; this session's sql_mode is {mode!r}"
|
|
1677
|
+
)
|
|
1678
|
+
|
|
1679
|
+
|
|
1680
|
+
def _version_numbers(version: str) -> tuple[int, int, int]:
|
|
1681
|
+
numbers: list[int] = []
|
|
1682
|
+
current: int | None = None
|
|
1683
|
+
for char in version:
|
|
1684
|
+
if char.isdigit():
|
|
1685
|
+
current = (current or 0) * 10 + int(char)
|
|
1686
|
+
elif current is not None:
|
|
1687
|
+
numbers.append(current)
|
|
1688
|
+
current = None
|
|
1689
|
+
if len(numbers) == 3:
|
|
1690
|
+
break
|
|
1691
|
+
if current is not None and len(numbers) < 3:
|
|
1692
|
+
numbers.append(current)
|
|
1693
|
+
while len(numbers) < 3:
|
|
1694
|
+
numbers.append(0)
|
|
1695
|
+
return numbers[0], numbers[1], numbers[2]
|
|
1696
|
+
|
|
1697
|
+
|
|
1698
|
+
__all__ = [
|
|
1699
|
+
"DRIVER_MYSQL",
|
|
1700
|
+
"DRIVER_POSTGRES",
|
|
1701
|
+
"NAME_MYSQL",
|
|
1702
|
+
"NAME_POSTGRES",
|
|
1703
|
+
"SCHEMA_VERSION",
|
|
1704
|
+
"SqlConfig",
|
|
1705
|
+
"SqlStore",
|
|
1706
|
+
"StoreLifecycle",
|
|
1707
|
+
"split_sql",
|
|
1708
|
+
]
|