104 lines
3.1 KiB
Python
104 lines
3.1 KiB
Python
"""NATS JetStream relay for the Stage 2 event fabric.
|
|
|
|
Run with a Python that has nats-py (see requirements.txt).
|
|
"""
|
|
import asyncio
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import nats
|
|
from nats.js.api import StreamConfig
|
|
|
|
from event_store import connect, consume, init
|
|
|
|
NATS_URL = os.getenv("NATS_URL", "nats://192.168.1.115:4222")
|
|
STREAM = os.getenv("EVENTS_STREAM", "BURYANS_EVENTS")
|
|
SUBJECT = "buryans.events.>"
|
|
SUBJECT_PREFIX = "buryans.events."
|
|
CONSUMER = os.getenv("EVENTS_CONSUMER", "buryans-worker")
|
|
|
|
|
|
async def connect_js():
|
|
nc = await nats.connect(NATS_URL, connect_timeout=5)
|
|
js = nc.jetstream()
|
|
try:
|
|
await js.stream_info(STREAM)
|
|
except Exception:
|
|
await js.add_stream(name=STREAM, subjects=[SUBJECT], storage="file")
|
|
return nc, js
|
|
|
|
|
|
async def relay_once(limit=50):
|
|
conn = connect()
|
|
init(conn)
|
|
nc, js = await connect_js()
|
|
sent = 0
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("""
|
|
select id,event_id,type,payload
|
|
from events.outbox
|
|
where status='pending'
|
|
order by created_at
|
|
limit %s
|
|
""", (limit,))
|
|
rows = cur.fetchall()
|
|
for rid, event_id, etype, payload in rows:
|
|
subject = SUBJECT_PREFIX + etype
|
|
try:
|
|
await js.publish(subject, json.dumps(payload, ensure_ascii=False).encode())
|
|
with conn.cursor() as cur:
|
|
cur.execute("""
|
|
update events.outbox
|
|
set status='published', published_at=now(), attempts=attempts+1
|
|
where id=%s
|
|
""", (rid,))
|
|
conn.commit()
|
|
sent += 1
|
|
except Exception as e:
|
|
with conn.cursor() as cur:
|
|
cur.execute("""
|
|
update events.outbox
|
|
set status='failed', attempts=attempts+1, last_error=%s
|
|
where id=%s
|
|
""", (str(e)[:300], rid))
|
|
conn.commit()
|
|
raise
|
|
finally:
|
|
await nc.close()
|
|
conn.close()
|
|
return sent
|
|
|
|
|
|
async def consume_once(timeout=5):
|
|
conn = connect()
|
|
init(conn)
|
|
nc, js = await connect_js()
|
|
processed = 0
|
|
try:
|
|
sub = await js.pull_subscribe(SUBJECT, CONSUMER, stream=STREAM)
|
|
msgs = await sub.fetch(10, timeout=timeout)
|
|
for m in msgs:
|
|
ev = json.loads(m.data.decode())
|
|
first = consume(conn, ev, CONSUMER, "event_observed", {"subject": m.subject})
|
|
await m.ack()
|
|
processed += 1 if first else 0
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
await nc.close()
|
|
conn.close()
|
|
return processed
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
action = sys.argv[1] if len(sys.argv) > 1 else "relay"
|
|
if action == "relay":
|
|
print(json.dumps({"relayed": asyncio.run(relay_once())}))
|
|
elif action == "consume":
|
|
print(json.dumps({"processed": asyncio.run(consume_once())}))
|
|
else:
|
|
raise SystemExit("usage: nats_relay.py relay|consume")
|