Add editable export workflow and new map sources
This commit is contained in:
1 parent
b079009d74
commit
234dc32c86
33 files changed
+1976
-112
No files matched your search
+2
-2
@@ -25,8 +25,8 @@
|
||||
# Tiles are rewritten wholesale by tools/build.py and never edited in
|
||||
# place, so a long lifetime is safe. `immutable` stops the browser
|
||||
# revalidating them on every pan.
|
||||
@tiles path /tiles/*
|
||||
header @tiles Cache-Control "public, max-age=604800, immutable"
|
||||
@tiles path /tiles/* /tiles-trimmed/*
|
||||
header @tiles Cache-Control "public, max-age=31536000, immutable"
|
||||
|
||||
# The shell and the manifest must never be stale, or the app can end up
|
||||
# pointing at tiles that no longer exist.
|
||||
|
||||
+48
-15
@@ -1,34 +1,46 @@
|
||||
# Serve the built site.
|
||||
#
|
||||
# pwsh server/run.ps1 # port 8080
|
||||
# pwsh server/run.ps1 # editable server, port 8080
|
||||
# pwsh server/run.ps1 -Port 9000
|
||||
# pwsh server/run.ps1 -Port 9000 -Editable # enable placement, trim and marker saves
|
||||
# pwsh server/run.ps1 -Port 9000 -ReadOnly # deployment-style preview
|
||||
#
|
||||
# Uses Caddy when server/caddy.exe is present (get it with get-caddy.ps1) and
|
||||
# falls back to the dependency-free serve.py otherwise. Caddy is roughly 3x
|
||||
# faster at low concurrency and does not fall over at high concurrency -- see
|
||||
# the table in the README.
|
||||
# Editable mode uses serve.py. Read-only mode uses Caddy when server/caddy.exe
|
||||
# is present (get it with get-caddy.ps1) and falls back to serve.py otherwise.
|
||||
# Caddy is roughly 3x faster at low concurrency and does not fall over at high
|
||||
# concurrency -- see the table in the README.
|
||||
|
||||
param(
|
||||
[int]$Port = 8080,
|
||||
[switch]$Editable
|
||||
[switch]$Editable,
|
||||
[switch]$ReadOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
Set-Location $here # Caddyfile's `root * ../web` resolves against the cwd
|
||||
|
||||
if ($Editable -and $ReadOnly) {
|
||||
throw '-Editable and -ReadOnly cannot be used together.'
|
||||
}
|
||||
$editMode = -not $ReadOnly
|
||||
|
||||
if (-not (Test-Path (Join-Path $here '..\web\data\world.json'))) {
|
||||
Write-Warning "web/data/world.json missing -- run 'python tools/build.py' first"
|
||||
}
|
||||
|
||||
$ip = (Get-NetIPConfiguration |
|
||||
Where-Object { $_.IPv4DefaultGateway -and $_.NetAdapter.Status -eq 'Up' } |
|
||||
Select-Object -First 1).IPv4Address.IPAddress
|
||||
if (-not $ip) { $ip = '127.0.0.1' }
|
||||
$ip = '127.0.0.1'
|
||||
try {
|
||||
$lanIp = (Get-NetIPConfiguration -ErrorAction Stop |
|
||||
Where-Object { $_.IPv4DefaultGateway -and $_.NetAdapter.Status -eq 'Up' } |
|
||||
Select-Object -First 1).IPv4Address.IPAddress
|
||||
if ($lanIp) { $ip = $lanIp }
|
||||
}
|
||||
catch {
|
||||
# Restricted shells may block the CIM query. Localhost still works.
|
||||
}
|
||||
|
||||
$caddy = Join-Path $here 'caddy.exe'
|
||||
$engine = if ($Editable) { 'serve.py (map editing enabled)' }
|
||||
$engine = if ($editMode) { 'serve.py (map editing enabled)' }
|
||||
elseif (Test-Path $caddy) { 'caddy' }
|
||||
else { 'serve.py (slower)' }
|
||||
|
||||
@@ -40,11 +52,32 @@ Write-Host ""
|
||||
Write-Host " Ctrl+C to stop"
|
||||
Write-Host ""
|
||||
|
||||
if (-not $Editable -and (Test-Path $caddy)) {
|
||||
if (-not $editMode -and (Test-Path $caddy)) {
|
||||
$env:TARKOVMAP_PORT = "$Port"
|
||||
& $caddy run --config (Join-Path $here 'Caddyfile')
|
||||
}
|
||||
else {
|
||||
if (-not $Editable) { Write-Host " (run get-caddy.ps1 for the faster server)" }
|
||||
python (Join-Path $here 'serve.py') $Port
|
||||
$python = Join-Path $here '..\.venv\Scripts\python.exe'
|
||||
$pythonArgs = @()
|
||||
if (-not (Test-Path $python)) {
|
||||
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||
if ($pythonCommand) {
|
||||
$python = $pythonCommand.Source
|
||||
}
|
||||
else {
|
||||
$pyCommand = Get-Command py -ErrorAction SilentlyContinue
|
||||
if (-not $pyCommand) {
|
||||
throw 'Python was not found. Create .venv or install Python.'
|
||||
}
|
||||
$python = $pyCommand.Source
|
||||
$pythonArgs = @('-3')
|
||||
}
|
||||
}
|
||||
if ($editMode) {
|
||||
& $python @pythonArgs (Join-Path $here 'serve.py') $Port --editable
|
||||
}
|
||||
else {
|
||||
Write-Host " (run get-caddy.ps1 for the faster server)"
|
||||
& $python @pythonArgs (Join-Path $here 'serve.py') $Port
|
||||
}
|
||||
}
|
||||
+134
-6
@@ -1,6 +1,7 @@
|
||||
"""Static server plus local placement, trim and marker editing API.
|
||||
"""Static server plus local map editing and read-only site export API.
|
||||
|
||||
python server/serve.py [port] # default 8080
|
||||
python server/serve.py [port] # read-only, default 8080
|
||||
python server/serve.py [port] --editable # trusted local editing
|
||||
|
||||
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
|
||||
@@ -24,6 +25,7 @@ import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
@@ -33,12 +35,15 @@ CONFIG = ROOT / "maps.json"
|
||||
BUILD_TOOL = ROOT / "tools" / "build.py"
|
||||
MARKER_DIR = WEB / "data" / "markers"
|
||||
MARKER_EDIT_DIR = WEB / "data" / "marker-edits"
|
||||
EXPORT_DIR = ROOT / "exports"
|
||||
EXPORT_ZIP = EXPORT_DIR / "tarkov-map-static.zip"
|
||||
CONFIG_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map,
|
||||
".webp": "image/webp"}
|
||||
editable = False
|
||||
|
||||
# SimpleHTTPRequestHandler defaults to HTTP/1.0, which closes the socket
|
||||
# after every response -- one TCP handshake per tile. A map view pulls ~30
|
||||
@@ -56,12 +61,65 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802 - stdlib handler API
|
||||
def send_export(self, include_body: bool) -> None:
|
||||
if not self.editable:
|
||||
self.send_json(403, {"error": "This server is read-only"})
|
||||
return
|
||||
if not EXPORT_ZIP.exists():
|
||||
self.send_json(404, {"error": "No static export has been created yet"})
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/zip")
|
||||
self.send_header(
|
||||
"Content-Disposition", f'attachment; filename="{EXPORT_ZIP.name}"'
|
||||
)
|
||||
self.send_header("Content-Length", str(EXPORT_ZIP.stat().st_size))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
if include_body:
|
||||
with EXPORT_ZIP.open("rb") as source:
|
||||
self.copyfile(source, self.wfile)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802 - stdlib handler API
|
||||
path = urlsplit(self.path).path
|
||||
if path not in {"/api/placement", "/api/trim", "/api/marker"}:
|
||||
if path == "/data/capabilities.json":
|
||||
self.send_json(200, {
|
||||
"mapEditing": self.editable,
|
||||
"markerEditing": self.editable,
|
||||
"markerPersistence": "server" if self.editable else "none",
|
||||
"exporting": self.editable,
|
||||
})
|
||||
return
|
||||
if path == "/api/export/download":
|
||||
self.send_export(include_body=True)
|
||||
return
|
||||
super().do_GET()
|
||||
|
||||
def do_HEAD(self) -> None: # noqa: N802 - stdlib handler API
|
||||
if urlsplit(self.path).path == "/api/export/download":
|
||||
self.send_export(include_body=False)
|
||||
return
|
||||
super().do_HEAD()
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802 - stdlib handler API
|
||||
if not self.editable:
|
||||
self.send_json(403, {"error": "This server is read-only"})
|
||||
return
|
||||
|
||||
path = urlsplit(self.path).path
|
||||
if path not in {"/api/placement", "/api/trim", "/api/marker", "/api/export"}:
|
||||
self.send_json(404, {"error": "unknown API endpoint"})
|
||||
return
|
||||
|
||||
if path == "/api/export":
|
||||
try:
|
||||
result = export_static_site()
|
||||
except PlacementError as exc:
|
||||
self.send_json(exc.status, {"error": str(exc)})
|
||||
return
|
||||
self.send_json(200, result)
|
||||
return
|
||||
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if not 0 < length <= 16_384:
|
||||
@@ -125,7 +183,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
|
||||
def end_headers(self):
|
||||
if "/tiles/" in self.path or "/tiles-trimmed/" in self.path:
|
||||
self.send_header("Cache-Control", "public, max-age=604800, immutable")
|
||||
self.send_header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
else:
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
super().end_headers()
|
||||
@@ -140,6 +198,72 @@ class PlacementError(Exception):
|
||||
self.status = status
|
||||
|
||||
|
||||
def export_static_site() -> dict:
|
||||
"""Create an atomic, read-only ZIP containing only the deployable web root."""
|
||||
required = [
|
||||
WEB / "index.html",
|
||||
WEB / "app.js",
|
||||
WEB / "style.css",
|
||||
WEB / "data" / "world.json",
|
||||
WEB / "data" / "capabilities.json",
|
||||
WEB / "tiles",
|
||||
]
|
||||
missing = [str(path.relative_to(ROOT)) for path in required if not path.exists()]
|
||||
if missing:
|
||||
raise PlacementError(
|
||||
"static export is incomplete; missing " + ", ".join(missing), 409
|
||||
)
|
||||
|
||||
stored_suffixes = {
|
||||
".webp", ".png", ".jpg", ".jpeg", ".gif", ".ico",
|
||||
".woff", ".woff2", ".zip",
|
||||
}
|
||||
excluded_prefixes = ("data/marker-defaults/",)
|
||||
with CONFIG_LOCK:
|
||||
EXPORT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
temporary = EXPORT_DIR / f".{EXPORT_ZIP.name}.{os.getpid()}.tmp"
|
||||
file_count = 0
|
||||
source_bytes = 0
|
||||
try:
|
||||
with zipfile.ZipFile(temporary, "w", allowZip64=True) as archive:
|
||||
for path in sorted(item for item in WEB.rglob("*") if item.is_file()):
|
||||
relative = path.relative_to(WEB).as_posix()
|
||||
if relative.startswith(excluded_prefixes):
|
||||
continue
|
||||
compression = (
|
||||
zipfile.ZIP_STORED
|
||||
if path.suffix.lower() in stored_suffixes
|
||||
else zipfile.ZIP_DEFLATED
|
||||
)
|
||||
archive.write(path, relative, compress_type=compression)
|
||||
file_count += 1
|
||||
source_bytes += path.stat().st_size
|
||||
manifest = {
|
||||
"format": 1,
|
||||
"readOnly": True,
|
||||
"fileCount": file_count,
|
||||
"sourceBytes": source_bytes,
|
||||
}
|
||||
archive.writestr(
|
||||
"export-manifest.json",
|
||||
json.dumps(manifest, indent=2) + "\n",
|
||||
compress_type=zipfile.ZIP_DEFLATED,
|
||||
)
|
||||
temporary.replace(EXPORT_ZIP)
|
||||
except (OSError, zipfile.BadZipFile) as exc:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise PlacementError(f"static export failed: {exc}") from exc
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"fileName": EXPORT_ZIP.name,
|
||||
"download": "/api/export/download",
|
||||
"fileCount": file_count + 1,
|
||||
"sourceBytes": source_bytes,
|
||||
"zipBytes": EXPORT_ZIP.stat().st_size,
|
||||
}
|
||||
|
||||
|
||||
def normalize_trim_points(value) -> list[list[float]]:
|
||||
if not isinstance(value, list) or len(value) > 500:
|
||||
raise ValueError("points must be a list containing at most 500 vertices")
|
||||
@@ -447,10 +571,14 @@ 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
|
||||
args = sys.argv[1:]
|
||||
Handler.editable = "--editable" in args
|
||||
positional = [arg for arg in args if not arg.startswith("--")]
|
||||
port = int(positional[0]) if positional 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" mode {'editable' if Handler.editable else 'read-only'}")
|
||||
print(f" local http://localhost:{port}/")
|
||||
print(f" LAN http://{lan_ip()}:{port}/")
|
||||
print("\nCtrl+C to stop")
|
||||
|
||||
Reference in new issue
Block a user