Repository Public BSD-3-Clause
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : ORIX Maps10# File : Infrastructure/distribution/dev-server.py11# Description : Development server for a map distribution directory,12# implementing docs/CATALOG_API.md on loopback: strong13# SHA-256 ETags, If-None-Match, single byte ranges,14# If-Range, 416, HEAD.15# Module : Infrastructure16# Repository : https://git.spboucher.ai/orix-maps17# Created : 2026-11-2518# Last Modified : 2026-11-2519#20# =============================================================================21# AUTHOR & PROFESSIONAL AFFILIATION22# =============================================================================23#24# Author : Simon-Pierre Boucher25# Position : Professor of Finance26# Institution : Université du Québec en Outaouais (UQO)27# Department : Département des sciences administratives28# Organization : SP Boucher29#30# Website : https://spboucher.ai31# Git : https://git.spboucher.ai32#33# =============================================================================34# OFFICIAL CONTACT DIRECTORY35# =============================================================================36#37# General : info@spboucher.ai38# Professional : contact@spboucher.ai39# Direct : simon@spboucher.ai40# Research : research@spboucher.ai41# Development : dev@spboucher.ai42# Support : support@spboucher.ai43# Security/Admin : admin@spboucher.ai44# Notifications : notifications@spboucher.ai45#46# Preferred Contact: support@spboucher.ai47#48# =============================================================================49# COPYRIGHT & INTELLECTUAL PROPERTY50# =============================================================================51#52# Copyright (c) 202653# Simon-Pierre Boucher54#55# All rights reserved where applicable.56#57# This file is governed by the applicable project license,58# copyright notices, institutional agreements and relevant law.59#60# Unless expressly authorized by the applicable license or61# rights holder, copying, redistribution, sublicensing,62# publication and commercial exploitation are not permitted.63#64# Existing third-party rights and notices remain unaffected.65#66# =============================================================================67# CONFIDENTIALITY & SECURITY68# =============================================================================69#70# Classification : Public71# Distribution : Public repository; use is governed by the project license72# Security Contact : admin@spboucher.ai73#74# Access to this source does not independently grant permission75# to redistribute or disclose confidential materials.76#77# Do not embed credentials, private keys, access tokens,78# certificates or confidential personal information.79#80# =============================================================================81# LICENSE & MAINTENANCE82# =============================================================================83#84# License : Proprietary, all rights reserved (see license file)85# License File : LICENSE86# Maintainer : Simon-Pierre Boucher87# Technical Contact: dev@spboucher.ai88#89# =============================================================================90# END OF SP BOUCHER SOURCE HEADER91# =============================================================================9293"""Development server for a map distribution directory, implementing docs/CATALOG_API.md on loopback:94strong SHA-256 ETags, If-None-Match, single byte ranges, If-Range, 416, HEAD. Standard library only.95For local testing of the application (launch argument -ORIXCatalogURL http://127.0.0.1:<port>/maps/v1/); never for production.96usage: dev-server.py <distribution dir> [port] [--throttle <bytes per second>]"""97import hashlib, http.server, json, os, re, sys, time9899root = os.path.realpath(sys.argv[1])100port = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 8765101throttle = int(sys.argv[sys.argv.index("--throttle") + 1]) if "--throttle" in sys.argv else 0102PREFIX = "/maps/v1/"103JSON_RE = re.compile(r"^(catalog\.json|regions/[a-z0-9-]{1,64}\.json|regions/[a-z0-9-]{1,64}/versions\.json)$")104FILE_RE = re.compile(r"^files/([a-z0-9-]{1,64})/([0-9]+(?:\.[0-9]+)*)/\1-\2\.orixmap$")105etags = {}106107def listed():108 """Artefacts the published documents list: path -> (size, sha256)."""109 out = {}110 try:111 cat = json.load(open(os.path.join(root, "catalog.json")))112 except Exception:113 return out114 for r in cat.get("regions", []):115 rel = [r.get("latest", {})]116 try: rel += json.load(open(os.path.join(root, "regions", r["id"], "versions.json"))).get("versions", [])117 except Exception: pass118 for x in rel:119 if "path" in x: out[x["path"]] = (x.get("downloadSize"), x.get("sha256"))120 return out121122class Handler(http.server.BaseHTTPRequestHandler):123 protocol_version = "HTTP/1.1"124 def log_message(self, fmt, *args): sys.stderr.write("%s %s\n" % (self.command, fmt % args))125 def fail(self, code, extra=None):126 self.send_response(code); self.send_header("Content-Length", "0")127 for k, v in (extra or {}).items(): self.send_header(k, v)128 self.end_headers()129 def do_HEAD(self): self.serve(False)130 def do_GET(self): self.serve(True)131 def serve(self, body):132 if not self.path.startswith(PREFIX): return self.fail(404)133 rel = self.path[len(PREFIX):]134 is_json, m = JSON_RE.match(rel), FILE_RE.match(rel)135 if not (is_json or m): return self.fail(404)136 path = os.path.realpath(os.path.join(root, rel))137 if not path.startswith(root + os.sep) or not os.path.isfile(path): return self.fail(404)138 size = os.path.getsize(path)139 if is_json:140 key = (path, os.path.getmtime(path), size)141 if key not in etags: etags[key] = hashlib.sha256(open(path, "rb").read()).hexdigest()142 sha, ctype, cache = etags[key], "application/json", "public, max-age=300"143 else:144 entry = listed().get(rel)145 if not entry or entry[0] != size: return self.fail(404)146 sha, ctype, cache = entry[1], "application/vnd.orix.map", "public, max-age=31536000, immutable"147 etag = '"%s"' % sha148 base = {"ETag": etag, "Cache-Control": cache, "Content-Type": ctype, "X-Content-Type-Options": "nosniff"}149 if self.headers.get("If-None-Match") == etag: return self.fail(304, base)150 start, end, status = 0, size - 1, 200151 rng = re.match(r"^bytes=(\d*)-(\d*)$", self.headers.get("Range", "")) if m else None152 if rng and (rng.group(1) or rng.group(2)) and self.headers.get("If-Range", etag) == etag:153 if rng.group(1):154 start = int(rng.group(1)); end = min(int(rng.group(2)), size - 1) if rng.group(2) else size - 1155 else:156 start = max(0, size - int(rng.group(2)))157 if start >= size or start > end: return self.fail(416, {"Content-Range": "bytes */%d" % size})158 status = 206159 self.send_response(status)160 for k, v in base.items(): self.send_header(k, v)161 if m: self.send_header("Accept-Ranges", "bytes")162 if status == 206: self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, size))163 self.send_header("Content-Length", str(end - start + 1))164 self.end_headers()165 if not body: return166 with open(path, "rb") as f:167 f.seek(start); left = end - start + 1168 while left > 0:169 chunk = f.read(min(256 * 1024, left))170 if not chunk: break171 try: self.wfile.write(chunk)172 except (BrokenPipeError, ConnectionResetError): return173 left -= len(chunk)174 if throttle: time.sleep(len(chunk) / throttle)175176print("serving %s on http://127.0.0.1:%d%s" % (root, port, PREFIX), flush=True)177http.server.ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()178