Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions args.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import argparse

def get_args():
parser = argparse.ArgumentParser()

parser.add_argument(
"--verbose",
"-v",
action="count",
default=0,
help="increase logging verbosity; can be used multiple times"
)

return parser.parse_args()
16 changes: 12 additions & 4 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@
import collections
import logging
import prometheus_client
from args import get_args

app = FastAPI()
args = get_args()

logging.basicConfig(
format="%(asctime)s.%(msecs)03dZ %(levelname)s:%(name)s:%(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
level=logging.INFO,
level=logging.ERROR - (args.verbose * 10),
)
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
logging.getLogger("uvicorn.error").setLevel(logging.WARNING)

app = FastAPI()

connected_clients = prometheus_client.Gauge(
"connected_clients",
"Number of connected websocket clients per subscription",
Expand All @@ -26,6 +28,7 @@

@app.post("/webhook/{subscription_id}")
async def webhook(subscription_id: str, request: Request):
logging.debug(f"Webhook received at id: {subscription_id}")
if subscription_id is not None:
header_val = request.headers.get("X-API-Key")
if (header_val != "hello"):
Expand All @@ -49,11 +52,14 @@ async def webhook(subscription_id: str, request: Request):

@app.websocket("/tunnel/{subscription_id}")
async def websocket_endpoint(subscription_id: str, websocket: WebSocket):
logging.debug(f"Establishing websocket connection at id: {subscription_id}")
await websocket.accept()

connected_clients.labels(subscription_id).inc()

clients[subscription_id].append(websocket)

logging.debug(f"Websocket connection successfully established at id: {subscription_id}")

try:
while True:
Expand All @@ -65,6 +71,8 @@ async def websocket_endpoint(subscription_id: str, websocket: WebSocket):

if not clients[subscription_id]:
clients.pop(subscription_id, None)

logging.debug(f"Websocket connection disconnected at id: {subscription_id}")


@app.get("/metrics")
Expand All @@ -75,5 +83,5 @@ def get_metrics():
)

if __name__ == "__main__":
uvicorn.run("server:app", host="0.0.0.0", port=5000)
uvicorn.run(app, host="0.0.0.0", port=5000)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why change this line