Added more websocket endpoints

Can now subscribe to:
- spool/filament/vendor level events, not specific to any specific ID
- root level events, captures all events sent
This commit is contained in:
Donkie
2023-10-15 20:36:48 +02:00
parent 03be75abca
commit 3e2bbed17e
4 changed files with 114 additions and 7 deletions

View File

@@ -2,9 +2,10 @@
# ruff: noqa: D103
import asyncio
import logging
from fastapi import FastAPI
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
from starlette.requests import Request
from starlette.responses import Response
@@ -12,6 +13,7 @@ from starlette.responses import Response
from spoolman import env
from spoolman.database.database import backup_global_db
from spoolman.exceptions import ItemNotFoundError
from spoolman.ws import websocket_manager
from . import filament, models, other, spool, vendor
@@ -20,6 +22,15 @@ logger = logging.getLogger(__name__)
app = FastAPI(
title="Spoolman REST API v1",
version="1.0.0",
description="""
REST API for Spoolman.
The API is served on the path `/api/v1/`.
Some endpoints also serve a websocket on the same path. The websocket is used to listen for changes to the data
that the endpoint serves. The websocket messages are JSON objects. Additionally, there is a root-level websocket
endpoint that listens for changes to any data in the database.
""",
)
@@ -73,6 +84,24 @@ async def backup(): # noqa: ANN201
return models.BackupResponse(path=str(path))
@app.websocket(
"/",
name="Listen to any changes",
)
async def notify(
websocket: WebSocket,
) -> None:
await websocket.accept()
websocket_manager.connect((), websocket)
try:
while True:
await asyncio.sleep(0.5)
if await websocket.receive_text():
await websocket.send_json({"status": "healthy"})
except WebSocketDisconnect:
websocket_manager.disconnect((), websocket)
# Add routers
app.include_router(filament.router)
app.include_router(spool.router)