One image for the whole app: engine, API and dashboard on one port
The backend image now builds the SPA and serves it on the API's own origin (fluksio/spa.py), so an instance is a single container with no proxy, DNS, port 80 or .env: `docker compose up -d` with the new compose.yml runs it on localhost:8080. It starts on fluksio serve (persisted secret key, first admin printed once) and brings its own Redis when REDIS_HOST is unset. Slimmer: python:3.13-slim, no dev group, uv once, fastapi without the cloud CLI. Optional features are per-feature extras (mqtt, influx, email, sentry, ml, server for all) picked with the EXTRAS build argument; numpy moved to `ml`. ffmpeg left the image for imageio-ffmpeg via the Modules screen. The operator stack runs the same image with app. and api. routed to it; the nginx frontend service, the LAN nginx proxy and DOMAIN in the backend are gone, and the MCP issuer is FRONTEND_HOST. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -54,7 +54,12 @@ class Settings(BaseSettings):
|
||||
SECRET_KEY: str = secrets.token_urlsafe(32)
|
||||
# 60 minutes * 24 hours * 8 days = 8 days
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
|
||||
#: The address people and devices reach this instance at: panel links,
|
||||
#: mails and the MCP issuer are built from it.
|
||||
FRONTEND_HOST: str = "http://localhost:5173"
|
||||
#: The built dashboard, served on the API's own origin when set. The image
|
||||
#: sets it; a checkout runs Vite instead and leaves it empty.
|
||||
FRONTEND_DIST: Path | None = None
|
||||
ENVIRONMENT: Literal["local", "staging", "production"] = "local"
|
||||
#: The proxies whose X-Forwarded-For is believed: uvicorn's own setting,
|
||||
#: read here too so a call replayed off the portal tunnel resolves its
|
||||
@@ -111,7 +116,6 @@ class Settings(BaseSettings):
|
||||
# unless asked for: an account can change what flows do, so who gets one
|
||||
# is a superuser's call (Admin → Users).
|
||||
SIGNUP_ENABLED: bool = False
|
||||
DOMAIN: str = "localhost"
|
||||
OAUTH_PRIVATE_KEY_FILE: Path = Path("flow-data/oauth-key.pem")
|
||||
# Written only when someone enrols this instance with a portal.
|
||||
# Its absence is what keeps remote access off.
|
||||
@@ -237,14 +241,14 @@ class Settings(BaseSettings):
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def oauth_issuer(self) -> str:
|
||||
"""Who issues MCP tokens — this app, on its API host.
|
||||
"""Who issues MCP tokens — this app, at the address it is reached on.
|
||||
|
||||
Kept separate from the app's own URL because a hosted deployment can
|
||||
later point agents at a different issuer without the resource server
|
||||
The API is a path on the dashboard's origin, so that one address is
|
||||
both. Kept a property of its own because a hosted deployment can later
|
||||
point agents at a different issuer without the resource server
|
||||
changing: it validates whatever issuer it is configured to trust.
|
||||
"""
|
||||
scheme = "http" if self.ENVIRONMENT == "local" else "https"
|
||||
return f"{scheme}://api.{self.DOMAIN}"
|
||||
return self.FRONTEND_HOST.rstrip("/")
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
|
||||
@@ -15,7 +15,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _influxdb() -> Any:
|
||||
"""The client library, which is a `fluksio[server]` extra.
|
||||
"""The client library, which is the `influx` extra.
|
||||
|
||||
Imported per use rather than at module level, because the node type is
|
||||
registered at boot and an instance with no InfluxDB behind it should
|
||||
@@ -25,7 +25,8 @@ def _influxdb() -> Any:
|
||||
import influxdb_client
|
||||
except ImportError:
|
||||
raise RuntimeError(
|
||||
"the influxdb node needs the server extra: pip install 'fluksio[server]'"
|
||||
"the influxdb node needs the influx extra: pip install 'fluksio[influx]', "
|
||||
"or build the image with EXTRAS=influx"
|
||||
) from None
|
||||
return influxdb_client
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import threading
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from fluksio.flow.messages import MessageSpec
|
||||
@@ -16,6 +15,22 @@ from fluksio.flow.nodes.base import Node
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _numpy() -> Any:
|
||||
"""numpy, which is the `ml` extra.
|
||||
|
||||
Imported when a node is built rather than at boot, so an instance without
|
||||
it still offers every other type, and a node placed without it says so.
|
||||
"""
|
||||
try:
|
||||
import numpy
|
||||
except ImportError:
|
||||
raise RuntimeError(
|
||||
"the mlp node needs the ml extra: pip install 'fluksio[ml]', "
|
||||
"or build the image with EXTRAS=ml"
|
||||
) from None
|
||||
return numpy
|
||||
|
||||
|
||||
class MLPNode(Node):
|
||||
"""
|
||||
Multi-Layer Perceptron node for neural network processing in pipelines.
|
||||
@@ -72,6 +87,7 @@ class MLPNode(Node):
|
||||
)
|
||||
cfg = self.Params.model_validate(self.params)
|
||||
|
||||
np = self._np = _numpy()
|
||||
rng = np.random.default_rng(seed=cfg.seed)
|
||||
num_inputs = max(1, len(self.input_ports))
|
||||
num_outputs = max(1, len(self.output_ports))
|
||||
@@ -91,6 +107,7 @@ class MLPNode(Node):
|
||||
self.id,
|
||||
)
|
||||
|
||||
np = self._np
|
||||
if kwargs:
|
||||
input_array = np.array([float(v) for v in kwargs.values()])
|
||||
else:
|
||||
|
||||
@@ -21,7 +21,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _aiomqtt() -> Any:
|
||||
"""The client library, which is a `fluksio[server]` extra.
|
||||
"""The client library, which is the `mqtt` extra.
|
||||
|
||||
Imported per use rather than at module level, because the node type is
|
||||
registered at boot and an instance that talks to no broker should not
|
||||
@@ -31,7 +31,8 @@ def _aiomqtt() -> Any:
|
||||
import aiomqtt
|
||||
except ImportError:
|
||||
raise RuntimeError(
|
||||
"the mqtt node needs the server extra: pip install 'fluksio[server]'"
|
||||
"the mqtt node needs the mqtt extra: pip install 'fluksio[mqtt]', "
|
||||
"or build the image with EXTRAS=mqtt"
|
||||
) from None
|
||||
return aiomqtt
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ def custom_generate_unique_id(route: APIRoute) -> str:
|
||||
|
||||
|
||||
if settings.SENTRY_DSN and settings.ENVIRONMENT != "local":
|
||||
# Imported here rather than at the top: it is a `fluksio[server]` extra, so
|
||||
# Imported here rather than at the top: it is the `sentry` extra, so
|
||||
# a pip install without one has no sentry to import — and no DSN either.
|
||||
import sentry_sdk
|
||||
|
||||
@@ -506,6 +506,11 @@ if settings.all_cors_origins:
|
||||
|
||||
app.add_middleware(DocsForThisMachine)
|
||||
|
||||
if settings.FRONTEND_DIST:
|
||||
from fluksio.spa import Dashboard
|
||||
|
||||
app.add_middleware(Dashboard, dist=settings.FRONTEND_DIST)
|
||||
|
||||
# The caller's address, for every per-address limit and the docs check above:
|
||||
# the rightmost X-Forwarded-For hop that is not a trusted proxy. uvicorn does
|
||||
# this for what it serves, but a call the portal tunnel replays arrives over an
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""The dashboard, served by the API on its own origin.
|
||||
|
||||
One process and one port: the built SPA comes off disk, and every path the API
|
||||
does not own answers with ``index.html``, so a client-side route survives a
|
||||
reload. Same origin also means the dashboard calls the API as a path, needs no
|
||||
CORS allowance and no second hostname, which is what lets the whole instance
|
||||
sit behind a single published port.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from starlette.middleware.gzip import GZipMiddleware
|
||||
from starlette.responses import FileResponse
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
#: What the API answers itself. Everything else is the dashboard's.
|
||||
API_PREFIXES = ("/api/", "/hooks/", "/mcp", "/.well-known/", "/docs", "/redoc")
|
||||
|
||||
# Older mime tables predate the manifest, and it would go out as a download.
|
||||
mimetypes.add_type("application/manifest+json", ".webmanifest")
|
||||
|
||||
|
||||
def content_security_policy(index_html: str) -> str:
|
||||
"""The policy for the dashboard, admitting its inline scripts by hash.
|
||||
|
||||
The hash is taken from the file being served, so editing the theme script
|
||||
in ``index.html`` cannot leave a stale one behind.
|
||||
style-src 'unsafe-inline': Monaco, Radix's scroll lock and the toasts insert
|
||||
<style> elements at runtime, which no hash can name. img/frame-src take any
|
||||
http(s): a camera stream or website widget points wherever its dashboard
|
||||
says.
|
||||
"""
|
||||
hashes = "".join(
|
||||
f" 'sha256-{base64.b64encode(hashlib.sha256(script.encode()).digest()).decode()}'"
|
||||
for script in re.findall(r"<script>([\s\S]*?)</script>", index_html)
|
||||
)
|
||||
return (
|
||||
f"default-src 'self'; script-src 'self'{hashes}; "
|
||||
"style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: http: https:; "
|
||||
"media-src 'self' blob:; font-src 'self'; connect-src 'self'; "
|
||||
"worker-src 'self'; frame-src http: https:; frame-ancestors 'self'; "
|
||||
"object-src 'none'; base-uri 'self'; form-action 'self'"
|
||||
)
|
||||
|
||||
|
||||
class Dashboard:
|
||||
"""Serve the built SPA for every GET the API does not own."""
|
||||
|
||||
def __init__(self, app: ASGIApp, dist: Path) -> None:
|
||||
self.app = app
|
||||
self.dist = dist.resolve()
|
||||
self.index = self.dist / "index.html"
|
||||
self.headers = {
|
||||
"Content-Security-Policy": content_security_policy(self.index.read_text()),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "strict-origin-when-cross-origin",
|
||||
}
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
path: str = scope.get("path", "")
|
||||
if (
|
||||
scope["type"] != "http"
|
||||
or scope["method"] not in ("GET", "HEAD")
|
||||
or path.startswith(API_PREFIXES)
|
||||
):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
file = (self.dist / path.lstrip("/")).resolve()
|
||||
if file.is_file() and file.is_relative_to(self.dist) and file != self.index:
|
||||
headers = dict(self.headers)
|
||||
# Vite puts a content hash in every asset's name, so one never
|
||||
# changes under its URL.
|
||||
if path.startswith("/assets/"):
|
||||
headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||
else:
|
||||
# The one file that must not be cached: it names the current
|
||||
# assets, so a stale copy pins the browser to the previous build.
|
||||
file = self.index
|
||||
headers = {**self.headers, "Cache-Control": "no-cache"}
|
||||
response = FileResponse(file, headers=headers)
|
||||
await GZipMiddleware(response, minimum_size=1024)(scope, receive, send)
|
||||
@@ -44,7 +44,8 @@ def send_email(
|
||||
import emails # type: ignore
|
||||
except ImportError:
|
||||
raise RuntimeError(
|
||||
"sending mail needs the server extra: pip install 'fluksio[server]'"
|
||||
"sending mail needs the email extra: pip install 'fluksio[email]', "
|
||||
"or build the image with EXTRAS=email"
|
||||
) from None
|
||||
message = emails.Message(
|
||||
subject=subject,
|
||||
|
||||
Reference in New Issue
Block a user