11"""The entrypoint for the Squonk2 FastAPI WebSocket service."""
22
3- from fastapi import FastAPI
3+ import uuid
4+
5+ from fastapi import FastAPI , HTTPException , WebSocket , status
46
57# Public (event-stream) and internal (REST) services
6- app_es = FastAPI ()
8+ app_public = FastAPI ()
79app_internal = FastAPI ()
810
11+ _ES_UUID_SET : set = set ()
12+
913
1014# Endpoints for the 'public-facing' event-stream web-socket API ------------------------
1115
1216
13- @app_es .get ("/event-stream/" )
14- def event_stream ():
15- """Read from the event-stream."""
16- return {"message" : "MESSAGE" }
17+ @app_public .websocket ("/event-stream/{es_id}" )
18+ async def event_stream (websocket : WebSocket , es_id : str ):
19+ """The websocket handler for the event-stream."""
20+ if not es_id in _ES_UUID_SET :
21+ raise HTTPException (
22+ status_code = status .HTTP_400_BAD_REQUEST ,
23+ detail = f"EventStream { es_id } is not known" ,
24+ )
25+ await websocket .accept ()
26+ while True :
27+ data = await websocket .receive_text ()
28+ await websocket .send_text (f"Message text was: { data } " )
1729
1830
1931# Endpoints for the 'internal' event-stream management API -----------------------------
@@ -22,10 +34,18 @@ def event_stream():
2234@app_internal .post ("/event-stream/" )
2335def post_es ():
2436 """Create a new event-stream."""
25- return {"id" : 1 }
37+ uuid_str = f"es-{ uuid .uuid4 ()} "
38+ _ES_UUID_SET .add (uuid_str )
39+ return {"id" : uuid_str }
2640
2741
2842@app_internal .delete ("/event-stream/{es_id}" )
29- def delete_es (es_id : int ):
43+ def delete_es (es_id : str ):
3044 """Destroys an existing event-stream."""
31- return {"message" : f"Destroy ES { es_id } " }
45+ if es_id not in _ES_UUID_SET :
46+ raise HTTPException (
47+ status_code = status .HTTP_400_BAD_REQUEST ,
48+ detail = f"EventStream { es_id } is not known" ,
49+ )
50+ _ES_UUID_SET .remove (es_id )
51+ return {}
0 commit comments