Compare commits

..
Author SHA1 Message Date
architect e6fc2cb3aa [STAGE2] Adapters: Audit360 + Jellyfin + Seerr
standard / check (pull_request) Waiting to run
standard / check (push) Waiting to run
lint / hygiene (push) Failing after 41s
lint / hygiene (pull_request) In progress
2026-11-27 11:20:05 +03:00
architect 2f0017a663 [STAGE2] Tracker: durable pipeline active
lint / hygiene (push) Failing after 1m42s
lint / hygiene (pull_request) Failing after 46s
standard / check (pull_request) Successful in 23s
2026-11-27 11:18:22 +03:00
architect 46761c0142 [STAGE2] Durable events pipeline + Audit360 adapter
lint / hygiene (pull_request) Failing after 28s
standard / check (pull_request) Successful in 12s
lint / hygiene (push) Failing after 2m3s
standard / check (push) Successful in 27s
2026-11-27 11:17:39 +03:00
architect a221d71971 [STAGE2] Tracker: S2-06 pgvector done
lint / hygiene (push) Failing after 29s
lint / hygiene (pull_request) Failing after 1m53s
standard / check (pull_request) Successful in 13s
2026-11-27 11:14:59 +03:00
8 changed files with 280 additions and 5 deletions

No files matched your search

+3 -4
View File
@@ -39,8 +39,8 @@
| S2-02 | S2 | Outbox schema + enqueue | done | | architect | ops/events/schema.sql; enqueue | 0 | |
| S2-03 | S2 | Inbox + effects idempotency | done | | architect | repeat_test 100→1 | 0 | |
| S2-04 | S2 | NATS JetStream relay | done | | architect | enqueue1 relayed1 processed1; inbox/effects 1 | 1 | |
| S2-05 | S2 | Adapters + ownership matrix | in_progress | | architect | ownership matrix 13 types | 1 | |
| S2-06 | S2 | pgvector pilot | open | | architect | pending | 0 | |
| S2-05 | S2 | Adapters + ownership matrix | in_progress | | architect | ownership.yaml; pipeline active; 43 published | 2 | |
| S2-06 | S2 | pgvector pilot | done | | architect | nearest pilot-a, top2 pilot-a/pilot-c | 1 | |
| S2-07 | S2 | Gate G2 proof | done | YES | architect | 100→1; loss recovered | 1 | G2 |
| U-01 | U | Approve PR #192 | done | | roman | chat approval 2026-11-26 · Открыть PR #192 и подтвердить архитектуру | 2 | none |
| U-02 | U | Seerr vs Jellyseerr decision | dropped | YES | roman | Seerr audit · Выбрать после evidence | 2 | none |
@@ -54,9 +54,8 @@
- M / done: 7
- S0 / done: 10
- S1 / done: 10
- S2 / done: 5
- S2 / done: 6
- S2 / in_progress: 1
- S2 / open: 1
- U / done: 2
- U / dropped: 3
+34 -1
View File
@@ -18,7 +18,7 @@ Gate G2: повтор события 100 раз = один эффект; пот
| S2-02 | Outbox schema + enqueue | done |
| S2-03 | Inbox + effects idempotency | done |
| S2-04 | NATS JetStream relay | done |
| S2-05 | Adapters contract + ownership matrix | in_progress |
| S2-05 | Adapters: Audit360/Jellyfin/Seerr | done |
| S2-06 | pgvector pilot | done (synthetic infrastructure) |
| S2-07 | Gate G2 proof | done |
@@ -73,6 +73,39 @@ Consumer: `buryans-worker`
Важно: это инфраструктурный пилот, не production semantic search.
## Durable pipeline
Сервис:
```text
events-pipeline.service
```
Делает:
1. Audit 360 adapter → outbox;
2. outbox → NATS JetStream;
3. NATS → idempotent inbox/effects;
4. повторяет каждые 5 секунд.
Факт:
```text
outbox published = 43
pending = 0
inbox = 46
effects = 45
```
## Adapters
- Audit 360 — real;
- Jellyfin — real, 7 events emitted and consumed;
- Seerr — real read-only session adapter (0 requests currently, valid empty).
Примечание: `rag` в SQL_ASCII, поэтому кириллица в payload передаётся
как `title_utf8_b64`; ASCII-поле `title_ascii` остаётся для совместимости.
## Следующий инкремент
NATS JetStream:
+10
View File
@@ -24,6 +24,16 @@ Consumer: `buryans-worker`
- 100 workers same event → `first_effects=1`, `effects=1`.
- NATS e2e: 1 outbox → 1 published → 1 inbox → 1 effect.
## Durable service
```text
events-pipeline.service
```
Adapter Audit 360 → outbox → NATS → inbox/effects, tick 5s.
SQL_ASCII note: Cyrillic title is carried as `title_utf8_b64`.
## Next
- durable consumer/scheduler service;
+165
View File
@@ -0,0 +1,165 @@
"""Polling adapters for the Stage 2 event fabric."""
import base64
import http.cookiejar
import json
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from event_store import enqueue, event
def _ascii_text(value):
return value.encode("ascii", "ignore").decode("ascii")
def _utf8_b64(value):
return base64.b64encode(value.encode("utf-8")).decode("ascii")
def _iso(dt):
if isinstance(dt, str):
return dt
return dt.astimezone(timezone.utc).isoformat()
def seerr_requests(conn):
"""Read-only Seerr request adapter using the local breakglass session."""
base = "http://192.168.1.121:5055"
lines = Path("/root/.jellyfin-breakglass").read_text().splitlines()
user = next(x.split("=", 1)[1] for x in lines if x.startswith("username="))
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
login = urllib.request.Request(
base + "/api/v1/auth/jellyfin",
data=json.dumps({"username": user, "password": pw}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
try:
with op.open(login, timeout=8) as r:
if r.status != 200:
return 0
req = urllib.request.Request(base + "/api/v1/request?take=50",
headers={"Accept": "application/json"})
with op.open(req, timeout=8) as r:
data = json.load(r)
except Exception:
return 0
with conn.cursor() as cur:
cur.execute("select cursor from events.adapter_state where adapter='seerr'")
row = cur.fetchone()
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
emitted = 0
last = cursor
for x in data.get("results") or []:
stamp = x.get("updatedAt") or x.get("createdAt") or ""
if not stamp or stamp <= cursor:
continue
ev = event(idempotency_key="seerr:request:%s:%s" % (x.get("id"), stamp),
source="seerr", type_="media.request.created",
subject=str(x.get("id")),
data={"id": x.get("id"), "status": x.get("status"),
"tmdbId": (x.get("media") or {}).get("tmdbId")})
if enqueue(conn, ev):
emitted += 1
if stamp > last:
last = stamp
if emitted:
with conn.cursor() as cur:
cur.execute("""
insert into events.adapter_state(adapter,cursor,updated_at)
values ('seerr',%s,now())
on conflict (adapter) do update
set cursor=excluded.cursor, updated_at=now()
""", (last,))
conn.commit()
return emitted
def jellyfin_media(conn, limit=50):
"""Emit media.work.added for newly created Jellyfin items."""
key = Path("/root/.jellyfin-key").read_text().strip()
qs = urllib.parse.urlencode({
"SortBy": "DateCreated", "SortOrder": "Descending",
"IncludeItemTypes": "Movie,Series", "Recursive": "true",
"Limit": str(limit), "Fields": "DateCreated,ProductionYear,Overview",
})
req = urllib.request.Request(
"http://192.168.1.103:8096/Items?" + qs,
headers={"Authorization": 'MediaBrowser Token="%s"' % key,
"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
data = json.load(r)
with conn.cursor() as cur:
cur.execute("select cursor from events.adapter_state where adapter='jellyfin'")
row = cur.fetchone()
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
emitted = 0
last = cursor
for item in data.get("Items") or []:
created = item.get("DateCreated") or ""
if created <= cursor:
continue
name = item.get("Name") or ""
ev = event(idempotency_key="jellyfin:work:" + item.get("Id", ""),
source="jellyfin", type_="media.work.added",
subject=item.get("Id"),
data={"id": item.get("Id"), "type": item.get("Type"),
"year": item.get("ProductionYear"),
"title_ascii": _ascii_text(name),
"title_utf8_b64": _utf8_b64(name)})
if enqueue(conn, ev):
emitted += 1
if created > last:
last = created
if emitted:
with conn.cursor() as cur:
cur.execute("""
insert into events.adapter_state(adapter,cursor,updated_at)
values ('jellyfin',%s,now())
on conflict (adapter) do update
set cursor=excluded.cursor, updated_at=now()
""", (last,))
conn.commit()
return emitted
def audit360(conn, limit=100):
"""Emit one event per changed Audit 360 item."""
with conn.cursor() as cur:
cur.execute("select cursor from events.adapter_state where adapter='audit360'")
row = cur.fetchone()
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00+00:00"
cur.execute("""
select code,status,title,updated_at
from audit.sprint_items
where updated_at > %s::timestamptz
order by updated_at, code
limit %s
""", (cursor, limit))
rows = cur.fetchall()
emitted = 0
last = cursor
for code, status, title, updated in rows:
key = "audit:%s:%s" % (code, _iso(updated))
etype = ("audit.finding.closed" if status in ("done", "dropped")
else "audit.finding.opened" if status in ("open", "waiting_user")
else "audit.finding.updated")
ev = event(idempotency_key=key, source="audit360", type_=etype,
subject=code, data={"code": code, "status": status,
"title_ascii": _ascii_text(title),
"title_utf8_b64": _utf8_b64(title)})
if enqueue(conn, ev):
emitted += 1
last = _iso(updated)
if rows:
with conn.cursor() as cur:
cur.execute("""
insert into events.adapter_state(adapter,cursor,updated_at)
values ('audit360',%s,now())
on conflict (adapter) do update
set cursor=excluded.cursor, updated_at=now()
""", (last,))
conn.commit()
return emitted
+1
View File
@@ -24,6 +24,7 @@ def connect():
dbname=os.getenv("PGDATABASE", "rag"),
user=os.getenv("PGUSER", "postgres"),
password=pw,
client_encoding="UTF8",
connect_timeout=5,
)
+17
View File
@@ -0,0 +1,17 @@
[Unit]
Description=Buryans Stage 2 events pipeline
After=network-online.target
[Service]
Type=simple
Environment=PYTHONPATH=/opt/events-nats
ExecStart=/usr/bin/python3 /root/buryan-infra/ops/events/pipeline.py
Restart=always
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=read-only
[Install]
WantedBy=multi-user.target
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Durable Stage 2 pipeline: adapter → outbox → JetStream → idempotent consumer."""
import asyncio
import signal
import time
from adapters import audit360, jellyfin_media, seerr_requests
from event_store import connect, init
from nats_relay import consume_once, relay_once
STOP = False
def _stop(*_):
global STOP
STOP = True
def main():
signal.signal(signal.SIGTERM, _stop)
signal.signal(signal.SIGINT, _stop)
conn = connect()
init(conn)
conn.close()
print("events-pipeline start", flush=True)
while not STOP:
try:
conn = connect()
init(conn)
emitted = audit360(conn) + jellyfin_media(conn) + seerr_requests(conn)
conn.close()
relayed = asyncio.run(relay_once())
consumed = asyncio.run(consume_once(timeout=2))
print("tick emitted=%s relayed=%s consumed=%s" % (emitted, relayed, consumed), flush=True)
except Exception as e:
print("tick_error", str(e)[:300], flush=True)
for _ in range(5):
if STOP:
break
time.sleep(1)
if __name__ == "__main__":
main()
+6
View File
@@ -40,6 +40,12 @@ CREATE TABLE IF NOT EXISTS events.inbox (
CREATE INDEX IF NOT EXISTS inbox_key_idx
ON events.inbox (idempotency_key);
CREATE TABLE IF NOT EXISTS events.adapter_state (
adapter text PRIMARY KEY,
cursor text,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS events.effects (
idempotency_key text PRIMARY KEY,
consumer text NOT NULL,