snodra-messaging-sql 0.6.0__tar.gz → 0.7.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.
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/PKG-INFO +5 -5
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/README.md +3 -3
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/pyproject.toml +2 -2
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/src/snodra_sql/__init__.py +4 -4
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/src/snodra_sql/sql.py +529 -35
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/tests/test_kit.py +14 -4
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/tests/test_schema.py +0 -4
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/tests/test_sql.py +144 -0
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/.gitignore +0 -0
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/DRIVER-SPIKE.md +0 -0
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/LICENSE +0 -0
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/src/snodra_sql/py.typed +0 -0
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/src/snodra_sql/schema/mysql/V1__snodra.sql +0 -0
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/src/snodra_sql/schema/postgresql/V1__snodra.sql +0 -0
- {snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/tests/conftest.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: snodra-messaging-sql
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.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.
|
|
12
|
+
Requires-Dist: snodra-messaging==0.7.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
|
|
59
|
-
|
|
60
|
-
`snodra.MessageStoreUnsupported` for now; the official add-ons implement every port by level 4.
|
|
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.
|
|
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
|
|
45
|
-
|
|
46
|
-
`snodra.MessageStoreUnsupported` for now; the official add-ons implement every port by level 4.
|
|
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.
|
|
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
|
+
version = "0.7.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.
|
|
14
|
+
"snodra-messaging==0.7.0",
|
|
15
15
|
"asyncpg==0.32.0",
|
|
16
16
|
"asyncmy==0.2.18",
|
|
17
17
|
]
|
|
@@ -1,10 +1,10 @@
|
|
|
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
|
|
5
|
-
database, on the shared SQL layout version 1 that every
|
|
6
|
-
|
|
7
|
-
and report ``snodra.MessageStoreUnsupported`` until this add-on implements them.
|
|
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.
|
|
8
8
|
|
|
9
9
|
See :mod:`snodra_sql.sql` for the layout and the guarantees, ``DRIVER-SPIKE.md`` for the driver
|
|
10
10
|
behaviour the add-on relies on, and ``SPEC-GAPS.md`` for the choices the public specification leaves
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"""The SQL message store: PostgreSQL and MySQL on the shared layout version 1.
|
|
2
2
|
|
|
3
|
-
The store keeps the outbox
|
|
4
|
-
operation joins the transaction bound to the current context
|
|
5
|
-
runs in a short transaction of its own, at READ COMMITTED;
|
|
6
|
-
connection the service already runs a transaction on, and the
|
|
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
|
|
5
|
+
(``async with store.transaction()``) or runs in a short transaction of its own, at READ COMMITTED;
|
|
6
|
+
``store.transaction(conn=conn)`` binds a connection the service already runs a transaction on, and the
|
|
7
|
+
store never commits or rolls it back.
|
|
7
8
|
|
|
8
9
|
The layout is the published SQL version 1, byte for byte:
|
|
9
10
|
|
|
@@ -19,9 +20,10 @@ append's transaction sends ``pg_notify('snodra_outbox', '')`` and :meth:`SqlStor
|
|
|
19
20
|
``on_append`` listens on a connection of its own, so a commit wakes the relay and a rollback wakes
|
|
20
21
|
nobody; MySQL has no notification and the relay polls.
|
|
21
22
|
|
|
22
|
-
The dead-letter
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
The dead-letter and processor-control stores use the layout's text/binary payload split and its
|
|
24
|
+
``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.
|
|
25
27
|
|
|
26
28
|
See https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/.
|
|
27
29
|
"""
|
|
@@ -36,7 +38,7 @@ import inspect
|
|
|
36
38
|
import json
|
|
37
39
|
import logging
|
|
38
40
|
import os
|
|
39
|
-
from collections.abc import AsyncIterator, Callable, Sequence
|
|
41
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
|
|
40
42
|
from contextlib import AbstractAsyncContextManager, asynccontextmanager
|
|
41
43
|
from dataclasses import dataclass, field
|
|
42
44
|
from datetime import UTC, datetime, timedelta
|
|
@@ -47,11 +49,15 @@ from urllib.parse import parse_qs, unquote, urlsplit
|
|
|
47
49
|
import asyncmy
|
|
48
50
|
import asyncmy.cursors
|
|
49
51
|
import asyncpg
|
|
52
|
+
from asyncmy.constants import CLIENT
|
|
50
53
|
from snodra import (
|
|
54
|
+
RESET_KIND,
|
|
51
55
|
AppendListener,
|
|
52
56
|
Conflict,
|
|
57
|
+
ControlOperation,
|
|
53
58
|
DeadLetter,
|
|
54
59
|
DeadLetterError,
|
|
60
|
+
DeadLetterReason,
|
|
55
61
|
DeadLetterStore,
|
|
56
62
|
DeadLetterSummary,
|
|
57
63
|
DeadlineDocument,
|
|
@@ -332,10 +338,12 @@ class SqlStore:
|
|
|
332
338
|
self._listener_task: asyncio.Task[None] | None = None
|
|
333
339
|
self._listener_conn: Any = None
|
|
334
340
|
self._listens = 0
|
|
341
|
+
self._lock_step: Callable[[str], Awaitable[None]] | None = None
|
|
342
|
+
"""A test hook around :meth:`_SqlControl.lock`'s renew/take sequence; ``None`` in production."""
|
|
335
343
|
self.outbox: OutboxStore = _SqlOutbox(self)
|
|
336
344
|
self.processed: ProcessedStore = _SqlProcessed(self)
|
|
337
|
-
self.dead_letters: DeadLetterStore =
|
|
338
|
-
self.control: ProcessorControlStore =
|
|
345
|
+
self.dead_letters: DeadLetterStore = _SqlDeadLetters(self)
|
|
346
|
+
self.control: ProcessorControlStore = _SqlControl(self)
|
|
339
347
|
self.external: ExternalCallStore = _UnsupportedExternal()
|
|
340
348
|
self.sagas: SagaStores = SagaStores(
|
|
341
349
|
sagas=_UnsupportedSagas(),
|
|
@@ -1134,72 +1142,555 @@ def _position_bound(op: str, position: str) -> tuple[str, Any]:
|
|
|
1134
1142
|
return f"position_num IS NULL AND position {op} ?", position
|
|
1135
1143
|
|
|
1136
1144
|
|
|
1137
|
-
# ---- the
|
|
1145
|
+
# ---- the dead letters -----------------------------------------------------------------------------
|
|
1138
1146
|
|
|
1139
1147
|
|
|
1140
|
-
|
|
1141
|
-
|
|
1148
|
+
class _SqlDeadLetters:
|
|
1149
|
+
"""The dead letters on ``snodra_dead_letters``. Every write but :meth:`delete_in` commits on its own; a letter
|
|
1150
|
+
whose ``expire_at`` passed is gone for every read and write here (it no longer blocks its key), and the purge
|
|
1151
|
+
deletes it. Positions are ordered as the layout says: decimal ones by value, then the others by their bytes; a
|
|
1152
|
+
bound compares only positions of its own kind."""
|
|
1153
|
+
|
|
1154
|
+
def __init__(self, store: SqlStore) -> None:
|
|
1155
|
+
self._store = store
|
|
1142
1156
|
|
|
1157
|
+
def _columns(self) -> str:
|
|
1158
|
+
return (
|
|
1159
|
+
"id, processor, source, segment, position, event_key, event_id, event_type, "
|
|
1160
|
+
f"CAST(headers AS {self._store._text_type()}) AS headers, payload, payload_binary, reason, "
|
|
1161
|
+
"error_type, error_message, blocked_by, attempts, parked_at, last_attempt_at, expire_at, replay"
|
|
1162
|
+
)
|
|
1143
1163
|
|
|
1144
|
-
class _UnsupportedDeadLetters:
|
|
1145
1164
|
async def park(self, letter: DeadLetter) -> Parked:
|
|
1146
|
-
|
|
1165
|
+
store = self._store
|
|
1166
|
+
_check_text("a dead letter's id", letter.id, 578)
|
|
1167
|
+
_check_optional_text("a dead letter's processor", letter.processor, MAX_PROCESSOR)
|
|
1168
|
+
_check_optional_text("a dead letter's source", letter.source, MAX_SOURCE)
|
|
1169
|
+
_check_optional_text("a dead letter's segment", letter.segment, MAX_SEGMENT)
|
|
1170
|
+
_check_optional_text("a dead letter's position", letter.position, MAX_POSITION)
|
|
1171
|
+
if letter.key is not None:
|
|
1172
|
+
_check_text("a dead letter's key", letter.key, -1)
|
|
1173
|
+
if letter.event_id is not None:
|
|
1174
|
+
_check_text("a dead letter's event id", letter.event_id, -1)
|
|
1175
|
+
if letter.event_type is not None:
|
|
1176
|
+
_check_text("a dead letter's event type", letter.event_type, -1)
|
|
1177
|
+
if letter.blocked_by is not None:
|
|
1178
|
+
_check_text("a dead letter's blocked-by id", letter.blocked_by, -1)
|
|
1179
|
+
headers = _headers_json(letter.headers)
|
|
1180
|
+
payload, payload_binary = _dead_letter_payload(letter.payload)
|
|
1181
|
+
error_type = _cut_free_text(letter.error.type_name)
|
|
1182
|
+
error_message = _cut_free_text(letter.error.message)
|
|
1183
|
+
key_hash = None if letter.key is None else _sha256(letter.key)
|
|
1184
|
+
now = store._now()
|
|
1185
|
+
query = (
|
|
1186
|
+
"INSERT INTO snodra_dead_letters (id, processor, source, segment, position, position_num, "
|
|
1187
|
+
"event_key, event_key_hash, event_id, event_type, headers, payload, payload_binary, reason, "
|
|
1188
|
+
"error_type, error_message, blocked_by, attempts, parked_at, last_attempt_at, expire_at, replay) "
|
|
1189
|
+
f"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS {store._json_type()}), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
1190
|
+
)
|
|
1191
|
+
if store._driver == DRIVER_POSTGRES:
|
|
1192
|
+
query += " ON CONFLICT (id) DO NOTHING"
|
|
1193
|
+
async with store._own() as conn:
|
|
1194
|
+
# An expired letter of the same id no longer exists: its id is free again.
|
|
1195
|
+
await store._exec(
|
|
1196
|
+
conn,
|
|
1197
|
+
"DELETE FROM snodra_dead_letters WHERE id = ? AND expire_at <= ?",
|
|
1198
|
+
(letter.id, store._time(now)),
|
|
1199
|
+
)
|
|
1200
|
+
try:
|
|
1201
|
+
affected = await store._exec(
|
|
1202
|
+
conn,
|
|
1203
|
+
query,
|
|
1204
|
+
(
|
|
1205
|
+
letter.id,
|
|
1206
|
+
letter.processor,
|
|
1207
|
+
letter.source,
|
|
1208
|
+
letter.segment,
|
|
1209
|
+
letter.position,
|
|
1210
|
+
_position_number(letter.position),
|
|
1211
|
+
letter.key,
|
|
1212
|
+
key_hash,
|
|
1213
|
+
letter.event_id,
|
|
1214
|
+
letter.event_type,
|
|
1215
|
+
headers,
|
|
1216
|
+
payload,
|
|
1217
|
+
payload_binary,
|
|
1218
|
+
letter.reason.value,
|
|
1219
|
+
error_type,
|
|
1220
|
+
error_message,
|
|
1221
|
+
letter.blocked_by,
|
|
1222
|
+
letter.attempts,
|
|
1223
|
+
store._time(letter.parked_at_ms),
|
|
1224
|
+
store._time(letter.last_attempt_at_ms),
|
|
1225
|
+
store._time(letter.expire_at_ms),
|
|
1226
|
+
letter.replay,
|
|
1227
|
+
),
|
|
1228
|
+
)
|
|
1229
|
+
except Conflict as error:
|
|
1230
|
+
if store._driver == DRIVER_MYSQL and _duplicate(error):
|
|
1231
|
+
return Parked.ALREADY
|
|
1232
|
+
raise
|
|
1233
|
+
return Parked.NEW if affected == 1 else Parked.ALREADY
|
|
1147
1234
|
|
|
1148
1235
|
async def head(self, processor: str, key: str) -> str | None:
|
|
1149
|
-
|
|
1236
|
+
_check_optional_text("a dead letter's processor", processor, MAX_PROCESSOR)
|
|
1237
|
+
_check_text("a dead letter's key", key, -1)
|
|
1238
|
+
store = self._store
|
|
1239
|
+
async with store._read() as conn:
|
|
1240
|
+
row = await store._fetchone(
|
|
1241
|
+
conn,
|
|
1242
|
+
"SELECT id FROM snodra_dead_letters WHERE processor = ? AND event_key_hash = ? "
|
|
1243
|
+
"AND reason <> 'INVALID' AND expire_at > ? "
|
|
1244
|
+
"ORDER BY position_num IS NULL, position_num, position, id LIMIT 1",
|
|
1245
|
+
(processor, _sha256(key), store._time(store._now())),
|
|
1246
|
+
)
|
|
1247
|
+
return None if row is None else str(row["id"])
|
|
1150
1248
|
|
|
1151
1249
|
async def earlier(self, processor: str, key: str, position: str) -> str | None:
|
|
1152
|
-
|
|
1250
|
+
_check_optional_text("a dead letter's processor", processor, MAX_PROCESSOR)
|
|
1251
|
+
_check_text("a dead letter's key", key, -1)
|
|
1252
|
+
_check_text("a dead letter's position", position, MAX_POSITION)
|
|
1253
|
+
bound, argument = _position_bound("<", position)
|
|
1254
|
+
store = self._store
|
|
1255
|
+
async with store._read() as conn:
|
|
1256
|
+
row = await store._fetchone(
|
|
1257
|
+
conn,
|
|
1258
|
+
"SELECT id FROM snodra_dead_letters WHERE processor = ? AND event_key_hash = ? "
|
|
1259
|
+
"AND reason <> 'INVALID' AND expire_at > ? AND "
|
|
1260
|
+
f"{bound} ORDER BY position_num IS NULL, position_num, position, id LIMIT 1",
|
|
1261
|
+
(processor, _sha256(key), store._time(store._now()), argument),
|
|
1262
|
+
)
|
|
1263
|
+
return None if row is None else str(row["id"])
|
|
1153
1264
|
|
|
1154
1265
|
async def parked_keys(self, processor: str, source: str, segments: Sequence[str]) -> set[str]:
|
|
1155
|
-
|
|
1266
|
+
if not segments:
|
|
1267
|
+
return set()
|
|
1268
|
+
_check_optional_text("a dead letter's processor", processor, MAX_PROCESSOR)
|
|
1269
|
+
_check_optional_text("a dead letter's source", source, MAX_SOURCE)
|
|
1270
|
+
for segment in segments:
|
|
1271
|
+
_check_text("a dead letter's segment", segment, MAX_SEGMENT)
|
|
1272
|
+
store = self._store
|
|
1273
|
+
places = ", ".join("?" for _ in segments)
|
|
1274
|
+
async with store._read() as conn:
|
|
1275
|
+
rows = await store._fetchall(
|
|
1276
|
+
conn,
|
|
1277
|
+
"SELECT DISTINCT event_key FROM snodra_dead_letters "
|
|
1278
|
+
f"WHERE processor = ? AND source = ? AND segment IN ({places}) "
|
|
1279
|
+
"AND event_key IS NOT NULL AND reason <> 'INVALID' AND expire_at > ?",
|
|
1280
|
+
(processor, source, *segments, store._time(store._now())),
|
|
1281
|
+
)
|
|
1282
|
+
return {str(row["event_key"]) for row in rows}
|
|
1156
1283
|
|
|
1157
1284
|
async def get(self, letter: str) -> DeadLetter | None:
|
|
1158
|
-
|
|
1285
|
+
_check_text("a dead letter's id", letter, 578)
|
|
1286
|
+
store = self._store
|
|
1287
|
+
async with store._read() as conn:
|
|
1288
|
+
row = await store._fetchone(
|
|
1289
|
+
conn,
|
|
1290
|
+
f"SELECT {self._columns()} FROM snodra_dead_letters WHERE id = ? AND expire_at > ?",
|
|
1291
|
+
(letter, store._time(store._now())),
|
|
1292
|
+
)
|
|
1293
|
+
return None if row is None else _dead_letter_from_row(row)
|
|
1159
1294
|
|
|
1160
1295
|
async def list(self, processor: str | None = None, limit: int | None = None) -> builtins.list[DeadLetter]:
|
|
1161
|
-
|
|
1296
|
+
_check_optional_text("a dead letter's processor", processor or "", MAX_PROCESSOR)
|
|
1297
|
+
store = self._store
|
|
1298
|
+
query = f"SELECT {self._columns()} FROM snodra_dead_letters WHERE expire_at > ?"
|
|
1299
|
+
args: list[Any] = [store._time(store._now())]
|
|
1300
|
+
if processor is not None:
|
|
1301
|
+
query += " AND processor = ?"
|
|
1302
|
+
args.append(processor)
|
|
1303
|
+
query += " ORDER BY parked_at, id"
|
|
1304
|
+
if limit is not None:
|
|
1305
|
+
query += " LIMIT ?"
|
|
1306
|
+
args.append(max(0, int(limit)))
|
|
1307
|
+
async with store._read() as conn:
|
|
1308
|
+
rows = await store._fetchall(conn, query, tuple(args))
|
|
1309
|
+
return [_dead_letter_from_row(row) for row in rows]
|
|
1162
1310
|
|
|
1163
1311
|
async def summaries(self, processor: str) -> builtins.list[DeadLetterSummary]:
|
|
1164
|
-
|
|
1312
|
+
_check_optional_text("a dead letter's processor", processor, MAX_PROCESSOR)
|
|
1313
|
+
store = self._store
|
|
1314
|
+
async with store._read() as conn:
|
|
1315
|
+
rows = await store._fetchall(
|
|
1316
|
+
conn,
|
|
1317
|
+
"SELECT id, event_key, position, reason, parked_at FROM snodra_dead_letters "
|
|
1318
|
+
"WHERE processor = ? AND expire_at > ? "
|
|
1319
|
+
"ORDER BY position_num IS NULL, position_num, position, id",
|
|
1320
|
+
(processor, store._time(store._now())),
|
|
1321
|
+
)
|
|
1322
|
+
return [
|
|
1323
|
+
DeadLetterSummary(
|
|
1324
|
+
id=str(row["id"]),
|
|
1325
|
+
key=None if row["event_key"] is None else str(row["event_key"]),
|
|
1326
|
+
position=str(row["position"]),
|
|
1327
|
+
reason=DeadLetterReason(str(row["reason"])),
|
|
1328
|
+
parked_at_ms=_ms_value(row["parked_at"]),
|
|
1329
|
+
)
|
|
1330
|
+
for row in rows
|
|
1331
|
+
]
|
|
1165
1332
|
|
|
1166
1333
|
async def count(self, processor: str | None = None) -> int:
|
|
1167
|
-
|
|
1334
|
+
_check_optional_text("a dead letter's processor", processor or "", MAX_PROCESSOR)
|
|
1335
|
+
store = self._store
|
|
1336
|
+
query = "SELECT COUNT(*) AS n FROM snodra_dead_letters WHERE expire_at > ?"
|
|
1337
|
+
args: list[Any] = [store._time(store._now())]
|
|
1338
|
+
if processor is not None:
|
|
1339
|
+
query += " AND processor = ?"
|
|
1340
|
+
args.append(processor)
|
|
1341
|
+
async with store._read() as conn:
|
|
1342
|
+
value = await store._fetchval(conn, query, tuple(args))
|
|
1343
|
+
return 0 if value is None else int(value)
|
|
1168
1344
|
|
|
1169
1345
|
async def delete(self, letter: str) -> bool:
|
|
1170
|
-
|
|
1346
|
+
_check_text("a dead letter's id", letter, 578)
|
|
1347
|
+
store = self._store
|
|
1348
|
+
async with store._own() as conn:
|
|
1349
|
+
affected = await store._exec(
|
|
1350
|
+
conn,
|
|
1351
|
+
"DELETE FROM snodra_dead_letters WHERE id = ? AND expire_at > ?",
|
|
1352
|
+
(letter, store._time(store._now())),
|
|
1353
|
+
)
|
|
1354
|
+
return affected > 0
|
|
1171
1355
|
|
|
1172
1356
|
async def delete_in(self, letter: str, *, tx: Tx | None = None) -> bool:
|
|
1173
|
-
|
|
1357
|
+
_check_text("a dead letter's id", letter, 578)
|
|
1358
|
+
store = self._store
|
|
1359
|
+
async with store._scoped(tx) as conn:
|
|
1360
|
+
affected = await store._exec(
|
|
1361
|
+
conn,
|
|
1362
|
+
"DELETE FROM snodra_dead_letters WHERE id = ? AND expire_at > ?",
|
|
1363
|
+
(letter, store._time(store._now())),
|
|
1364
|
+
)
|
|
1365
|
+
return affected > 0
|
|
1174
1366
|
|
|
1175
1367
|
async def record_failure(self, letter: str, error: DeadLetterError, now_ms: int) -> bool:
|
|
1176
|
-
|
|
1368
|
+
_check_text("a dead letter's id", letter, 578)
|
|
1369
|
+
store = self._store
|
|
1370
|
+
async with store._own() as conn:
|
|
1371
|
+
affected = await store._exec(
|
|
1372
|
+
conn,
|
|
1373
|
+
"UPDATE snodra_dead_letters SET attempts = attempts + 1, error_type = ?, error_message = ?, "
|
|
1374
|
+
"last_attempt_at = ?, reason = 'HANDLER_FAILED', blocked_by = NULL "
|
|
1375
|
+
"WHERE id = ? AND expire_at > ?",
|
|
1376
|
+
(
|
|
1377
|
+
_cut_free_text(error.type_name),
|
|
1378
|
+
_cut_free_text(error.message),
|
|
1379
|
+
store._time(now_ms),
|
|
1380
|
+
letter,
|
|
1381
|
+
store._time(store._now()),
|
|
1382
|
+
),
|
|
1383
|
+
)
|
|
1384
|
+
return affected > 0
|
|
1385
|
+
|
|
1386
|
+
|
|
1387
|
+
def _dead_letter_payload(payload: bytes) -> tuple[str | None, bytes | None]:
|
|
1388
|
+
"""The text or binary column a letter's payload needs: text only when it is UTF-8 without U+0000."""
|
|
1389
|
+
raw = bytes(payload)
|
|
1390
|
+
if not raw:
|
|
1391
|
+
return "", None
|
|
1392
|
+
try:
|
|
1393
|
+
text = raw.decode("utf-8")
|
|
1394
|
+
except UnicodeDecodeError:
|
|
1395
|
+
return None, raw
|
|
1396
|
+
if "\x00" in text:
|
|
1397
|
+
return None, raw
|
|
1398
|
+
return text, None
|
|
1399
|
+
|
|
1400
|
+
|
|
1401
|
+
def _dead_letter_from_row(row: dict[str, Any]) -> DeadLetter:
|
|
1402
|
+
payload = row["payload"]
|
|
1403
|
+
if payload is not None:
|
|
1404
|
+
raw = str(payload).encode()
|
|
1405
|
+
else:
|
|
1406
|
+
raw = b"" if row["payload_binary"] is None else bytes(row["payload_binary"])
|
|
1407
|
+
return DeadLetter(
|
|
1408
|
+
id=str(row["id"]),
|
|
1409
|
+
processor=str(row["processor"]),
|
|
1410
|
+
source=str(row["source"]),
|
|
1411
|
+
segment=str(row["segment"]),
|
|
1412
|
+
position=str(row["position"]),
|
|
1413
|
+
key=None if row["event_key"] is None else str(row["event_key"]),
|
|
1414
|
+
event_id=None if row["event_id"] is None else str(row["event_id"]),
|
|
1415
|
+
event_type=None if row["event_type"] is None else str(row["event_type"]),
|
|
1416
|
+
headers=_headers_from_json(row["headers"]),
|
|
1417
|
+
payload=raw,
|
|
1418
|
+
reason=DeadLetterReason(str(row["reason"])),
|
|
1419
|
+
error=DeadLetterError(str(row["error_type"]), str(row["error_message"])),
|
|
1420
|
+
blocked_by=None if row["blocked_by"] is None else str(row["blocked_by"]),
|
|
1421
|
+
attempts=int(row["attempts"]),
|
|
1422
|
+
parked_at_ms=_ms_value(row["parked_at"]),
|
|
1423
|
+
last_attempt_at_ms=_ms_value(row["last_attempt_at"]),
|
|
1424
|
+
expire_at_ms=_ms_value(row["expire_at"]),
|
|
1425
|
+
replay=bool(row["replay"]),
|
|
1426
|
+
)
|
|
1427
|
+
|
|
1177
1428
|
|
|
1429
|
+
# ---- the processor control ------------------------------------------------------------------------
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
class _SqlControl:
|
|
1433
|
+
"""The processor control state on ``snodra_processor_control``: one row per processor, created by the first write
|
|
1434
|
+
that needs it. Every write commits on its own; a lock is one conditional ``UPDATE`` after a renewal attempt."""
|
|
1435
|
+
|
|
1436
|
+
def __init__(self, store: SqlStore) -> None:
|
|
1437
|
+
self._store = store
|
|
1438
|
+
|
|
1439
|
+
def _columns(self) -> str:
|
|
1440
|
+
return (
|
|
1441
|
+
"processor, paused, paused_at, paused_by, op_id, op_kind, op_lease_until, op_prepared_at, "
|
|
1442
|
+
f"CAST(replay AS {self._store._text_type()}) AS replay, updated_at"
|
|
1443
|
+
)
|
|
1178
1444
|
|
|
1179
|
-
class _UnsupportedControl:
|
|
1180
1445
|
async def get(self, processor: str) -> ProcessorControlState:
|
|
1181
|
-
|
|
1446
|
+
_check_optional_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1447
|
+
store = self._store
|
|
1448
|
+
async with store._read() as conn:
|
|
1449
|
+
row = await store._fetchone(
|
|
1450
|
+
conn,
|
|
1451
|
+
f"SELECT {self._columns()} FROM snodra_processor_control WHERE processor = ?",
|
|
1452
|
+
(processor,),
|
|
1453
|
+
)
|
|
1454
|
+
return _control_state(processor, row)
|
|
1455
|
+
|
|
1456
|
+
async def _get_on(self, conn: Any, processor: str) -> ProcessorControlState:
|
|
1457
|
+
row = await self._store._fetchone(
|
|
1458
|
+
conn,
|
|
1459
|
+
f"SELECT {self._columns()} FROM snodra_processor_control WHERE processor = ?",
|
|
1460
|
+
(processor,),
|
|
1461
|
+
)
|
|
1462
|
+
return _control_state(processor, row)
|
|
1463
|
+
|
|
1464
|
+
async def _ensure(self, conn: Any, processor: str) -> None:
|
|
1465
|
+
_check_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1466
|
+
store = self._store
|
|
1467
|
+
query = (
|
|
1468
|
+
"INSERT INTO snodra_processor_control (processor, paused, replay) "
|
|
1469
|
+
f"VALUES (?, FALSE, CAST(? AS {store._json_type()}))"
|
|
1470
|
+
)
|
|
1471
|
+
if store._driver == DRIVER_POSTGRES:
|
|
1472
|
+
query += " ON CONFLICT (processor) DO NOTHING"
|
|
1473
|
+
else:
|
|
1474
|
+
query += " ON DUPLICATE KEY UPDATE processor = processor"
|
|
1475
|
+
await store._exec(conn, query, (processor, "[]"))
|
|
1182
1476
|
|
|
1183
1477
|
async def set_paused(self, processor: str, paused: bool, by: str, now_ms: int) -> None:
|
|
1184
|
-
|
|
1478
|
+
_check_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1479
|
+
_check_text("a pause's control id", by, -1)
|
|
1480
|
+
store = self._store
|
|
1481
|
+
async with store._own() as conn:
|
|
1482
|
+
await self._ensure(conn, processor)
|
|
1483
|
+
await store._exec(
|
|
1484
|
+
conn,
|
|
1485
|
+
"UPDATE snodra_processor_control SET paused = ?, paused_at = ?, paused_by = ?, updated_at = ? "
|
|
1486
|
+
"WHERE processor = ?",
|
|
1487
|
+
(
|
|
1488
|
+
paused,
|
|
1489
|
+
store._time(now_ms) if paused else None,
|
|
1490
|
+
by if paused else None,
|
|
1491
|
+
store._time(now_ms),
|
|
1492
|
+
processor,
|
|
1493
|
+
),
|
|
1494
|
+
)
|
|
1185
1495
|
|
|
1186
1496
|
async def lock(self, processor: str, operation: str, lease_until_ms: int, now_ms: int) -> Locked:
|
|
1187
|
-
|
|
1497
|
+
_check_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1498
|
+
_check_text("a reset's operation id", operation, -1)
|
|
1499
|
+
store = self._store
|
|
1500
|
+
async with store._own() as conn:
|
|
1501
|
+
await self._ensure(conn, processor)
|
|
1502
|
+
renewed = await store._exec(
|
|
1503
|
+
conn,
|
|
1504
|
+
"UPDATE snodra_processor_control SET op_lease_until = ?, updated_at = ? "
|
|
1505
|
+
"WHERE processor = ? AND op_id = ?",
|
|
1506
|
+
(store._time(lease_until_ms), store._time(now_ms), processor, operation),
|
|
1507
|
+
)
|
|
1508
|
+
if renewed == 1:
|
|
1509
|
+
return Locked.was_taken()
|
|
1510
|
+
if store._lock_step is not None:
|
|
1511
|
+
await store._lock_step("renewed")
|
|
1512
|
+
taken = await store._exec(
|
|
1513
|
+
conn,
|
|
1514
|
+
"UPDATE snodra_processor_control SET op_id = ?, op_kind = ?, op_lease_until = ?, "
|
|
1515
|
+
"op_prepared_at = ?, updated_at = ? "
|
|
1516
|
+
"WHERE processor = ? AND (op_id IS NULL OR op_lease_until <= ?)",
|
|
1517
|
+
(
|
|
1518
|
+
operation,
|
|
1519
|
+
RESET_KIND,
|
|
1520
|
+
store._time(lease_until_ms),
|
|
1521
|
+
store._time(now_ms),
|
|
1522
|
+
store._time(now_ms),
|
|
1523
|
+
processor,
|
|
1524
|
+
store._time(now_ms),
|
|
1525
|
+
),
|
|
1526
|
+
)
|
|
1527
|
+
if taken == 1:
|
|
1528
|
+
# The take matched: hold the transaction (and its row lock) here when a test asks,
|
|
1529
|
+
# so another instance's take queues behind this commit.
|
|
1530
|
+
if store._lock_step is not None:
|
|
1531
|
+
await store._lock_step("taken")
|
|
1532
|
+
return Locked.was_taken()
|
|
1533
|
+
state = await self._get_on(conn, processor)
|
|
1534
|
+
if state.operation is not None and state.operation.id == operation:
|
|
1535
|
+
# Another instance prepared the same operation concurrently: this transaction's
|
|
1536
|
+
# renewal ran before that prepare committed. A fresh statement sees the commit,
|
|
1537
|
+
# and a prepare for the operation that holds the lock is a renewal, not a refusal.
|
|
1538
|
+
renewed = await store._exec(
|
|
1539
|
+
conn,
|
|
1540
|
+
"UPDATE snodra_processor_control SET op_lease_until = ?, updated_at = ? "
|
|
1541
|
+
"WHERE processor = ? AND op_id = ?",
|
|
1542
|
+
(store._time(lease_until_ms), store._time(now_ms), processor, operation),
|
|
1543
|
+
)
|
|
1544
|
+
if renewed == 1:
|
|
1545
|
+
return Locked.was_taken()
|
|
1546
|
+
return Locked(False, state.operation)
|
|
1188
1547
|
|
|
1189
1548
|
async def extend(self, processor: str, operation: str, lease_until_ms: int, now_ms: int) -> bool:
|
|
1190
|
-
|
|
1549
|
+
_check_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1550
|
+
_check_text("a reset's operation id", operation, -1)
|
|
1551
|
+
store = self._store
|
|
1552
|
+
async with store._own() as conn:
|
|
1553
|
+
affected = await store._exec(
|
|
1554
|
+
conn,
|
|
1555
|
+
"UPDATE snodra_processor_control SET op_lease_until = ?, updated_at = ? "
|
|
1556
|
+
"WHERE processor = ? AND op_id = ?",
|
|
1557
|
+
(store._time(lease_until_ms), store._time(now_ms), processor, operation),
|
|
1558
|
+
)
|
|
1559
|
+
return affected == 1
|
|
1191
1560
|
|
|
1192
1561
|
async def release(self, processor: str, operation: str, now_ms: int) -> bool:
|
|
1193
|
-
|
|
1562
|
+
return await self._clear(processor, operation, now_ms, expired_only=False)
|
|
1194
1563
|
|
|
1195
1564
|
async def expire(self, processor: str, operation: str, now_ms: int) -> bool:
|
|
1196
|
-
|
|
1565
|
+
return await self._clear(processor, operation, now_ms, expired_only=True)
|
|
1566
|
+
|
|
1567
|
+
async def _clear(self, processor: str, operation: str, now_ms: int, *, expired_only: bool) -> bool:
|
|
1568
|
+
_check_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1569
|
+
_check_text("a reset's operation id", operation, -1)
|
|
1570
|
+
store = self._store
|
|
1571
|
+
query = (
|
|
1572
|
+
"UPDATE snodra_processor_control SET op_id = NULL, op_kind = NULL, op_lease_until = NULL, "
|
|
1573
|
+
"op_prepared_at = NULL, updated_at = ? WHERE processor = ? AND op_id = ?"
|
|
1574
|
+
)
|
|
1575
|
+
args: list[Any] = [store._time(now_ms), processor, operation]
|
|
1576
|
+
if expired_only:
|
|
1577
|
+
query += " AND op_lease_until <= ?"
|
|
1578
|
+
args.append(store._time(now_ms))
|
|
1579
|
+
async with store._own() as conn:
|
|
1580
|
+
affected = await store._exec(conn, query, tuple(args))
|
|
1581
|
+
return affected == 1
|
|
1197
1582
|
|
|
1198
1583
|
async def set_replay(self, processor: str, ranges: Sequence[ReplayRange], now_ms: int) -> None:
|
|
1199
|
-
|
|
1584
|
+
_check_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1585
|
+
encoded = _encode_replay(ranges)
|
|
1586
|
+
store = self._store
|
|
1587
|
+
async with store._own() as conn:
|
|
1588
|
+
await self._ensure(conn, processor)
|
|
1589
|
+
await store._exec(
|
|
1590
|
+
conn,
|
|
1591
|
+
"UPDATE snodra_processor_control "
|
|
1592
|
+
f"SET replay = CAST(? AS {store._json_type()}), updated_at = ? WHERE processor = ?",
|
|
1593
|
+
(encoded, store._time(now_ms), processor),
|
|
1594
|
+
)
|
|
1200
1595
|
|
|
1201
1596
|
async def remove_range(self, processor: str, replay_range: ReplayRange, now_ms: int) -> bool:
|
|
1202
|
-
|
|
1597
|
+
_check_text("a processor's name", processor, MAX_PROCESSOR)
|
|
1598
|
+
_encode_replay((replay_range,))
|
|
1599
|
+
store = self._store
|
|
1600
|
+
async with store._own() as conn:
|
|
1601
|
+
row = await store._fetchone(
|
|
1602
|
+
conn,
|
|
1603
|
+
"SELECT "
|
|
1604
|
+
f"CAST(replay AS {store._text_type()}) AS replay FROM snodra_processor_control "
|
|
1605
|
+
"WHERE processor = ? FOR UPDATE",
|
|
1606
|
+
(processor,),
|
|
1607
|
+
)
|
|
1608
|
+
if row is None:
|
|
1609
|
+
return False
|
|
1610
|
+
ranges = list(_decode_replay(row["replay"]))
|
|
1611
|
+
try:
|
|
1612
|
+
ranges.remove(replay_range)
|
|
1613
|
+
except ValueError:
|
|
1614
|
+
return False
|
|
1615
|
+
await store._exec(
|
|
1616
|
+
conn,
|
|
1617
|
+
"UPDATE snodra_processor_control "
|
|
1618
|
+
f"SET replay = CAST(? AS {store._json_type()}), updated_at = ? WHERE processor = ?",
|
|
1619
|
+
(_encode_replay(ranges), store._time(now_ms), processor),
|
|
1620
|
+
)
|
|
1621
|
+
return True
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
def _control_state(processor: str, row: dict[str, Any] | None) -> ProcessorControlState:
|
|
1625
|
+
if row is None:
|
|
1626
|
+
return ProcessorControlState(processor)
|
|
1627
|
+
operation: ControlOperation | None = None
|
|
1628
|
+
if row["op_id"] is not None:
|
|
1629
|
+
lease = row["op_lease_until"]
|
|
1630
|
+
prepared = row["op_prepared_at"]
|
|
1631
|
+
operation = ControlOperation(
|
|
1632
|
+
id=str(row["op_id"]),
|
|
1633
|
+
kind=RESET_KIND if row["op_kind"] is None else str(row["op_kind"]),
|
|
1634
|
+
lease_until_ms=0 if lease is None else _ms_value(lease),
|
|
1635
|
+
prepared_at_ms=0 if prepared is None else _ms_value(prepared),
|
|
1636
|
+
)
|
|
1637
|
+
paused_at = row["paused_at"]
|
|
1638
|
+
updated_at = row["updated_at"]
|
|
1639
|
+
return ProcessorControlState(
|
|
1640
|
+
processor=str(row["processor"]),
|
|
1641
|
+
paused=bool(row["paused"]),
|
|
1642
|
+
paused_at_ms=None if paused_at is None else _ms_value(paused_at),
|
|
1643
|
+
paused_by=None if row["paused_by"] is None else str(row["paused_by"]),
|
|
1644
|
+
operation=operation,
|
|
1645
|
+
replay=_decode_replay(row["replay"]),
|
|
1646
|
+
updated_at_ms=None if updated_at is None else _ms_value(updated_at),
|
|
1647
|
+
)
|
|
1648
|
+
|
|
1649
|
+
|
|
1650
|
+
def _encode_replay(ranges: Sequence[ReplayRange]) -> str:
|
|
1651
|
+
stored: list[dict[str, str]] = []
|
|
1652
|
+
for replay in ranges:
|
|
1653
|
+
_check_optional_text("a replay range's source", replay.source, MAX_SOURCE)
|
|
1654
|
+
_check_optional_text("a replay range's segment", replay.segment, MAX_SEGMENT)
|
|
1655
|
+
_check_optional_text("a replay range's from position", replay.start, MAX_POSITION)
|
|
1656
|
+
_check_optional_text("a replay range's until position", replay.until, MAX_POSITION)
|
|
1657
|
+
stored.append({"source": replay.source, "segment": replay.segment, "from": replay.start, "until": replay.until})
|
|
1658
|
+
return json.dumps(stored, ensure_ascii=False, separators=(",", ":"))
|
|
1659
|
+
|
|
1660
|
+
|
|
1661
|
+
def _decode_replay(text: Any) -> tuple[ReplayRange, ...]:
|
|
1662
|
+
if text is None:
|
|
1663
|
+
return ()
|
|
1664
|
+
raw = str(text)
|
|
1665
|
+
if not raw.strip() or raw.strip() == "null":
|
|
1666
|
+
return ()
|
|
1667
|
+
try:
|
|
1668
|
+
stored: Any = json.loads(raw)
|
|
1669
|
+
except ValueError as error:
|
|
1670
|
+
raise MessageStoreFailed(f"the SQL message store cannot read a replay column: {error}") from error
|
|
1671
|
+
if not isinstance(stored, list):
|
|
1672
|
+
raise MessageStoreFailed("the SQL message store cannot read a replay column: not an array")
|
|
1673
|
+
ranges: list[ReplayRange] = []
|
|
1674
|
+
for item in stored:
|
|
1675
|
+
if not isinstance(item, dict):
|
|
1676
|
+
continue
|
|
1677
|
+
source = item.get("source")
|
|
1678
|
+
segment = item.get("segment")
|
|
1679
|
+
start = item.get("from")
|
|
1680
|
+
until = item.get("until")
|
|
1681
|
+
if not isinstance(source, str) or not isinstance(segment, str):
|
|
1682
|
+
continue
|
|
1683
|
+
if not isinstance(start, str) or not isinstance(until, str):
|
|
1684
|
+
continue
|
|
1685
|
+
ranges.append(ReplayRange(source=source, segment=segment, start=start, until=until))
|
|
1686
|
+
return tuple(ranges)
|
|
1687
|
+
|
|
1688
|
+
|
|
1689
|
+
# ---- the ports this level does not implement ------------------------------------------------------
|
|
1690
|
+
|
|
1691
|
+
|
|
1692
|
+
def _unsupported(what: str) -> MessageStoreUnsupported:
|
|
1693
|
+
return MessageStoreUnsupported(f"{what} in the SQL message store (level 2)")
|
|
1203
1694
|
|
|
1204
1695
|
|
|
1205
1696
|
class _UnsupportedExternal:
|
|
@@ -1385,7 +1876,9 @@ class _MySQLTarget:
|
|
|
1385
1876
|
)
|
|
1386
1877
|
|
|
1387
1878
|
def kwargs(self) -> dict[str, Any]:
|
|
1388
|
-
"""The keyword arguments ``asyncmy.connect`` and ``asyncmy.create_pool`` take.
|
|
1879
|
+
"""The keyword arguments ``asyncmy.connect`` and ``asyncmy.create_pool`` take. ``CLIENT_FOUND_ROWS`` makes an
|
|
1880
|
+
update report the rows it matched, as the Kotlin and Rust drivers report them, so a renewal that writes the
|
|
1881
|
+
values already there still counts."""
|
|
1389
1882
|
return {
|
|
1390
1883
|
"host": self.host,
|
|
1391
1884
|
"port": self.port,
|
|
@@ -1393,6 +1886,7 @@ class _MySQLTarget:
|
|
|
1393
1886
|
"password": self.password,
|
|
1394
1887
|
"db": self.database,
|
|
1395
1888
|
"charset": self.charset,
|
|
1889
|
+
"client_flag": CLIENT.FOUND_ROWS,
|
|
1396
1890
|
**self.options,
|
|
1397
1891
|
}
|
|
1398
1892
|
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"""The nine level-2 message-store checks on PostgreSQL and MySQL."""
|
|
1
|
+
"""The nine level-2 and eight level-3 message-store checks on PostgreSQL and MySQL."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import pytest
|
|
6
|
-
from snodra.testing import MESSAGE_STORE_CHECKS, run_store_conformance
|
|
6
|
+
from snodra.testing import MESSAGE_STORE_CHECKS, MESSAGE_STORE_L3_CHECKS, run_store_conformance
|
|
7
7
|
from snodra_sql import SqlStore
|
|
8
8
|
|
|
9
9
|
pytestmark = pytest.mark.timeout(300)
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
async def test_the_sql_message_store_passes_the_kit(store: SqlStore) -> None:
|
|
13
|
-
await run_store_conformance(lambda: store)
|
|
13
|
+
await run_store_conformance(lambda: store, level=3)
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
async def test_the_store_reports_its_name_and_has_the_six_ports(store: SqlStore) -> None:
|
|
@@ -23,7 +23,7 @@ async def test_the_store_reports_its_name_and_has_the_six_ports(store: SqlStore)
|
|
|
23
23
|
assert store.sagas is store.sagas
|
|
24
24
|
|
|
25
25
|
|
|
26
|
-
def
|
|
26
|
+
def test_the_kit_is_the_nine_level_two_checks_and_the_eight_level_three_ones() -> None:
|
|
27
27
|
assert tuple(check.__name__ for check in MESSAGE_STORE_CHECKS) == (
|
|
28
28
|
"appended_entry_is_claimed_in_created_seq_order",
|
|
29
29
|
"outbox_rejects_a_payload_that_is_not_a_json_object",
|
|
@@ -35,3 +35,13 @@ def test_the_kit_is_the_nine_level_two_checks() -> None:
|
|
|
35
35
|
"expired_lease_is_reclaimed",
|
|
36
36
|
"purge_removes_only_sent_before",
|
|
37
37
|
)
|
|
38
|
+
assert tuple(check.__name__ for check in MESSAGE_STORE_L3_CHECKS) == (
|
|
39
|
+
"delete_markers_removes_only_the_range",
|
|
40
|
+
"dead_letters_sequence_per_key",
|
|
41
|
+
"dead_letter_parked_inside_rolled_back_transaction_is_kept",
|
|
42
|
+
"dead_letter_deleted_in_a_transaction_goes_with_it",
|
|
43
|
+
"control_lock_is_exclusive_until_lease_expires",
|
|
44
|
+
"pause_state_round_trips",
|
|
45
|
+
"replay_ranges_round_trip",
|
|
46
|
+
"processor_control_write_inside_rolled_back_transaction_is_kept",
|
|
47
|
+
)
|
|
@@ -127,10 +127,6 @@ def test_the_store_offers_the_lifecycle() -> None:
|
|
|
127
127
|
|
|
128
128
|
async def test_the_unimplemented_ports_name_the_level() -> None:
|
|
129
129
|
store = SqlStore(SqlConfig(url="postgres://u@h/db"))
|
|
130
|
-
with pytest.raises(MessageStoreUnsupported, match="level 2"):
|
|
131
|
-
await store.dead_letters.get("letter")
|
|
132
|
-
with pytest.raises(MessageStoreUnsupported, match="level 2"):
|
|
133
|
-
await store.control.get("default")
|
|
134
130
|
with pytest.raises(MessageStoreUnsupported, match="level 2"):
|
|
135
131
|
await store.external.find("key")
|
|
136
132
|
with pytest.raises(MessageStoreUnsupported, match="level 2"):
|
|
@@ -10,9 +10,14 @@ from typing import Any, cast
|
|
|
10
10
|
|
|
11
11
|
import pytest
|
|
12
12
|
from snodra import (
|
|
13
|
+
DeadLetter,
|
|
14
|
+
DeadLetterError,
|
|
15
|
+
DeadLetterReason,
|
|
13
16
|
InvalidMessage,
|
|
17
|
+
Locked,
|
|
14
18
|
MessageStoreFailed,
|
|
15
19
|
OutboxEntry,
|
|
20
|
+
Parked,
|
|
16
21
|
ProcessedMarker,
|
|
17
22
|
ReplayRange,
|
|
18
23
|
Tx,
|
|
@@ -356,6 +361,145 @@ async def test_delete_markers_removes_only_the_range(store: SqlStore) -> None:
|
|
|
356
361
|
assert await store.processed.exists(marker.id) == exists, marker.id
|
|
357
362
|
|
|
358
363
|
|
|
364
|
+
async def test_a_dead_letter_payload_is_text_or_binary_and_expiry_is_its_retention(store: SqlStore) -> None:
|
|
365
|
+
"""The layout's text/binary payload split keeps every byte; a letter whose expire_at passed is invisible and its
|
|
366
|
+
id is free again, so a park replaces it."""
|
|
367
|
+
t0 = 1_800_000_000_000
|
|
368
|
+
|
|
369
|
+
def letter(letter_id: str, payload: bytes, expire_at_ms: int) -> DeadLetter:
|
|
370
|
+
return DeadLetter(
|
|
371
|
+
id=letter_id,
|
|
372
|
+
processor="orders",
|
|
373
|
+
source="snodra.events",
|
|
374
|
+
segment="0",
|
|
375
|
+
position="1",
|
|
376
|
+
key=None,
|
|
377
|
+
event_id="evt-1",
|
|
378
|
+
event_type="orders.OrderShipped",
|
|
379
|
+
headers={"type": "orders.OrderShipped"},
|
|
380
|
+
payload=payload,
|
|
381
|
+
reason=DeadLetterReason.HANDLER_FAILED,
|
|
382
|
+
error=DeadLetterError.new("RuntimeError", "boom"),
|
|
383
|
+
blocked_by=None,
|
|
384
|
+
attempts=1,
|
|
385
|
+
parked_at_ms=t0,
|
|
386
|
+
last_attempt_at_ms=t0,
|
|
387
|
+
expire_at_ms=expire_at_ms,
|
|
388
|
+
replay=False,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
text = letter("conformance:snodra.events:0:text", b'{"text":"\xc3\xa9"}', t0 + 86_400_000)
|
|
392
|
+
binary = letter("conformance:snodra.events:0:binary", b"\xff\xfe\x00\x01", t0 + 86_400_000)
|
|
393
|
+
for row in (text, binary):
|
|
394
|
+
assert await store.dead_letters.park(row) is Parked.NEW
|
|
395
|
+
async with store._read() as conn:
|
|
396
|
+
text_row = await store._fetchone(
|
|
397
|
+
conn, "SELECT payload, payload_binary FROM snodra_dead_letters WHERE id = ?", (text.id,)
|
|
398
|
+
)
|
|
399
|
+
binary_row = await store._fetchone(
|
|
400
|
+
conn, "SELECT payload, payload_binary FROM snodra_dead_letters WHERE id = ?", (binary.id,)
|
|
401
|
+
)
|
|
402
|
+
assert text_row is not None
|
|
403
|
+
assert text_row["payload"] == '{"text":"é"}'
|
|
404
|
+
assert text_row["payload_binary"] is None
|
|
405
|
+
assert binary_row is not None
|
|
406
|
+
assert binary_row["payload"] is None
|
|
407
|
+
assert binary_row["payload_binary"] == b"\xff\xfe\x00\x01"
|
|
408
|
+
found_text = await store.dead_letters.get(text.id)
|
|
409
|
+
assert found_text is not None
|
|
410
|
+
assert found_text.payload == text.payload
|
|
411
|
+
found_binary = await store.dead_letters.get(binary.id)
|
|
412
|
+
assert found_binary is not None
|
|
413
|
+
assert found_binary.payload == binary.payload
|
|
414
|
+
|
|
415
|
+
expired = letter("conformance:snodra.events:0:expired", b"{}", 1)
|
|
416
|
+
assert await store.dead_letters.park(expired) is Parked.NEW
|
|
417
|
+
assert await store.dead_letters.get(expired.id) is None, "expired: invisible"
|
|
418
|
+
assert await store.dead_letters.count("orders") == 2, "expired letters are not counted or blocking"
|
|
419
|
+
replacement = letter(expired.id, b'{"fresh":true}', t0 + 86_400_000)
|
|
420
|
+
assert await store.dead_letters.park(replacement) is Parked.NEW, "the id is free again"
|
|
421
|
+
found = await store.dead_letters.get(expired.id)
|
|
422
|
+
assert found is not None
|
|
423
|
+
assert found.payload == b'{"fresh":true}'
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
async def test_a_renewal_that_writes_the_same_values_is_still_taken(store: SqlStore) -> None:
|
|
427
|
+
"""A retried request can renew with the same lease and time; MySQL must report the matched row, not the changed
|
|
428
|
+
one, so the holder is not refused its own lock."""
|
|
429
|
+
processor = f"conformance-{uuid.uuid4()}"
|
|
430
|
+
assert await store.control.lock(processor, "op-1", 1_800_000_005_000, 1_800_000_000_000) == Locked.was_taken()
|
|
431
|
+
assert await store.control.lock(processor, "op-1", 1_800_000_005_000, 1_800_000_000_000) == Locked.was_taken()
|
|
432
|
+
assert await store.control.extend(processor, "op-1", 1_800_000_005_000, 1_800_000_000_000)
|
|
433
|
+
assert await store.control.release(processor, "op-1", 1_800_000_000_000)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
async def test_two_instances_preparing_one_operation_both_hold_the_lock(store: SqlStore) -> None:
|
|
437
|
+
"""The hub prepares every instance with the same operation; a prepare that loses the race to the other
|
|
438
|
+
instance's commit must be recognised as a renewal of the same operation, not as another holder.
|
|
439
|
+
|
|
440
|
+
On MySQL the store's no-op ON DUPLICATE KEY UPDATE locks the control row in ``_ensure``, so two ``lock``
|
|
441
|
+
calls serialise before the renew; this stress run is defensive there. PostgreSQL's INSERT ... ON CONFLICT DO
|
|
442
|
+
NOTHING leaves the row free, so the deterministic test below forces the interleaving.
|
|
443
|
+
"""
|
|
444
|
+
now = 1_800_000_000_000
|
|
445
|
+
for _ in range(30):
|
|
446
|
+
processor = f"conformance-{uuid.uuid4()}"
|
|
447
|
+
outcomes = await asyncio.gather(
|
|
448
|
+
store.control.lock(processor, "op-1", now + 30_000, now),
|
|
449
|
+
store.control.lock(processor, "op-1", now + 30_000, now),
|
|
450
|
+
)
|
|
451
|
+
assert all(outcome == Locked.was_taken() for outcome in outcomes), outcomes
|
|
452
|
+
assert await store.control.release(processor, "op-1", now)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
async def test_a_concurrent_preparation_on_postgres_is_a_renewal(store: SqlStore) -> None:
|
|
456
|
+
"""Force the PostgreSQL interleaving: the second instance's renew misses the first instance's uncommitted
|
|
457
|
+
take, its take queues behind the row lock and matches nothing after the commit, and the store must see that
|
|
458
|
+
the holder is its own operation and renew it. The same test fails when the recovery renewal is removed."""
|
|
459
|
+
if store.name != "postgres":
|
|
460
|
+
pytest.skip(
|
|
461
|
+
"MySQL's ensureControl locks the control row before the renew; the race is not reachable through lock"
|
|
462
|
+
)
|
|
463
|
+
other = SqlStore(store.config)
|
|
464
|
+
try:
|
|
465
|
+
await other.open()
|
|
466
|
+
now = 1_800_000_000_000
|
|
467
|
+
processor = f"conformance-{uuid.uuid4()}"
|
|
468
|
+
await store.control.set_paused(processor, False, "test", now)
|
|
469
|
+
|
|
470
|
+
a_renewed, b_renewed, a_took = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
|
471
|
+
allow_a_take, allow_b_take, allow_a_commit = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
|
472
|
+
|
|
473
|
+
async def first_step(step: str) -> None:
|
|
474
|
+
if step == "renewed":
|
|
475
|
+
a_renewed.set()
|
|
476
|
+
await allow_a_take.wait()
|
|
477
|
+
elif step == "taken":
|
|
478
|
+
a_took.set()
|
|
479
|
+
await allow_a_commit.wait()
|
|
480
|
+
|
|
481
|
+
async def second_step(step: str) -> None:
|
|
482
|
+
if step == "renewed":
|
|
483
|
+
b_renewed.set()
|
|
484
|
+
await allow_b_take.wait()
|
|
485
|
+
|
|
486
|
+
store._lock_step = first_step
|
|
487
|
+
other._lock_step = second_step
|
|
488
|
+
first = asyncio.create_task(store.control.lock(processor, "op-1", now + 30_000, now))
|
|
489
|
+
await asyncio.wait_for(a_renewed.wait(), 10)
|
|
490
|
+
second = asyncio.create_task(other.control.lock(processor, "op-1", now + 30_000, now))
|
|
491
|
+
await asyncio.wait_for(b_renewed.wait(), 10)
|
|
492
|
+
allow_a_take.set()
|
|
493
|
+
await asyncio.wait_for(a_took.wait(), 10)
|
|
494
|
+
allow_b_take.set()
|
|
495
|
+
await asyncio.sleep(0.2) # let B's take queue behind A's row lock
|
|
496
|
+
allow_a_commit.set()
|
|
497
|
+
outcomes = await asyncio.wait_for(asyncio.gather(first, second), 10)
|
|
498
|
+
assert all(outcome == Locked.was_taken() for outcome in outcomes), outcomes
|
|
499
|
+
finally:
|
|
500
|
+
await other.close()
|
|
501
|
+
|
|
502
|
+
|
|
359
503
|
async def test_notify_false_on_postgres_registers_no_listener(store: SqlStore) -> None:
|
|
360
504
|
if store.name != "postgres":
|
|
361
505
|
pytest.skip("MySQL has no notification at all")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{snodra_messaging_sql-0.6.0 → snodra_messaging_sql-0.7.0}/src/snodra_sql/schema/mysql/V1__snodra.sql
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|