snodra-messaging-sql 0.5.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.
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ dist/
3
+ bin/
4
+ __pycache__/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ .pytest_cache/
@@ -0,0 +1,66 @@
1
+ # Driver spike: asyncpg and asyncmy
2
+
3
+ Recorded 2026-11-26 against `asyncpg==0.32.0`, `asyncmy==0.2.18`, PostgreSQL 17.7 and MySQL 8.4.7,
4
+ the images the tests pin. The spike drove both drivers through the operations the add-on needs; the
5
+ tests `tests/test_sql.py` and `tests/test_kit.py` pin the behaviour that matters.
6
+
7
+ ## asyncpg 0.32
8
+
9
+ - **Placeholders** are numbered (`$1`, `$2`, ...). The add-on writes its SQL with `?` and
10
+ `Store._bind` numbers it, exactly as the Go add-on does for `pgx`.
11
+ - **A JSON column** takes a Python text through a cast: `CAST($1 AS jsonb)`. Reading it back as
12
+ `CAST(headers AS TEXT)` returns `str`, so the add-on parses the header object itself.
13
+ - **`Connection.execute`** returns the command status (`"INSERT 0 1"`, `"UPDATE 2"`, `"SELECT 1"`),
14
+ not a row count; the add-on reads the last number. `fetch`/`fetchrow`/`fetchval` return records
15
+ that convert to dictionaries.
16
+ - **Transactions** are explicit: `transaction = conn.transaction(isolation="read_committed")`, then
17
+ `await transaction.start()`, `commit()` or `rollback()`. The default isolation is already READ
18
+ COMMITTED; the add-on sets it explicitly so the contract is visible in the code.
19
+ - **`add_listener` is a coroutine** (`await conn.add_listener(channel, callback)`). A notification is
20
+ delivered only when the appending transaction commits; a rollback delivers nothing. The listener
21
+ needs its own connection (the store opens one, never one from its pool) and `remove_listener`
22
+ takes the same callback object.
23
+ - **Times** go in and come out as timezone-aware `datetime` values at the column's milliseconds.
24
+ - **`FOR UPDATE SKIP LOCKED`** is accepted after `LIMIT ?`; the add-on's claim order is
25
+ `ORDER BY created_at, seq, id LIMIT ? FOR UPDATE SKIP LOCKED`.
26
+ - **Pool release** (`pool.release(conn)`) is awaitable.
27
+
28
+ ## asyncmy 0.2.18
29
+
30
+ - **Placeholders** are `%s` (the driver's format style), not `?`. The add-on's `?` SQL is turned
31
+ into `%s`; no statement has a literal question mark.
32
+ - **A JSON column** takes text through `CAST(%s AS JSON)`. Reading it back with `CAST(... AS CHAR)`
33
+ returns the JSON text with the server's own whitespace (`{"x": 1}`); the add-on compares parsed
34
+ values, never the text.
35
+ - **Cursors**: `conn.cursor()` returns tuples; `conn.cursor(asyncmy.cursors.DictCursor)` returns
36
+ dictionaries, which the add-on uses for every read.
37
+ - **Isolation**: the default is REPEATABLE READ. The pool is created with
38
+ `init_command="SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"`, and every store-owned
39
+ transaction also sends `SET TRANSACTION ISOLATION LEVEL READ COMMITTED` before `START TRANSACTION`.
40
+ Both variants were proved by a visibility read (a row committed after the transaction began was
41
+ seen by its next read). `SELECT @@transaction_isolation` keeps showing the session default and is
42
+ **not** a proof that the next transaction is READ COMMITTED: `SET TRANSACTION` applies to the next
43
+ transaction without changing the variable.
44
+ - **`SELECT ... FOR UPDATE SKIP LOCKED`** is accepted, with `LIMIT` before the locking clause:
45
+ `... ORDER BY created_at, seq, id LIMIT %s FOR UPDATE SKIP LOCKED`. The add-on pins the skip in
46
+ `test_a_claim_skips_a_row_another_transaction_holds` on both engines.
47
+ - **A duplicate key** (1062) raises `asyncmy.errors.IntegrityError` and leaves the transaction usable,
48
+ so `Processed.record` catches it and returns `False`; PostgreSQL uses `ON CONFLICT (id_hash) DO
49
+ NOTHING` instead because a duplicate would abort the caller's transaction.
50
+ - **`GET_LOCK(name, seconds)`** returns 1 when the named lock was taken and 0 on timeout;
51
+ `RELEASE_LOCK(name)` returns 1. These are the schema lock on MySQL.
52
+ - **DATETIME** columns return naive `datetime` values; the layout stores UTC, so the add-on attaches
53
+ UTC on read and binds naive UTC on write. `TIMESTAMPTZ` is not available.
54
+ - **Pool release** (`pool.release(conn)`) returns a `Future`, so the add-on awaits it when it is
55
+ awaitable; `pool.close()` then `await pool.wait_closed()` closes the pool.
56
+ - **Startup**: the official image logs `ready for connections` once during initialization, before the
57
+ server accepts application connections. The tests therefore poll a query after the container's
58
+ port is up instead of trusting the first log line.
59
+
60
+ ## Choices
61
+
62
+ - `asyncpg` and `asyncmy` are both asyncio-native, so a store call never blocks the event loop. No
63
+ blocking driver (psycopg, PyMySQL) is imported by the add-on or the core.
64
+ - The core imports no SQL client; the drivers live only in `snodra-messaging-sql`.
65
+ - `asyncmy` is the maintained asyncio fork of aiomysql with the same wire behaviour; aiomysql was not
66
+ selected because it is not maintained for current Python versions.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: snodra-messaging-sql
3
+ Version: 0.5.0
4
+ Summary: The PostgreSQL and MySQL message store for the Snodra messaging suite.
5
+ Project-URL: Homepage, https://snodra.damoreira.com/
6
+ Project-URL: Repository, https://github.com/snodra/snodra-messaging-python
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: asyncmy==0.2.18
11
+ Requires-Dist: asyncpg==0.32.0
12
+ Requires-Dist: snodra-messaging==0.5.0
13
+ Description-Content-Type: text/markdown
14
+
15
+ # snodra-messaging-sql
16
+
17
+ The PostgreSQL and MySQL message store for the Snodra messaging suite: the outbox, the processed-event
18
+ markers and the rest of the message-store ports in the service's own database, on the shared SQL layout
19
+ version 1 that every Snodra library reads and writes.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ pip install snodra-messaging-sql
25
+ ```
26
+
27
+ The distribution needs Python 3.12 or later and depends on `snodra-messaging`, `asyncpg` (PostgreSQL) and
28
+ `asyncmy` (MySQL). The core library never imports a SQL client; this add-on is where they live.
29
+
30
+ ## Use
31
+
32
+ ```python
33
+ import asyncio
34
+
35
+ import snodra
36
+ from snodra_sql import SqlConfig, SqlStore
37
+
38
+
39
+ async def main() -> None:
40
+ store = SqlStore(SqlConfig.from_env())
41
+ try:
42
+ settings = snodra.Settings.from_env(service="orders-service")
43
+ # The event store reads what the relay publishes; the message store holds the outbox and markers.
44
+ app = snodra.App(settings, store=store, event_store=...)
45
+ await app.run()
46
+ finally:
47
+ await store.close()
48
+
49
+
50
+ asyncio.run(main())
51
+ ```
52
+
53
+ `SqlConfig.from_env()` reads `SNODRA_STORE_SQL_URL` (required), `SNODRA_STORE_SQL_DRIVER`,
54
+ `SNODRA_STORE_SQL_NOTIFY` and `SNODRA_STORE_SQL_PURGE_INTERVAL_MS`. The URL names the database:
55
+ `postgres://` or `postgresql://` for PostgreSQL, `mysql://` for MySQL. The driver is read from the scheme when
56
+ the variable is empty.
57
+
58
+ The store implements the level-2 ports: the outbox and the processed-event markers. The dead-letter,
59
+ processor-control, external-call and saga ports are part of the interface frozen at level 2 and report
60
+ `snodra.MessageStoreUnsupported` for now; the official add-ons implement every port by level 4.
61
+
62
+ ### The transaction is the service's
63
+
64
+ `async with store.transaction():` begins a transaction, binds it to the current context and commits on a clean
65
+ exit or rolls back on an exception. An outbox append and a processed marker recorded inside it join it. A
66
+ service that already runs a transaction on its own connection binds it with `store.transaction(conn=conn)`:
67
+ the store writes on that connection and never commits or rolls back the service's transaction.
68
+
69
+ ```python
70
+ async with pool.acquire() as conn:
71
+ async with conn.transaction():
72
+ async with store.transaction(conn=conn):
73
+ await store.outbox.append(entry)
74
+ await conn.execute("INSERT INTO orders (id) VALUES ($1)", order.id)
75
+ ```
76
+
77
+ The store's own transactions (claims, the purge) run at READ COMMITTED. An outbox claim takes
78
+ `SELECT ... FOR UPDATE SKIP LOCKED` in `(created_at, seq)` order, so two relays on one outbox never hold the
79
+ same entry.
80
+
81
+ ### The layout
82
+
83
+ The schema files are the published version 1 files, byte for byte, embedded in the package
84
+ (`src/snodra_sql/schema/{postgresql,mysql}/V1__snodra.sql`) and checked against their published SHA-256
85
+ values. `init_schema()` applies version 1 unless the database has it or later, under the database lock every
86
+ Snodra library uses, so instances starting together apply it once. `check_schema()` only checks it, for a
87
+ service that runs its own migrations. The add-on also reads `snodra_schema` and refuses a database below
88
+ version 1. Schema versions are additive: code that knows version 1 reads a database at version 1 or later.
89
+
90
+ PostgreSQL 13 or later; MySQL 8.0.17 or later on InnoDB with a strict `sql_mode` (MariaDB is not supported).
91
+ The store needs a connection pool of at least two connections: a write that commits on its own inside the
92
+ service's transaction takes a second one.
93
+
94
+ ### Lifecycle
95
+
96
+ `App.start()` drives the store's lifecycle when it is the app's store: it hands the store the application's
97
+ clock, calls `init_schema()` (or `check_schema()` when `Settings.store_init_schema` is false) and starts
98
+ `background()` in a `snodra:store-background` task until shutdown. A failing schema step fails `start()`, naming
99
+ the store; an error from `background()` is logged and the app keeps running.
100
+
101
+ - `use_clock(clock)` sets the application's clock (epoch milliseconds), which stamps every time the store
102
+ sets itself: an entry's sending, a claim's lease, a purge bound.
103
+ - `init_schema()` prepares the schema; `check_schema()` fails unless it is there. They are public for a store
104
+ constructed after `app.start()`, or used outside an `App`.
105
+ - `background()` runs the retention purge every `purge_interval` seconds until it is cancelled. A negative
106
+ interval turns it off and it waits for cancellation.
107
+ - `open()` opens the pool on demand; `close()` closes the pool and the PostgreSQL listener.
108
+
109
+ On PostgreSQL an append's transaction sends `pg_notify('snodra_outbox', '')` and `outbox.on_append(wake)`
110
+ listens on a connection of its own, so a relay claims as soon as an append commits; a rollback notifies
111
+ nobody. MySQL has no such notification and the relay polls.
112
+
113
+ Where the public specification leaves a choice, [SPEC-GAPS.md](../../SPEC-GAPS.md) records what this library
114
+ does. The driver behaviour the add-on relies on is recorded in [DRIVER-SPIKE.md](DRIVER-SPIKE.md).
115
+
116
+ ## Test
117
+
118
+ The tests start PostgreSQL and MySQL through Testcontainers (pinned by digest) and run the message-store
119
+ conformance kit against both. Docker is required:
120
+
121
+ ```sh
122
+ uv run pytest -q packages/snodra-messaging-sql/tests
123
+ ```
124
+
125
+ ## Links
126
+
127
+ - Documentation: <https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/>
128
+ - Repository: <https://github.com/snodra/snodra-messaging-python>
129
+ - PyPI: <https://pypi.org/project/snodra-messaging-sql/>
@@ -0,0 +1,115 @@
1
+ # snodra-messaging-sql
2
+
3
+ The PostgreSQL and MySQL message store for the Snodra messaging suite: the outbox, the processed-event
4
+ markers and the rest of the message-store ports in the service's own database, on the shared SQL layout
5
+ version 1 that every Snodra library reads and writes.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pip install snodra-messaging-sql
11
+ ```
12
+
13
+ The distribution needs Python 3.12 or later and depends on `snodra-messaging`, `asyncpg` (PostgreSQL) and
14
+ `asyncmy` (MySQL). The core library never imports a SQL client; this add-on is where they live.
15
+
16
+ ## Use
17
+
18
+ ```python
19
+ import asyncio
20
+
21
+ import snodra
22
+ from snodra_sql import SqlConfig, SqlStore
23
+
24
+
25
+ async def main() -> None:
26
+ store = SqlStore(SqlConfig.from_env())
27
+ try:
28
+ settings = snodra.Settings.from_env(service="orders-service")
29
+ # The event store reads what the relay publishes; the message store holds the outbox and markers.
30
+ app = snodra.App(settings, store=store, event_store=...)
31
+ await app.run()
32
+ finally:
33
+ await store.close()
34
+
35
+
36
+ asyncio.run(main())
37
+ ```
38
+
39
+ `SqlConfig.from_env()` reads `SNODRA_STORE_SQL_URL` (required), `SNODRA_STORE_SQL_DRIVER`,
40
+ `SNODRA_STORE_SQL_NOTIFY` and `SNODRA_STORE_SQL_PURGE_INTERVAL_MS`. The URL names the database:
41
+ `postgres://` or `postgresql://` for PostgreSQL, `mysql://` for MySQL. The driver is read from the scheme when
42
+ the variable is empty.
43
+
44
+ The store implements the level-2 ports: the outbox and the processed-event markers. The dead-letter,
45
+ processor-control, external-call and saga ports are part of the interface frozen at level 2 and report
46
+ `snodra.MessageStoreUnsupported` for now; the official add-ons implement every port by level 4.
47
+
48
+ ### The transaction is the service's
49
+
50
+ `async with store.transaction():` begins a transaction, binds it to the current context and commits on a clean
51
+ exit or rolls back on an exception. An outbox append and a processed marker recorded inside it join it. A
52
+ service that already runs a transaction on its own connection binds it with `store.transaction(conn=conn)`:
53
+ the store writes on that connection and never commits or rolls back the service's transaction.
54
+
55
+ ```python
56
+ async with pool.acquire() as conn:
57
+ async with conn.transaction():
58
+ async with store.transaction(conn=conn):
59
+ await store.outbox.append(entry)
60
+ await conn.execute("INSERT INTO orders (id) VALUES ($1)", order.id)
61
+ ```
62
+
63
+ The store's own transactions (claims, the purge) run at READ COMMITTED. An outbox claim takes
64
+ `SELECT ... FOR UPDATE SKIP LOCKED` in `(created_at, seq)` order, so two relays on one outbox never hold the
65
+ same entry.
66
+
67
+ ### The layout
68
+
69
+ The schema files are the published version 1 files, byte for byte, embedded in the package
70
+ (`src/snodra_sql/schema/{postgresql,mysql}/V1__snodra.sql`) and checked against their published SHA-256
71
+ values. `init_schema()` applies version 1 unless the database has it or later, under the database lock every
72
+ Snodra library uses, so instances starting together apply it once. `check_schema()` only checks it, for a
73
+ service that runs its own migrations. The add-on also reads `snodra_schema` and refuses a database below
74
+ version 1. Schema versions are additive: code that knows version 1 reads a database at version 1 or later.
75
+
76
+ PostgreSQL 13 or later; MySQL 8.0.17 or later on InnoDB with a strict `sql_mode` (MariaDB is not supported).
77
+ The store needs a connection pool of at least two connections: a write that commits on its own inside the
78
+ service's transaction takes a second one.
79
+
80
+ ### Lifecycle
81
+
82
+ `App.start()` drives the store's lifecycle when it is the app's store: it hands the store the application's
83
+ clock, calls `init_schema()` (or `check_schema()` when `Settings.store_init_schema` is false) and starts
84
+ `background()` in a `snodra:store-background` task until shutdown. A failing schema step fails `start()`, naming
85
+ the store; an error from `background()` is logged and the app keeps running.
86
+
87
+ - `use_clock(clock)` sets the application's clock (epoch milliseconds), which stamps every time the store
88
+ sets itself: an entry's sending, a claim's lease, a purge bound.
89
+ - `init_schema()` prepares the schema; `check_schema()` fails unless it is there. They are public for a store
90
+ constructed after `app.start()`, or used outside an `App`.
91
+ - `background()` runs the retention purge every `purge_interval` seconds until it is cancelled. A negative
92
+ interval turns it off and it waits for cancellation.
93
+ - `open()` opens the pool on demand; `close()` closes the pool and the PostgreSQL listener.
94
+
95
+ On PostgreSQL an append's transaction sends `pg_notify('snodra_outbox', '')` and `outbox.on_append(wake)`
96
+ listens on a connection of its own, so a relay claims as soon as an append commits; a rollback notifies
97
+ nobody. MySQL has no such notification and the relay polls.
98
+
99
+ Where the public specification leaves a choice, [SPEC-GAPS.md](../../SPEC-GAPS.md) records what this library
100
+ does. The driver behaviour the add-on relies on is recorded in [DRIVER-SPIKE.md](DRIVER-SPIKE.md).
101
+
102
+ ## Test
103
+
104
+ The tests start PostgreSQL and MySQL through Testcontainers (pinned by digest) and run the message-store
105
+ conformance kit against both. Docker is required:
106
+
107
+ ```sh
108
+ uv run pytest -q packages/snodra-messaging-sql/tests
109
+ ```
110
+
111
+ ## Links
112
+
113
+ - Documentation: <https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/>
114
+ - Repository: <https://github.com/snodra/snodra-messaging-python>
115
+ - PyPI: <https://pypi.org/project/snodra-messaging-sql/>
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.33,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "snodra-messaging-sql"
7
+ version = "0.5.0"
8
+ description = "The PostgreSQL and MySQL message store for the Snodra messaging suite."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ dependencies = [
14
+ "snodra-messaging==0.5.0",
15
+ "asyncpg==0.32.0",
16
+ "asyncmy==0.2.18",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://snodra.damoreira.com/"
21
+ Repository = "https://github.com/snodra/snodra-messaging-python"
22
+
23
+ [tool.uv.sources]
24
+ snodra-messaging = { workspace = true }
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/snodra_sql"]
@@ -0,0 +1,37 @@
1
+ """The SQL message-store add-on: the core's message-store ports on PostgreSQL and MySQL.
2
+
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 and the processed-event markers in the service's own
5
+ database, on the shared SQL layout version 1 that every Snodra library reads and writes; the
6
+ dead-letter, processor-control, external-call and saga ports belong to the interface frozen at level 2
7
+ and report ``snodra.MessageStoreUnsupported`` until this add-on implements them.
8
+
9
+ See :mod:`snodra_sql.sql` for the layout and the guarantees, ``DRIVER-SPIKE.md`` for the driver
10
+ behaviour the add-on relies on, and ``SPEC-GAPS.md`` for the choices the public specification leaves
11
+ open.
12
+ """
13
+
14
+ from snodra import StoreLifecycle
15
+
16
+ from snodra_sql.sql import (
17
+ DRIVER_MYSQL,
18
+ DRIVER_POSTGRES,
19
+ NAME_MYSQL,
20
+ NAME_POSTGRES,
21
+ SCHEMA_VERSION,
22
+ SqlConfig,
23
+ SqlStore,
24
+ split_sql,
25
+ )
26
+
27
+ __all__ = [
28
+ "DRIVER_MYSQL",
29
+ "DRIVER_POSTGRES",
30
+ "NAME_MYSQL",
31
+ "NAME_POSTGRES",
32
+ "SCHEMA_VERSION",
33
+ "SqlConfig",
34
+ "SqlStore",
35
+ "StoreLifecycle",
36
+ "split_sql",
37
+ ]
File without changes