Files
codexPySnake/run.py

107 lines
4.2 KiB
Python

import asyncio
import os
import logging
from server.server import GameServer
from server.config import ServerConfig
async def _run_tasks_with_optional_timeout(tasks):
"""Await tasks, optionally honoring RUN_SECONDS env var to cancel after a timeout."""
timeout_s = os.environ.get("RUN_SECONDS")
if not timeout_s:
await asyncio.gather(*tasks)
return
try:
await asyncio.wait_for(asyncio.gather(*tasks), timeout=float(timeout_s))
except asyncio.TimeoutError:
logging.info("Timeout reached (RUN_SECONDS=%s); stopping server tasks...", timeout_s)
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
async def run_in_memory():
from server.transport import InMemoryTransport
cfg = ServerConfig()
server = GameServer(transport=InMemoryTransport(lambda d, p: server.on_datagram(d, p)), config=cfg)
tasks = [asyncio.create_task(server.transport.run()), asyncio.create_task(server.tick_loop())]
await _run_tasks_with_optional_timeout(tasks)
async def run_quic():
from server.quic_transport import QuicWebTransportServer
cfg = ServerConfig()
host = os.environ.get("QUIC_HOST", "0.0.0.0")
port = int(os.environ.get("QUIC_PORT", "4433"))
cert = os.environ["QUIC_CERT"]
key = os.environ["QUIC_KEY"]
server = GameServer(transport=QuicWebTransportServer(host, port, cert, key, lambda d, p: server.on_datagram(d, p)), config=cfg)
tasks = [asyncio.create_task(server.transport.run()), asyncio.create_task(server.tick_loop())]
await _run_tasks_with_optional_timeout(tasks)
async def run_webtransport():
from server.webtransport_server import WebTransportServer
from server.static_server import start_https_static
cfg = ServerConfig()
host = os.environ.get("WT_HOST", os.environ.get("QUIC_HOST", "0.0.0.0"))
port = int(os.environ.get("WT_PORT", os.environ.get("QUIC_PORT", "4433")))
cert = os.environ.get("WT_CERT") or os.environ["QUIC_CERT"]
key = os.environ.get("WT_KEY") or os.environ["QUIC_KEY"]
# Optional static HTTPS server for client assets
static = os.environ.get("STATIC", "1")
static_host = os.environ.get("STATIC_HOST", host)
static_port = int(os.environ.get("STATIC_PORT", "8443"))
static_root = os.environ.get("STATIC_ROOT", "client")
httpd = None
if static == "1":
httpd, _t = start_https_static(static_host, static_port, cert, key, static_root)
print(f"HTTPS static server: https://{static_host}:{static_port}/ serving '{static_root}'")
server = GameServer(transport=WebTransportServer(host, port, cert, key, lambda d, p: server.on_datagram(d, p)), config=cfg)
print(f"WebTransport server: https://{host}:{port}/ (HTTP/3)")
try:
tasks = [asyncio.create_task(server.transport.run()), asyncio.create_task(server.tick_loop())]
await _run_tasks_with_optional_timeout(tasks)
finally:
if httpd is not None:
httpd.shutdown()
if __name__ == "__main__":
try:
# Logging setup
level = os.environ.get("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=getattr(logging, level, logging.INFO), format="[%(asctime)s] %(levelname)s: %(message)s")
mode = os.environ.get("MODE", "mem").lower()
if mode == "wt":
logging.info("Starting in WebTransport mode")
asyncio.run(run_webtransport())
elif mode == "quic":
logging.info("Starting in QUIC datagram mode")
asyncio.run(run_quic())
else:
logging.info("Starting in in-memory transport mode")
asyncio.run(run_in_memory())
except KeyboardInterrupt:
pass
async def _run_tasks_with_optional_timeout(tasks):
"""Await tasks, optionally honoring RUN_SECONDS env var to cancel after a timeout."""
timeout_s = os.environ.get("RUN_SECONDS")
if not timeout_s:
await asyncio.gather(*tasks)
return
try:
await asyncio.wait_for(asyncio.gather(*tasks), timeout=float(timeout_s))
except asyncio.TimeoutError:
logging.info("Timeout reached (RUN_SECONDS=%s); stopping server tasks...", timeout_s)
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)