forked from upstream-mirrors/OrcaSlicer
98 lines
3.5 KiB
Python
98 lines
3.5 KiB
Python
"""Entry point of the embedded backend in the Android app.
|
|
|
|
The app starts this module in its own process thread. It serves the API under
|
|
/api and the built web client from the same local origin, which nginx does in
|
|
the server deployment, and listens on the loopback interface only.
|
|
"""
|
|
import asyncio
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from starlette.exceptions import HTTPException
|
|
from starlette.responses import FileResponse, PlainTextResponse
|
|
from starlette.staticfiles import StaticFiles
|
|
|
|
|
|
class SpaFiles(StaticFiles):
|
|
"""Static web client; unknown paths fall back to index.html like nginx try_files."""
|
|
|
|
async def get_response(self, path, scope):
|
|
try:
|
|
response = await super().get_response(path, scope)
|
|
except HTTPException as error:
|
|
if error.status_code != 404:
|
|
raise
|
|
response = FileResponse(Path(self.directory) / 'index.html')
|
|
response.headers.setdefault('X-Content-Type-Options', 'nosniff')
|
|
response.headers.setdefault('Referrer-Policy', 'same-origin')
|
|
return response
|
|
|
|
|
|
def build(frontend: Path):
|
|
"""One local origin: /api goes to the backend, everything else to the web client."""
|
|
from orca_web.app import create_app
|
|
api = create_app()
|
|
files = SpaFiles(directory=frontend, html=True)
|
|
|
|
async def app(scope, receive, send):
|
|
if scope['type'] == 'lifespan':
|
|
await api(scope, receive, send)
|
|
elif scope['path'].startswith('/api/'):
|
|
await api(scope, receive, _logging_errors(scope, send))
|
|
elif scope['path'] == '/healthz':
|
|
await PlainTextResponse('ok')(scope, receive, send)
|
|
else:
|
|
await files(scope, receive, send)
|
|
return app
|
|
|
|
|
|
def _logging_errors(scope, send):
|
|
"""Copy API error bodies to stderr (logcat): app storage is not readable over adb."""
|
|
status = {}
|
|
|
|
async def wrapped(message):
|
|
if message['type'] == 'http.response.start':
|
|
status['code'] = message['status']
|
|
elif message['type'] == 'http.response.body' and status.get('code', 200) >= 400:
|
|
body = message.get('body', b'')[:4000].decode(errors='replace')
|
|
print(f"API {status['code']} {scope['method']} {scope['path']}: {body}", file=sys.stderr, flush=True)
|
|
await send(message)
|
|
return wrapped
|
|
|
|
|
|
async def serve(app, port, shutdown_fd):
|
|
import uvicorn
|
|
# Keep forwarded idle connections available. Bound shutdown waits for
|
|
# open preview streams before running the backend's lifespan cleanup.
|
|
config = uvicorn.Config(app, host='127.0.0.1', port=port, log_level='info',
|
|
lifespan='on', ws='websockets', http='h11', loop='asyncio',
|
|
timeout_keep_alive=120, timeout_graceful_shutdown=3)
|
|
server = uvicorn.Server(config)
|
|
loop = asyncio.get_running_loop()
|
|
|
|
def stop():
|
|
loop.remove_reader(shutdown_fd)
|
|
server.should_exit = True
|
|
|
|
if shutdown_fd is not None:
|
|
os.set_inheritable(shutdown_fd, False)
|
|
loop.add_reader(shutdown_fd, stop)
|
|
try:
|
|
await server.serve()
|
|
finally:
|
|
if shutdown_fd is not None:
|
|
loop.remove_reader(shutdown_fd)
|
|
os.close(shutdown_fd)
|
|
|
|
|
|
def main(argv):
|
|
port = int(argv[1]) if len(argv) > 1 else 8765
|
|
shutdown_fd = int(argv[2]) if len(argv) > 2 else None
|
|
frontend = Path(os.environ['WEBSLICER_FRONTEND'])
|
|
asyncio.run(serve(build(frontend), port, shutdown_fd))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main(sys.argv)
|