"""Static server for web/, reachable from other devices on the LAN. python server/serve.py [port] # default 8080 Deliberately dependency-free. Tiles are immutable once built, so they get a long cache lifetime while the app shell stays uncached -- that is the whole difference between a snappy second visit and re-downloading every tile. For heavier use put Caddy or nginx in front of web/ instead; nothing here is special. """ from __future__ import annotations import functools import http.server import socket import socketserver import sys from pathlib import Path WEB = Path(__file__).resolve().parent.parent / "web" class Handler(http.server.SimpleHTTPRequestHandler): extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map, ".webp": "image/webp"} # SimpleHTTPRequestHandler defaults to HTTP/1.0, which closes the socket # after every response -- one TCP handshake per tile. A map view pulls ~30 # tiles, so over WiFi that is ~30 extra round trips. HTTP/1.1 keeps the # connection open. Safe here because every response carries Content-Length. protocol_version = "HTTP/1.1" timeout = 10 # don't let idle keep-alive sockets pin threads forever def end_headers(self): if "/tiles/" in self.path: self.send_header("Cache-Control", "public, max-age=604800, immutable") else: self.send_header("Cache-Control", "no-cache") super().end_headers() def log_message(self, fmt, *args): pass # one line per tile is unreadable class Server(socketserver.ThreadingTCPServer): allow_reuse_address = True daemon_threads = True def lan_ip() -> str: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("10.255.255.255", 1)) # no packets sent; just picks the route return s.getsockname()[0] except OSError: return "127.0.0.1" finally: s.close() def main() -> None: if not (WEB / "data" / "world.json").exists(): print("warning: web/data/world.json missing -- run tools/build.py first\n") port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080 handler = functools.partial(Handler, directory=str(WEB)) with Server(("0.0.0.0", port), handler) as httpd: print(f"serving {WEB}") print(f" local http://localhost:{port}/") print(f" LAN http://{lan_ip()}:{port}/") print("\nCtrl+C to stop") try: httpd.serve_forever() except KeyboardInterrupt: print("\nstopped") if __name__ == "__main__": main()