Download src/api/p2p.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/api/p2p.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/api/p2p.py
-
curl -L -o p2p.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/api/p2p.py
13.3 kB
| """ | |
| YAZ Platform — P2P Sync API (Sprint 69) | |
| SSE event stream + case event broadcast for P2P case synchronisation. | |
| Integrates with the GunDB relay (docker profile: p2p) via the /gun nginx proxy. | |
| Endpoints: | |
| GET /api/v1/p2p/stream — SSE stream for real-time case events | |
| POST /api/v1/p2p/case-event — Publish a case event (auth required) | |
| GET /api/v1/p2p/status — P2P relay health check | |
| Architecture: | |
| Browser ──[SSE]──► /api/v1/p2p/stream ──[asyncio queue]──► all subscribers | |
| Browser ──[POST]─► /api/v1/p2p/case-event ─────────────────────────────────► | |
| Browser ──[JS]───► GunDB relay at /gun ─────────────────────────────────────► | |
| SC-1 Conflict resolution (CRDT-style): | |
| Each event carries: | |
| - vector_clock: {actor_id: sequence_number} ← monotonic per actor | |
| - actor_hash: sha256 of (actor_id + event_type + entity_id + ts) | |
| On conflict (same entity, overlapping clocks): last-write-wins by | |
| server_ts (UTC), with the loser's actor_hash appended to conflict_log. | |
| PHI: NONE — events carry entity IDs and event types only, never patient data. | |
| Sprint: 69 (P2P-2, SC-1) | Perf: <50ms publish, streaming SSE | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import hashlib | |
| import json | |
| import os | |
| import time | |
| from datetime import UTC, datetime, timezone | |
| from typing import Any, Optional | |
| from uuid import UUID, uuid4 | |
| import structlog | |
| from fastapi import APIRouter, Depends, HTTPException, Request, status | |
| from fastapi.responses import StreamingResponse | |
| from pydantic import BaseModel, Field | |
| from auth.dependencies import get_current_user | |
| from shared.models.user import User | |
| logger = structlog.get_logger(__name__) | |
| router = APIRouter(prefix="/api/v1/p2p", tags=["P2P Sync"]) | |
| # ── In-process event bus ─────────────────────────────────────────────────── | |
| # Maps channel_key → list of asyncio.Queue subscribers. | |
| # channel_key = tenant_id (case events are tenant-scoped — isolation preserved) | |
| _subscribers: dict[str, list[asyncio.Queue]] = {} | |
| _sub_lock = asyncio.Lock() | |
| # ── SC-1: In-memory conflict log (ring buffer, max 500) ────────────────── | |
| _conflict_log: list[dict] = [] | |
| _CONFLICT_LOG_MAX = 500 | |
| # ── P2P enabled guard ───────────────────────────────────────────────────── | |
| _P2P_ENABLED = os.environ.get("YAZ_P2P_ENABLED", "").lower() in ("1", "true", "yes") | |
| def _check_p2p_enabled() -> None: | |
| if not _P2P_ENABLED: | |
| raise HTTPException( | |
| status_code=503, | |
| detail="P2P sync is not enabled on this node. Set YAZ_P2P_ENABLED=true.", | |
| ) | |
| # ── Schemas ────────────────────────────────────────────────────────────── | |
| class CaseEventPublish(BaseModel): | |
| """ | |
| P2P case event published by an authenticated actor. | |
| Sprint: 69 (P2P-2) | PHI: NONE | |
| """ | |
| event_type: str = Field( | |
| ..., | |
| min_length=3, | |
| max_length=64, | |
| description="Domain event type e.g. case.updated, checklist.completed", | |
| json_schema_extra={"example": "case.status_changed"}, | |
| ) | |
| entity_id: UUID = Field(..., description="Case or entity UUID affected") | |
| entity_type: str = Field( | |
| default="case", | |
| max_length=32, | |
| description="Entity kind: case, checklist, annotation, protocol", | |
| ) | |
| payload: dict = Field( | |
| default_factory=dict, | |
| description="Non-PHI event payload (status, field names, counts — never patient data)", | |
| ) | |
| vector_clock: dict[str, int] = Field( | |
| default_factory=dict, | |
| description="SC-1: CRDT vector clock {actor_id: seq}", | |
| ) | |
| class CaseEventEnvelope(BaseModel): | |
| """Full event envelope stored in the event bus.""" | |
| event_id: str | |
| event_type: str | |
| entity_id: str | |
| entity_type: str | |
| actor_id: str | |
| tenant_id: str | |
| payload: dict | |
| vector_clock: dict[str, int] | |
| actor_hash: str # SC-1: sha256(actor_id+event_type+entity_id+ts) | |
| server_ts: float # UTC epoch — authoritative for LWW resolution | |
| conflict: dict | None = None | |
| # ── SC-1: Conflict detection & resolution ──────────────────────────────── | |
| def _compute_actor_hash(actor_id: str, event_type: str, entity_id: str, ts: float) -> str: | |
| """Generate a deterministic 16-char actor hash for the chain log.""" | |
| raw = f"{actor_id}:{event_type}:{entity_id}:{ts:.6f}" | |
| return hashlib.sha256(raw.encode()).hexdigest()[:16] | |
| def _detect_conflict( | |
| new_event: CaseEventEnvelope, | |
| tenant_id: str, | |
| ) -> dict | None: | |
| """ | |
| SC-1: Scan the recent conflict log for a concurrent event on the same entity. | |
| Returns conflict metadata if a concurrent operation is found. | |
| Conflict = same entity_id + overlapping vector clocks on different actors. | |
| """ | |
| entity_key = f"{tenant_id}:{new_event.entity_id}" | |
| recent = [ | |
| e for e in _conflict_log[-50:] # check last 50 only (performance guard) | |
| if e.get("entity_key") == entity_key | |
| and abs(e["server_ts"] - new_event.server_ts) < 2.0 # within 2s window | |
| ] | |
| if not recent: | |
| return None | |
| for prior in recent: | |
| prior_clock: dict = prior.get("vector_clock", {}) | |
| new_clock = new_event.vector_clock | |
| # Concurrent if neither clock dominates the other | |
| concurrent = any( | |
| new_clock.get(a, 0) < prior_clock.get(a, 0) for a in prior_clock | |
| ) and any( | |
| prior_clock.get(a, 0) < new_clock.get(a, 0) for a in new_clock | |
| ) | |
| if concurrent: | |
| return { | |
| "conflict_type": "concurrent_write", | |
| "resolution": "last_write_wins", | |
| "winning_ts": max(new_event.server_ts, prior["server_ts"]), | |
| "losing_actor_hash": prior["actor_hash"] | |
| if new_event.server_ts >= prior["server_ts"] | |
| else new_event.actor_hash, | |
| } | |
| return None | |
| def _record_in_conflict_log(event: CaseEventEnvelope, tenant_id: str) -> None: | |
| """Add event to the SC-1 ring buffer for future conflict checks.""" | |
| if len(_conflict_log) >= _CONFLICT_LOG_MAX: | |
| _conflict_log.pop(0) | |
| _conflict_log.append( | |
| { | |
| "entity_key": f"{tenant_id}:{event.entity_id}", | |
| "event_type": event.event_type, | |
| "actor_id": event.actor_id, | |
| "vector_clock": dict(event.vector_clock), | |
| "actor_hash": event.actor_hash, | |
| "server_ts": event.server_ts, | |
| } | |
| ) | |
| # ── Subscriber helpers ──────────────────────────────────────────────────── | |
| async def _subscribe(channel: str) -> asyncio.Queue: | |
| async with _sub_lock: | |
| q: asyncio.Queue = asyncio.Queue(maxsize=100) | |
| _subscribers.setdefault(channel, []).append(q) | |
| return q | |
| async def _unsubscribe(channel: str, q: asyncio.Queue) -> None: | |
| async with _sub_lock: | |
| try: | |
| _subscribers[channel].remove(q) | |
| except (KeyError, ValueError): | |
| pass | |
| async def _broadcast(channel: str, data: dict) -> None: | |
| async with _sub_lock: | |
| queues = list(_subscribers.get(channel, [])) | |
| for q in queues: | |
| try: | |
| q.put_nowait(data) | |
| except asyncio.QueueFull: | |
| pass # Slow consumer — skip (data is non-critical event metadata) | |
| # ── Routes ──────────────────────────────────────────────────────────────── | |
| async def p2p_status() -> dict: | |
| """ | |
| P2P relay health check — returns enabled status, relay URL, and subscriber count. | |
| Sprint: 69 (P2P-1) | PHI: NONE | Auth: none (public health probe) | |
| """ | |
| relay_url = os.environ.get("GUN_RELAY_URL", "") | |
| total_subs = sum(len(v) for v in _subscribers.values()) | |
| return { | |
| "p2p_enabled": _P2P_ENABLED, | |
| "gun_relay_url": relay_url or None, | |
| "gun_relay_path": "/gun", | |
| "active_subscribers": total_subs, | |
| "conflict_log_size": len(_conflict_log), | |
| "ts": datetime.now(UTC).isoformat(), | |
| } | |
| async def p2p_event_stream( | |
| request: Request, | |
| current_user: User = Depends(get_current_user), | |
| ) -> StreamingResponse: | |
| """ | |
| Server-Sent Events stream for real-time case event delivery. | |
| The client connects, receives a keep-alive ping every 15 s, and gets | |
| case events as they are published. Scoped to the authenticated user's | |
| tenant_id — tenant isolation is enforced at subscription level. | |
| Client reconnects automatically via EventSource API. | |
| The frontend bridges events to GunDB via JS after receipt. | |
| Sprint: 69 (P2P-2) | PHI: NONE | Auth: required | |
| """ | |
| _check_p2p_enabled() | |
| channel = str(current_user.tenant_id) | |
| q = await _subscribe(channel) | |
| async def event_generator(): | |
| try: | |
| # Initial connection ack | |
| yield "event: connected\ndata: {\"status\":\"connected\"}\n\n" | |
| while True: | |
| if await request.is_disconnected(): | |
| break | |
| try: | |
| # Wait for event or keep-alive timeout | |
| event_data = await asyncio.wait_for(q.get(), timeout=15.0) | |
| payload = json.dumps(event_data, default=str) | |
| yield f"event: case_event\ndata: {payload}\n\n" | |
| except TimeoutError: | |
| # Keep-alive ping | |
| yield "event: ping\ndata: {\"ts\":" + str(int(time.time())) + "}\n\n" | |
| finally: | |
| await _unsubscribe(channel, q) | |
| return StreamingResponse( | |
| event_generator(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "X-Accel-Buffering": "no", # Disable nginx buffering for SSE | |
| }, | |
| ) | |
| async def publish_case_event( | |
| data: CaseEventPublish, | |
| current_user: User = Depends(get_current_user), | |
| ) -> dict: | |
| """ | |
| Publish a case domain event to all SSE subscribers in the tenant channel. | |
| SC-1 CRDT conflict resolution: | |
| 1. Compute actor_hash for this event | |
| 2. Scan recent conflict log for concurrent writes on the same entity | |
| 3. If concurrent: annotate with conflict metadata (last-write-wins) | |
| 4. Broadcast to all subscribers (including conflicting events — clients | |
| resolve based on server_ts) | |
| Multi-tenancy: events are scoped to current_user.tenant_id (NEVER cross-tenant). | |
| Performance: <50ms (in-memory queue, no DB writes). | |
| PHI: NONE — entity IDs and event types only. | |
| Sprint: 69 (P2P-2, SC-1) | |
| """ | |
| _check_p2p_enabled() | |
| ts = time.time() | |
| actor_id = str(current_user.id) | |
| tenant_id = str(current_user.tenant_id) | |
| entity_id = str(data.entity_id) | |
| actor_hash = _compute_actor_hash(actor_id, data.event_type, entity_id, ts) | |
| envelope = CaseEventEnvelope( | |
| event_id=str(uuid4()), | |
| event_type=data.event_type, | |
| entity_id=entity_id, | |
| entity_type=data.entity_type, | |
| actor_id=actor_id, | |
| tenant_id=tenant_id, | |
| payload=data.payload, | |
| vector_clock=data.vector_clock, | |
| actor_hash=actor_hash, | |
| server_ts=ts, | |
| ) | |
| # SC-1: Detect concurrent writes | |
| conflict = _detect_conflict(envelope, tenant_id) | |
| if conflict: | |
| envelope.conflict = conflict | |
| logger.warning( | |
| "p2p_conflict_detected", | |
| entity_id=entity_id, | |
| event_type=data.event_type, | |
| conflict_type=conflict["conflict_type"], | |
| tenant_id=tenant_id, | |
| ) | |
| _record_in_conflict_log(envelope, tenant_id) | |
| # Broadcast to all tenant subscribers | |
| await _broadcast(tenant_id, envelope.model_dump()) | |
| logger.info( | |
| "p2p_case_event_published", | |
| event_id=envelope.event_id, | |
| event_type=data.event_type, | |
| entity_id=entity_id, | |
| tenant_id=tenant_id, | |
| subscribers=len(_subscribers.get(tenant_id, [])), | |
| conflict=conflict is not None, | |
| ) | |
| return { | |
| "event_id": envelope.event_id, | |
| "actor_hash": actor_hash, | |
| "server_ts": ts, | |
| "conflict": conflict, | |
| "subscribers_notified": len(_subscribers.get(tenant_id, [])), | |
| } | |