Repository navigation
Expand file tree
/
Copy pathlaunch-local-server.py
More file actions
executable file
·189 lines (166 loc) · 7.8 KB
/
Copy pathlaunch-local-server.py
File metadata and controls
executable file
·189 lines (166 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/usr/bin/env python3
"""Launch MPAS Configuration Studio V1.0.0 locally (Windows, Linux, macOS)."""
from __future__ import annotations
import argparse
import errno
import functools
import hashlib
import http.server
import os
import socket
import sys
import threading
import webbrowser
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import unquote, urlsplit
from urllib.request import build_opener, ProxyHandler, Request
HOST = '127.0.0.1'
DEFAULT_PORT = 8000
MAX_PORT_TRIES = 50
class LocalServer(http.server.ThreadingHTTPServer):
# POSIX restart behavior is useful; Windows needs exclusive ownership.
allow_reuse_address = os.name != 'nt'
allow_reuse_port = False
daemon_threads = True
def server_bind(self):
if os.name == 'nt':
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
super().server_bind()
class Handler(http.server.SimpleHTTPRequestHandler):
extensions_map = {
**http.server.SimpleHTTPRequestHandler.extensions_map,
'.js': 'application/javascript', '.css': 'text/css',
'.json': 'application/json', '.wasm': 'application/wasm',
'.svg': 'image/svg+xml', '.mpct': 'application/octet-stream',
}
def end_headers(self):
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
self.send_header('Pragma', 'no-cache')
self.send_header('Expires', '0')
self.send_header('X-MPAS-Server-PID', str(os.getpid()))
super().end_headers()
def send_head(self):
# Do not return a cached representation based on a stale validator.
for name in ('If-Modified-Since', 'If-None-Match'):
if name in self.headers:
del self.headers[name]
return super().send_head()
def log_message(self, format, *args):
# Report failed asset requests, not thousands of successful mesh tiles.
if len(args) >= 2 and str(args[1]).startswith(('4', '5')):
super().log_message(format, *args)
class AssetParser(HTMLParser):
def __init__(self):
super().__init__()
self.assets = []
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag in ('script', 'img', 'iframe'):
ref = attrs.get('src')
elif tag == 'link':
ref = attrs.get('href')
else:
return
if ref:
parts = urlsplit(ref)
if not parts.scheme and not parts.netloc and parts.path:
self.assets.append((ref, unquote(parts.path).lstrip('/')))
def collect_assets(root):
assets = [('index.html', 'index.html'), ('component-map.html', 'component-map.html')]
for name in ('index.html', 'component-map.html'):
parser = AssetParser()
parser.feed((root / name).read_text(encoding='utf-8-sig'))
print(f'{name}: {len(parser.assets)} direct asset references', flush=True)
assets.extend(parser.assets)
return list(dict.fromkeys(assets))
def bind_server(root, preferred):
handler = functools.partial(Handler, directory=str(root))
ports = [0] if preferred == 0 else range(preferred, min(preferred + MAX_PORT_TRIES, 65536))
for port in ports:
try:
# Bind and listen atomically from the application's perspective;
# the successful socket is retained, never probed and discarded.
return LocalServer((HOST, port), handler)
except OSError as exc:
if exc.errno not in (errno.EADDRINUSE, errno.EACCES, 10013, 10048) and getattr(exc, 'winerror', None) not in (10013, 10048):
raise
raise OSError('No usable local port was found')
def verify_http(root, base, assets):
opener = build_opener(ProxyHandler({}))
passed = 0
failures = []
for ref, rel in assets:
try:
expected = hashlib.sha256((root / rel).read_bytes()).digest()
with opener.open(Request(base + ref.lstrip('/'), headers={'Cache-Control': 'no-cache'}), timeout=15) as response:
actual = hashlib.sha256(response.read()).digest()
if response.status != 200 or actual != expected:
raise ValueError('HTTP status or SHA-256 mismatch')
if response.headers.get('X-MPAS-Server-PID') != str(os.getpid()):
raise ValueError('response came from another server process')
if rel.endswith('.js') and response.headers.get_content_type() not in ('application/javascript', 'text/javascript'):
raise ValueError('unexpected JavaScript MIME type')
passed += 1
except Exception as exc:
failures.append((rel, str(exc)))
print(f'[FAIL] {rel}: {exc}', flush=True)
print(f'[HTTP CHECK] {passed}/{len(assets)} distinct HTML/asset references match local bytes and server PID', flush=True)
return not failures
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('port', nargs='?', type=int, default=DEFAULT_PORT, help='preferred port (default: 8000); 0 selects a free port')
parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parent, help='extracted application root')
parser.add_argument('--no-browser', action='store_true', help='do not open a browser automatically')
parser.add_argument('--verify', action='store_true', help='verify all direct HTML assets over HTTP using SHA-256')
parser.add_argument('--verify-only', action='store_true', help='verify direct HTML assets, then exit without opening a browser')
args = parser.parse_args()
if not 0 <= args.port <= 65535:
parser.error('port must be 0 through 65535')
root = args.root.resolve()
print('MPAS Configuration Studio V1.0.0 local server', flush=True)
print(f'OS: {os.name}; Python: {sys.version.split()[0]}; PID: {os.getpid()}', flush=True)
print(f'Serving: {root}', flush=True)
try:
assets = collect_assets(root)
except OSError as exc:
parser.exit(1, f'[FAIL] Incorrect or incomplete application root: {exc}\n')
missing = [rel for _, rel in assets if not (root / rel).is_file()]
if missing:
for rel in sorted(set(missing)):
print(f'[FAIL] Missing local asset: {rel}', flush=True)
return 1
try:
server = bind_server(root, args.port)
except OSError as exc:
print(f'[FAIL] Unable to start local server: {exc}', file=sys.stderr, flush=True)
return 1
with server:
url = f'http://{HOST}:{server.server_port}/'
if args.port and server.server_port != args.port:
print(f'Port {args.port} unavailable; using {server.server_port}.', flush=True)
print('Windows exclusive binding enabled.' if os.name == 'nt' else 'POSIX address reuse enabled.', flush=True)
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
# Always check that the active HTTP server returns the correct entry pages.
# Full asset hashing is optional for normal launches.
check_assets = assets if (args.verify or args.verify_only) else assets[:2]
if not verify_http(root, url, check_assets):
return 1
if args.verify_only:
print('Direct asset delivery verified. No browser test performed.', flush=True)
return 0
print(f'Open: {url}', flush=True)
if not args.no_browser:
threading.Thread(target=webbrowser.open, args=(url,), daemon=True).start()
while worker.is_alive():
worker.join(timeout=0.5)
except KeyboardInterrupt:
print('\nServer stopped.', flush=True)
finally:
server.shutdown()
worker.join(timeout=5)
return 0
if __name__ == '__main__':
raise SystemExit(main())