[STAGE2] Event envelope + outbox/inbox idempotency (100→1)
This commit is contained in:
1 parent
c1f9136bbe
commit
8f8ee4186e
6 files changed
+259
No files matched your search
@@ -0,0 +1,123 @@
|
||||
"""Stage 2 event fabric: CloudEvents outbox + idempotent inbox/effects.
|
||||
|
||||
This is the deterministic PostgreSQL core used before the NATS relay.
|
||||
It intentionally does not import NATS; the relay is a separate adapter.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg2
|
||||
from psycopg2.extras import Json
|
||||
|
||||
REQUIRED = ("specversion", "id", "source", "type", "time", "idempotency_key", "data")
|
||||
|
||||
|
||||
def connect():
|
||||
pw = os.getenv("PGPASSWORD")
|
||||
if not pw:
|
||||
pw = Path("/root/.pg-superuser-pass").read_text().strip()
|
||||
return psycopg2.connect(
|
||||
host=os.getenv("PGHOST", "192.168.1.151"),
|
||||
dbname=os.getenv("PGDATABASE", "rag"),
|
||||
user=os.getenv("PGUSER", "postgres"),
|
||||
password=pw,
|
||||
connect_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
def init(conn):
|
||||
sql = Path(__file__).with_name("schema.sql").read_text()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def event(event_id=None, source="buryans.test", type_="test.created",
|
||||
idempotency_key=None, data=None, subject=None, correlation_id=None):
|
||||
return {
|
||||
"specversion": "1.0",
|
||||
"id": event_id or str(uuid.uuid4()),
|
||||
"source": source,
|
||||
"type": type_,
|
||||
"subject": subject,
|
||||
"time": datetime.now(timezone.utc).isoformat(),
|
||||
"datacontenttype": "application/json",
|
||||
"idempotency_key": idempotency_key or str(uuid.uuid4()),
|
||||
"correlation_id": correlation_id or str(uuid.uuid4()),
|
||||
"data": data or {},
|
||||
}
|
||||
|
||||
|
||||
def validate(ev):
|
||||
missing = [k for k in REQUIRED if not ev.get(k)]
|
||||
if missing:
|
||||
raise ValueError("missing fields: " + ",".join(missing))
|
||||
if ev["specversion"] != "1.0":
|
||||
raise ValueError("specversion must be 1.0")
|
||||
return ev
|
||||
|
||||
|
||||
def enqueue(conn, ev):
|
||||
validate(ev)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.outbox
|
||||
(event_id, source, type, subject, time, idempotency_key,
|
||||
correlation_id, causation_id, payload)
|
||||
values (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
on conflict (idempotency_key) do nothing
|
||||
returning event_id
|
||||
""", (ev["id"], ev["source"], ev["type"], ev.get("subject"),
|
||||
ev["time"], ev["idempotency_key"], ev.get("correlation_id"),
|
||||
ev.get("causation_id"), Json(ev)))
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
def consume(conn, ev, consumer, effect_type, result=None):
|
||||
"""Transactionally process once. Returns True for first effect, False for duplicate."""
|
||||
validate(ev)
|
||||
with conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.inbox (consumer,event_id,idempotency_key,payload)
|
||||
values (%s,%s,%s,%s)
|
||||
on conflict (consumer,event_id) do nothing
|
||||
returning id
|
||||
""", (consumer, ev["id"], ev["idempotency_key"], Json(ev)))
|
||||
if cur.fetchone() is None:
|
||||
return False
|
||||
cur.execute("""
|
||||
insert into events.effects (idempotency_key,consumer,effect_type,result)
|
||||
values (%s,%s,%s,%s)
|
||||
on conflict (idempotency_key) do nothing
|
||||
""", (ev["idempotency_key"], consumer, effect_type, Json(result or {})))
|
||||
return True
|
||||
|
||||
|
||||
def repeat_test(n=100):
|
||||
conn = connect()
|
||||
init(conn)
|
||||
ev = event(idempotency_key="repeat-test", data={"n": 0})
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("delete from events.outbox where idempotency_key=%s", ("repeat-test",))
|
||||
cur.execute("delete from events.inbox where event_id=%s", (ev["id"],))
|
||||
cur.execute("delete from events.effects where idempotency_key=%s", ("repeat-test",))
|
||||
conn.commit()
|
||||
first = 0
|
||||
for _ in range(n):
|
||||
if consume(conn, ev, "repeat-test", "counted", {"ok": True}):
|
||||
first += 1
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select count(*) from events.effects where idempotency_key=%s", ("repeat-test",))
|
||||
effects = cur.fetchone()[0]
|
||||
conn.close()
|
||||
return {"workers": n, "first_effects": first, "effects": effects}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(repeat_test(), ensure_ascii=False))
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Stage 2 event fabric: outbox/inbox/effects
|
||||
CREATE SCHEMA IF NOT EXISTS events;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.outbox (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
event_id text NOT NULL UNIQUE,
|
||||
specversion text NOT NULL DEFAULT '1.0',
|
||||
source text NOT NULL,
|
||||
type text NOT NULL,
|
||||
subject text,
|
||||
time timestamptz NOT NULL,
|
||||
datacontenttype text NOT NULL DEFAULT 'application/json',
|
||||
idempotency_key text NOT NULL UNIQUE,
|
||||
correlation_id text,
|
||||
causation_id text,
|
||||
payload jsonb NOT NULL,
|
||||
status text NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending','published','failed')),
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
published_at timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS outbox_pending_idx
|
||||
ON events.outbox (status, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.inbox (
|
||||
id bigserial PRIMARY KEY,
|
||||
consumer text NOT NULL,
|
||||
event_id text NOT NULL,
|
||||
idempotency_key text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
status text NOT NULL DEFAULT 'processed'
|
||||
CHECK (status IN ('processed','failed')),
|
||||
received_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (consumer, event_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS inbox_key_idx
|
||||
ON events.inbox (idempotency_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.effects (
|
||||
idempotency_key text PRIMARY KEY,
|
||||
consumer text NOT NULL,
|
||||
effect_type text NOT NULL,
|
||||
result jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from event_store import repeat_test
|
||||
|
||||
|
||||
def test_repeat_100_one_effect():
|
||||
r = repeat_test(100)
|
||||
assert r["workers"] == 100
|
||||
assert r["first_effects"] == 1
|
||||
assert r["effects"] == 1
|
||||
Reference in new issue
Block a user