226 lines
8.7 KiB
Python
226 lines
8.7 KiB
Python
"""
|
|
Transactional Outbox Worker & Scheduled Upload Cleanup:
|
|
Processes DUPLICATE_CHECK, HIS_CREATE (with reconcileRegistration on timeout),
|
|
and EMAIL_CONFIRMATION events outside the HTTP intake transaction.
|
|
Run continuously (`python worker.py`) or once (`python worker.py --once`).
|
|
"""
|
|
|
|
import argparse
|
|
import logging
|
|
import os
|
|
import signal
|
|
import time
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import db
|
|
from email_service import send_confirmation_email
|
|
from his_adapter import BaseHISAdapter, get_his_adapter
|
|
|
|
logger = logging.getLogger("dmh.worker")
|
|
_STOP = False
|
|
|
|
|
|
def _utcnow() -> datetime:
|
|
return datetime.now(timezone.utc).replace(tzinfo=None)
|
|
|
|
|
|
def process_outbox_event(cur, event: dict, his_adapter: BaseHISAdapter) -> None:
|
|
reg_id = event["registration_id"]
|
|
ev_type = event["event_type"]
|
|
corr_id = event["correlation_id"]
|
|
|
|
cur.execute("SELECT * FROM patient_registration WHERE id = %s", (reg_id,))
|
|
reg = cur.fetchone()
|
|
if not reg:
|
|
cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],))
|
|
return
|
|
|
|
if ev_type == "DUPLICATE_CHECK":
|
|
if reg["status"] == "SUBMITTED":
|
|
db.transition_registration_status(cur, reg_id, "CHECKING_DUPLICATES", "OUTBOX_WORKER", correlation_id=corr_id)
|
|
cur.execute(
|
|
"SELECT match_token FROM patient_identifiers WHERE reference_form_id = %s AND match_token IS NOT NULL",
|
|
(reg["reference_form_id"],),
|
|
)
|
|
tokens = [r["match_token"] for r in cur.fetchall()]
|
|
res = his_adapter.search_patient(
|
|
match_tokens=tokens,
|
|
fname=reg["fname"],
|
|
lname=reg["lname"],
|
|
dob=str(reg["dob"]),
|
|
mobile=reg["cell_phone"],
|
|
)
|
|
if res.outcome == "CANDIDATE":
|
|
db.transition_registration_status(
|
|
cur, reg_id, "PENDING_REVIEW", "OUTBOX_WORKER",
|
|
reason=res.reason or "Possible HIS duplicate", correlation_id=corr_id,
|
|
)
|
|
elif res.outcome == "NONE":
|
|
db.transition_registration_status(cur, reg_id, "PENDING_HIS_SYNC", "OUTBOX_WORKER", correlation_id=corr_id)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO outbox_events (id, registration_id, event_type, status, correlation_id)
|
|
VALUES (%s, %s, 'HIS_CREATE', 'PENDING', %s)
|
|
""",
|
|
(str(uuid.uuid4()), reg_id, corr_id),
|
|
)
|
|
else:
|
|
raise RuntimeError(res.reason or "HIS search error")
|
|
cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],))
|
|
|
|
elif ev_type == "HIS_CREATE":
|
|
create_res = his_adapter.create_patient(correlation_id=corr_id, payload=reg)
|
|
if create_res.outcome == "SUCCESS" and create_res.uhid:
|
|
db.transition_registration_status(
|
|
cur, reg_id, "REGISTERED", "OUTBOX_WORKER",
|
|
hospital_patient_id=create_res.uhid, correlation_id=corr_id,
|
|
)
|
|
cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],))
|
|
elif create_res.outcome == "TIMEOUT":
|
|
rec = his_adapter.reconcile_registration(correlation_id=corr_id, reference_form_id=reg["reference_form_id"])
|
|
if rec.outcome == "FOUND" and rec.uhid:
|
|
db.transition_registration_status(
|
|
cur, reg_id, "REGISTERED", "OUTBOX_WORKER",
|
|
hospital_patient_id=rec.uhid, reason="Reconciled after timeout", correlation_id=corr_id,
|
|
)
|
|
cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],))
|
|
elif rec.outcome == "ABSENT":
|
|
raise RuntimeError("HIS timeout reconciled as absent; safe to retry")
|
|
else:
|
|
db.transition_registration_status(
|
|
cur, reg_id, "SYNC_FAILED", "OUTBOX_WORKER",
|
|
reason=rec.reason or "Unresolved HIS timeout", correlation_id=corr_id,
|
|
)
|
|
cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],))
|
|
else:
|
|
db.transition_registration_status(
|
|
cur, reg_id, "SYNC_FAILED", "OUTBOX_WORKER",
|
|
reason=create_res.reason or "HIS rejected patient creation", correlation_id=corr_id,
|
|
)
|
|
cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],))
|
|
|
|
elif ev_type == "EMAIL_CONFIRMATION":
|
|
try:
|
|
send_confirmation_email(
|
|
to_email=reg["email"],
|
|
reference_form_id=reg["reference_form_id"],
|
|
status=reg["status"],
|
|
)
|
|
cur.execute("UPDATE patient_registration SET email_status = 'SENT' WHERE id = %s", (reg_id,))
|
|
cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],))
|
|
except Exception as exc:
|
|
cur.execute("UPDATE patient_registration SET email_status = 'FAILED' WHERE id = %s", (reg_id,))
|
|
raise RuntimeError(f"Email delivery failed: {exc}") from exc
|
|
|
|
|
|
def cleanup_expired_uploads(upload_root: str) -> int:
|
|
"""Delete expired unattached staged uploads from DB and disk."""
|
|
removed = 0
|
|
conn = db.get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
now = _utcnow()
|
|
cur.execute(
|
|
"SELECT id, storage_key FROM patient_documents WHERE patient_id IS NULL AND expires_at < %s LIMIT 100 FOR UPDATE",
|
|
(now,),
|
|
)
|
|
rows = cur.fetchall()
|
|
for r in rows:
|
|
path = os.path.join(upload_root, r["storage_key"])
|
|
if os.path.exists(path):
|
|
try:
|
|
os.remove(path)
|
|
except OSError:
|
|
pass
|
|
cur.execute("DELETE FROM patient_documents WHERE id = %s", (r["id"],))
|
|
removed += 1
|
|
conn.commit()
|
|
except Exception:
|
|
conn.rollback()
|
|
raise
|
|
finally:
|
|
conn.close()
|
|
return removed
|
|
|
|
|
|
def run_once(his_adapter: BaseHISAdapter | None = None, batch_size: int = 10) -> int:
|
|
"""Process one batch of pending outbox events."""
|
|
adapter = his_adapter or get_his_adapter()
|
|
processed = 0
|
|
conn = db.get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
now = _utcnow()
|
|
cur.execute(
|
|
"""
|
|
SELECT * FROM outbox_events
|
|
WHERE status = 'PENDING' AND next_run_at <= %s
|
|
ORDER BY created_at ASC
|
|
LIMIT %s
|
|
FOR UPDATE SKIP LOCKED
|
|
""",
|
|
(now, batch_size),
|
|
)
|
|
events = cur.fetchall()
|
|
for ev in events:
|
|
try:
|
|
process_outbox_event(cur, ev, adapter)
|
|
processed += 1
|
|
except Exception as exc:
|
|
attempts = ev["attempts"] + 1
|
|
status = "FAILED" if attempts >= 5 else "PENDING"
|
|
backoff = now + timedelta(seconds=min(300, 2 ** attempts * 5))
|
|
cur.execute(
|
|
"""
|
|
UPDATE outbox_events
|
|
SET status = %s, attempts = %s, next_run_at = %s, last_error = %s
|
|
WHERE id = %s
|
|
""",
|
|
(status, attempts, backoff, str(exc)[:490], ev["id"]),
|
|
)
|
|
conn.commit()
|
|
except Exception:
|
|
conn.rollback()
|
|
raise
|
|
finally:
|
|
conn.close()
|
|
return processed
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="DMH Outbox Worker")
|
|
parser.add_argument("--once", action="store_true", help="Process one batch and exit")
|
|
args = parser.parse_args()
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
upload_root = os.getenv("UPLOAD_FOLDER", "uploads")
|
|
poll_sec = float(os.getenv("WORKER_POLL_INTERVAL", "5"))
|
|
|
|
def _handle_sig(_sig, _frame):
|
|
global _STOP
|
|
_STOP = True
|
|
|
|
signal.signal(signal.SIGINT, _handle_sig)
|
|
signal.signal(signal.SIGTERM, _handle_sig)
|
|
|
|
adapter = get_his_adapter()
|
|
if args.once:
|
|
count = run_once(adapter)
|
|
cleaned = cleanup_expired_uploads(upload_root)
|
|
logger.info("Processed %d outbox events, cleaned %d expired uploads.", count, cleaned)
|
|
return
|
|
|
|
logger.info("Starting DMH outbox worker (poll=%ss, mode=%s)", poll_sec, os.getenv("HIS_MODE", "disabled"))
|
|
while not _STOP:
|
|
try:
|
|
run_once(adapter)
|
|
cleanup_expired_uploads(upload_root)
|
|
except Exception as exc:
|
|
logger.error("Worker iteration error: %s", exc)
|
|
time.sleep(poll_sec)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|