cmvr-visual/backend/app/api/routes/events.py

79 lines
2.6 KiB
Python
Raw Normal View History

import asyncio
import json
import time
from fastapi import APIRouter, Depends, Request
from fastapi.responses import StreamingResponse
from sqlalchemy import func, select
from app.core.security import Actor, COOKIE
from app.api.dependencies import current_actor
from app.core.errors import fail
from app.models import Event
from app.services.events import event_batch, session_is_active
router = APIRouter(tags=["events"])
async def event_stream(request, owner_id, token, after):
# Authentication was checked by the endpoint. Flush a body immediately so
# EventSource/proxies need not wait for the first durable event or heartbeat.
yield ": connected\n\n"
db = request.app.state.db
heartbeat = request.app.state.settings.event_heartbeat_seconds
last_heartbeat = time.monotonic()
async with db.session() as session:
maximum = (
await session.scalar(select(func.max(Event.id)).where(Event.owner_id == owner_id)) or 0
)
minimum = (
await session.scalar(select(func.min(Event.id)).where(Event.owner_id == owner_id)) or 0
)
if after > maximum or (after > 0 and minimum > 0 and after < minimum - 1):
yield f"id: {maximum}\nevent: reset\ndata: {{}}\n\n"
after = maximum
while not await request.is_disconnected():
if getattr(request.app.state, "draining", False):
return
if not await session_is_active(db, token):
return
rows = await event_batch(db, owner_id, after)
for event in rows:
after = event["id"]
yield f"id: {after}\nevent: {event['event']}\ndata: {json.dumps(event['data'], ensure_ascii=False, separators=(',', ':'))}\n\n"
if time.monotonic() - last_heartbeat >= heartbeat:
yield ": heartbeat\n\n"
last_heartbeat = time.monotonic()
if not rows:
await asyncio.sleep(min(0.5, heartbeat))
@router.get("/events")
async def events(request: Request, after: int = 0, actor: Actor = Depends(current_actor)):
try:
cursor = int(request.headers.get("Last-Event-ID", after))
if cursor < 0:
raise ValueError
except ValueError:
fail(422, "invalid_cursor", "事件游标必须为非负整数")
return StreamingResponse(
event_stream(
request,
actor.id,
request.headers.get("Authorization")
if actor.auth_kind == "bearer"
else request.cookies.get(COOKIE),
cursor,
),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"},
)