qaechi-outbox 1.0.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.
- qaechi/outbox/__init__.py +47 -0
- qaechi/outbox/_outbox.py +266 -0
- qaechi/outbox/py.typed +0 -0
- qaechi/outbox/sql/mysql.sql +13 -0
- qaechi/outbox/sql/postgresql.sql +13 -0
- qaechi_outbox-1.0.0.dist-info/METADATA +135 -0
- qaechi_outbox-1.0.0.dist-info/RECORD +10 -0
- qaechi_outbox-1.0.0.dist-info/WHEEL +5 -0
- qaechi_outbox-1.0.0.dist-info/licenses/LICENSE +202 -0
- qaechi_outbox-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""qaechi-outbox: request qaechi parse jobs in your own database transaction.
|
|
2
|
+
|
|
3
|
+
from qaechi.contracts import JobRequest
|
|
4
|
+
from qaechi.outbox import add_parse_request
|
|
5
|
+
|
|
6
|
+
with psycopg.connect(dsn) as conn: # one transaction
|
|
7
|
+
conn.execute("INSERT INTO invoices ...")
|
|
8
|
+
job_id = add_parse_request(conn, JobRequest(
|
|
9
|
+
document_id="inv-2026-0042", source="s3://bucket/0042.pdf", doc_type="invoice"))
|
|
10
|
+
# committed together; a Debezium relay sends the job to Kafka
|
|
11
|
+
|
|
12
|
+
The table and job IDs are the same as those of the Java outbox, so one relay serves both.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from ._outbox import (
|
|
16
|
+
DEFAULT_JOB_ID_PREFIX,
|
|
17
|
+
DEFAULT_TABLE,
|
|
18
|
+
DIALECTS,
|
|
19
|
+
TYPE,
|
|
20
|
+
Dialect,
|
|
21
|
+
NoTransactionError,
|
|
22
|
+
add_job_message,
|
|
23
|
+
add_parse_request,
|
|
24
|
+
create_table,
|
|
25
|
+
ddl,
|
|
26
|
+
new_job_id,
|
|
27
|
+
owns,
|
|
28
|
+
purge,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__version__ = "1.0.0" # x-release-please-version
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"DEFAULT_JOB_ID_PREFIX",
|
|
35
|
+
"DEFAULT_TABLE",
|
|
36
|
+
"DIALECTS",
|
|
37
|
+
"TYPE",
|
|
38
|
+
"Dialect",
|
|
39
|
+
"NoTransactionError",
|
|
40
|
+
"add_job_message",
|
|
41
|
+
"add_parse_request",
|
|
42
|
+
"create_table",
|
|
43
|
+
"ddl",
|
|
44
|
+
"new_job_id",
|
|
45
|
+
"owns",
|
|
46
|
+
"purge",
|
|
47
|
+
]
|
qaechi/outbox/_outbox.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Write parse requests to the outbox table in the caller's transaction.
|
|
2
|
+
|
|
3
|
+
The table, the SQL and the job IDs are the same as those of the Java outbox
|
|
4
|
+
(`io.github.qaechi:qaechi-outbox`), so one Debezium relay serves both.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import uuid
|
|
12
|
+
from datetime import timedelta
|
|
13
|
+
from importlib import resources
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
from qaechi.contracts import JobMessage, JobRequest, Topics
|
|
17
|
+
|
|
18
|
+
DEFAULT_TABLE = "qaechi_outbox"
|
|
19
|
+
DEFAULT_JOB_ID_PREFIX = "qo-"
|
|
20
|
+
TYPE = "JobMessage" # the value of the `type` column
|
|
21
|
+
|
|
22
|
+
Dialect = Literal["postgresql", "mysql"]
|
|
23
|
+
DIALECTS: tuple[str, ...] = ("postgresql", "mysql")
|
|
24
|
+
|
|
25
|
+
_IDENTIFIER = r"[A-Za-z_][A-Za-z0-9_]{0,62}"
|
|
26
|
+
_TABLE = re.compile(rf"(?:{_IDENTIFIER}\.)?{_IDENTIFIER}")
|
|
27
|
+
_PREFIX = re.compile(r"[A-Za-z0-9._:-]{0,100}")
|
|
28
|
+
_TRACEPARENT = re.compile(r"[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}")
|
|
29
|
+
_DDL_NAMES = re.compile(r"\bqaechi_outbox(_created_at)?\b")
|
|
30
|
+
|
|
31
|
+
_INSERT = {
|
|
32
|
+
"postgresql": "INSERT INTO {t} (id, aggregatetype, aggregateid, type, payload, traceparent) "
|
|
33
|
+
"VALUES (%s, %s, %s, %s, CAST(%s AS jsonb), %s)",
|
|
34
|
+
"mysql": "INSERT INTO {t} (id, aggregatetype, aggregateid, type, payload, traceparent) "
|
|
35
|
+
"VALUES (%s, %s, %s, %s, CAST(%s AS JSON), %s)",
|
|
36
|
+
}
|
|
37
|
+
_PURGE = {
|
|
38
|
+
"postgresql": "DELETE FROM {t} WHERE id IN (SELECT id FROM {t} "
|
|
39
|
+
"WHERE created_at < now() - make_interval(secs => %s) LIMIT %s)",
|
|
40
|
+
"mysql": "DELETE FROM {t} WHERE created_at < NOW(6) - INTERVAL %s SECOND LIMIT %s",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class NoTransactionError(RuntimeError):
|
|
45
|
+
"""The connection is in autocommit mode, so the request would not commit with your data."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def new_job_id(prefix: str = DEFAULT_JOB_ID_PREFIX) -> str:
|
|
49
|
+
"""A new job ID: the prefix and a random UUID, for example `qo-0b6c...`."""
|
|
50
|
+
return _check_prefix(prefix) + str(uuid.uuid4())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def owns(job_id: str | None, prefix: str = DEFAULT_JOB_ID_PREFIX) -> bool:
|
|
54
|
+
"""Whether a job ID (for example from a result event) was made with this prefix."""
|
|
55
|
+
return job_id is not None and job_id.startswith(_check_prefix(prefix))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def add_parse_request(
|
|
59
|
+
conn: Any,
|
|
60
|
+
request: JobRequest | dict[str, Any],
|
|
61
|
+
*,
|
|
62
|
+
topic: str = Topics.JOBS,
|
|
63
|
+
run_id: str | None = None,
|
|
64
|
+
table: str = DEFAULT_TABLE,
|
|
65
|
+
job_id_prefix: str = DEFAULT_JOB_ID_PREFIX,
|
|
66
|
+
traceparent: str | None = None,
|
|
67
|
+
delete_after_insert: bool = False,
|
|
68
|
+
dialect: Dialect | None = None,
|
|
69
|
+
) -> str:
|
|
70
|
+
"""Request a parse job in the connection's current transaction and return its job ID.
|
|
71
|
+
|
|
72
|
+
The row commits, or rolls back, with your own writes: commit as you always do. Keep the job ID
|
|
73
|
+
with your own row to match the result event later.
|
|
74
|
+
|
|
75
|
+
`conn` is a psycopg 3 or PyMySQL connection, or a SQLAlchemy 2 `Connection` or `Session` on
|
|
76
|
+
PostgreSQL or MySQL. A connection in autocommit mode raises `NoTransactionError`.
|
|
77
|
+
|
|
78
|
+
`traceparent` joins the parse job to your trace. Left out, it is taken from the current
|
|
79
|
+
OpenTelemetry span when `opentelemetry-api` is installed. A value that is not a valid W3C
|
|
80
|
+
traceparent is left out.
|
|
81
|
+
"""
|
|
82
|
+
if not isinstance(request, JobRequest):
|
|
83
|
+
request = JobRequest.model_validate(request)
|
|
84
|
+
job_id = new_job_id(job_id_prefix)
|
|
85
|
+
add_job_message(conn, JobMessage(job_id=job_id, request=request, run_id=run_id),
|
|
86
|
+
topic=topic, table=table, traceparent=traceparent,
|
|
87
|
+
delete_after_insert=delete_after_insert, dialect=dialect)
|
|
88
|
+
return job_id
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def add_job_message(
|
|
92
|
+
conn: Any,
|
|
93
|
+
message: JobMessage,
|
|
94
|
+
*,
|
|
95
|
+
topic: str = Topics.JOBS,
|
|
96
|
+
table: str = DEFAULT_TABLE,
|
|
97
|
+
traceparent: str | None = None,
|
|
98
|
+
delete_after_insert: bool = False,
|
|
99
|
+
dialect: Dialect | None = None,
|
|
100
|
+
) -> None:
|
|
101
|
+
"""Write a job message you made yourself, with your own job ID. See `add_parse_request`."""
|
|
102
|
+
if not isinstance(message, JobMessage):
|
|
103
|
+
raise TypeError("message must be a qaechi.contracts.JobMessage")
|
|
104
|
+
if not topic or len(topic) > 64:
|
|
105
|
+
raise ValueError("topic must be 1 to 64 characters")
|
|
106
|
+
_check_table(table)
|
|
107
|
+
db = _Db(conn, dialect)
|
|
108
|
+
db.require_transaction()
|
|
109
|
+
row_id = str(uuid.uuid4())
|
|
110
|
+
# Nulls are left out, as the Java outbox writes them: the same bytes reach the worker.
|
|
111
|
+
payload = message.model_dump_json(by_alias=True, exclude_none=True)
|
|
112
|
+
db.execute(_INSERT[db.dialect].format(t=table),
|
|
113
|
+
(row_id, topic, message.request.document_id, TYPE, payload,
|
|
114
|
+
_traceparent(traceparent)))
|
|
115
|
+
if delete_after_insert:
|
|
116
|
+
# The INSERT stays in the write-ahead log (or binlog), which is all the relay reads.
|
|
117
|
+
db.execute(f"DELETE FROM {table} WHERE id = %s", (row_id,))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def purge(
|
|
121
|
+
conn: Any,
|
|
122
|
+
older_than: timedelta = timedelta(days=7),
|
|
123
|
+
*,
|
|
124
|
+
batch_size: int = 1000,
|
|
125
|
+
table: str = DEFAULT_TABLE,
|
|
126
|
+
dialect: Dialect | None = None,
|
|
127
|
+
) -> int:
|
|
128
|
+
"""Delete rows older than `older_than` (by the database clock), in batches; return the count.
|
|
129
|
+
|
|
130
|
+
The relay has read a row long before it is purged. On an autocommit connection each batch
|
|
131
|
+
commits on its own, so a large backlog never holds locks for long; in a transaction, commit
|
|
132
|
+
afterwards.
|
|
133
|
+
"""
|
|
134
|
+
if older_than < timedelta(0) or batch_size < 1:
|
|
135
|
+
raise ValueError("older_than must not be negative and batch_size must be positive")
|
|
136
|
+
_check_table(table)
|
|
137
|
+
db = _Db(conn, dialect)
|
|
138
|
+
seconds = int(older_than.total_seconds())
|
|
139
|
+
# PostgreSQL's make_interval takes double precision seconds.
|
|
140
|
+
arg: int | float = float(seconds) if db.dialect == "postgresql" else seconds
|
|
141
|
+
sql = _PURGE[db.dialect].format(t=table)
|
|
142
|
+
total = 0
|
|
143
|
+
while True:
|
|
144
|
+
n = db.execute(sql, (arg, batch_size))
|
|
145
|
+
total += n
|
|
146
|
+
if n < batch_size:
|
|
147
|
+
return total
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def ddl(dialect: Dialect = "postgresql", table: str = DEFAULT_TABLE) -> str:
|
|
151
|
+
"""The CREATE TABLE and CREATE INDEX statements, for your migration tool (Alembic, Flyway)."""
|
|
152
|
+
if dialect not in DIALECTS:
|
|
153
|
+
raise ValueError(f"dialect must be one of {DIALECTS}: {dialect!r}")
|
|
154
|
+
name = _check_table(table)
|
|
155
|
+
base = name.rsplit(".", 1)[-1]
|
|
156
|
+
sql = (resources.files("qaechi.outbox") / "sql" / f"{dialect}.sql").read_text("utf-8")
|
|
157
|
+
return _DDL_NAMES.sub(lambda m: name if m.group(1) is None else f"{base}_created_at", sql)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def create_table(conn: Any, *, table: str = DEFAULT_TABLE, dialect: Dialect | None = None) -> None:
|
|
161
|
+
"""Run `ddl()` on a connection: creates the table and index if they do not exist yet.
|
|
162
|
+
|
|
163
|
+
Prefer your migration tool in production. On a connection in a transaction, commit afterwards.
|
|
164
|
+
"""
|
|
165
|
+
db = _Db(conn, dialect)
|
|
166
|
+
for statement in _statements(ddl(db.dialect, table)):
|
|
167
|
+
db.execute(statement, None)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _statements(sql: str) -> list[str]:
|
|
171
|
+
lines = [line for line in sql.splitlines() if not line.lstrip().startswith("--")]
|
|
172
|
+
return [s.strip() for s in "\n".join(lines).split(";") if s.strip()]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _check_table(table: str) -> str:
|
|
176
|
+
if not isinstance(table, str) or not _TABLE.fullmatch(table):
|
|
177
|
+
raise ValueError(f"table must be a plain name, optionally schema.name: {table!r}")
|
|
178
|
+
return table
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _check_prefix(prefix: str) -> str:
|
|
182
|
+
if not isinstance(prefix, str) or not _PREFIX.fullmatch(prefix):
|
|
183
|
+
raise ValueError("job_id_prefix may hold letters, digits and . _ : - only (at most 100)")
|
|
184
|
+
return prefix
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _traceparent(value: str | None) -> str | None:
|
|
188
|
+
if value is None:
|
|
189
|
+
value = _current_traceparent()
|
|
190
|
+
return value if value is not None and _TRACEPARENT.fullmatch(value) else None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _current_traceparent() -> str | None:
|
|
194
|
+
if "opentelemetry" not in sys.modules:
|
|
195
|
+
return None # no tracing set up in this process
|
|
196
|
+
try:
|
|
197
|
+
from opentelemetry import propagate
|
|
198
|
+
except ImportError:
|
|
199
|
+
return None
|
|
200
|
+
carrier: dict[str, str] = {}
|
|
201
|
+
propagate.inject(carrier)
|
|
202
|
+
return carrier.get("traceparent")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class _Db:
|
|
206
|
+
"""A psycopg 3, PyMySQL or SQLAlchemy connection seen through one small interface."""
|
|
207
|
+
|
|
208
|
+
def __init__(self, conn: Any, dialect: str | None) -> None:
|
|
209
|
+
if dialect is not None and dialect not in DIALECTS:
|
|
210
|
+
raise ValueError(f"dialect must be one of {DIALECTS}: {dialect!r}")
|
|
211
|
+
self.sqlalchemy = False
|
|
212
|
+
sa_orm = sys.modules.get("sqlalchemy.orm")
|
|
213
|
+
if sa_orm is not None and isinstance(conn, sa_orm.Session):
|
|
214
|
+
conn = conn.connection()
|
|
215
|
+
sa_engine = sys.modules.get("sqlalchemy.engine")
|
|
216
|
+
if sa_engine is not None and isinstance(conn, sa_engine.Connection):
|
|
217
|
+
self.sqlalchemy = True
|
|
218
|
+
name = conn.dialect.name
|
|
219
|
+
detected = name if name in DIALECTS else None
|
|
220
|
+
if conn.dialect.paramstyle not in ("format", "pyformat"):
|
|
221
|
+
raise TypeError(f"the {conn.dialect.driver} driver is not supported: its "
|
|
222
|
+
f"parameter style is {conn.dialect.paramstyle}")
|
|
223
|
+
elif _is(conn, "psycopg", "Connection"):
|
|
224
|
+
detected = "postgresql"
|
|
225
|
+
elif _is(conn, "pymysql.connections", "Connection"):
|
|
226
|
+
detected = "mysql"
|
|
227
|
+
else:
|
|
228
|
+
raise TypeError("conn must be a psycopg 3 or PyMySQL connection, or a SQLAlchemy "
|
|
229
|
+
f"Connection or Session: got {type(conn).__module__}."
|
|
230
|
+
f"{type(conn).__qualname__}")
|
|
231
|
+
if detected is None and dialect is None:
|
|
232
|
+
raise ValueError(f"no outbox table for {conn.dialect.name}; supported: {DIALECTS}")
|
|
233
|
+
self.conn = conn
|
|
234
|
+
self.dialect: str = dialect or detected # type: ignore[assignment]
|
|
235
|
+
|
|
236
|
+
def require_transaction(self) -> None:
|
|
237
|
+
conn = self.conn
|
|
238
|
+
if self.sqlalchemy:
|
|
239
|
+
import sqlalchemy
|
|
240
|
+
|
|
241
|
+
# SQLAlchemy 2 begins a transaction on first use; 1.x would autocommit the INSERT.
|
|
242
|
+
if int(sqlalchemy.__version__.split(".")[0]) < 2 and not conn.in_transaction():
|
|
243
|
+
raise NoTransactionError("begin a transaction first (conn.begin())")
|
|
244
|
+
conn = conn.connection.dbapi_connection
|
|
245
|
+
if _autocommit(conn):
|
|
246
|
+
raise NoTransactionError("the outbox needs a transaction: turn autocommit off and "
|
|
247
|
+
"commit the request with your own data")
|
|
248
|
+
|
|
249
|
+
def execute(self, sql: str, params: tuple[Any, ...] | None) -> int:
|
|
250
|
+
if self.sqlalchemy:
|
|
251
|
+
return self.conn.exec_driver_sql(sql, params or ()).rowcount
|
|
252
|
+
with self.conn.cursor() as cur:
|
|
253
|
+
cur.execute(sql, params)
|
|
254
|
+
return cur.rowcount
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _is(obj: Any, module: str, cls: str) -> bool:
|
|
258
|
+
mod = sys.modules.get(module)
|
|
259
|
+
return mod is not None and isinstance(obj, getattr(mod, cls))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _autocommit(dbapi_conn: Any) -> bool:
|
|
263
|
+
getter = getattr(dbapi_conn, "get_autocommit", None) # PyMySQL, mysqlclient
|
|
264
|
+
if callable(getter):
|
|
265
|
+
return bool(getter())
|
|
266
|
+
return bool(getattr(dbapi_conn, "autocommit", False)) # psycopg 2 and 3
|
qaechi/outbox/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
-- qaechi outbox table for MySQL 8.4 and later. Column names are those Debezium's outbox
|
|
2
|
+
-- EventRouter expects by default: aggregatetype routes to the topic, aggregateid is the Kafka
|
|
3
|
+
-- key, payload is the message, traceparent goes to a Kafka header.
|
|
4
|
+
CREATE TABLE IF NOT EXISTS qaechi_outbox (
|
|
5
|
+
id char(36) NOT NULL PRIMARY KEY,
|
|
6
|
+
aggregatetype varchar(64) NOT NULL,
|
|
7
|
+
aggregateid varchar(200) NOT NULL,
|
|
8
|
+
type varchar(64) NOT NULL,
|
|
9
|
+
payload json NOT NULL,
|
|
10
|
+
traceparent varchar(55) NULL,
|
|
11
|
+
created_at timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
|
12
|
+
KEY qaechi_outbox_created_at (created_at)
|
|
13
|
+
);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
-- qaechi outbox table for PostgreSQL. Column names are those Debezium's outbox EventRouter
|
|
2
|
+
-- expects by default: aggregatetype routes to the topic, aggregateid is the Kafka key, payload
|
|
3
|
+
-- is the message, traceparent goes to a Kafka header.
|
|
4
|
+
CREATE TABLE IF NOT EXISTS qaechi_outbox (
|
|
5
|
+
id uuid PRIMARY KEY,
|
|
6
|
+
aggregatetype varchar(64) NOT NULL,
|
|
7
|
+
aggregateid varchar(200) NOT NULL,
|
|
8
|
+
type varchar(64) NOT NULL,
|
|
9
|
+
payload jsonb NOT NULL,
|
|
10
|
+
traceparent varchar(55),
|
|
11
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
12
|
+
);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS qaechi_outbox_created_at ON qaechi_outbox (created_at);
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qaechi-outbox
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Transactional outbox for qaechi: request parse jobs in your own PostgreSQL or MySQL transaction.
|
|
5
|
+
Author: Taeyong Kang
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://qaechi.github.io/
|
|
8
|
+
Project-URL: Source, https://github.com/qaechi/qaechi-outbox
|
|
9
|
+
Project-URL: Documentation, https://qaechi.github.io/modules/
|
|
10
|
+
Project-URL: Issues, https://github.com/qaechi/qaechi-outbox/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/qaechi/qaechi-outbox/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: qaechi,outbox,transactional-outbox,debezium,cdc,kafka
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Database
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: qaechi-contracts<2,>=1.1
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest<10,>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: jsonschema<5,>=4.26; extra == "dev"
|
|
28
|
+
Requires-Dist: ruff==0.16.*; extra == "dev"
|
|
29
|
+
Requires-Dist: psycopg[binary]<4,>=3.2; extra == "dev"
|
|
30
|
+
Requires-Dist: PyMySQL<2,>=1.1; extra == "dev"
|
|
31
|
+
Requires-Dist: SQLAlchemy<3,>=2; extra == "dev"
|
|
32
|
+
Requires-Dist: opentelemetry-sdk<2,>=1.30; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# qaechi-outbox
|
|
36
|
+
|
|
37
|
+
Request [qaechi](https://qaechi.github.io/) parse jobs inside your own database transaction. The
|
|
38
|
+
request commits with your row, or rolls back with it, and is never lost on the way to Kafka.
|
|
39
|
+
|
|
40
|
+
[한국어](README.ko.md) | [How the modules fit together](https://qaechi.github.io/modules/)
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install qaechi-outbox
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import psycopg
|
|
48
|
+
from qaechi.contracts import FieldSpec, JobRequest
|
|
49
|
+
from qaechi.outbox import add_parse_request
|
|
50
|
+
|
|
51
|
+
with psycopg.connect(dsn) as conn: # one transaction, committed at the end of the block
|
|
52
|
+
conn.execute("INSERT INTO contracts (id, path) VALUES (%s, %s)", (contract_id, path))
|
|
53
|
+
job_id = add_parse_request(conn, JobRequest(
|
|
54
|
+
document_id=contract_id, source=path, doc_type="contract",
|
|
55
|
+
fields=[FieldSpec(name="party"), FieldSpec(name="amount", kind="number")]))
|
|
56
|
+
conn.execute("UPDATE contracts SET parse_job_id = %s WHERE id = %s", (job_id, contract_id))
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
your transaction ──INSERT──▶ qaechi_outbox ──Debezium──▶ qaechi.parse.jobs ──▶ qaechi-parser worker
|
|
61
|
+
│
|
|
62
|
+
your result consumer ◀───────────────────── qaechi.parse.results ◀───────────────────┘
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The table, the SQL and the job IDs are those of the Java outbox (`io.github.qaechi:qaechi-outbox`),
|
|
66
|
+
so a Python and a Java service can share one table and one relay.
|
|
67
|
+
|
|
68
|
+
## Connections
|
|
69
|
+
|
|
70
|
+
| Connection | Database |
|
|
71
|
+
|---|---|
|
|
72
|
+
| psycopg 3 `Connection` | PostgreSQL 13 and later |
|
|
73
|
+
| PyMySQL `Connection` | MySQL 8.4 and later |
|
|
74
|
+
| SQLAlchemy 2 `Connection` or `Session` (psycopg, PyMySQL and other `%s` drivers) | PostgreSQL, MySQL |
|
|
75
|
+
|
|
76
|
+
The only dependency is `qaechi-contracts`; your driver is yours. A connection in autocommit mode
|
|
77
|
+
raises `NoTransactionError`: the point of an outbox is that the request commits with your data.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
with Session(engine) as session, session.begin():
|
|
81
|
+
session.add(contract)
|
|
82
|
+
contract.parse_job_id = add_parse_request(session, request)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Functions
|
|
86
|
+
|
|
87
|
+
| Function | |
|
|
88
|
+
|---|---|
|
|
89
|
+
| `add_parse_request(conn, request, *, topic=Topics.JOBS, run_id=None, ...) -> str` | One INSERT in the current transaction. `request` is a `JobRequest` or its JSON as a dict. Returns the new job ID |
|
|
90
|
+
| `add_job_message(conn, message, ...)` | The same for a `JobMessage` with your own job ID |
|
|
91
|
+
| `ddl(dialect="postgresql", table="qaechi_outbox") -> str` | `CREATE TABLE` and `CREATE INDEX` for your migration tool. `dialect` is `postgresql` or `mysql` |
|
|
92
|
+
| `create_table(conn, *, table=...)` | Runs `ddl()` (`IF NOT EXISTS`), for tests and small setups |
|
|
93
|
+
| `purge(conn, older_than=timedelta(days=7), *, batch_size=1000) -> int` | Deletes old rows in batches; returns how many |
|
|
94
|
+
| `new_job_id(prefix="qo-")`, `owns(job_id, prefix="qo-")` | Job IDs are the prefix and a UUID |
|
|
95
|
+
|
|
96
|
+
Keyword arguments of `add_parse_request` and `add_job_message`:
|
|
97
|
+
|
|
98
|
+
| Argument | Default | |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| `topic` | `qaechi.parse.jobs` | Where the request is routed (`aggregatetype`), at most 64 characters. For example `Topics.BATCH_JOBS` |
|
|
101
|
+
| `run_id` | none | The batch run, returned as is in the result event |
|
|
102
|
+
| `table` | `qaechi_outbox` | Optionally `schema.name` |
|
|
103
|
+
| `job_id_prefix` | `qo-` | Give each service its own, for example `qo-contracts-`, and keep only its results with `owns()` |
|
|
104
|
+
| `traceparent` | the current OpenTelemetry span | W3C trace context, moved to a Kafka header so the parse job joins your trace. Invalid values are left out |
|
|
105
|
+
| `delete_after_insert` | `False` | Delete the row in the same transaction; the relay still reads the INSERT from the write-ahead log |
|
|
106
|
+
| `dialect` | from the connection | `postgresql` or `mysql` |
|
|
107
|
+
|
|
108
|
+
## Results
|
|
109
|
+
|
|
110
|
+
The job ID is made before the commit: keep it with your row. Delivery is at least once; a worker
|
|
111
|
+
skips a job ID it has already finished, and your consumer should update by job ID so a repeated
|
|
112
|
+
event changes nothing.
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from qaechi.contracts import ResultEvent
|
|
116
|
+
from qaechi.outbox import owns
|
|
117
|
+
|
|
118
|
+
event = ResultEvent.model_validate_json(record.value()) # from qaechi.parse.results
|
|
119
|
+
if owns(event.job_id, "qo-contracts-"):
|
|
120
|
+
mark_parsed(event.job_id, event.result_id, event.status)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Operations
|
|
124
|
+
|
|
125
|
+
- **Table**: put `ddl("postgresql")` or `ddl("mysql")` in your migration. The columns are those
|
|
126
|
+
Debezium's outbox EventRouter reads by default: `aggregatetype` is the topic, `aggregateid` (the
|
|
127
|
+
`documentId`) the Kafka key, `payload` the `JobMessage`, `traceparent` a header.
|
|
128
|
+
- **Relay**: Debezium with the outbox EventRouter on this table. The qaechi-stack `enterprise`
|
|
129
|
+
profile sets it up.
|
|
130
|
+
- **Purge**: run `purge()` on a schedule (cron, Celery beat) with an autocommit connection, so each
|
|
131
|
+
batch commits on its own. The relay reads a row long before it is purged.
|
|
132
|
+
|
|
133
|
+
## License
|
|
134
|
+
|
|
135
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
qaechi/outbox/__init__.py,sha256=HrZewpbqMawxygrccXkYDlOzZD5g-bA2lzfAzTVbadA,1142
|
|
2
|
+
qaechi/outbox/_outbox.py,sha256=8P6mYV1ibDcVSj03V0Y85eTcUWJKaSY1FBhcELRoa9E,10952
|
|
3
|
+
qaechi/outbox/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
qaechi/outbox/sql/mysql.sql,sha256=92TqxyuRLSCLvruIIJ-r7FQvDg6KUnAI84n61kmTsDc,652
|
|
5
|
+
qaechi/outbox/sql/postgresql.sql,sha256=P2LgZjZNVqlqHFa6Zc461mPYS7AbBhoQ4cKgora3Wzw,651
|
|
6
|
+
qaechi_outbox-1.0.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
|
|
7
|
+
qaechi_outbox-1.0.0.dist-info/METADATA,sha256=tWBwHBYhapVAIti-GFOWRyy73q8ZJaCTKD2lwgzqZ2E,6433
|
|
8
|
+
qaechi_outbox-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
qaechi_outbox-1.0.0.dist-info/top_level.txt,sha256=uD_gOde0YCWlGMtrDzR5FuXld9uzJkwJnJtoXcvNScM,7
|
|
10
|
+
qaechi_outbox-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
qaechi
|