"""One-origin OpenPELS workbench and NGSpice job API.""" from functools import partial from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import unquote, urlsplit import argparse import gzip import json import mimetypes import os import re import shutil from simulator_service import Simulator, STUDY, FIXED_PRESETS from simulator_frame import simulator_html HERE = Path(__file__).resolve().parent class WorkbenchHandler(SimpleHTTPRequestHandler): def send_head(self): path = unquote(urlsplit(self.path).path) # Library and workbench URLs are stable across rebuilds. File mtimes can # go backwards after an archive extraction or switching checkouts. self.mutable_static = not path.startswith('/assets/') and ( path.endswith('/') or Path(path).suffix in {'.html', '.js', '.css', '.json', '.svg'} ) if self.mutable_static and 'If-Modified-Since' in self.headers: del self.headers['If-Modified-Since'] return super().send_head() def end_headers(self): if getattr(self, 'mutable_static', False): self.send_header('Cache-Control', 'no-store') super().end_headers() def send_bytes(self, body, content_type, status=200): if len(body) > 10000 and 'gzip' in self.headers.get('Accept-Encoding', ''): body = gzip.compress(body) encoding = True else: encoding = False self.send_response(status) self.send_header('Content-Type', content_type) self.send_header('Content-Length', str(len(body))) self.send_header('Cache-Control', 'no-store') self.send_header('X-Content-Type-Options', 'nosniff') if encoding: self.send_header('Content-Encoding', 'gzip') self.end_headers() self.wfile.write(body) def send_json(self, value, status=200): self.send_bytes(json.dumps(value, allow_nan=False).encode(), 'application/json', status) def do_GET(self): path = unquote(urlsplit(self.path).path) simulator = self.server.simulator if path == '/healthz': return self.send_json({'ok': True, 'simulator': bool(shutil.which('ngspice')), 'topologies': [*simulator.engine.TOPOLOGIES, *FIXED_PRESETS], 'engine_revision': simulator.source_metadata['revision']}) if path in {'/simulator', '/simulator/'}: return self.send_bytes(simulator_html(simulator.engine.HTML).encode(), 'text/html; charset=utf-8') if path == '/simulator/bridge.js': return self.send_bytes((HERE / 'simulator_bridge.js').read_bytes(), 'text/javascript; charset=utf-8') if path.startswith('/api/simulation/jobs/'): job_id = path.rsplit('/', 1)[-1] job = simulator.get(job_id) if re.fullmatch(r'[0-9a-f]{32}', job_id) else None return self.send_json(job or {'error': 'Simulation job expired or does not exist'}, 200 if job else 404) for prefix, base in [('/simulator/runs/', simulator.engine.RUN_ROOT), ('/simulator/assets/', simulator.site / 'testbenches/images')]: if path.startswith(prefix): target = (base / path.removeprefix(prefix)).resolve() if not target.is_relative_to(base.resolve()) or not target.is_file() or target.is_symlink(): return self.send_json({'error': 'Artifact not found'}, 404) self.send_response(200) self.send_header('Content-Type', mimetypes.guess_type(target.name)[0] or 'application/octet-stream') self.send_header('Content-Length', str(target.stat().st_size)) self.send_header('Cache-Control', 'no-store') self.end_headers() with target.open('rb') as stream: shutil.copyfileobj(stream, self.wfile) return super().do_GET() def do_POST(self): if urlsplit(self.path).path != '/api/simulation/jobs': return self.send_json({'error': 'Endpoint not found'}, 404) try: length = int(self.headers.get('Content-Length', '0')) if not 0 < length <= 16384: return self.send_json({'error': 'Invalid simulation request size'}, 413) payload = json.loads(self.rfile.read(length)) if not isinstance(payload, dict) or set(payload) != {'kind', 'payload'}: raise ValueError('Use a simulation kind and parameter payload') job = self.server.simulator.submit(payload['kind'], payload['payload']) self.send_json(job, 202) except (ValueError, TypeError, KeyError) as error: self.send_json({'error': str(error)}, 400) except BlockingIOError as error: self.send_json({'error': str(error)}, 429) class WorkbenchServer(ThreadingHTTPServer): # Chrome loads the shell and the editor's hashed module graph concurrently. request_queue_size = 128 def create_server(host, port, site, work, engine_path): site = Path(site).resolve() simulator = Simulator(engine_path, site, work) handler = partial(WorkbenchHandler, directory=str(site)) server = WorkbenchServer((host, port), handler) server.simulator = simulator return server def argument_parser(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--host', default='127.0.0.1') parser.add_argument('--port', type=int, default=int(os.environ.get('PORT', 8765))) parser.add_argument('--site', type=Path, default=Path(os.environ.get('OPENPELS_STATIC_DIR') or HERE.parent.parent / 'apps/editor/dist-pe')) parser.add_argument('--work', type=Path, default=Path(os.environ.get('OPENPELS_RUN_DIR', '/tmp/openpels-runtime'))) parser.add_argument('--engine', type=Path, default=Path(os.environ.get('OPENPELS_ENGINE') or HERE.parent.parent.parent / 'openpels-analysis' / STUDY / 'gui/xfly_compare_gui.py')) return parser def main(): parser = argument_parser() args = parser.parse_args() if not shutil.which('ngspice'): parser.error('NGSpice must be installed') server = create_server(args.host, args.port, args.site, args.work, args.engine) print(f'OpenPELS workbench and simulator listening on http://{args.host}:{server.server_port}', flush=True) try: server.serve_forever() finally: server.server_close() server.simulator.worker.shutdown(wait=True) if __name__ == '__main__': main()