xtr-orm-messenger 6.8.0__tar.gz → 7.0.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.
Files changed (28) hide show
  1. xtr_orm_messenger-6.8.0/README.md → xtr_orm_messenger-7.0.0/PKG-INFO +62 -6
  2. xtr_orm_messenger-6.8.0/PKG-INFO → xtr_orm_messenger-7.0.0/README.md +39 -33
  3. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/pyproject.toml +16 -20
  4. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/pyproject.toml.orig +16 -20
  5. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/.agents/skills/xtr-orm-messenger/SKILL.md +13 -3
  6. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/connection.py +126 -26
  7. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/messages_table_driver.py +1 -2
  8. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/orm_options.py +39 -3
  9. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/orm_receiver.py +126 -25
  10. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/orm_sender.py +1 -2
  11. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/orm_transport.py +6 -3
  12. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/orm_transport_factory.py +1 -2
  13. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/postgresql_notifier.py +34 -3
  14. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/LICENSE +0 -0
  15. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/__init__.py +0 -0
  16. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/exception/__init__.py +0 -0
  17. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/exception/invalid_orm_dsn_error.py +0 -0
  18. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/exception/orm_messenger_error.py +0 -0
  19. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/exception/transport_error.py +0 -0
  20. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/py.typed +0 -0
  21. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/recipe/__init__.py +0 -0
  22. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/recipe/manifest.toml +0 -0
  23. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/__init__.py +0 -0
  24. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/_database_errors.py +0 -0
  25. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/messages_table.py +0 -0
  26. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/messages_tables.py +0 -0
  27. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/orm_received_stamp.py +0 -0
  28. {xtr_orm_messenger-6.8.0 → xtr_orm_messenger-7.0.0}/src/xtr_orm_messenger/transport/stored_message.py +0 -0
@@ -1,10 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: xtr-orm-messenger
3
+ Version: 7.0.0
4
+ Summary: A database transport for xtr-messenger: messages kept in a table on an xtr-orm connection, claimed by workers, delayed, redelivered and woken by notifications.
5
+ Keywords: message-bus,message-queue,transport,database,sqlalchemy,asyncio
6
+ Author: Xterr
7
+ Author-email: Xterr <me@xterr.dev>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Topic :: Database
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: msgspec>=0.20
17
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.52
18
+ Requires-Dist: xtr-clock>=7.0,<8
19
+ Requires-Dist: xtr-messenger>=7.0,<8
20
+ Requires-Dist: xtr-orm>=7.0,<8
21
+ Requires-Python: >=3.14.4
22
+ Description-Content-Type: text/markdown
23
+
1
24
  <div align="center">
2
25
 
3
26
  # xtr-orm-messenger
4
27
 
5
28
  **A database transport for xtr-messenger: messages kept in a table on an xtr-orm connection, claimed by workers, delayed, redelivered and woken by notifications.**
6
29
 
7
- <img alt="python 3.11+" src="https://img.shields.io/badge/python-%E2%89%A5%203.11-3776AB?logo=python&logoColor=white">
30
+ <img alt="python 3.14+" src="https://img.shields.io/badge/python-%E2%89%A5%203.14-3776AB?logo=python&logoColor=white">
8
31
  <img alt="typed" src="https://img.shields.io/badge/typed-ty%20%2B%20basedpyright-1f6feb">
9
32
  <img alt="license MIT" src="https://img.shields.io/badge/license-MIT-blue">
10
33
 
@@ -83,17 +106,38 @@ handlers and deletes it. With a [container](#use-in-an-application) all of that
83
106
  | Send | One row: the encoded envelope, its queue, `created_at`, and `available_at` — later by the delay, rounded up to a whole second |
84
107
  | Claim | In one transaction, the oldest row of the queue that is due and not handed out is selected `FOR UPDATE SKIP LOCKED` and stamped `delivered_at` |
85
108
  | Handle | The worker dispatches it; the envelope carries `OrmReceivedStamp` and `TransportMessageIdStamp`, both the row's id |
86
- | Settle | Acknowledged or rejected, the row is deleted |
87
- | Redeliver | A row handed out more than `redeliver_timeout` seconds ago is claimable again: its worker is taken for dead |
109
+ | Keep alive | While the worker holds it, the row's `delivered_at` is renewed every half of `redeliver_timeout`, so a long handler keeps its message |
110
+ | Settle | Acknowledged, the row is deleted. Rejected, it is retried or moved to the failure queue (see below) |
111
+ | Redeliver | A row not renewed for `redeliver_timeout` seconds is claimable again: its worker is taken for dead. A handler must be idempotent: a worker frozen that long has its message handled twice |
112
+
113
+ Due times and the redelivery window are measured on each worker's clock, not the database's:
114
+ keep the workers' clocks synchronized. A clock running ahead claims delayed messages early and
115
+ takes a live worker's message for abandoned.
116
+
117
+ A rejected message gets `max_attempts` attempts in all, the first included. While it has
118
+ attempts left its row is put back in its queue, due `base_delay_seconds` later, the delay
119
+ doubling with each attempt; the envelope carries a `RedeliveryStamp` with the attempt count and
120
+ an `ErrorDetailsStamp` with why the last one failed. Once its attempts run out the row moves to
121
+ the `failure_queue` of the same table, `failed` unless named otherwise, where `count()`, `all()`
122
+ and `find()` on a transport reading that queue show it, and a worker consuming it tries it
123
+ again, with a fresh count. A message failing for good in the failure queue itself is deleted.
124
+ The worker asks the transport before it announces a failure, so `WorkerMessageFailedEvent`
125
+ carries `will_retry=True` for an attempt that will be made again.
88
126
 
89
127
  A worker that finds nothing due waits `poll_interval` seconds before asking again. On
90
128
  PostgreSQL through asyncpg it listens instead: every send announces itself on the table's
91
129
  channel, naming its queue, and the worker asks again at once — or after
92
130
  `check_delayed_interval`, for a delayed message falling due. Listening holds one connection of
93
131
  the pool for as long as the worker runs.
132
+ If the database drops that connection, the wait under way ends and the next one listens on a
133
+ fresh connection; while listening again fails, the worker polls every `poll_interval` and keeps
134
+ trying. A claim whose worker is cancelled before it hears of it is handed back at once, not left
135
+ until `redeliver_timeout`.
94
136
 
95
- SQLite has no row locks, so the lock clause is left out there. A second worker reaching for the
96
- row another is claiming gets "database is locked", which counts as a conflict and is tried again.
137
+ SQLite has no row locks, so the lock clause is left out there, and SQLite is for development and
138
+ tests. With the driver's default transaction mode two workers can claim one row; run one worker
139
+ on SQLite, or pass `connect_args={"autocommit": False}`, under which the second
140
+ gets "database is locked", which counts as a conflict and is tried again.
97
141
 
98
142
  Conflicts between workers — a deadlock, a lock wait that timed out — say nothing about the
99
143
  message. A poll sits through 3 in a row before it raises; an acknowledgement or a rejection
@@ -142,6 +186,9 @@ An unknown one is refused with `UnknownTransportOptionError`, a bad value with
142
186
  | `use_notify` | `true` | on PostgreSQL through asyncpg, wait for notifications instead of polling |
143
187
  | `check_delayed_interval` | `60000` | milliseconds a listening worker waits at most before asking anyway |
144
188
  | `get_notify_timeout` | `60000` | milliseconds one wait for a notification lasts at most |
189
+ | `max_attempts` | `3` | attempts a message gets, the first included, before it moves to the failure queue |
190
+ | `base_delay_seconds` | `1.0` | seconds before the second attempt; each later one waits twice as long |
191
+ | `failure_queue` | `failed` | the queue of the same table a message is moved to once its attempts run out |
145
192
 
146
193
  `orm://` with no name uses the default connection. A name the application did not configure is
147
194
  refused with `InvalidOrmDsnError` when the transport is built.
@@ -153,6 +200,9 @@ command: any unit of work — is written in that unit's session and sent only wh
153
200
  commits. Run the `orm_transaction` middleware, or commit yourself: a session never commits on
154
201
  its own. Outside a unit of work the message is written in a transaction of its own, as it is
155
202
  without the option.
203
+ A follow-up held back with `DispatchAfterCurrentBusStamp` in a worker goes out after the
204
+ handled message's unit is over; with `transactional=true` it is written in the worker's session
205
+ only when `orm_transaction` runs for it too, so keep that middleware on the bus the worker uses.
156
206
 
157
207
  ## Looking into a queue
158
208
 
@@ -170,7 +220,8 @@ await transport.setup() # create the table ahead of time
170
220
  ```
171
221
 
172
222
  `keepalive` restarts a message's redelivery clock; `seconds` is how long until the next call,
173
- refused when longer than `redeliver_timeout`.
223
+ refused when longer than `redeliver_timeout`. A worker already renews what it holds on its own;
224
+ call it for a message held some other way.
174
225
 
175
226
  ## Use in an application
176
227
 
@@ -230,6 +281,11 @@ Everything this library raises derives from `OrmMessengerError`, itself a
230
281
  | `TransportError` | the database refuses what a transport asked — sending, claiming, settling, listing — or an envelope settled here was not received here; the driver's error is its cause |
231
282
  | `InvalidOrmDsnError` | an `orm://` DSN names a connection the application does not configure; also a `LookupError` |
232
283
 
284
+ ## Upgrading
285
+
286
+ What changes for an application moving to 7.0, and how to keep the old behaviour where that is
287
+ still possible: [Upgrading to 7.0](../../UPGRADING.md#xtr-orm-messenger).
288
+
233
289
  ## Development
234
290
 
235
291
  Developed in the [python-xtr](https://github.com/xterr/python-xtr) monorepo, under
@@ -1,37 +1,10 @@
1
- Metadata-Version: 2.4
2
- Name: xtr-orm-messenger
3
- Version: 6.8.0
4
- Summary: A database transport for xtr-messenger: messages kept in a table on an xtr-orm connection, claimed by workers, delayed, redelivered and woken by notifications.
5
- Keywords: message-bus,message-queue,transport,database,sqlalchemy,asyncio
6
- Author: Xterr
7
- Author-email: Xterr <me@xterr.dev>
8
- License-Expression: MIT
9
- License-File: LICENSE
10
- Classifier: Development Status :: 3 - Alpha
11
- Classifier: Framework :: AsyncIO
12
- Classifier: Intended Audience :: Developers
13
- Classifier: Programming Language :: Python :: 3.11
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Programming Language :: Python :: 3.13
16
- Classifier: Programming Language :: Python :: 3.14
17
- Classifier: Topic :: Database
18
- Classifier: Typing :: Typed
19
- Requires-Dist: msgspec>=0.18
20
- Requires-Dist: sqlalchemy[asyncio]>=2.0.41
21
- Requires-Dist: typing-extensions>=4.4
22
- Requires-Dist: xtr-clock>=6.0,<7
23
- Requires-Dist: xtr-messenger>=6.0,<7
24
- Requires-Dist: xtr-orm>=6.0,<7
25
- Requires-Python: >=3.11
26
- Description-Content-Type: text/markdown
27
-
28
1
  <div align="center">
29
2
 
30
3
  # xtr-orm-messenger
31
4
 
32
5
  **A database transport for xtr-messenger: messages kept in a table on an xtr-orm connection, claimed by workers, delayed, redelivered and woken by notifications.**
33
6
 
34
- <img alt="python 3.11+" src="https://img.shields.io/badge/python-%E2%89%A5%203.11-3776AB?logo=python&logoColor=white">
7
+ <img alt="python 3.14+" src="https://img.shields.io/badge/python-%E2%89%A5%203.14-3776AB?logo=python&logoColor=white">
35
8
  <img alt="typed" src="https://img.shields.io/badge/typed-ty%20%2B%20basedpyright-1f6feb">
36
9
  <img alt="license MIT" src="https://img.shields.io/badge/license-MIT-blue">
37
10
 
@@ -110,17 +83,38 @@ handlers and deletes it. With a [container](#use-in-an-application) all of that
110
83
  | Send | One row: the encoded envelope, its queue, `created_at`, and `available_at` — later by the delay, rounded up to a whole second |
111
84
  | Claim | In one transaction, the oldest row of the queue that is due and not handed out is selected `FOR UPDATE SKIP LOCKED` and stamped `delivered_at` |
112
85
  | Handle | The worker dispatches it; the envelope carries `OrmReceivedStamp` and `TransportMessageIdStamp`, both the row's id |
113
- | Settle | Acknowledged or rejected, the row is deleted |
114
- | Redeliver | A row handed out more than `redeliver_timeout` seconds ago is claimable again: its worker is taken for dead |
86
+ | Keep alive | While the worker holds it, the row's `delivered_at` is renewed every half of `redeliver_timeout`, so a long handler keeps its message |
87
+ | Settle | Acknowledged, the row is deleted. Rejected, it is retried or moved to the failure queue (see below) |
88
+ | Redeliver | A row not renewed for `redeliver_timeout` seconds is claimable again: its worker is taken for dead. A handler must be idempotent: a worker frozen that long has its message handled twice |
89
+
90
+ Due times and the redelivery window are measured on each worker's clock, not the database's:
91
+ keep the workers' clocks synchronized. A clock running ahead claims delayed messages early and
92
+ takes a live worker's message for abandoned.
93
+
94
+ A rejected message gets `max_attempts` attempts in all, the first included. While it has
95
+ attempts left its row is put back in its queue, due `base_delay_seconds` later, the delay
96
+ doubling with each attempt; the envelope carries a `RedeliveryStamp` with the attempt count and
97
+ an `ErrorDetailsStamp` with why the last one failed. Once its attempts run out the row moves to
98
+ the `failure_queue` of the same table, `failed` unless named otherwise, where `count()`, `all()`
99
+ and `find()` on a transport reading that queue show it, and a worker consuming it tries it
100
+ again, with a fresh count. A message failing for good in the failure queue itself is deleted.
101
+ The worker asks the transport before it announces a failure, so `WorkerMessageFailedEvent`
102
+ carries `will_retry=True` for an attempt that will be made again.
115
103
 
116
104
  A worker that finds nothing due waits `poll_interval` seconds before asking again. On
117
105
  PostgreSQL through asyncpg it listens instead: every send announces itself on the table's
118
106
  channel, naming its queue, and the worker asks again at once — or after
119
107
  `check_delayed_interval`, for a delayed message falling due. Listening holds one connection of
120
108
  the pool for as long as the worker runs.
109
+ If the database drops that connection, the wait under way ends and the next one listens on a
110
+ fresh connection; while listening again fails, the worker polls every `poll_interval` and keeps
111
+ trying. A claim whose worker is cancelled before it hears of it is handed back at once, not left
112
+ until `redeliver_timeout`.
121
113
 
122
- SQLite has no row locks, so the lock clause is left out there. A second worker reaching for the
123
- row another is claiming gets "database is locked", which counts as a conflict and is tried again.
114
+ SQLite has no row locks, so the lock clause is left out there, and SQLite is for development and
115
+ tests. With the driver's default transaction mode two workers can claim one row; run one worker
116
+ on SQLite, or pass `connect_args={"autocommit": False}`, under which the second
117
+ gets "database is locked", which counts as a conflict and is tried again.
124
118
 
125
119
  Conflicts between workers — a deadlock, a lock wait that timed out — say nothing about the
126
120
  message. A poll sits through 3 in a row before it raises; an acknowledgement or a rejection
@@ -169,6 +163,9 @@ An unknown one is refused with `UnknownTransportOptionError`, a bad value with
169
163
  | `use_notify` | `true` | on PostgreSQL through asyncpg, wait for notifications instead of polling |
170
164
  | `check_delayed_interval` | `60000` | milliseconds a listening worker waits at most before asking anyway |
171
165
  | `get_notify_timeout` | `60000` | milliseconds one wait for a notification lasts at most |
166
+ | `max_attempts` | `3` | attempts a message gets, the first included, before it moves to the failure queue |
167
+ | `base_delay_seconds` | `1.0` | seconds before the second attempt; each later one waits twice as long |
168
+ | `failure_queue` | `failed` | the queue of the same table a message is moved to once its attempts run out |
172
169
 
173
170
  `orm://` with no name uses the default connection. A name the application did not configure is
174
171
  refused with `InvalidOrmDsnError` when the transport is built.
@@ -180,6 +177,9 @@ command: any unit of work — is written in that unit's session and sent only wh
180
177
  commits. Run the `orm_transaction` middleware, or commit yourself: a session never commits on
181
178
  its own. Outside a unit of work the message is written in a transaction of its own, as it is
182
179
  without the option.
180
+ A follow-up held back with `DispatchAfterCurrentBusStamp` in a worker goes out after the
181
+ handled message's unit is over; with `transactional=true` it is written in the worker's session
182
+ only when `orm_transaction` runs for it too, so keep that middleware on the bus the worker uses.
183
183
 
184
184
  ## Looking into a queue
185
185
 
@@ -197,7 +197,8 @@ await transport.setup() # create the table ahead of time
197
197
  ```
198
198
 
199
199
  `keepalive` restarts a message's redelivery clock; `seconds` is how long until the next call,
200
- refused when longer than `redeliver_timeout`.
200
+ refused when longer than `redeliver_timeout`. A worker already renews what it holds on its own;
201
+ call it for a message held some other way.
201
202
 
202
203
  ## Use in an application
203
204
 
@@ -257,6 +258,11 @@ Everything this library raises derives from `OrmMessengerError`, itself a
257
258
  | `TransportError` | the database refuses what a transport asked — sending, claiming, settling, listing — or an envelope settled here was not received here; the driver's error is its cause |
258
259
  | `InvalidOrmDsnError` | an `orm://` DSN names a connection the application does not configure; also a `LookupError` |
259
260
 
261
+ ## Upgrading
262
+
263
+ What changes for an application moving to 7.0, and how to keep the old behaviour where that is
264
+ still possible: [Upgrading to 7.0](../../UPGRADING.md#xtr-orm-messenger).
265
+
260
266
  ## Development
261
267
 
262
268
  Developed in the [python-xtr](https://github.com/xterr/python-xtr) monorepo, under
@@ -1,9 +1,9 @@
1
1
  [project]
2
2
  name = "xtr-orm-messenger"
3
- version = "6.8.0"
3
+ version = "7.0.0"
4
4
  description = "A database transport for xtr-messenger: messages kept in a table on an xtr-orm connection, claimed by workers, delayed, redelivered and woken by notifications."
5
5
  readme = "README.md"
6
- requires-python = ">=3.11"
6
+ requires-python = ">=3.14.4"
7
7
  license = "MIT"
8
8
  license-files = ["LICENSE"]
9
9
  keywords = [
@@ -18,20 +18,16 @@ classifiers = [
18
18
  "Development Status :: 3 - Alpha",
19
19
  "Framework :: AsyncIO",
20
20
  "Intended Audience :: Developers",
21
- "Programming Language :: Python :: 3.11",
22
- "Programming Language :: Python :: 3.12",
23
- "Programming Language :: Python :: 3.13",
24
21
  "Programming Language :: Python :: 3.14",
25
22
  "Topic :: Database",
26
23
  "Typing :: Typed",
27
24
  ]
28
25
  dependencies = [
29
- "msgspec>=0.18",
30
- "sqlalchemy[asyncio]>=2.0.41",
31
- "typing-extensions>=4.4",
32
- "xtr-clock>=6.0,<7",
33
- "xtr-messenger>=6.0,<7",
34
- "xtr-orm>=6.0,<7",
26
+ "msgspec>=0.20",
27
+ "sqlalchemy[asyncio]>=2.0.52",
28
+ "xtr-clock>=7.0,<8",
29
+ "xtr-messenger>=7.0,<8",
30
+ "xtr-orm>=7.0,<8",
35
31
  ]
36
32
 
37
33
  [[project.authors]]
@@ -43,15 +39,15 @@ orm_messenger = "xtr_orm_messenger.recipe"
43
39
 
44
40
  [dependency-groups]
45
41
  dev = [
46
- "basedpyright>=1.21",
47
- "ruff>=0.8",
48
- "pytest>=8",
49
- "pytest-cov>=5",
50
- "anyio>=4.0",
42
+ "basedpyright>=1.31.7",
43
+ "ruff>=0.14.7",
44
+ "pytest>=8.4",
45
+ "pytest-cov>=7.1",
46
+ "anyio>=4.10",
51
47
  "ty>=0.0.83",
52
48
  "aiosqlite>=0.20",
53
- "asyncpg>=0.29",
54
- "xtr-serializer>=6.0,<7",
49
+ "asyncpg>=0.31",
50
+ "xtr-serializer>=7.0,<8",
55
51
  ]
56
52
 
57
53
  [build-system]
@@ -60,7 +56,7 @@ build-backend = "uv_build"
60
56
 
61
57
  [tool.basedpyright]
62
58
  typeCheckingMode = "all"
63
- pythonVersion = "3.11"
59
+ pythonVersion = "3.14"
64
60
  pythonPlatform = "All"
65
61
  include = [
66
62
  "src",
@@ -86,7 +82,7 @@ extraPaths = ["."]
86
82
  reportPrivateUsage = "none"
87
83
 
88
84
  [tool.ruff]
89
- target-version = "py311"
85
+ target-version = "py314"
90
86
  line-length = 100
91
87
  src = [
92
88
  "src",
@@ -1,9 +1,9 @@
1
1
  [project]
2
2
  name = "xtr-orm-messenger"
3
- version = "6.8.0"
3
+ version = "7.0.0"
4
4
  description = "A database transport for xtr-messenger: messages kept in a table on an xtr-orm connection, claimed by workers, delayed, redelivered and woken by notifications."
5
5
  readme = "README.md"
6
- requires-python = ">=3.11"
6
+ requires-python = ">=3.14.4"
7
7
  license = "MIT"
8
8
  license-files = ["LICENSE"]
9
9
  authors = [
@@ -14,20 +14,16 @@ classifiers = [
14
14
  "Development Status :: 3 - Alpha",
15
15
  "Framework :: AsyncIO",
16
16
  "Intended Audience :: Developers",
17
- "Programming Language :: Python :: 3.11",
18
- "Programming Language :: Python :: 3.12",
19
- "Programming Language :: Python :: 3.13",
20
17
  "Programming Language :: Python :: 3.14",
21
18
  "Topic :: Database",
22
19
  "Typing :: Typed",
23
20
  ]
24
21
  dependencies = [
25
- "msgspec>=0.18",
26
- "sqlalchemy[asyncio]>=2.0.41",
27
- "typing-extensions>=4.4",
28
- "xtr-clock>=6.0,<7",
29
- "xtr-messenger>=6.0,<7",
30
- "xtr-orm>=6.0,<7",
22
+ "msgspec>=0.20",
23
+ "sqlalchemy[asyncio]>=2.0.52",
24
+ "xtr-clock>=7.0,<8",
25
+ "xtr-messenger>=7.0,<8",
26
+ "xtr-orm>=7.0,<8",
31
27
  ]
32
28
 
33
29
  # Advertises the recipe — what *Use in an application* takes — for recipes:sync.
@@ -38,19 +34,19 @@ orm_messenger = "xtr_orm_messenger.recipe"
38
34
 
39
35
  [dependency-groups]
40
36
  dev = [
41
- "basedpyright>=1.21",
42
- "ruff>=0.8",
43
- "pytest>=8",
44
- "pytest-cov>=5",
45
- "anyio>=4.0",
37
+ "basedpyright>=1.31.7",
38
+ "ruff>=0.14.7",
39
+ "pytest>=8.4",
40
+ "pytest-cov>=7.1",
41
+ "anyio>=4.10",
46
42
  "ty>=0.0.83",
47
43
  # Every test runs on SQLite files under the test's own directory: no server.
48
44
  "aiosqlite>=0.20",
49
45
  # The PostgreSQL suite, run when XTR_TEST_POSTGRES_URL names a server. An
50
46
  # application's driver is the one its connection already uses.
51
- "asyncpg>=0.29",
47
+ "asyncpg>=0.31",
52
48
  # The envelope serializer the tests encode with is built on it, as the messenger's is.
53
- "xtr-serializer>=6.0,<7",
49
+ "xtr-serializer>=7.0,<8",
54
50
  ]
55
51
 
56
52
  [build-system]
@@ -62,7 +58,7 @@ build-backend = "uv_build"
62
58
  # ─────────────────────────────────────────────────────────────────
63
59
  [tool.basedpyright]
64
60
  typeCheckingMode = "all"
65
- pythonVersion = "3.11"
61
+ pythonVersion = "3.14"
66
62
  pythonPlatform = "All"
67
63
  include = ["src", "tests"]
68
64
  exclude = ["**/__pycache__", "**/.venv", "**/build", "**/dist", ".tmp"]
@@ -88,7 +84,7 @@ reportPrivateUsage = "none"
88
84
  # ruff — select = ["ALL"], minimal justified ignores
89
85
  # ─────────────────────────────────────────────────────────────────
90
86
  [tool.ruff]
91
- target-version = "py311"
87
+ target-version = "py314"
92
88
  line-length = 100
93
89
  src = ["src", "tests"]
94
90
 
@@ -17,13 +17,22 @@ skill; for connections and migrations, `xtr-orm`.
17
17
  - Options (DSN query or `options`) — `table_name` (`messenger_messages`), `redeliver_timeout`
18
18
  (`3600` s), `auto_setup` (`true`), `poll_interval` (`1.0` s), `transactional` (`false`),
19
19
  `use_notify` (`true`), `check_delayed_interval` / `get_notify_timeout` (`60000` ms).
20
+ Retries: `max_attempts` (`3`, the first included), `base_delay_seconds` (`1.0`, doubling),
21
+ `failure_queue` (`failed`).
20
22
  - `OrmTransportFactory(registry, serializer, clock=None)` — not discovered by scheme: the orm
21
23
  bundle registers it with the messenger's envelope serializer, or you pass it to
22
24
  `MessageBusFactory` / `WorkerFactory`.
23
25
  - Migrations — each connection's migrator adds the table of every `orm://` transport on it, so
24
26
  `orm:migrations:diff` writes it; `messages_tables(bus_config, connection, default)` names them.
25
- - Settling deletes the row; a row handed out longer than `redeliver_timeout` is claimed again.
27
+ - Acknowledging deletes the row. Rejecting puts it back in its queue with a `RedeliveryStamp`
28
+ while attempts are left, then moves it to `failure_queue` — consume that queue to try it
29
+ again; a failure there deletes it. `transport.will_retry(envelope)` says which, and the
30
+ worker's `WorkerMessageFailedEvent.will_retry` follows it. While a worker holds a message its claim is renewed every half of
31
+ `redeliver_timeout`; a row not renewed that long (a dead or frozen worker) is claimed again,
32
+ so handlers must be idempotent.
26
33
  - A `DelayStamp` makes the message due later, rounded up to a whole second.
34
+ - A dropped LISTEN connection is replaced on the next wait (polling while that fails); a claim
35
+ cancelled before its worker heard of it is released at once.
27
36
 
28
37
  ## Send and consume without a container
29
38
 
@@ -67,7 +76,7 @@ transport = factory.transport("jobs", config.transports["jobs"])
67
76
  await transport.count()
68
77
  messages = [envelope async for envelope in transport.all(limit=10)]
69
78
  await transport.find(message_id)
70
- await transport.keepalive(envelope, seconds=600) # a handler running past redeliver_timeout
79
+ await transport.keepalive(envelope, seconds=600) # a message held outside a worker
71
80
  ```
72
81
 
73
82
  ## Testing
@@ -103,6 +112,7 @@ do not care where messages are kept.
103
112
 
104
113
  - Do not put a database URL in the DSN: it names a connection, configured in the orm.
105
114
  - Do not rely on `transactional=true` without something committing the unit's session.
106
- - Do not set `redeliver_timeout` below the time a handler takes, unless it calls `keepalive`.
115
+ - Do not run several workers on SQLite with the driver's default transaction mode: two can claim
116
+ one row (SQLite is for development and tests).
107
117
  - Do not expect notifications through a PostgreSQL driver other than asyncpg: it polls.
108
118
  - Do not look for an `OrmMessengerBundle`: there is none; list `OrmBundle` and `MessengerBundle`.
@@ -5,21 +5,27 @@ deal in rows and never in SQL. A worker claims the oldest message of its queue
5
5
  that is due and not handed out, marking it handed out in the same transaction;
6
6
  a message handed out and never settled is handed out again once
7
7
  ``redeliver_timeout`` has passed, the worker holding it being taken for dead.
8
- Settling a message — handled or rejected — deletes it.
8
+ A handled message is deleted; a rejected one is put back in line — in its own
9
+ queue for another attempt, or in the failure queue — by rewriting its row.
9
10
 
10
11
  A claim selects the oldest due row ``FOR UPDATE SKIP LOCKED`` and marks it
11
12
  handed out, in one transaction, so concurrent workers each take a different row
12
13
  without waiting on each other. A database without row locks — SQLite — gets the
13
- same statements with the lock clause left out; its single writer then turns two
14
- workers reaching for one row into a "database is locked" error for the second,
15
- which the receiver treats as a conflict worth trying again.
14
+ same statements with the lock clause left out. With the driver's own
15
+ transaction mode, two workers can then claim one row; with its transaction
16
+ control off (``autocommit=False``), its single writer turns the second into a
17
+ "database is locked" error, which the receiver treats as a conflict worth
18
+ trying again. SQLite is for development and tests.
16
19
  """
17
20
 
18
21
  from __future__ import annotations
19
22
 
23
+ import asyncio
24
+ import logging
25
+ from contextlib import suppress
20
26
  from dataclasses import replace
21
27
  from datetime import datetime, timedelta
22
- from typing import TYPE_CHECKING, Final, TypeVar, cast, final
28
+ from typing import TYPE_CHECKING, Final, cast, final
23
29
 
24
30
  import msgspec
25
31
  from sqlalchemy import (
@@ -57,7 +63,9 @@ if TYPE_CHECKING:
57
63
 
58
64
  __all__ = ["LISTING_PAGE_SIZE", "Connection"]
59
65
 
60
- _T = TypeVar("_T")
66
+
67
+ #: Through the messenger channel, beside the rest of the bus's output.
68
+ _LOGGER: Final = logging.getLogger("messenger")
61
69
 
62
70
  LISTING_PAGE_SIZE: Final = 100
63
71
  """How many rows :meth:`Connection.all` reads per statement when it lists every message."""
@@ -79,6 +87,7 @@ class Connection:
79
87
  "_notifier",
80
88
  "_notifier_resolved",
81
89
  "_options",
90
+ "_relisten",
82
91
  "_session_factory",
83
92
  "_table",
84
93
  )
@@ -112,6 +121,7 @@ class Connection:
112
121
  self._auto_setup = options.auto_setup
113
122
  self._notifier: PostgreSqlNotifier | None = None
114
123
  self._notifier_resolved = False
124
+ self._relisten = False
115
125
 
116
126
  @property
117
127
  def options(self) -> OrmOptions:
@@ -134,15 +144,12 @@ class Connection:
134
144
  written in that unit's session and is sent only once the unit commits.
135
145
  """
136
146
  now = self._now()
137
- available_at = now + timedelta(milliseconds=delay_ms)
138
- if delay_ms > 0 and available_at.microsecond:
139
- available_at = available_at.replace(microsecond=0) + timedelta(seconds=1)
140
147
  statement = insert(self._table).values(
141
148
  body=body,
142
149
  headers=msgspec.json.encode(dict(headers)).decode(),
143
150
  queue_name=self._options.queue,
144
151
  created_at=now,
145
- available_at=available_at,
152
+ available_at=_due(now, delay_ms),
146
153
  )
147
154
  session = await self._unit_session()
148
155
  if session is not None:
@@ -163,12 +170,31 @@ class Connection:
163
170
  await self._with_setup(lambda: self._delete(message_id))
164
171
 
165
172
  async def reject(self, message_id: str) -> None:
166
- """Forget the message ``message_id``: it failed for good.
173
+ """Forget the message ``message_id``: it failed for good, with nowhere left to go."""
174
+ await self._with_setup(lambda: self._delete(message_id))
167
175
 
168
- The same as :meth:`ack`: whatever retries a message gets have run by
169
- the time it is rejected, and keeping it would hand it out again.
176
+ async def requeue(
177
+ self, message_id: str, *, queue: str, body: str, headers: Mapping[str, str], delay_ms: int
178
+ ) -> None:
179
+ """Put the message ``message_id`` back in line in ``queue``, due ``delay_ms`` from now.
180
+
181
+ Its body and headers are replaced, so what the failed attempt
182
+ learned — the attempt count, the reason — travels with it. The row
183
+ keeps its id and the time it was first sent.
170
184
  """
171
- await self._with_setup(lambda: self._delete(message_id))
185
+ table = self._table
186
+ statement = (
187
+ update(table)
188
+ .where(table.c.id == int(message_id))
189
+ .values(
190
+ queue_name=queue,
191
+ body=body,
192
+ headers=msgspec.json.encode(dict(headers)).decode(),
193
+ available_at=_due(self._now(), delay_ms),
194
+ delivered_at=None,
195
+ )
196
+ )
197
+ await self._with_setup(lambda: self._requeue(statement, queue))
172
198
 
173
199
  async def keepalive(self, message_id: str) -> None:
174
200
  """Mark the message ``message_id`` handed out now, restarting its redelivery clock.
@@ -262,9 +288,29 @@ class Connection:
262
288
  returns: a message sent between the poll that found nothing and the
263
289
  moment the listening started announced itself to nobody, so the worker
264
290
  asks once more before it waits for real.
291
+
292
+ A listening connection the database dropped is replaced the same way
293
+ on the next wait; while listening again fails, the worker waits its
294
+ ``poll_interval`` and tries again the time after.
265
295
  """
296
+ if self._notifier is not None and self._notifier.lost:
297
+ await self._drop_notifier()
298
+ self._relisten = True
266
299
  if not self._notifier_resolved:
267
- await self._resolve_notifier()
300
+ try:
301
+ await self._resolve_notifier()
302
+ except (DBAPIError, OSError) as error:
303
+ if not self._relisten:
304
+ raise
305
+ _LOGGER.warning(
306
+ "could not listen on %r again (%s); polling until it can",
307
+ self._options.table_name,
308
+ type(error).__name__,
309
+ )
310
+ self._notifier_resolved = False
311
+ await self._clock.sleep_async(self._options.poll_interval)
312
+ return
313
+ self._relisten = False
268
314
  if self._notifier is not None:
269
315
  return
270
316
  notifier = self._notifier
@@ -279,10 +325,22 @@ class Connection:
279
325
  notifier = self._notifier
280
326
  self._notifier = None
281
327
  self._notifier_resolved = False
328
+ self._relisten = False
282
329
  if notifier is not None:
283
330
  await notifier.close()
284
331
 
285
- async def _with_setup(self, operation: Callable[[], Awaitable[_T]]) -> _T:
332
+ async def _drop_notifier(self) -> None:
333
+ """Give back the connection of a notifier whose listening was dropped."""
334
+ notifier = self._notifier
335
+ self._notifier = None
336
+ self._notifier_resolved = False
337
+ if notifier is None:
338
+ return
339
+ # The connection is already gone; closing it may only report as much.
340
+ with suppress(DBAPIError, OSError):
341
+ await notifier.close()
342
+
343
+ async def _with_setup[T](self, operation: Callable[[], Awaitable[T]]) -> T:
286
344
  """Run ``operation``; on a missing table, with ``auto_setup``, create it and run again."""
287
345
  try:
288
346
  return await operation()
@@ -323,13 +381,20 @@ class Connection:
323
381
  _ = await connection.execute(self._notification())
324
382
  return _identifier(result)
325
383
 
326
- def _notification(self) -> Executable:
384
+ def _notification(self, queue: str | None = None) -> Executable:
327
385
  """Announce a message on the table's channel, naming its queue.
328
386
 
329
387
  Sent in the transaction that wrote the message, so a listener hears it
330
388
  only once the message can be claimed.
331
389
  """
332
- return select(func.pg_notify(self._options.table_name, self._options.queue))
390
+ return select(func.pg_notify(self._options.table_name, queue or self._options.queue))
391
+
392
+ async def _requeue(self, statement: Executable, queue: str) -> None:
393
+ engine = await self._engine_factory()
394
+ async with engine.begin() as connection:
395
+ _ = await connection.execute(statement)
396
+ if isinstance(connection.dialect, PGDialect):
397
+ _ = await connection.execute(self._notification(queue))
333
398
 
334
399
  async def _claim(self) -> StoredMessage | None:
335
400
  now = self._now()
@@ -342,16 +407,38 @@ class Connection:
342
407
  .with_for_update(skip_locked=True)
343
408
  )
344
409
  engine = await self._engine_factory()
345
- async with engine.begin() as connection:
346
- row = (await connection.execute(statement)).mappings().first()
347
- if row is None:
348
- return None
349
- stored = _stored(row)
350
- _ = await connection.execute(
351
- update(table).where(table.c.id == int(stored.id)).values(delivered_at=now)
352
- )
410
+ stored: StoredMessage | None = None
411
+ try:
412
+ async with engine.begin() as connection:
413
+ row = (await connection.execute(statement)).mappings().first()
414
+ if row is None:
415
+ return None
416
+ stored = _stored(row)
417
+ _ = await connection.execute(
418
+ update(table).where(table.c.id == int(stored.id)).values(delivered_at=now)
419
+ )
420
+ except asyncio.CancelledError:
421
+ if stored is not None:
422
+ await self._release_claim(stored.id, now)
423
+ raise
353
424
  return replace(stored, delivered_at=now)
354
425
 
426
+ async def _release_claim(self, message_id: str, delivered_at: datetime) -> None:
427
+ """Hand back a claim its caller was cancelled before it heard of.
428
+
429
+ The claim may have committed or not; the update only matches a row
430
+ still marked handed out by this claim, so it never releases another
431
+ worker's. Not shielded: a second cancellation leaves the row to
432
+ ``redeliver_timeout``.
433
+ """
434
+ table = self._table
435
+ statement = (
436
+ update(table)
437
+ .where(table.c.id == int(message_id), table.c.delivered_at == delivered_at)
438
+ .values(delivered_at=None)
439
+ )
440
+ await self._execute(statement)
441
+
355
442
  def _available(self, now: datetime) -> ColumnElement[bool]:
356
443
  """Select the queue's messages that are due and not held by a worker that is still alive."""
357
444
  table = self._table
@@ -422,6 +509,19 @@ def _identifier(result: CursorResult[tuple[object, ...]]) -> str:
422
509
  return str(values[0])
423
510
 
424
511
 
512
+ def _due(now: datetime, delay_ms: int) -> datetime:
513
+ """Return when a message delayed ``delay_ms`` from ``now`` falls due.
514
+
515
+ A positive delay is rounded up to a whole second: some databases keep a
516
+ datetime to the second, and dropping the fraction would make the message
517
+ due before the delay asked for.
518
+ """
519
+ available_at = now + timedelta(milliseconds=delay_ms)
520
+ if delay_ms > 0 and available_at.microsecond:
521
+ available_at = available_at.replace(microsecond=0) + timedelta(seconds=1)
522
+ return available_at
523
+
524
+
425
525
  def _stored(row: RowMapping) -> StoredMessage:
426
526
  """Read one row of the table into a :class:`StoredMessage`."""
427
527
  # The table's columns are untyped to SQLAlchemy; their types are the table's own.
@@ -2,9 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, final
5
+ from typing import TYPE_CHECKING, final, override
6
6
 
7
- from typing_extensions import override
8
7
  from xtr_orm import MappingDriverInterface
9
8
 
10
9
  from .messages_table import messages_table
@@ -17,7 +17,14 @@ from xtr_messenger.transport.transport_options import (
17
17
  if TYPE_CHECKING:
18
18
  from collections.abc import Mapping
19
19
 
20
- __all__ = ["DEFAULT_QUEUE", "DEFAULT_TABLE_NAME", "ORM_OPTIONS", "ORM_SCHEME", "OrmOptions"]
20
+ __all__ = [
21
+ "DEFAULT_FAILURE_QUEUE",
22
+ "DEFAULT_QUEUE",
23
+ "DEFAULT_TABLE_NAME",
24
+ "ORM_OPTIONS",
25
+ "ORM_SCHEME",
26
+ "OrmOptions",
27
+ ]
21
28
 
22
29
  ORM_SCHEME: Final = "orm"
23
30
  """The DSN scheme the transport serves."""
@@ -28,10 +35,16 @@ DEFAULT_TABLE_NAME: Final = "messenger_messages"
28
35
  DEFAULT_QUEUE: Final = "default"
29
36
  """The queue a transport reads and writes when the configuration names none."""
30
37
 
38
+ DEFAULT_FAILURE_QUEUE: Final = "failed"
39
+ """The queue a message is moved to once its attempts run out, when the configuration names none."""
40
+
31
41
  ORM_OPTIONS: Final = (
32
42
  "auto_setup",
43
+ "base_delay_seconds",
33
44
  "check_delayed_interval",
45
+ "failure_queue",
34
46
  "get_notify_timeout",
47
+ "max_attempts",
35
48
  "poll_interval",
36
49
  "queue",
37
50
  "redeliver_timeout",
@@ -73,6 +86,14 @@ class OrmOptions:
73
86
  falling due sends none.
74
87
  get_notify_timeout: Milliseconds one wait for a notification lasts at
75
88
  most.
89
+ max_attempts: Attempts a message gets, the first included; a rejected
90
+ message with attempts left is put back in its queue.
91
+ base_delay_seconds: Seconds before the second attempt; each later one
92
+ waits twice as long as the one before.
93
+ failure_queue: The queue of the same table a message is moved to once
94
+ its attempts run out, where it can be inspected, or consumed like
95
+ any queue to try it again. A transport reading the failure queue
96
+ itself deletes a message whose attempts there run out.
76
97
  """
77
98
 
78
99
  table_name: str = DEFAULT_TABLE_NAME
@@ -84,6 +105,9 @@ class OrmOptions:
84
105
  use_notify: bool = True
85
106
  check_delayed_interval: int = 60_000
86
107
  get_notify_timeout: int = 60_000
108
+ max_attempts: int = 3
109
+ base_delay_seconds: float = 1.0
110
+ failure_queue: str = DEFAULT_FAILURE_QUEUE
87
111
 
88
112
  def __post_init__(self) -> None:
89
113
  """Refuse values the transport would misread.
@@ -97,9 +121,18 @@ class OrmOptions:
97
121
  raise InvalidTransportOptionError(
98
122
  "table_name", self.table_name, "a plain identifier: letters, digits and '_'"
99
123
  )
100
- if not 0 < len(self.queue) <= _QUEUE_LENGTH:
124
+ for name, queue in (("queue", self.queue), ("failure_queue", self.failure_queue)):
125
+ if not 0 < len(queue) <= _QUEUE_LENGTH:
126
+ raise InvalidTransportOptionError(
127
+ name, queue, f"between 1 and {_QUEUE_LENGTH} characters"
128
+ )
129
+ if self.max_attempts <= 0:
130
+ raise InvalidTransportOptionError(
131
+ "max_attempts", str(self.max_attempts), "a positive number of attempts"
132
+ )
133
+ if self.base_delay_seconds < 0:
101
134
  raise InvalidTransportOptionError(
102
- "queue", self.queue, f"between 1 and {_QUEUE_LENGTH} characters"
135
+ "base_delay_seconds", str(self.base_delay_seconds), "zero or more seconds"
103
136
  )
104
137
  if self.redeliver_timeout <= 0:
105
138
  raise InvalidTransportOptionError(
@@ -142,4 +175,7 @@ class OrmOptions:
142
175
  settings, "check_delayed_interval", base.check_delayed_interval
143
176
  ),
144
177
  get_notify_timeout=as_int(settings, "get_notify_timeout", base.get_notify_timeout),
178
+ max_attempts=as_int(settings, "max_attempts", base.max_attempts),
179
+ base_delay_seconds=as_float(settings, "base_delay_seconds", base.base_delay_seconds),
180
+ failure_queue=settings.get("failure_queue", base.failure_queue),
145
181
  )
@@ -2,18 +2,20 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
5
6
  import logging
6
7
  import secrets
7
- from typing import TYPE_CHECKING, Final, final
8
+ from typing import TYPE_CHECKING, Final, final, override
8
9
 
9
10
  from sqlalchemy.exc import DBAPIError
10
- from typing_extensions import override
11
11
  from xtr_clock import SystemClock
12
12
  from xtr_messenger import (
13
13
  EncodedEnvelope,
14
+ ErrorDetailsStamp,
14
15
  MessageDecodingFailedError,
15
16
  ReceivedStamp,
16
17
  ReceiverInterface,
18
+ RedeliveryStamp,
17
19
  TransportMessageIdStamp,
18
20
  )
19
21
 
@@ -52,7 +54,15 @@ _LOGGER: Final = logging.getLogger("messenger")
52
54
 
53
55
  @final
54
56
  class OrmReceiver(ReceiverInterface):
55
- """Claims the messages of one queue, and deletes each once it is settled.
57
+ """Claims the messages of one queue, deleting each once handled and retrying each rejected.
58
+
59
+ A rejected message with attempts left is put back in its queue, due
60
+ after ``base_delay_seconds`` doubled for each attempt it already had, its
61
+ attempt count kept in a :class:`~xtr_messenger.RedeliveryStamp` and the
62
+ reason it failed in an :class:`~xtr_messenger.ErrorDetailsStamp`. Once
63
+ its ``max_attempts`` are spent it is moved to the ``failure_queue`` with
64
+ a fresh count, so whoever consumes that queue gets to try it again; a
65
+ message failing for good in the failure queue itself is deleted.
56
66
 
57
67
  Workers polling one table run into each other's transactions; a conflict
58
68
  says nothing about the message, so a poll sits through
@@ -61,9 +71,15 @@ class OrmReceiver(ReceiverInterface):
61
71
  up to :data:`RECONNECT_TIMEOUT` seconds for it and tries once more: losing
62
72
  an acknowledgement to a database restart would have the message handed
63
73
  out, and handled, again.
74
+
75
+ A message is kept alive while it is held: from the moment it is handed
76
+ to the worker until it is settled, its claim is renewed every half of
77
+ ``redeliver_timeout``, so a handler running longer than that is not
78
+ taken for dead and its message handed to another worker under it. A
79
+ renewal the database refuses is logged and tried again at the next one.
64
80
  """
65
81
 
66
- __slots__ = ("_clock", "_conflicts", "_connection", "_name", "_serializer")
82
+ __slots__ = ("_clock", "_conflicts", "_connection", "_held", "_name", "_serializer")
67
83
 
68
84
  def __init__(
69
85
  self,
@@ -78,6 +94,7 @@ class OrmReceiver(ReceiverInterface):
78
94
  self._name = name
79
95
  self._clock: ClockInterface = clock if clock is not None else SystemClock()
80
96
  self._conflicts = 0
97
+ self._held: dict[str, asyncio.Task[None]] = {}
81
98
 
82
99
  @override
83
100
  async def get(self) -> AsyncIterator[Envelope]:
@@ -97,23 +114,28 @@ class OrmReceiver(ReceiverInterface):
97
114
  but a conflict, or for a conflict :data:`MAX_RETRIES` times in
98
115
  a row.
99
116
  """
100
- while True:
101
- stored = await self._claim()
102
- if stored is None:
103
- await self._connection.wait()
104
- continue
105
- try:
106
- envelope = self.decode(stored)
107
- except MessageDecodingFailedError as error:
108
- _LOGGER.warning(
109
- "rejecting message %s of the %r transport: it does not decode (%s)",
110
- stored.id,
111
- self._name,
112
- error.reason,
113
- )
114
- await self._settle(stored.id, self._connection.reject, "reject")
115
- continue
116
- yield envelope.with_stamps(ReceivedStamp(self._name))
117
+ try:
118
+ while True:
119
+ stored = await self._claim()
120
+ if stored is None:
121
+ await self._connection.wait()
122
+ continue
123
+ try:
124
+ envelope = self.decode(stored)
125
+ except MessageDecodingFailedError as error:
126
+ _LOGGER.warning(
127
+ "rejecting message %s of the %r transport: it does not decode (%s)",
128
+ stored.id,
129
+ self._name,
130
+ error.reason,
131
+ )
132
+ await self._settle(stored.id, self._connection.reject, "reject")
133
+ continue
134
+ self._hold(stored.id)
135
+ yield envelope.with_stamps(ReceivedStamp(self._name))
136
+ finally:
137
+ for message_id in list(self._held):
138
+ await self._release(message_id)
117
139
 
118
140
  @override
119
141
  async def ack(self, envelope: Envelope) -> None:
@@ -123,17 +145,48 @@ class OrmReceiver(ReceiverInterface):
123
145
  TransportError: When ``envelope`` was not received from this
124
146
  transport, or the database refuses the delete.
125
147
  """
126
- await self._settle(self._message_id(envelope), self._connection.ack, "acknowledge")
148
+ message_id = self._message_id(envelope)
149
+ await self._release(message_id)
150
+ await self._settle(message_id, self._connection.ack, "acknowledge")
127
151
 
128
152
  @override
129
153
  async def reject(self, envelope: Envelope) -> None:
130
- """Delete the message ``envelope`` was received as: it failed for good.
154
+ """Retry the message ``envelope`` was received as, or move it to the failure queue.
131
155
 
132
156
  Raises:
133
157
  TransportError: When ``envelope`` was not received from this
134
- transport, or the database refuses the delete.
158
+ transport, or the database refuses the update.
135
159
  """
136
- await self._settle(self._message_id(envelope), self._connection.reject, "reject")
160
+ message_id = self._message_id(envelope)
161
+ await self._release(message_id)
162
+ options = self._connection.options
163
+ attempt = _attempts_had(envelope)
164
+ failure = envelope.last(ErrorDetailsStamp)
165
+ next_try = envelope.without_stamps(RedeliveryStamp).without_stamps(ErrorDetailsStamp)
166
+ if failure is not None:
167
+ next_try = next_try.with_stamps(failure)
168
+ if self.will_retry(envelope):
169
+ queue = options.queue
170
+ delay_ms = int(options.base_delay_seconds * (1 << (attempt - 1)) * 1000)
171
+ next_try = next_try.with_stamps(RedeliveryStamp(attempt))
172
+ elif options.queue != options.failure_queue:
173
+ queue = options.failure_queue
174
+ delay_ms = 0
175
+ else:
176
+ await self._settle(message_id, self._connection.reject, "reject")
177
+ return
178
+ encoded = self._serializer.encode(next_try)
179
+
180
+ async def requeue(row: str) -> None:
181
+ await self._connection.requeue(
182
+ row, queue=queue, body=encoded.body, headers=encoded.headers, delay_ms=delay_ms
183
+ )
184
+
185
+ await self._settle(message_id, requeue, "reject")
186
+
187
+ def will_retry(self, envelope: Envelope) -> bool:
188
+ """Tell whether rejecting ``envelope`` puts it back in its queue for another attempt."""
189
+ return _attempts_had(envelope) < self._connection.options.max_attempts
137
190
 
138
191
  def decode(self, stored: StoredMessage) -> Envelope:
139
192
  """Rebuild the envelope ``stored`` keeps, stamped with the row it came from.
@@ -167,6 +220,38 @@ class OrmReceiver(ReceiverInterface):
167
220
  self._conflicts = 0
168
221
  return stored
169
222
 
223
+ def _hold(self, message_id: str) -> None:
224
+ """Keep the claim on ``message_id`` alive until it is released."""
225
+ # The current context is right: it is the receiver's own, where the worker collects
226
+ # messages, never a unit of work; the renewals are cancelled when the claim is released.
227
+ # ast-grep-ignore: task-without-context
228
+ self._held[message_id] = asyncio.get_running_loop().create_task(
229
+ self._keep_alive(message_id)
230
+ )
231
+
232
+ async def _release(self, message_id: str) -> None:
233
+ """Stop keeping ``message_id`` alive, and wait until its renewals stopped."""
234
+ task = self._held.pop(message_id, None)
235
+ if task is None:
236
+ return
237
+ _ = task.cancel()
238
+ _ = await asyncio.gather(task, return_exceptions=True)
239
+
240
+ async def _keep_alive(self, message_id: str) -> None:
241
+ """Renew the claim on ``message_id`` every half of ``redeliver_timeout``."""
242
+ every = self._connection.options.redeliver_timeout / 2
243
+ while True:
244
+ await _pause(every)
245
+ try:
246
+ await self._connection.keepalive(message_id)
247
+ except DBAPIError as error:
248
+ _LOGGER.warning(
249
+ "could not keep message %s of the %r transport alive (%s); trying again",
250
+ message_id,
251
+ self._name,
252
+ type(error.orig).__name__,
253
+ )
254
+
170
255
  async def _settle(
171
256
  self, message_id: str, operation: Callable[[str], Awaitable[None]], action: str
172
257
  ) -> None:
@@ -212,3 +297,19 @@ class OrmReceiver(ReceiverInterface):
212
297
  def _jitter() -> float:
213
298
  """Return a factor within 10% of one, so workers that collided do not collide again."""
214
299
  return 1 + (secrets.randbelow(21) - 10) / 100
300
+
301
+
302
+ def _attempts_had(envelope: Envelope) -> int:
303
+ """Return how many attempts ``envelope`` has had, the one just made included."""
304
+ redelivery = envelope.last(RedeliveryStamp)
305
+ return 1 + (redelivery.retry_count if redelivery is not None else 0)
306
+
307
+
308
+ async def _pause(seconds: float) -> None:
309
+ """Wait ``seconds`` of the event loop's own time between two renewals of a claim.
310
+
311
+ Paced by the loop, not by the receiver's clock: a renewal runs beside
312
+ whatever handles the message, and a clock that only moves when told —
313
+ a test's — would be moved for every reader by a background wait.
314
+ """
315
+ await asyncio.sleep(seconds)
@@ -2,10 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, final
5
+ from typing import TYPE_CHECKING, final, override
6
6
 
7
7
  from sqlalchemy.exc import DBAPIError
8
- from typing_extensions import override
9
8
  from xtr_messenger import DelayStamp, SenderInterface, TransportMessageIdStamp
10
9
 
11
10
  from xtr_orm_messenger.exception import TransportError
@@ -2,10 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, final
5
+ from typing import TYPE_CHECKING, final, override
6
6
 
7
7
  from sqlalchemy.exc import DBAPIError
8
- from typing_extensions import override
9
8
  from xtr_messenger import TransportInterface
10
9
 
11
10
  from xtr_orm_messenger.exception import TransportError
@@ -82,9 +81,13 @@ class OrmTransport(TransportInterface):
82
81
 
83
82
  @override
84
83
  async def reject(self, envelope: Envelope) -> None:
85
- """Delete the message ``envelope`` was received as: it failed for good."""
84
+ """Retry the message ``envelope`` was received as, or move it to the failure queue."""
86
85
  await self._receiver.reject(envelope)
87
86
 
87
+ def will_retry(self, envelope: Envelope) -> bool:
88
+ """Tell whether rejecting ``envelope`` puts it back in its queue for another attempt."""
89
+ return self._receiver.will_retry(envelope)
90
+
88
91
  async def keepalive(self, envelope: Envelope, seconds: int | None = None) -> None:
89
92
  """Keep the message ``envelope`` was received as from being handed out again.
90
93
 
@@ -9,10 +9,9 @@ them.
9
9
 
10
10
  from __future__ import annotations
11
11
 
12
- from typing import TYPE_CHECKING, final
12
+ from typing import TYPE_CHECKING, final, override
13
13
  from urllib.parse import urlsplit
14
14
 
15
- from typing_extensions import override
16
15
  from xtr_messenger import PublisherClosingInterface, TransportFactoryInterface
17
16
 
18
17
  from xtr_orm_messenger.exception import InvalidOrmDsnError
@@ -34,12 +34,21 @@ class _Listening(Protocol):
34
34
  self, channel: str, callback: Callable[[object, int, str, str], None]
35
35
  ) -> Awaitable[None]: ...
36
36
 
37
+ def add_termination_listener(self, callback: Callable[[object], None]) -> None: ...
38
+
39
+ def remove_termination_listener(self, callback: Callable[[object], None]) -> None: ...
40
+
37
41
 
38
42
  @final
39
43
  class PostgreSqlNotifier:
40
- """Listens on a table's channel and wakes a waiting worker when its queue is named."""
44
+ """Listens on a table's channel and wakes a waiting worker when its queue is named.
45
+
46
+ A listening connection the database drops hears nothing more: the
47
+ notifier is then :attr:`lost`, and the wait under way returns at once so
48
+ whoever waits can listen again.
49
+ """
41
50
 
42
- __slots__ = ("_channel", "_connection", "_driver", "_engine", "_queue", "_woken")
51
+ __slots__ = ("_channel", "_connection", "_driver", "_engine", "_lost", "_queue", "_woken")
43
52
 
44
53
  def __init__(self, engine: AsyncEngine, channel: str, queue: str) -> None:
45
54
  """Listen on ``channel`` through ``engine``, waking for ``queue``'s messages only.
@@ -52,6 +61,12 @@ class PostgreSqlNotifier:
52
61
  self._woken = asyncio.Event()
53
62
  self._connection: AsyncConnection | None = None
54
63
  self._driver: _Listening | None = None
64
+ self._lost = False
65
+
66
+ @property
67
+ def lost(self) -> bool:
68
+ """Whether the listening connection was dropped, so nothing more is heard on it."""
69
+ return self._lost
55
70
 
56
71
  async def listen(self) -> None:
57
72
  """Take a connection of the engine's and start listening on it.
@@ -67,6 +82,7 @@ class PostgreSqlNotifier:
67
82
  raw = await connection.get_raw_connection()
68
83
  driver = cast("_Listening", raw.driver_connection)
69
84
  await driver.add_listener(self._channel, self._heard)
85
+ driver.add_termination_listener(self._dropped)
70
86
  except BaseException:
71
87
  await connection.close()
72
88
  raise
@@ -87,14 +103,23 @@ class PostgreSqlNotifier:
87
103
  self._woken.clear()
88
104
 
89
105
  async def close(self) -> None:
90
- """Stop listening and give the connection back."""
106
+ """Stop listening and give the connection back.
107
+
108
+ A connection the database dropped is discarded rather than given back,
109
+ so the pool never hands the dead connection to the next statement.
110
+ """
91
111
  driver, connection = self._driver, self._connection
92
112
  self._driver = None
93
113
  self._connection = None
94
114
  if driver is None or connection is None:
95
115
  return
116
+ if self._lost:
117
+ await connection.invalidate()
118
+ await connection.close()
119
+ return
96
120
  try:
97
121
  await driver.remove_listener(self._channel, self._heard)
122
+ driver.remove_termination_listener(self._dropped)
98
123
  finally:
99
124
  await connection.close()
100
125
 
@@ -103,3 +128,9 @@ class PostgreSqlNotifier:
103
128
  del connection, pid, channel
104
129
  if payload == self._queue:
105
130
  self._woken.set()
131
+
132
+ def _dropped(self, connection: object) -> None:
133
+ """Mark the notifier lost and end the wait under way: nothing more will wake it."""
134
+ del connection
135
+ self._lost = True
136
+ self._woken.set()