Files
map-asset-gateway/demo/demo_callback_receiver.py
T
Harmon 73ad03fa59 Rewrite the gateway around health, retries, slicing and a Windows service
Scanner
- manifest lookup is now depth-bounded and prunes numeric zoom directories, so
  a scan no longer walks the whole tile payload
- rescans only report a version as updated when something actually changed
- overlapping runs are refused instead of interleaving their bookkeeping

Hot path
- token authorisation loads only that token grants and throttles the
  last_used_at write instead of touching it on every tile
- SQLite runs in WAL with a busy timeout and a real connection pool
- the catalog lookup used by /tiles no longer loads every basemap

Security
- the admin surface requires ADMIN_TOKEN (bearer) or ADMIN_USER/ADMIN_PASSWORD
  (basic), and the service refuses to bind off-host without credentials
- CORS is an explicit allow-list; newly minted tokens never reach a redirect URL
- client tokens are redacted from the access log

Operations
- resource health inspection flags a moved or deleted tile root before a 404
- pushes retry with backoff and can be re-queued by hand; the schedule lives in
  the database so a restart does not lose it
- access log plus /metrics counters

Image slicing
- tile_jobs drive the GDAL bundled with QGIS via scripts/gdal2tiles-qgis.bat
- layer_sources remembers what a layer is made of: submit one source to append
  a flight, or all of them to rebuild the layer as a VRT mosaic with no tile
  seams; the console exposes both, including a one-click rebuild
- slicing is available to integrations through a narrow slice token scope
  (submit, poll, idempotent by code, completion callback)

Console
- rebuilt around a fixed rail and single-view navigation with health and
  outstanding work leading, instead of one long scrolling page

Windows service
- native install/start/stop/status with crash recovery, auto-start and a
  rotating log file, so no NSSM wrapper is needed
- start-all.bat and stop-all.bat are removed: they killed the process by port
  with taskkill, which fought the service restart policy

Verified with 49 tests and live runs against real tile data and real GDAL.
2026-10-16 10:35:30 +08:00

110 lines
3.6 KiB
Python

import argparse
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
def parse_args():
parser = argparse.ArgumentParser(description="Simple callback receiver for tile-server demos.")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8920)
parser.add_argument("--path", default="/callback")
parser.add_argument("--output-dir", required=True)
return parser.parse_args()
class State:
def __init__(self, output_dir: Path, callback_path: str):
self.output_dir = output_dir
self.callback_path = callback_path
self.counter = 0
self.lock = threading.Lock()
def next_file(self) -> Path:
with self.lock:
self.counter += 1
name = f"{time.strftime('%Y%m%d_%H%M%S')}_{self.counter:04d}.json"
return self.output_dir / name
def make_handler(state: State):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode("utf-8"))
return
self.send_response(404)
self.end_headers()
def do_POST(self):
self._handle_payload()
def do_PUT(self):
self._handle_payload()
def _handle_payload(self):
if self.path != state.callback_path:
self.send_response(404)
self.end_headers()
return
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length)
text = raw.decode("utf-8", errors="replace")
try:
body_json = json.loads(text)
except json.JSONDecodeError:
body_json = None
record = {
"received_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"method": self.command,
"path": self.path,
"headers": {key: value for key, value in self.headers.items()},
"body_text": text,
"body_json": body_json,
}
output_path = state.next_file()
output_path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"[callback] saved {output_path}", flush=True)
response = {"saved": str(output_path), "ok": True}
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps(response).encode("utf-8"))
def log_message(self, fmt, *args):
print("[callback] " + (fmt % args), flush=True)
return Handler
def main():
args = parse_args()
output_dir = Path(args.output_dir).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
state = State(output_dir=output_dir, callback_path=args.path)
server = ThreadingHTTPServer((args.host, args.port), make_handler(state))
print(f"Callback receiver listening on http://{args.host}:{args.port}{args.path}", flush=True)
print(f"Health endpoint: http://{args.host}:{args.port}/health", flush=True)
print(f"Output dir: {output_dir}", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()