qaechi-sink 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/sink/__init__.py +8 -0
- qaechi/sink/cli.py +57 -0
- qaechi/sink/config.py +90 -0
- qaechi/sink/record.py +73 -0
- qaechi/sink/runner.py +142 -0
- qaechi/sink/targets/__init__.py +50 -0
- qaechi/sink/targets/mongodb.py +43 -0
- qaechi/sink/targets/mysql.py +111 -0
- qaechi/sink/targets/postgres.py +92 -0
- qaechi/sink/targets/webhook.py +74 -0
- qaechi_sink-1.0.0.dist-info/METADATA +156 -0
- qaechi_sink-1.0.0.dist-info/RECORD +16 -0
- qaechi_sink-1.0.0.dist-info/WHEEL +5 -0
- qaechi_sink-1.0.0.dist-info/entry_points.txt +2 -0
- qaechi_sink-1.0.0.dist-info/licenses/LICENSE +202 -0
- qaechi_sink-1.0.0.dist-info/top_level.txt +1 -0
qaechi/sink/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""qaechi-sink: load finished Qaechi jobs into your database or webhook.
|
|
2
|
+
|
|
3
|
+
Consumes result events (qaechi.parse.results), fetches the values with their evidence from the
|
|
4
|
+
parser API, and writes them idempotently to PostgreSQL (Supabase, Neon, ...), MySQL, MongoDB or
|
|
5
|
+
an HTTPS webhook.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "1.0.0" # x-release-please-version
|
qaechi/sink/cli.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Command line.
|
|
2
|
+
|
|
3
|
+
qaechi-sink run consume result events and write them to QAECHI_SINK_TARGET
|
|
4
|
+
qaechi-sink check connect to the target and create tables or collections
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import logging
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from . import __version__, config
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _check(_args: argparse.Namespace) -> int:
|
|
17
|
+
from .targets import open_target
|
|
18
|
+
|
|
19
|
+
target = open_target(config.target_url(), prefix=config.table_prefix())
|
|
20
|
+
try:
|
|
21
|
+
target.prepare()
|
|
22
|
+
finally:
|
|
23
|
+
target.close()
|
|
24
|
+
print(f"target {target.name}: ready")
|
|
25
|
+
return 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _run(_args: argparse.Namespace) -> int:
|
|
29
|
+
try:
|
|
30
|
+
import confluent_kafka # noqa: F401
|
|
31
|
+
except ImportError:
|
|
32
|
+
print("qaechi-sink run needs Kafka: pip install 'qaechi-sink[kafka]'", file=sys.stderr)
|
|
33
|
+
return 2
|
|
34
|
+
from .runner import run
|
|
35
|
+
|
|
36
|
+
run()
|
|
37
|
+
return 0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main(argv: list[str] | None = None) -> int:
|
|
41
|
+
parser = argparse.ArgumentParser(prog="qaechi-sink",
|
|
42
|
+
description="Load finished Qaechi jobs into your database.")
|
|
43
|
+
parser.add_argument("--version", action="version", version=f"qaechi-sink {__version__}")
|
|
44
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
45
|
+
sub.add_parser("run", help="consume result events and write them").set_defaults(func=_run)
|
|
46
|
+
sub.add_parser("check", help="connect and create tables").set_defaults(func=_check)
|
|
47
|
+
args = parser.parse_args(argv)
|
|
48
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
|
49
|
+
try:
|
|
50
|
+
return args.func(args)
|
|
51
|
+
except config.MissingConfig as exc:
|
|
52
|
+
print(str(exc), file=sys.stderr)
|
|
53
|
+
return 2
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
if __name__ == "__main__":
|
|
57
|
+
sys.exit(main())
|
qaechi/sink/config.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Settings from environment variables. Only the target and the brokers are required."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
KAFKA_CONF_PREFIX = "QAECHI_KAFKA_CONF_"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MissingConfig(RuntimeError):
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _get(name: str) -> str | None:
|
|
15
|
+
value = os.getenv(name)
|
|
16
|
+
return value.strip() if value and value.strip() else None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _int(name: str, default: int, minimum: int = 0) -> int:
|
|
20
|
+
try:
|
|
21
|
+
value = int(_get(name) or default)
|
|
22
|
+
except ValueError:
|
|
23
|
+
return default
|
|
24
|
+
return value if value >= minimum else default
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def require(name: str) -> str:
|
|
28
|
+
value = _get(name)
|
|
29
|
+
if not value:
|
|
30
|
+
raise MissingConfig(f"{name} is not set")
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def target_url() -> str:
|
|
35
|
+
# postgresql://, mysql://, mongodb://, or https:// for a webhook.
|
|
36
|
+
return require("QAECHI_SINK_TARGET")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def table_prefix() -> str:
|
|
40
|
+
prefix = _get("QAECHI_SINK_TABLE_PREFIX") or "qaechi_"
|
|
41
|
+
if not prefix.replace("_", "").isalnum():
|
|
42
|
+
raise MissingConfig("QAECHI_SINK_TABLE_PREFIX may contain only letters, digits and _")
|
|
43
|
+
return prefix
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def parser_url() -> str | None:
|
|
47
|
+
# Where to fetch values: GET {parser_url}/results/{resultId}. Unset = write status only.
|
|
48
|
+
url = _get("QAECHI_PARSER_URL")
|
|
49
|
+
return url.rstrip("/") if url else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def internal_token() -> str | None:
|
|
53
|
+
return _get("QAECHI_INTERNAL_TOKEN")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def webhook_secret() -> str | None:
|
|
57
|
+
return _get("QAECHI_SINK_WEBHOOK_SECRET")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def include_failed() -> bool:
|
|
61
|
+
return (_get("QAECHI_SINK_INCLUDE_FAILED") or "true").lower() in ("1", "true", "on", "yes")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def max_retries() -> int:
|
|
65
|
+
return _int("QAECHI_SINK_MAX_RETRIES", 5)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def kafka_bootstrap_servers() -> str:
|
|
69
|
+
return require("QAECHI_KAFKA_BOOTSTRAP_SERVERS")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def topic_results() -> str:
|
|
73
|
+
return _get("QAECHI_KAFKA_TOPIC_RESULTS") or "qaechi.parse.results"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def topic_dlq() -> str:
|
|
77
|
+
return _get("QAECHI_SINK_TOPIC_DLQ") or "qaechi.sink.dlq"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def group_id() -> str:
|
|
81
|
+
return _get("QAECHI_SINK_GROUP_ID") or "qaechi-sink"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def kafka_conf() -> dict[str, str]:
|
|
85
|
+
"""QAECHI_KAFKA_CONF_SECURITY_PROTOCOL=SASL_SSL becomes security.protocol=SASL_SSL."""
|
|
86
|
+
conf: dict[str, str] = {}
|
|
87
|
+
for name, value in os.environ.items():
|
|
88
|
+
if name.startswith(KAFKA_CONF_PREFIX) and value.strip():
|
|
89
|
+
conf[name[len(KAFKA_CONF_PREFIX):].lower().replace("_", ".")] = value.strip()
|
|
90
|
+
return conf
|
qaechi/sink/record.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""What gets written: one row per job, plus one row per extracted value with its evidence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from qaechi.contracts import Extraction, FieldValue, ResultEvent
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class ValueRow:
|
|
14
|
+
path: str # fields.total, lines[0].amount, total
|
|
15
|
+
label: str | None # line label for lines[i]
|
|
16
|
+
value_text: str | None
|
|
17
|
+
value_number: float | None
|
|
18
|
+
page: int | None
|
|
19
|
+
quote: str | None
|
|
20
|
+
confidence: float
|
|
21
|
+
verified: bool # has a quote, and the quote was found in the source
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class SinkRecord:
|
|
26
|
+
job_id: str
|
|
27
|
+
document_id: str
|
|
28
|
+
doc_type: str
|
|
29
|
+
status: str
|
|
30
|
+
result_id: str | None
|
|
31
|
+
route: str | None
|
|
32
|
+
groundedness: str | None
|
|
33
|
+
error: str | None
|
|
34
|
+
attempts: int
|
|
35
|
+
finished_at: datetime | None
|
|
36
|
+
extraction: dict[str, Any] | None = None
|
|
37
|
+
values: list[ValueRow] = field(default_factory=list)
|
|
38
|
+
|
|
39
|
+
def summary(self) -> dict[str, Any]:
|
|
40
|
+
return {"jobId": self.job_id, "documentId": self.document_id, "docType": self.doc_type,
|
|
41
|
+
"status": self.status, "resultId": self.result_id, "route": self.route,
|
|
42
|
+
"groundedness": self.groundedness, "error": self.error,
|
|
43
|
+
"attempts": self.attempts,
|
|
44
|
+
"finishedAt": self.finished_at.isoformat() if self.finished_at else None}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _row(path: str, fv: FieldValue, missing: set[str], label: str | None = None) -> ValueRow:
|
|
48
|
+
value = fv.value
|
|
49
|
+
number = float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None
|
|
50
|
+
prov = fv.provenance
|
|
51
|
+
return ValueRow(path=path, label=label,
|
|
52
|
+
value_text=None if value is None else str(value), value_number=number,
|
|
53
|
+
page=prov.page if prov else None, quote=prov.quote if prov else None,
|
|
54
|
+
confidence=fv.confidence,
|
|
55
|
+
verified=prov is not None and value is not None and path not in missing)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build(event: ResultEvent, extraction: Extraction | None) -> SinkRecord:
|
|
59
|
+
values: list[ValueRow] = []
|
|
60
|
+
body = None
|
|
61
|
+
if extraction is not None:
|
|
62
|
+
missing = set(extraction.quote_check.not_in_source)
|
|
63
|
+
values += [_row(f"fields.{name}", fv, missing) for name, fv in extraction.fields.items()]
|
|
64
|
+
values += [_row(f"lines[{i}].amount", line.amount, missing, label=line.label)
|
|
65
|
+
for i, line in enumerate(extraction.lines)]
|
|
66
|
+
if extraction.total is not None:
|
|
67
|
+
values.append(_row("total", extraction.total, missing))
|
|
68
|
+
body = extraction.model_dump(mode="json", by_alias=True)
|
|
69
|
+
return SinkRecord(job_id=event.job_id, document_id=event.document_id,
|
|
70
|
+
doc_type=event.doc_type, status=event.status, result_id=event.result_id,
|
|
71
|
+
route=event.route, groundedness=event.groundedness, error=event.error,
|
|
72
|
+
attempts=event.attempts, finished_at=event.finished_at,
|
|
73
|
+
extraction=body, values=values)
|
qaechi/sink/runner.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""The consume loop: result event in, record written, offset committed.
|
|
2
|
+
|
|
3
|
+
Per event:
|
|
4
|
+
1. Unreadable event -> sink DLQ with the reason, commit.
|
|
5
|
+
2. Failed job and QAECHI_SINK_INCLUDE_FAILED -> write status only.
|
|
6
|
+
3. Succeeded job -> fetch values from the parser API, write.
|
|
7
|
+
4. Write fails -> retry with backoff up to QAECHI_SINK_MAX_RETRIES,
|
|
8
|
+
then sink DLQ. A rejected webhook goes to the DLQ
|
|
9
|
+
at once.
|
|
10
|
+
The offset is committed only after the write (or the DLQ copy) succeeded. Writes are upserts, so
|
|
11
|
+
a redelivered event changes nothing.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import signal
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from pydantic import ValidationError
|
|
23
|
+
from qaechi.contracts import Extraction, ResultEvent
|
|
24
|
+
|
|
25
|
+
from . import config
|
|
26
|
+
from .record import build
|
|
27
|
+
from .targets import Target, open_target
|
|
28
|
+
from .targets.webhook import PermanentError
|
|
29
|
+
|
|
30
|
+
log = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
Fetch = Callable[[str], Extraction]
|
|
33
|
+
Publish = Callable[[str, bytes, list[tuple[str, bytes]]], None]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ResultFetcher:
|
|
37
|
+
"""GET {parser}/results/{id} with the internal token."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, base_url: str, token: str | None, client: Any = None) -> None:
|
|
40
|
+
import httpx
|
|
41
|
+
|
|
42
|
+
self.base_url = base_url
|
|
43
|
+
self.headers = {"X-Internal-Token": token} if token else {}
|
|
44
|
+
self._client = client or httpx.Client(timeout=30.0)
|
|
45
|
+
|
|
46
|
+
def __call__(self, result_id: str) -> Extraction:
|
|
47
|
+
resp = self._client.get(f"{self.base_url}/results/{result_id}", headers=self.headers)
|
|
48
|
+
resp.raise_for_status()
|
|
49
|
+
return Extraction.model_validate_json(resp.content)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def handle(value: bytes | None, headers: list[tuple[str, bytes]] | None, *, target: Target,
|
|
53
|
+
fetch: Fetch | None, dlq: Publish, sleep: Callable[[float], None] = time.sleep,
|
|
54
|
+
max_retries: int | None = None, include_failed: bool | None = None) -> str:
|
|
55
|
+
"""Process one result event. Returns the outcome; raises only if the DLQ is unreachable."""
|
|
56
|
+
retries = config.max_retries() if max_retries is None else max_retries
|
|
57
|
+
failed_too = config.include_failed() if include_failed is None else include_failed
|
|
58
|
+
try:
|
|
59
|
+
event = ResultEvent.model_validate_json(value or b"")
|
|
60
|
+
except ValidationError as exc:
|
|
61
|
+
dlq(value or b"", [*(headers or []), ("qaechi-error",
|
|
62
|
+
f"unreadable result event: {exc.error_count()} error(s)".encode())])
|
|
63
|
+
return "dlq"
|
|
64
|
+
|
|
65
|
+
if event.status == "failed" and not failed_too:
|
|
66
|
+
return "skipped"
|
|
67
|
+
|
|
68
|
+
attempt = 0
|
|
69
|
+
while True:
|
|
70
|
+
try:
|
|
71
|
+
extraction = None
|
|
72
|
+
if event.status == "succeeded" and event.result_id and fetch is not None:
|
|
73
|
+
extraction = fetch(event.result_id)
|
|
74
|
+
target.write(build(event, extraction))
|
|
75
|
+
return "written"
|
|
76
|
+
except PermanentError as exc:
|
|
77
|
+
reason = str(exc)
|
|
78
|
+
except Exception as exc: # noqa: BLE001 - database, network: retry, then DLQ
|
|
79
|
+
attempt += 1
|
|
80
|
+
reason = f"{type(exc).__name__}: {exc}"
|
|
81
|
+
if attempt <= retries:
|
|
82
|
+
delay = min(30.0, 0.5 * 2 ** (attempt - 1))
|
|
83
|
+
log.warning("job %s: write failed (%s), retry %d in %.1fs", event.job_id,
|
|
84
|
+
reason, attempt, delay)
|
|
85
|
+
sleep(delay)
|
|
86
|
+
continue
|
|
87
|
+
log.error("job %s sent to the sink DLQ: %s", event.job_id, reason)
|
|
88
|
+
dlq(value or b"", [*(headers or []), ("qaechi-error", reason[:500].encode())])
|
|
89
|
+
return "dlq"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run(target: Target | None = None, stop: Callable[[], bool] | None = None) -> None:
|
|
93
|
+
from confluent_kafka import Consumer, KafkaError, Producer
|
|
94
|
+
|
|
95
|
+
target = target or open_target(config.target_url(), prefix=config.table_prefix())
|
|
96
|
+
target.prepare()
|
|
97
|
+
parser = config.parser_url()
|
|
98
|
+
fetch = ResultFetcher(parser, config.internal_token()) if parser else None
|
|
99
|
+
if fetch is None:
|
|
100
|
+
log.warning("QAECHI_PARSER_URL is not set: writing job status without values")
|
|
101
|
+
|
|
102
|
+
base = {"bootstrap.servers": config.kafka_bootstrap_servers(), **config.kafka_conf()}
|
|
103
|
+
producer = Producer({**base, "acks": "all", "enable.idempotence": True})
|
|
104
|
+
consumer = Consumer({**base, "group.id": config.group_id(), "enable.auto.commit": False,
|
|
105
|
+
"auto.offset.reset": "earliest",
|
|
106
|
+
"partition.assignment.strategy": "cooperative-sticky"})
|
|
107
|
+
dlq_topic = config.topic_dlq()
|
|
108
|
+
|
|
109
|
+
def dlq(value: bytes, headers: list[tuple[str, bytes]]) -> None:
|
|
110
|
+
producer.produce(dlq_topic, value=value, headers=headers)
|
|
111
|
+
if producer.flush(10) > 0:
|
|
112
|
+
raise RuntimeError("sink DLQ unreachable")
|
|
113
|
+
|
|
114
|
+
stopping = {"now": False}
|
|
115
|
+
if stop is None:
|
|
116
|
+
def on_signal(*_: Any) -> None:
|
|
117
|
+
stopping["now"] = True
|
|
118
|
+
|
|
119
|
+
signal.signal(signal.SIGTERM, on_signal)
|
|
120
|
+
signal.signal(signal.SIGINT, on_signal)
|
|
121
|
+
stop = lambda: stopping["now"] # noqa: E731
|
|
122
|
+
|
|
123
|
+
consumer.subscribe([config.topic_results()])
|
|
124
|
+
log.info("sink: %s -> %s", config.topic_results(), target.name)
|
|
125
|
+
try:
|
|
126
|
+
while not stop():
|
|
127
|
+
msg = consumer.poll(1.0)
|
|
128
|
+
if msg is None:
|
|
129
|
+
continue
|
|
130
|
+
if msg.error():
|
|
131
|
+
if msg.error().code() == KafkaError._PARTITION_EOF:
|
|
132
|
+
continue
|
|
133
|
+
if msg.error().fatal():
|
|
134
|
+
raise RuntimeError(f"fatal Kafka error: {msg.error()}")
|
|
135
|
+
log.warning("Kafka: %s", msg.error())
|
|
136
|
+
continue
|
|
137
|
+
outcome = handle(msg.value(), msg.headers(), target=target, fetch=fetch, dlq=dlq)
|
|
138
|
+
log.info("%s offset %d: %s", msg.topic(), msg.offset(), outcome)
|
|
139
|
+
consumer.commit(message=msg, asynchronous=False)
|
|
140
|
+
finally:
|
|
141
|
+
consumer.close()
|
|
142
|
+
target.close()
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Where records go. Pick one with the URL scheme of QAECHI_SINK_TARGET.
|
|
2
|
+
|
|
3
|
+
postgresql:// PostgreSQL, Supabase, Neon, Amazon RDS and Aurora PostgreSQL [postgres]
|
|
4
|
+
mysql:// MySQL, MariaDB, Amazon Aurora MySQL [mysql]
|
|
5
|
+
mongodb:// MongoDB, MongoDB Atlas (mongodb+srv://), Amazon DocumentDB [mongodb]
|
|
6
|
+
https:// Any HTTPS endpoint, signed with HMAC-SHA256 (built in)
|
|
7
|
+
|
|
8
|
+
Every target is idempotent: writing the same job twice leaves one row per job and per value.
|
|
9
|
+
To add your own, implement `Target` and pass it to `qaechi.sink.runner.run(target=...)`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Protocol
|
|
15
|
+
|
|
16
|
+
from ..record import SinkRecord
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Target(Protocol):
|
|
20
|
+
name: str
|
|
21
|
+
|
|
22
|
+
def prepare(self) -> None:
|
|
23
|
+
"""Create tables, collections or indexes if missing. Safe to call every start."""
|
|
24
|
+
|
|
25
|
+
def write(self, record: SinkRecord) -> None:
|
|
26
|
+
"""Upsert one job and replace its values. Raise to retry."""
|
|
27
|
+
|
|
28
|
+
def close(self) -> None: ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def open_target(url: str, *, prefix: str = "qaechi_") -> Target:
|
|
32
|
+
scheme = url.split("://", 1)[0].lower()
|
|
33
|
+
if scheme in ("postgres", "postgresql"):
|
|
34
|
+
from .postgres import PostgresTarget
|
|
35
|
+
|
|
36
|
+
return PostgresTarget(url, prefix=prefix)
|
|
37
|
+
if scheme in ("mysql", "mariadb", "mysql+pymysql"):
|
|
38
|
+
from .mysql import MySQLTarget
|
|
39
|
+
|
|
40
|
+
return MySQLTarget(url, prefix=prefix)
|
|
41
|
+
if scheme in ("mongodb", "mongodb+srv"):
|
|
42
|
+
from .mongodb import MongoTarget
|
|
43
|
+
|
|
44
|
+
return MongoTarget(url, prefix=prefix)
|
|
45
|
+
if scheme in ("https", "http"):
|
|
46
|
+
from .webhook import WebhookTarget
|
|
47
|
+
|
|
48
|
+
return WebhookTarget(url)
|
|
49
|
+
raise ValueError(f"QAECHI_SINK_TARGET: unsupported scheme {scheme}:// "
|
|
50
|
+
"(use postgresql://, mysql://, mongodb:// or https://)")
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""MongoDB target: MongoDB 7+, MongoDB Atlas, Amazon DocumentDB.
|
|
2
|
+
|
|
3
|
+
QAECHI_SINK_TARGET=mongodb+srv://user:pass@cluster.example.net/qaechi
|
|
4
|
+
|
|
5
|
+
One document per job in {prefix}extractions, with `_id` = jobId and the values embedded.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import asdict
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ..record import SinkRecord
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MongoTarget:
|
|
18
|
+
name = "mongodb"
|
|
19
|
+
|
|
20
|
+
def __init__(self, url: str, *, prefix: str = "qaechi_") -> None:
|
|
21
|
+
try:
|
|
22
|
+
from pymongo import MongoClient
|
|
23
|
+
except ImportError as exc:
|
|
24
|
+
raise RuntimeError("a mongodb:// target needs: pip install 'qaechi-sink[mongodb]'") from exc
|
|
25
|
+
self._client: Any = MongoClient(url, tz_aware=True, appname="qaechi-sink")
|
|
26
|
+
self._col = self._client.get_default_database(default="qaechi")[f"{prefix}extractions"]
|
|
27
|
+
|
|
28
|
+
def prepare(self) -> None:
|
|
29
|
+
self._col.create_index([("document_id", 1), ("finished_at", -1)],
|
|
30
|
+
name="document_idx")
|
|
31
|
+
self._col.create_index([("values.path", 1)], name="value_path_idx")
|
|
32
|
+
|
|
33
|
+
def write(self, r: SinkRecord) -> None:
|
|
34
|
+
self._col.replace_one({"_id": r.job_id}, {
|
|
35
|
+
"document_id": r.document_id, "doc_type": r.doc_type, "status": r.status,
|
|
36
|
+
"result_id": r.result_id, "route": r.route, "groundedness": r.groundedness,
|
|
37
|
+
"error": r.error, "attempts": r.attempts, "finished_at": r.finished_at,
|
|
38
|
+
"extraction": r.extraction, "values": [asdict(v) for v in r.values],
|
|
39
|
+
"written_at": datetime.now(timezone.utc),
|
|
40
|
+
}, upsert=True)
|
|
41
|
+
|
|
42
|
+
def close(self) -> None:
|
|
43
|
+
self._client.close()
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""MySQL target: MySQL 8.4+, MariaDB 11+, Amazon Aurora MySQL.
|
|
2
|
+
|
|
3
|
+
QAECHI_SINK_TARGET=mysql://user:pass@host:3306/db (?ssl=true for managed services)
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from datetime import timezone
|
|
10
|
+
from typing import Any
|
|
11
|
+
from urllib.parse import parse_qs, unquote, urlsplit
|
|
12
|
+
|
|
13
|
+
from ..record import SinkRecord
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def connect_args(url: str) -> dict[str, Any]:
|
|
17
|
+
parts = urlsplit(url)
|
|
18
|
+
args: dict[str, Any] = {
|
|
19
|
+
"host": parts.hostname or "localhost", "port": parts.port or 3306,
|
|
20
|
+
"user": unquote(parts.username or ""), "password": unquote(parts.password or ""),
|
|
21
|
+
"database": parts.path.lstrip("/") or None, "charset": "utf8mb4", "autocommit": False,
|
|
22
|
+
}
|
|
23
|
+
query = {k: v[-1] for k, v in parse_qs(parts.query).items()}
|
|
24
|
+
if query.get("ssl", "").lower() in ("1", "true", "required", "require"):
|
|
25
|
+
args.update(ssl={"ca": None}, ssl_verify_cert=True, ssl_verify_identity=True)
|
|
26
|
+
return args
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MySQLTarget:
|
|
30
|
+
name = "mysql"
|
|
31
|
+
|
|
32
|
+
def __init__(self, url: str, *, prefix: str = "qaechi_") -> None:
|
|
33
|
+
try:
|
|
34
|
+
import pymysql
|
|
35
|
+
except ImportError as exc:
|
|
36
|
+
raise RuntimeError("a mysql:// target needs: pip install 'qaechi-sink[mysql]'") from exc
|
|
37
|
+
self._conn: Any = pymysql.connect(**connect_args(url))
|
|
38
|
+
self.t = f"{prefix}extractions"
|
|
39
|
+
self.v = f"{prefix}extraction_values"
|
|
40
|
+
|
|
41
|
+
def prepare(self) -> None:
|
|
42
|
+
with self._conn.cursor() as cur:
|
|
43
|
+
cur.execute("SELECT GET_LOCK('qaechi_sink_schema', 30)")
|
|
44
|
+
try:
|
|
45
|
+
cur.execute(f"""
|
|
46
|
+
CREATE TABLE IF NOT EXISTS {self.t} (
|
|
47
|
+
job_id VARCHAR(200) NOT NULL PRIMARY KEY,
|
|
48
|
+
document_id VARCHAR(200) NOT NULL,
|
|
49
|
+
doc_type VARCHAR(64) NOT NULL,
|
|
50
|
+
status VARCHAR(16) NOT NULL,
|
|
51
|
+
result_id VARCHAR(64),
|
|
52
|
+
route VARCHAR(16),
|
|
53
|
+
groundedness VARCHAR(16),
|
|
54
|
+
error TEXT,
|
|
55
|
+
attempts INT NOT NULL DEFAULT 0,
|
|
56
|
+
finished_at DATETIME(6),
|
|
57
|
+
extraction JSON,
|
|
58
|
+
written_at DATETIME(6) NOT NULL,
|
|
59
|
+
KEY {self.t}_document_idx (document_id, finished_at)
|
|
60
|
+
) CHARACTER SET utf8mb4""")
|
|
61
|
+
cur.execute(f"""
|
|
62
|
+
CREATE TABLE IF NOT EXISTS {self.v} (
|
|
63
|
+
job_id VARCHAR(200) NOT NULL,
|
|
64
|
+
path VARCHAR(255) NOT NULL,
|
|
65
|
+
label TEXT,
|
|
66
|
+
value_text TEXT,
|
|
67
|
+
value_number DOUBLE,
|
|
68
|
+
page INT,
|
|
69
|
+
quote TEXT,
|
|
70
|
+
confidence FLOAT NOT NULL,
|
|
71
|
+
verified BOOLEAN NOT NULL,
|
|
72
|
+
PRIMARY KEY (job_id, path),
|
|
73
|
+
CONSTRAINT {self.v}_job_fk FOREIGN KEY (job_id)
|
|
74
|
+
REFERENCES {self.t} (job_id) ON DELETE CASCADE
|
|
75
|
+
) CHARACTER SET utf8mb4""")
|
|
76
|
+
finally:
|
|
77
|
+
cur.execute("SELECT RELEASE_LOCK('qaechi_sink_schema')")
|
|
78
|
+
self._conn.commit()
|
|
79
|
+
|
|
80
|
+
def write(self, r: SinkRecord) -> None:
|
|
81
|
+
self._conn.ping(reconnect=True)
|
|
82
|
+
finished = (r.finished_at.astimezone(timezone.utc).replace(tzinfo=None)
|
|
83
|
+
if r.finished_at else None)
|
|
84
|
+
try:
|
|
85
|
+
with self._conn.cursor() as cur:
|
|
86
|
+
cur.execute(f"""
|
|
87
|
+
INSERT INTO {self.t} (job_id, document_id, doc_type, status, result_id, route,
|
|
88
|
+
groundedness, error, attempts, finished_at, extraction, written_at)
|
|
89
|
+
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(6))
|
|
90
|
+
ON DUPLICATE KEY UPDATE status = VALUES(status), result_id = VALUES(result_id),
|
|
91
|
+
route = VALUES(route), groundedness = VALUES(groundedness),
|
|
92
|
+
error = VALUES(error), attempts = VALUES(attempts),
|
|
93
|
+
finished_at = VALUES(finished_at), extraction = VALUES(extraction),
|
|
94
|
+
written_at = UTC_TIMESTAMP(6)""",
|
|
95
|
+
(r.job_id, r.document_id, r.doc_type, r.status, r.result_id, r.route,
|
|
96
|
+
r.groundedness, r.error, r.attempts, finished,
|
|
97
|
+
json.dumps(r.extraction, ensure_ascii=False) if r.extraction is not None else None))
|
|
98
|
+
cur.execute(f"DELETE FROM {self.v} WHERE job_id = %s", (r.job_id,))
|
|
99
|
+
if r.values:
|
|
100
|
+
cur.executemany(
|
|
101
|
+
f"INSERT INTO {self.v} (job_id, path, label, value_text, value_number, page, "
|
|
102
|
+
"quote, confidence, verified) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
|
103
|
+
[(r.job_id, v.path, v.label, v.value_text, v.value_number, v.page, v.quote,
|
|
104
|
+
v.confidence, v.verified) for v in r.values])
|
|
105
|
+
self._conn.commit()
|
|
106
|
+
except Exception:
|
|
107
|
+
self._conn.rollback()
|
|
108
|
+
raise
|
|
109
|
+
|
|
110
|
+
def close(self) -> None:
|
|
111
|
+
self._conn.close()
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""PostgreSQL target, including Supabase, Neon and managed PostgreSQL.
|
|
2
|
+
|
|
3
|
+
QAECHI_SINK_TARGET=postgresql://user:pass@host:5432/db?sslmode=require
|
|
4
|
+
|
|
5
|
+
Tables (prefix configurable): {prefix}extractions (one row per job) and
|
|
6
|
+
{prefix}extraction_values (one row per value, with page, quote and verified flag).
|
|
7
|
+
On Supabase, enable Row Level Security on both tables before exposing them through the API.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ..record import SinkRecord
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PostgresTarget:
|
|
18
|
+
name = "postgres"
|
|
19
|
+
|
|
20
|
+
def __init__(self, url: str, *, prefix: str = "qaechi_") -> None:
|
|
21
|
+
try:
|
|
22
|
+
import psycopg
|
|
23
|
+
from psycopg.types.json import Jsonb
|
|
24
|
+
except ImportError as exc:
|
|
25
|
+
raise RuntimeError("a postgresql:// target needs: pip install 'qaechi-sink[postgres]'") from exc
|
|
26
|
+
self._jsonb = Jsonb
|
|
27
|
+
# prepare_threshold=None keeps transaction-mode poolers (Supabase pooler, PgBouncer) working.
|
|
28
|
+
self._conn: Any = psycopg.connect(url, prepare_threshold=None)
|
|
29
|
+
self.t = f"{prefix}extractions"
|
|
30
|
+
self.v = f"{prefix}extraction_values"
|
|
31
|
+
|
|
32
|
+
def prepare(self) -> None:
|
|
33
|
+
with self._conn.transaction():
|
|
34
|
+
self._conn.execute("SELECT pg_advisory_xact_lock(hashtext('qaechi_sink_schema'))")
|
|
35
|
+
self._conn.execute(f"""
|
|
36
|
+
CREATE TABLE IF NOT EXISTS {self.t} (
|
|
37
|
+
job_id text PRIMARY KEY,
|
|
38
|
+
document_id text NOT NULL,
|
|
39
|
+
doc_type text NOT NULL,
|
|
40
|
+
status text NOT NULL,
|
|
41
|
+
result_id text,
|
|
42
|
+
route text,
|
|
43
|
+
groundedness text,
|
|
44
|
+
error text,
|
|
45
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
46
|
+
finished_at timestamptz,
|
|
47
|
+
extraction jsonb,
|
|
48
|
+
written_at timestamptz NOT NULL DEFAULT now()
|
|
49
|
+
)""")
|
|
50
|
+
self._conn.execute(f"""
|
|
51
|
+
CREATE INDEX IF NOT EXISTS {self.t}_document_idx
|
|
52
|
+
ON {self.t} (document_id, finished_at DESC)""")
|
|
53
|
+
self._conn.execute(f"""
|
|
54
|
+
CREATE TABLE IF NOT EXISTS {self.v} (
|
|
55
|
+
job_id text NOT NULL REFERENCES {self.t} (job_id) ON DELETE CASCADE,
|
|
56
|
+
path text NOT NULL,
|
|
57
|
+
label text,
|
|
58
|
+
value_text text,
|
|
59
|
+
value_number double precision,
|
|
60
|
+
page integer,
|
|
61
|
+
quote text,
|
|
62
|
+
confidence real NOT NULL,
|
|
63
|
+
verified boolean NOT NULL,
|
|
64
|
+
PRIMARY KEY (job_id, path)
|
|
65
|
+
)""")
|
|
66
|
+
|
|
67
|
+
def write(self, r: SinkRecord) -> None:
|
|
68
|
+
with self._conn.transaction():
|
|
69
|
+
self._conn.execute(f"""
|
|
70
|
+
INSERT INTO {self.t} (job_id, document_id, doc_type, status, result_id, route,
|
|
71
|
+
groundedness, error, attempts, finished_at, extraction)
|
|
72
|
+
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
|
73
|
+
ON CONFLICT (job_id) DO UPDATE SET
|
|
74
|
+
status = EXCLUDED.status, result_id = EXCLUDED.result_id,
|
|
75
|
+
route = EXCLUDED.route, groundedness = EXCLUDED.groundedness,
|
|
76
|
+
error = EXCLUDED.error, attempts = EXCLUDED.attempts,
|
|
77
|
+
finished_at = EXCLUDED.finished_at, extraction = EXCLUDED.extraction,
|
|
78
|
+
written_at = now()""",
|
|
79
|
+
(r.job_id, r.document_id, r.doc_type, r.status, r.result_id, r.route,
|
|
80
|
+
r.groundedness, r.error, r.attempts, r.finished_at,
|
|
81
|
+
self._jsonb(r.extraction) if r.extraction is not None else None))
|
|
82
|
+
self._conn.execute(f"DELETE FROM {self.v} WHERE job_id = %s", (r.job_id,))
|
|
83
|
+
if r.values:
|
|
84
|
+
with self._conn.cursor() as cur:
|
|
85
|
+
cur.executemany(
|
|
86
|
+
f"INSERT INTO {self.v} (job_id, path, label, value_text, value_number, "
|
|
87
|
+
"page, quote, confidence, verified) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
|
88
|
+
[(r.job_id, v.path, v.label, v.value_text, v.value_number, v.page, v.quote,
|
|
89
|
+
v.confidence, v.verified) for v in r.values])
|
|
90
|
+
|
|
91
|
+
def close(self) -> None:
|
|
92
|
+
self._conn.close()
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""HTTPS webhook target: POST one JSON body per finished job.
|
|
2
|
+
|
|
3
|
+
QAECHI_SINK_TARGET=https://api.example.com/hooks/qaechi
|
|
4
|
+
QAECHI_SINK_WEBHOOK_SECRET=... (strongly recommended)
|
|
5
|
+
|
|
6
|
+
Headers:
|
|
7
|
+
X-Qaechi-Signature: sha256=<hex HMAC-SHA256 of the raw body with the secret>
|
|
8
|
+
Idempotency-Key: <jobId> the same job may be delivered more than once; dedupe on it
|
|
9
|
+
traceparent: W3C trace context, when available
|
|
10
|
+
|
|
11
|
+
2xx = done. 408, 429 and 5xx are retried; other 4xx go to the sink DLQ.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import hmac
|
|
18
|
+
import json
|
|
19
|
+
from dataclasses import asdict
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from .. import config
|
|
23
|
+
from ..record import SinkRecord
|
|
24
|
+
|
|
25
|
+
RETRYABLE = {408, 425, 429}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PermanentError(RuntimeError):
|
|
29
|
+
"""The receiver rejected the record; retrying will not help."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def sign(body: bytes, secret: str) -> str:
|
|
33
|
+
return "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def body_for(r: SinkRecord) -> bytes:
|
|
37
|
+
return json.dumps({**r.summary(), "extraction": r.extraction,
|
|
38
|
+
"values": [asdict(v) for v in r.values]},
|
|
39
|
+
ensure_ascii=False, separators=(",", ":")).encode()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class WebhookTarget:
|
|
43
|
+
name = "webhook"
|
|
44
|
+
|
|
45
|
+
def __init__(self, url: str, *, secret: str | None = None, client: Any = None) -> None:
|
|
46
|
+
import httpx
|
|
47
|
+
|
|
48
|
+
if url.startswith("http://") and not url.startswith(("http://localhost", "http://127.0.0.1")):
|
|
49
|
+
raise ValueError("webhook targets must use https:// (http:// only for localhost)")
|
|
50
|
+
self.url = url
|
|
51
|
+
self.secret = secret if secret is not None else config.webhook_secret()
|
|
52
|
+
self._client = client or httpx.Client(timeout=30.0)
|
|
53
|
+
self.traceparent: str | None = None
|
|
54
|
+
|
|
55
|
+
def prepare(self) -> None:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
def write(self, r: SinkRecord) -> None:
|
|
59
|
+
body = body_for(r)
|
|
60
|
+
headers = {"Content-Type": "application/json", "Idempotency-Key": r.job_id,
|
|
61
|
+
"User-Agent": "qaechi-sink"}
|
|
62
|
+
if self.secret:
|
|
63
|
+
headers["X-Qaechi-Signature"] = sign(body, self.secret)
|
|
64
|
+
if self.traceparent:
|
|
65
|
+
headers["traceparent"] = self.traceparent
|
|
66
|
+
resp = self._client.post(self.url, content=body, headers=headers)
|
|
67
|
+
if resp.status_code < 300:
|
|
68
|
+
return
|
|
69
|
+
if resp.status_code in RETRYABLE or resp.status_code >= 500:
|
|
70
|
+
raise RuntimeError(f"webhook answered {resp.status_code}, will retry")
|
|
71
|
+
raise PermanentError(f"webhook rejected the record: {resp.status_code}")
|
|
72
|
+
|
|
73
|
+
def close(self) -> None:
|
|
74
|
+
self._client.close()
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qaechi-sink
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Load finished Qaechi jobs, values and evidence into PostgreSQL, Supabase, MySQL, MongoDB or a webhook.
|
|
5
|
+
Author: Taeyong Kang
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/qaechi/qaechi-sink
|
|
8
|
+
Project-URL: Documentation, https://qaechi.github.io/modules/
|
|
9
|
+
Project-URL: Issues, https://github.com/qaechi/qaechi-sink/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/qaechi/qaechi-sink/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: qaechi,kafka,sink,postgresql,supabase,mysql,mongodb,webhook
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: qaechi-contracts<2,>=1
|
|
23
|
+
Requires-Dist: httpx<1,>=0.29
|
|
24
|
+
Provides-Extra: kafka
|
|
25
|
+
Requires-Dist: confluent-kafka<3,>=2.16.2; extra == "kafka"
|
|
26
|
+
Provides-Extra: postgres
|
|
27
|
+
Requires-Dist: psycopg[binary]<4,>=3.3.9; extra == "postgres"
|
|
28
|
+
Provides-Extra: mysql
|
|
29
|
+
Requires-Dist: pymysql<2,>=1.2.4; extra == "mysql"
|
|
30
|
+
Provides-Extra: mongodb
|
|
31
|
+
Requires-Dist: pymongo<5,>=4.20.2; extra == "mongodb"
|
|
32
|
+
Requires-Dist: dnspython<3,>=2.9.2; extra == "mongodb"
|
|
33
|
+
Provides-Extra: all
|
|
34
|
+
Requires-Dist: qaechi-sink[kafka,mongodb,mysql,postgres]; extra == "all"
|
|
35
|
+
Provides-Extra: dev
|
|
36
|
+
Requires-Dist: qaechi-sink[all]; extra == "dev"
|
|
37
|
+
Requires-Dist: pytest<10,>=8; extra == "dev"
|
|
38
|
+
Requires-Dist: ruff==0.16.*; extra == "dev"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
# qaechi-sink
|
|
42
|
+
|
|
43
|
+
Load finished [Qaechi](https://qaechi.github.io/) jobs into the database you already run. The sink
|
|
44
|
+
consumes result events from Kafka, fetches the values with their evidence from the parser, and
|
|
45
|
+
writes them idempotently to **PostgreSQL** (Supabase, Neon, Amazon RDS), **MySQL** (MariaDB,
|
|
46
|
+
Aurora), **MongoDB** (Atlas, DocumentDB) or an **HTTPS webhook**.
|
|
47
|
+
|
|
48
|
+
[한국어](README.ko.md) | [How the modules fit together](https://qaechi.github.io/modules/)
|
|
49
|
+
|
|
50
|
+
```text
|
|
51
|
+
qaechi.parse.results ──▶ qaechi-sink ──GET /results/{id}──▶ qaechi-parser
|
|
52
|
+
│
|
|
53
|
+
└──upsert──▶ PostgreSQL | MySQL | MongoDB | https://your-app
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Run it
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install "qaechi-sink[kafka,postgres]" # or mysql, mongodb; the webhook needs no extra
|
|
60
|
+
|
|
61
|
+
export QAECHI_KAFKA_BOOTSTRAP_SERVERS=kafka:9092
|
|
62
|
+
export QAECHI_PARSER_URL=http://parser:3100
|
|
63
|
+
export QAECHI_INTERNAL_TOKEN=... # the parser's token
|
|
64
|
+
export QAECHI_SINK_TARGET=postgresql://app:secret@db:5432/app
|
|
65
|
+
|
|
66
|
+
qaechi-sink check # connect and create the tables
|
|
67
|
+
qaechi-sink run
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Run one or more replicas; they share the consumer group `qaechi-sink`.
|
|
71
|
+
|
|
72
|
+
## Targets
|
|
73
|
+
|
|
74
|
+
| `QAECHI_SINK_TARGET` | Extra | What is written |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| `postgresql://...` (Supabase: add `?sslmode=require`) | `postgres` | Tables `qaechi_extractions` and `qaechi_extraction_values` |
|
|
77
|
+
| `mysql://...` (`?ssl=true` for managed services) | `mysql` | The same two tables |
|
|
78
|
+
| `mongodb://...` or `mongodb+srv://...` | `mongodb` | Collection `qaechi_extractions`, one document per job with the values embedded |
|
|
79
|
+
| `https://...` | none | One signed `POST` per job |
|
|
80
|
+
|
|
81
|
+
Tables are created on first start (`qaechi-sink check` does it explicitly). Rename them with
|
|
82
|
+
`QAECHI_SINK_TABLE_PREFIX`. On Supabase, enable Row Level Security on both tables before exposing
|
|
83
|
+
them through the Supabase API.
|
|
84
|
+
|
|
85
|
+
### Tables
|
|
86
|
+
|
|
87
|
+
`qaechi_extractions`: one row per job, the latest outcome.
|
|
88
|
+
|
|
89
|
+
| Column | |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `job_id` | primary key |
|
|
92
|
+
| `document_id`, `doc_type` | what was parsed |
|
|
93
|
+
| `status` | `succeeded` or `failed` |
|
|
94
|
+
| `result_id`, `route`, `groundedness`, `error`, `attempts`, `finished_at` | from the result event |
|
|
95
|
+
| `extraction` | the full result as JSON, including notes and payload |
|
|
96
|
+
|
|
97
|
+
`qaechi_extraction_values`: one row per value, ready to query.
|
|
98
|
+
|
|
99
|
+
| Column | |
|
|
100
|
+
|---|---|
|
|
101
|
+
| `job_id`, `path` | primary key. `path` is `fields.total`, `lines[0].amount` or `total` |
|
|
102
|
+
| `label` | line label for `lines[i]` |
|
|
103
|
+
| `value_text`, `value_number` | the value; numbers also in `value_number` |
|
|
104
|
+
| `page`, `quote` | the evidence |
|
|
105
|
+
| `confidence`, `verified` | `verified` = it has a quote and the quote was found in the source |
|
|
106
|
+
|
|
107
|
+
```sql
|
|
108
|
+
-- Latest verified totals per document
|
|
109
|
+
SELECT e.document_id, v.value_number AS total, v.page, v.quote
|
|
110
|
+
FROM qaechi_extractions e JOIN qaechi_extraction_values v USING (job_id)
|
|
111
|
+
WHERE v.path = 'fields.total' AND v.verified AND e.status = 'succeeded';
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Webhook
|
|
115
|
+
|
|
116
|
+
Each job is one `POST` with the job summary, the full extraction and the flattened values.
|
|
117
|
+
|
|
118
|
+
| Header | |
|
|
119
|
+
|---|---|
|
|
120
|
+
| `X-Qaechi-Signature` | `sha256=` HMAC-SHA256 of the raw body with `QAECHI_SINK_WEBHOOK_SECRET`. Check it |
|
|
121
|
+
| `Idempotency-Key` | the job ID. A job can arrive more than once; deduplicate on it |
|
|
122
|
+
| `traceparent` | W3C trace context when available |
|
|
123
|
+
|
|
124
|
+
Answer `2xx` when stored. `408`, `429` and `5xx` are retried; other `4xx` go to the sink DLQ.
|
|
125
|
+
Only `https://` is accepted (`http://` only for localhost).
|
|
126
|
+
|
|
127
|
+
## Delivery
|
|
128
|
+
|
|
129
|
+
At least once, made safe by upserts: a redelivered event rewrites the same rows. A failed write is
|
|
130
|
+
retried with backoff (`QAECHI_SINK_MAX_RETRIES`, default 5) and then copied to `qaechi.sink.dlq`
|
|
131
|
+
with the reason in the `qaechi-error` header. The offset is committed only after the write or the
|
|
132
|
+
DLQ copy, so nothing is lost when the database is down.
|
|
133
|
+
|
|
134
|
+
## Settings
|
|
135
|
+
|
|
136
|
+
| Variable | Default | |
|
|
137
|
+
|---|---|---|
|
|
138
|
+
| `QAECHI_SINK_TARGET` | | where to write (required) |
|
|
139
|
+
| `QAECHI_KAFKA_BOOTSTRAP_SERVERS` | | brokers (required) |
|
|
140
|
+
| `QAECHI_PARSER_URL` | | parser API to fetch values from. Unset = status only |
|
|
141
|
+
| `QAECHI_INTERNAL_TOKEN` | | the parser's internal token |
|
|
142
|
+
| `QAECHI_SINK_INCLUDE_FAILED` | `true` | also record failed jobs |
|
|
143
|
+
| `QAECHI_SINK_TABLE_PREFIX` | `qaechi_` | table and collection prefix |
|
|
144
|
+
| `QAECHI_SINK_WEBHOOK_SECRET` | | HMAC key for webhook signatures |
|
|
145
|
+
| `QAECHI_SINK_MAX_RETRIES` | `5` | retries before the DLQ |
|
|
146
|
+
| `QAECHI_KAFKA_TOPIC_RESULTS` | `qaechi.parse.results` | |
|
|
147
|
+
| `QAECHI_SINK_TOPIC_DLQ` | `qaechi.sink.dlq` | |
|
|
148
|
+
| `QAECHI_SINK_GROUP_ID` | `qaechi-sink` | |
|
|
149
|
+
| `QAECHI_KAFKA_CONF_*` | | any librdkafka setting, e.g. SASL for Amazon MSK |
|
|
150
|
+
|
|
151
|
+
Another database? Implement the four-method `Target` protocol in `qaechi.sink.targets` and pass it
|
|
152
|
+
to `qaechi.sink.runner.run(target=...)`.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
qaechi/sink/__init__.py,sha256=aApPIcvhtm8XbMyZSEhj-s2fQ2eZoKkXZktq2lGQUFk,338
|
|
2
|
+
qaechi/sink/cli.py,sha256=WNv4vCp0uhjcHPxNM8GU1PqK7NIwiGhNqd14Sce27U0,1742
|
|
3
|
+
qaechi/sink/config.py,sha256=8NtjHUzqj6TVbnYMAYGBST6wZj_P0TESUoD0oXvGBak,2397
|
|
4
|
+
qaechi/sink/record.py,sha256=3vERXR19nvtNig4Pf-Sumj_jDZPVlE44BgYlxsDy_o8,3111
|
|
5
|
+
qaechi/sink/runner.py,sha256=DDXh5hjT2sDLfpGiot1Zzcho6lmgb1fFDkkLdU3wdWc,5995
|
|
6
|
+
qaechi/sink/targets/__init__.py,sha256=jOtvNbJdm14JqZvqG4Q7I-BOjeM7q7_tcBckRPN60go,1842
|
|
7
|
+
qaechi/sink/targets/mongodb.py,sha256=i0OTfJX631DsOuY2AAdYJxAxZnpJab8zXXbnFpPDpKg,1693
|
|
8
|
+
qaechi/sink/targets/mysql.py,sha256=OEDaJH1r5sMtLIC8fQziX_gYyORoaP1hhblP6GVswc0,5287
|
|
9
|
+
qaechi/sink/targets/postgres.py,sha256=IqUnd6wj0gh5q-TYZ5t1Lt_plC2fZvqrBFNIx6VX6Bs,4416
|
|
10
|
+
qaechi/sink/targets/webhook.py,sha256=vRrjUakVjV3ImV8d9QaF9cUdi1TTNqsDU9WPsX6y-Po,2624
|
|
11
|
+
qaechi_sink-1.0.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
|
|
12
|
+
qaechi_sink-1.0.0.dist-info/METADATA,sha256=xzJBnwAxsEpTBNg37rI6jtpcYbAYhH0KBv_BPNw4wQs,6606
|
|
13
|
+
qaechi_sink-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
14
|
+
qaechi_sink-1.0.0.dist-info/entry_points.txt,sha256=UqKf645pYVnETYNUCiAJQc5j0UL0xnVyope3DTqeSsM,53
|
|
15
|
+
qaechi_sink-1.0.0.dist-info/top_level.txt,sha256=uD_gOde0YCWlGMtrDzR5FuXld9uzJkwJnJtoXcvNScM,7
|
|
16
|
+
qaechi_sink-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
|