Debian Codegraph @

testing/web-platform/tests/tools/third_party/websockets/example/deployment/kubernetes/app.py

raw
1 #!/usr/bin/env python
2
3 import asyncio
4 import http
5 import signal
6 import sys
7 import time
8
9 import websockets
10
11
12 async def slow_echo(websocket):
13 async for message in websocket:
14 # Block the event loop! This allows saturating a single asyncio
15 # process without opening an impractical number of connections.
16 time.sleep(0.1) # 100ms
17 await websocket.send(message)
18
19
20 async def health_check(path, request_headers):
21 if path == "/healthz":
22 return http.HTTPStatus.OK, [], b"OK\n"
23 if path == "/inemuri":
24 loop = asyncio.get_running_loop()
25 loop.call_later(1, time.sleep, 10)
26 return http.HTTPStatus.OK, [], b"Sleeping for 10s\n"
27 if path == "/seppuku":
28 loop = asyncio.get_running_loop()
29 loop.call_later(1, sys.exit, 69)
30 return http.HTTPStatus.OK, [], b"Terminating\n"
31
32
33 async def main():
34 # Set the stop condition when receiving SIGTERM.
35 loop = asyncio.get_running_loop()
36 stop = loop.create_future()
37 loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
38
39 async with websockets.serve(
40 slow_echo,
41 host="",
42 port=80,
43 process_request=health_check,
44 ):
45 await stop
46
47
48 if __name__ == "__main__":
49 asyncio.run(main())