snodra-messaging-sql 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,9 @@
1
+ snodra_sql/__init__.py,sha256=oOZne3QvKRVqH1jdye-a2dXzAjyGgqJ2o-Git54YZoo,1174
2
+ snodra_sql/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ snodra_sql/sql.py,sha256=zLAgBzScUke832TrE7O6EU4uC0P-uJ_1h0rjKx8fmEw,69698
4
+ snodra_sql/schema/mysql/V1__snodra.sql,sha256=7Hclnal38HuoOr6LqRBNz3qeKSdgyHrnEmOdeGZxVX0,10722
5
+ snodra_sql/schema/postgresql/V1__snodra.sql,sha256=iCv_lo-PLhPgIRePV3LRJOY1Lj77PsEE9-jl_tJUoBI,11324
6
+ snodra_messaging_sql-0.5.0.dist-info/METADATA,sha256=80JBglazLiLmaxRBNGXETH_g-4ewVzXWzP-tS7VkB24,5946
7
+ snodra_messaging_sql-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ snodra_messaging_sql-0.5.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ snodra_messaging_sql-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.
snodra_sql/__init__.py ADDED
@@ -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
+ ]
snodra_sql/py.typed ADDED
File without changes
@@ -0,0 +1,212 @@
1
+ -- snodra-messaging message store, schema version 1 (MySQL 8.0.17 or later, InnoDB, a STRICT sql_mode).
2
+ -- Shared by the Kotlin add-on (snodra-messaging-jdbc) and the Rust one (snodra-messaging-sqlx): both read and write these
3
+ -- tables the same way. Idempotent: it can run again over itself. Frozen once released: later changes are V2, V3, ...
4
+ -- Times are UTC instants at millisecond precision in DATETIME(3), stamped by the application (never NOW()).
5
+ -- utf8mb4_0900_bin (NO PAD): identifiers and positions are compared and ordered by their bytes, case, accents and trailing
6
+ -- spaces included.
7
+ -- *_hash columns hold the lowercase hex SHA-256 of a value's UTF-8 bytes: they carry the uniqueness and the lookups of values
8
+ -- with no length bound (marker ids, idempotency keys, start keys, record keys, associations); the value itself is in a
9
+ -- MEDIUMTEXT column next to it. Bounded columns are checked by the libraries before any write (see the module README).
10
+ -- Free text (errors) is cut by the libraries to 16 KiB of UTF-8, which TEXT holds.
11
+
12
+ CREATE TABLE IF NOT EXISTS snodra_schema (
13
+ version INT NOT NULL PRIMARY KEY,
14
+ applied_at DATETIME(3) NOT NULL DEFAULT (UTC_TIMESTAMP(3))
15
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
16
+
17
+ -- The outbox: events appended in the service's transaction, relayed to the event store afterwards.
18
+ CREATE TABLE IF NOT EXISTS snodra_outbox (
19
+ id VARCHAR(255) NOT NULL PRIMARY KEY,
20
+ type VARCHAR(255) NOT NULL,
21
+ event_key MEDIUMTEXT NULL,
22
+ headers JSON NOT NULL,
23
+ payload JSON NOT NULL,
24
+ created_at DATETIME(3) NOT NULL,
25
+ seq BIGINT NOT NULL,
26
+ attempts INT NOT NULL DEFAULT 0,
27
+ sent_at DATETIME(3) NULL,
28
+ failed_at DATETIME(3) NULL,
29
+ last_error TEXT NULL,
30
+ owner MEDIUMTEXT NULL,
31
+ lease_until DATETIME(3) NULL,
32
+ INDEX snodra_outbox_pending (sent_at, failed_at, created_at, seq)
33
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
34
+
35
+ -- Processed-event markers: one per id (processor:<name>:<eventId>, saga:<type>:<eventId>, ingress:<source>:<key>, ...).
36
+ -- A stage-1 marker also carries its processor, source, segment and position (position_num: the position as a number when
37
+ -- it is a canonical decimal one, so a reset deletes a range by value).
38
+ CREATE TABLE IF NOT EXISTS snodra_processed_events (
39
+ id_hash CHAR(64) NOT NULL PRIMARY KEY,
40
+ id MEDIUMTEXT NOT NULL,
41
+ type MEDIUMTEXT NOT NULL,
42
+ processed_at DATETIME(3) NOT NULL,
43
+ processor VARCHAR(64) NULL,
44
+ source VARCHAR(255) NULL,
45
+ segment VARCHAR(128) NULL,
46
+ position VARCHAR(128) NULL,
47
+ position_num BIGINT NULL,
48
+ INDEX snodra_processed_events_range (processor, source, segment, position_num),
49
+ INDEX snodra_processed_events_processed_at (processed_at)
50
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
51
+
52
+ -- Dead letters, sequenced per (processor, key). id = <processor>:<source>:<segment>:<position> (at most 578).
53
+ CREATE TABLE IF NOT EXISTS snodra_dead_letters (
54
+ id VARCHAR(578) NOT NULL PRIMARY KEY,
55
+ processor VARCHAR(64) NOT NULL,
56
+ source VARCHAR(255) NOT NULL,
57
+ segment VARCHAR(128) NOT NULL,
58
+ position VARCHAR(128) NOT NULL,
59
+ position_num BIGINT NULL,
60
+ event_key MEDIUMTEXT NULL,
61
+ event_key_hash CHAR(64) NULL,
62
+ event_id MEDIUMTEXT NULL,
63
+ event_type MEDIUMTEXT NULL,
64
+ headers JSON NOT NULL,
65
+ payload MEDIUMTEXT NULL,
66
+ payload_binary LONGBLOB NULL,
67
+ reason VARCHAR(32) NOT NULL,
68
+ error_type TEXT NOT NULL,
69
+ error_message TEXT NOT NULL,
70
+ blocked_by MEDIUMTEXT NULL,
71
+ attempts INT NOT NULL,
72
+ parked_at DATETIME(3) NOT NULL,
73
+ last_attempt_at DATETIME(3) NOT NULL,
74
+ expire_at DATETIME(3) NOT NULL,
75
+ replay BOOLEAN NOT NULL DEFAULT FALSE,
76
+ INDEX snodra_dead_letters_key (processor, event_key_hash, position_num),
77
+ INDEX snodra_dead_letters_parked (processor, parked_at),
78
+ INDEX snodra_dead_letters_expire (expire_at)
79
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
80
+
81
+ -- One row per event processor: its pause, the reset operation holding its lock, its open replay ranges
82
+ -- (a JSON array of {"source","segment","from","until"} strings, in order).
83
+ CREATE TABLE IF NOT EXISTS snodra_processor_control (
84
+ processor VARCHAR(64) NOT NULL PRIMARY KEY,
85
+ paused BOOLEAN NOT NULL DEFAULT FALSE,
86
+ paused_at DATETIME(3) NULL,
87
+ paused_by MEDIUMTEXT NULL,
88
+ op_id MEDIUMTEXT NULL,
89
+ op_kind MEDIUMTEXT NULL,
90
+ op_lease_until DATETIME(3) NULL,
91
+ op_prepared_at DATETIME(3) NULL,
92
+ replay JSON NOT NULL,
93
+ updated_at DATETIME(3) NULL
94
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
95
+
96
+ -- Idempotent external calls and ingress (@IdempotentHandler): one record per idempotency key (id). reply and error are JSON
97
+ -- text, kept as written.
98
+ CREATE TABLE IF NOT EXISTS snodra_external_calls (
99
+ id_hash CHAR(64) NOT NULL PRIMARY KEY,
100
+ id MEDIUMTEXT NOT NULL,
101
+ status VARCHAR(32) NOT NULL,
102
+ reply MEDIUMTEXT NULL,
103
+ error MEDIUMTEXT NULL,
104
+ attempts INT NOT NULL,
105
+ updated_at DATETIME(3) NOT NULL,
106
+ lease_until DATETIME(3) NULL,
107
+ owner MEDIUMTEXT NULL,
108
+ INDEX snodra_external_calls_updated (updated_at)
109
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
110
+
111
+ -- Saga instances. state is the saga as JSON text, kept as written. live_start_key_hash is the start key's hash
112
+ -- while the saga is live: its unique index lets one live saga hold a start key.
113
+ CREATE TABLE IF NOT EXISTS snodra_sagas (
114
+ id VARCHAR(255) NOT NULL PRIMARY KEY,
115
+ type VARCHAR(255) NOT NULL,
116
+ state MEDIUMTEXT NOT NULL,
117
+ start_key MEDIUMTEXT NULL,
118
+ start_key_hash CHAR(64) NULL,
119
+ ended BOOLEAN NOT NULL,
120
+ ended_at DATETIME(3) NULL,
121
+ version BIGINT NOT NULL,
122
+ created_at DATETIME(3) NOT NULL,
123
+ updated_at DATETIME(3) NOT NULL,
124
+ live_start_key_hash CHAR(64) GENERATED ALWAYS AS (CASE WHEN ended THEN NULL ELSE start_key_hash END) STORED,
125
+ UNIQUE INDEX snodra_sagas_live_start_key (live_start_key_hash),
126
+ INDEX snodra_sagas_type_ended (type, ended),
127
+ INDEX snodra_sagas_ended_at (ended_at)
128
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
129
+
130
+ -- A saga's associations key = value, in order (idx from 0): what routes events to it. assoc_hash = SHA-256 of
131
+ -- key, a zero byte, value.
132
+ CREATE TABLE IF NOT EXISTS snodra_saga_associations (
133
+ saga_id VARCHAR(255) NOT NULL,
134
+ idx INT NOT NULL,
135
+ assoc_key MEDIUMTEXT NOT NULL,
136
+ assoc_value MEDIUMTEXT NOT NULL,
137
+ assoc_hash CHAR(64) NOT NULL,
138
+ PRIMARY KEY (saga_id, idx),
139
+ INDEX snodra_saga_associations_hash (assoc_hash),
140
+ CONSTRAINT snodra_saga_associations_saga FOREIGN KEY (saga_id) REFERENCES snodra_sagas (id) ON DELETE CASCADE
141
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
142
+
143
+ -- The saga-side outbox: commands and events a saga recorded, sent in seq order per saga.
144
+ CREATE TABLE IF NOT EXISTS snodra_saga_dispatch (
145
+ id VARCHAR(255) NOT NULL PRIMARY KEY,
146
+ saga_id VARCHAR(255) NOT NULL,
147
+ seq BIGINT NOT NULL,
148
+ kind VARCHAR(16) NOT NULL,
149
+ type VARCHAR(255) NOT NULL,
150
+ payload MEDIUMTEXT NOT NULL,
151
+ headers JSON NOT NULL,
152
+ routing_key MEDIUMTEXT NULL,
153
+ created_at DATETIME(3) NOT NULL,
154
+ dispatched_at DATETIME(3) NULL,
155
+ attempts INT NOT NULL,
156
+ next_attempt_at DATETIME(3) NULL,
157
+ failed_at DATETIME(3) NULL,
158
+ failure_reason VARCHAR(32) NULL,
159
+ failure_message TEXT NULL,
160
+ notice_pending BOOLEAN NULL,
161
+ notice_attempts INT NULL,
162
+ notice_next_at DATETIME(3) NULL,
163
+ INDEX snodra_saga_dispatch_saga_seq (saga_id, seq),
164
+ INDEX snodra_saga_dispatch_pending (dispatched_at, failed_at, saga_id, seq),
165
+ INDEX snodra_saga_dispatch_notice (notice_pending, notice_next_at),
166
+ INDEX snodra_saga_dispatch_failed (failed_at)
167
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
168
+
169
+ -- One dispatch relay instance per saga at a time.
170
+ CREATE TABLE IF NOT EXISTS snodra_saga_dispatch_leases (
171
+ saga_id VARCHAR(255) NOT NULL PRIMARY KEY,
172
+ owner MEDIUMTEXT NOT NULL,
173
+ lease_until DATETIME(3) NOT NULL
174
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
175
+
176
+ -- Saga deadlines. payload is JSON text (any JSON value), kept as written.
177
+ CREATE TABLE IF NOT EXISTS snodra_deadlines (
178
+ id VARCHAR(255) NOT NULL PRIMARY KEY,
179
+ saga_type VARCHAR(255) NOT NULL,
180
+ saga_id VARCHAR(255) NOT NULL,
181
+ name VARCHAR(255) NOT NULL,
182
+ payload MEDIUMTEXT NULL,
183
+ payload_type MEDIUMTEXT NULL,
184
+ due_at DATETIME(3) NOT NULL,
185
+ correlation_id MEDIUMTEXT NOT NULL,
186
+ status VARCHAR(16) NOT NULL,
187
+ claimed_by MEDIUMTEXT NULL,
188
+ claimed_until DATETIME(3) NULL,
189
+ finished_at DATETIME(3) NULL,
190
+ INDEX snodra_deadlines_due (status, due_at),
191
+ INDEX snodra_deadlines_saga (saga_id, status),
192
+ INDEX snodra_deadlines_finished (finished_at)
193
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
194
+
195
+ -- Saga events parked after their last attempt. id = <sagaType>:<eventId>.
196
+ CREATE TABLE IF NOT EXISTS snodra_saga_failures (
197
+ id_hash CHAR(64) NOT NULL PRIMARY KEY,
198
+ id MEDIUMTEXT NOT NULL,
199
+ saga_type VARCHAR(255) NOT NULL,
200
+ event_id MEDIUMTEXT NOT NULL,
201
+ event_type MEDIUMTEXT NOT NULL,
202
+ payload MEDIUMTEXT NOT NULL,
203
+ headers JSON NOT NULL,
204
+ error TEXT NOT NULL,
205
+ attempts INT NOT NULL,
206
+ first_failed_at DATETIME(3) NOT NULL,
207
+ last_failed_at DATETIME(3) NOT NULL,
208
+ INDEX snodra_saga_failures_type (saga_type, last_failed_at),
209
+ INDEX snodra_saga_failures_last (last_failed_at)
210
+ ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_bin;
211
+
212
+ INSERT INTO snodra_schema (version) VALUES (1) ON DUPLICATE KEY UPDATE version = version;