Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: mpl proxy middleware (#2875)

Myles Scolnick78358ea73094
diff --git a/docs/guides/deploying/deploying_docker.md b/docs/guides/deploying/deploying_docker.md
index f023b5ce6d..32af45e568 100644
--- a/docs/guides/deploying/deploying_docker.md
+++ b/docs/guides/deploying/deploying_docker.md
@@ -75,19 +75,6 @@ docker run -p 8080:8080 -it my_app
After verifying that your application runs without errors, you can use these files to deploy your application on your preferred cloud provider that supports dockerized applications.
-### Using Interactive Matplotlib Plots in Docker
-
-If your notebook uses `mo.mpl.interactive()` for interactive matplotlib plots, you'll need to make some additional configurations in your Dockerfile:
-
-```Dockerfile
-# Add these lines before the CMD instruction
-ENV MARIMO_MPL_HOST="0.0.0.0" # same as main host from `marimo run`.
-ENV MARIMO_MPL_SECURE=true # if you are running on https
-EXPOSE 10000 # Expose in addition to your main application port
-```
-
-This exposes the additional CSS and JavaScript required.
-
## Health checks
You can add a health check to your Dockerfile to ensure that your application is running as expected. This is especially useful when deploying to a cloud provider.
diff --git a/docs/guides/working_with_data/plotting.md b/docs/guides/working_with_data/plotting.md
index a9bb3363e4..37750c01ec 100644
--- a/docs/guides/working_with_data/plotting.md
+++ b/docs/guides/working_with_data/plotting.md
@@ -285,4 +285,3 @@ If you want to output the plot in the console area, use `plt.show()` or
To make matplotlib plots interactive, use
[mo.mpl.interactive](/api/plotting.md#marimo.mpl.interactive).
(Matplotlib plots are not yet reactive.)
-For additional instructions when deploying an interactive matplotlib plot in Docker, see [Interactive Matplotlib Plots in Docker](/guides/deploying/deploying_docker.md#using-interactive-matplotlib-plots-in-docker)
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index 20b95db58a..3bea3fddef 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -18,6 +18,11 @@ import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
+from starlette.websockets import (
+ WebSocketDisconnect,
+ WebSocketState,
+)
+
from marimo._output.builder import h
from marimo._output.formatting import as_html
from marimo._output.hypertext import Html
@@ -97,21 +102,15 @@ def _get_secure() -> bool:
)
-def _template(host: str, port: int, fig_id: str, secure: bool = False) -> str:
- ws_protocol = "wss" if secure else "ws"
- http_protocol = "https" if secure else "http"
-
+def _template(fig_id: str, port: int) -> str:
return html_content % {
- "ws_uri": f"{ws_protocol}://{host}:{port}/ws?figure={fig_id}",
+ "ws_uri": f"/mpl/{port}/ws?figure={fig_id}",
"fig_id": fig_id,
- "base_url": f"{http_protocol}://{host}:{port}",
+ "port": port,
}
-def create_application(
- host: str,
- port: int,
-) -> Starlette:
+def create_application() -> Starlette:
import matplotlib as mpl
from matplotlib.backends.backend_webagg_core import (
FigureManagerWebAgg,
@@ -124,7 +123,8 @@ def create_application(
async def main_page(request: Request) -> HTMLResponse:
figure_id = request.query_params.get("figure")
assert figure_id is not None
- content = _template(host, port, figure_id)
+ port = request.app.state.port
+ content = _template(figure_id, port)
return HTMLResponse(content=content)
async def mpl_js(request: Request) -> Response:
@@ -155,8 +155,7 @@ def create_application(
async def websocket_endpoint(websocket: WebSocket) -> None:
await websocket.accept()
-
- queue = asyncio.Queue[Tuple[Any, str]]()
+ queue: asyncio.Queue[Tuple[Any, str]] = asyncio.Queue()
class SyncWebSocket:
def send_json(self, content: str) -> None:
@@ -166,8 +165,25 @@ def create_application(
queue.put_nowait((blob, "binary"))
figure_id = websocket.query_params.get("figure")
- assert figure_id is not None
- figure_manager = figure_managers.get(figure_id)
+ if not figure_id:
+ await websocket.send_json(
+ {"type": "error", "message": "No figure ID provided"}
+ )
+ await websocket.close()
+ return
+
+ try:
+ figure_manager = figure_managers.get(figure_id)
+ except RuntimeError:
+ await websocket.send_json(
+ {
+ "type": "error",
+ "message": f"Figure with id '{figure_id}' not found",
+ }
+ )
+ await websocket.close()
+ return
+
figure_manager.add_web_socket(SyncWebSocket()) # type: ignore[no-untyped-call]
async def receive() -> None:
@@ -181,11 +197,14 @@ def create_application(
pass
else:
figure_manager.handle_json(data) # type: ignore[no-untyped-call]
- except Exception:
+ except WebSocketDisconnect:
pass
+ except Exception as e:
+ if websocket.application_state != WebSocketState.DISCONNECTED:
+ await websocket.send_json(
+ {"type": "error", "message": str(e)}
+ )
finally:
- from starlette.websockets import WebSocketState
-
if websocket.application_state != WebSocketState.DISCONNECTED:
await websocket.close()
@@ -197,25 +216,34 @@ def create_application(
await websocket.send_json(data)
else:
await websocket.send_bytes(data)
- except Exception:
+ except WebSocketDisconnect:
+ # Client disconnected normally
pass
+ except Exception as e:
+ if websocket.application_state != WebSocketState.DISCONNECTED:
+ await websocket.send_json(
+ {"type": "error", "message": str(e)}
+ )
finally:
- from starlette.websockets import WebSocketState
-
if websocket.application_state != WebSocketState.DISCONNECTED:
await websocket.close()
- await asyncio.gather(receive(), send())
+ try:
+ await asyncio.gather(receive(), send())
+ except Exception as e:
+ if websocket.application_state != WebSocketState.DISCONNECTED:
+ await websocket.send_json({"type": "error", "message": str(e)})
+ await websocket.close()
return Starlette(
routes=[
Route("/", main_page, methods=["GET"]),
- Route("/mpl/mpl.js", mpl_js, methods=["GET"]),
- Route("/mpl/custom.css", mpl_custom_css, methods=["GET"]),
+ Route("/mpl.js", mpl_js, methods=["GET"]),
+ Route("/custom.css", mpl_custom_css, methods=["GET"]),
Route("/download.{fmt}", download, methods=["GET"]),
WebSocketRoute("/ws", websocket_endpoint),
Mount(
- "/mpl/_static",
+ "/_static",
StaticFiles(
directory=FigureManagerWebAgg.get_static_file_path() # type: ignore[no-untyped-call]
),
@@ -224,7 +252,7 @@ def create_application(
Mount(
"/_images",
StaticFiles(directory=Path(mpl.get_data_path(), "images")),
- name="images",
+ name="mpl_images",
),
],
)
@@ -246,7 +274,7 @@ def get_or_create_application(
host = app_host if app_host is not None else _get_host()
port = free_port if free_port is not None else find_free_port(10_000)
secure = secure_host if secure_host is not None else _get_secure()
- app = create_application(host, port)
+ app = create_application()
app.state.host = host
app.state.port = port
app.state.secure = secure
@@ -335,10 +363,8 @@ def interactive(figure: Union[Figure, Axes]) -> Html:
# TODO(akshayka): Proxy this server through the marimo server to help with
# deployment.
- application = get_or_create_application()
- host = application.state.host
- port = application.state.port
- secure = application.state.secure
+ app = get_or_create_application()
+ port = app.state.port
class CleanupHandle(CellLifecycleItem):
def create(self, context: RuntimeContext) -> None:
@@ -355,11 +381,10 @@ def interactive(figure: Union[Figure, Axes]) -> Html:
ctx.cell_lifecycle_registry.add(CleanupHandle())
ctx.stream.cell_id = ctx.execution_context.cell_id
- content = _template(host, port, str(figure_manager.num), secure)
+ content = _template(str(figure_manager.num), port)
return Html(
h.iframe(
- # srcdoc allows us to use __resizeIframe
srcdoc=html.escape(content),
width="100%",
height="550px",
@@ -371,14 +396,14 @@ def interactive(figure: Union[Figure, Axes]) -> Html:
html_content = """
<!DOCTYPE html>
<html lang="en">
- <base href="%(base_url)s" />
<head>
- <link rel="stylesheet" href="mpl/_static/css/page.css" type="text/css" />
- <link rel="stylesheet" href="mpl/_static/css/boilerplate.css" type="text/css" />
- <link rel="stylesheet" href="mpl/_static/css/fbm.css" type="text/css" />
- <link rel="stylesheet" href="mpl/_static/css/mpl.css" type="text/css" />
- <link rel="stylesheet" href="mpl/custom.css" type="text/css" />
- <script src="mpl/mpl.js"></script>
+ <base href='/mpl/%(port)s/ ' />
+ <link rel="stylesheet" href="/mpl/%(port)s/_static/css/page.css" type="text/css" />
+ <link rel="stylesheet" href="/mpl/%(port)s/_static/css/boilerplate.css" type="text/css" />
+ <link rel="stylesheet" href="/mpl/%(port)s/_static/css/fbm.css" type="text/css" />
+ <link rel="stylesheet" href="/mpl/%(port)s/_static/css/mpl.css" type="text/css" />
+ <link rel="stylesheet" href="/mpl/%(port)s/custom.css" type="text/css" />
+ <script src="/mpl/%(port)s/mpl.js"></script>
<script>
function ondownload(figure, format) {
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 921fb9a572..0e655bee1a 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -1,7 +1,17 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional
+import asyncio
+from http.client import HTTPResponse, HTTPSConnection
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterable,
+ Callable,
+ Optional,
+ Union,
+)
+from urllib.parse import urljoin, urlparse
import starlette.status as status
from starlette.authentication import (
@@ -10,13 +20,17 @@ from starlette.authentication import (
BaseUser,
SimpleUser,
)
+from starlette.background import BackgroundTask
from starlette.middleware.base import (
BaseHTTPMiddleware,
DispatchFunction,
RequestResponseEndpoint,
)
-from starlette.requests import HTTPConnection, Request
-from starlette.responses import JSONResponse, Response
+from starlette.requests import Request
+from starlette.responses import JSONResponse, Response, StreamingResponse
+from starlette.websockets import WebSocket, WebSocketState
+from websockets import ConnectionClosed
+from websockets.client import connect
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
@@ -144,3 +158,266 @@ class OpenTelemetryMiddleware(BaseHTTPMiddleware):
span.set_status(self.Status(self.StatusCode.ERROR, str(e)))
raise
return response
+
+
+class _URLRequest:
+ def __init__(
+ self, url: str, method: str, headers: dict[str, str], data: Any
+ ):
+ self.full_url = url
+ self.method = method
+ self.headers = headers
+ self.data = data
+
+
+class _AsyncHTTPResponse:
+ def __init__(self, response: HTTPResponse):
+ self.raw_response = response
+ self.status_code = response.status
+ self.headers = {k.lower(): v for k, v in response.getheaders()}
+
+ async def aiter_raw(self) -> AsyncIterable[bytes]:
+ try:
+ while True:
+ chunk = self.raw_response.read(8192)
+ if not chunk:
+ break
+ yield chunk
+ except Exception:
+ raise
+ finally:
+ await self.aclose()
+
+ async def aclose(self) -> None:
+ self.raw_response.close()
+
+
+class _AsyncHTTPClient:
+ def __init__(self, base_url: str):
+ self.base_url = base_url.rstrip("/")
+ parsed = urlparse(base_url)
+ self.host = parsed.netloc
+ self.is_https = parsed.scheme == "https"
+
+ def build_request(
+ self, method: str, url: Any, headers: dict[str, str], content: Any
+ ) -> _URLRequest:
+ # Combine base_url with path and query to form a full URL
+ full_url = f"{self.base_url}{url.path}"
+ if hasattr(url, "query") and url.query:
+ full_url += f"?{url.query.decode('utf-8')}"
+
+ headers = dict(headers)
+ headers["host"] = self.host
+
+ request = _URLRequest(
+ full_url, # Use the full URL here
+ method=method,
+ headers=headers,
+ data=content,
+ )
+
+ request.method = method
+ return request
+
+ async def send(
+ self, request: _URLRequest, stream: bool = False
+ ) -> _AsyncHTTPResponse:
+ del stream
+ loop = asyncio.get_event_loop()
+
+ async def collect_body() -> bytes:
+ if hasattr(request, "data"):
+ if request.data is None:
+ return b""
+ if isinstance(request.data, AsyncIterable):
+ chunks: list[bytes] = []
+ try:
+ async for chunk in request.data:
+ if isinstance(chunk, str):
+ chunks.append(chunk.encode())
+ else:
+ chunks.append(chunk)
+ return b"".join(chunks)
+ except Exception:
+ raise
+ if isinstance(request.data, str):
+ return request.data.encode()
+ if isinstance(request.data, bytes):
+ return request.data
+ if hasattr(request.data, "read"):
+ return request.data.read() # type: ignore
+ raise ValueError(
+ f"Unsupported request data type: {type(request.data)}"
+ )
+ return b""
+
+ try:
+ body = await collect_body()
+ except Exception:
+ raise
+
+ def _send() -> HTTPResponse:
+ from http.client import HTTPConnection
+
+ parsed_url = urlparse(request.full_url)
+ path_and_query = parsed_url.path
+ if parsed_url.query:
+ path_and_query += f"?{parsed_url.query}"
+
+ conn_class = HTTPSConnection if self.is_https else HTTPConnection
+ conn = conn_class(self.host)
+
+ method = request.method if request.method is not None else "GET"
+
+ try:
+ conn.request(
+ method=method,
+ url=path_and_query, # Only path and query
+ body=body,
+ headers=request.headers,
+ )
+ resp = conn.getresponse()
+ return resp # type: ignore[no-any-return]
+ except Exception:
+ raise
+
+ response = await loop.run_in_executor(None, _send)
+ return _AsyncHTTPResponse(response)
+
+
+class ProxyMiddleware:
+ def __init__(
+ self,
+ app: ASGIApp,
+ proxy_path: str,
+ target_url: Union[str, Callable[[str], str]],
+ path_rewrite: Callable[[str], str] | None = None,
+ ) -> None:
+ self.app = app
+ self.path = proxy_path.rstrip("/")
+ self.target_url = target_url
+ self.path_rewrite = path_rewrite
+
+ def _get_target_url(self, path: str) -> str:
+ """Get target URL either from rewrite function or default MPL logic."""
+ if callable(self.target_url):
+ return self.target_url(path)
+
+ return self.target_url
+
+ async def __call__(
+ self, scope: Scope, receive: Receive, send: Send
+ ) -> None:
+ if scope["type"] == "websocket":
+ if not scope["path"].startswith(self.path):
+ return await self.app(scope, receive, send)
+
+ ws_target_url = self._get_target_url(scope["path"])
+ ws_path = scope["path"]
+ if self.path_rewrite:
+ ws_path = self.path_rewrite(ws_path)
+ ws_url = urljoin(ws_target_url, ws_path)
+ if scope["scheme"] in ("http", "ws"):
+ ws_url = ws_url.replace("http", "ws", 1)
+ elif scope["scheme"] in ("https", "wss"):
+ ws_url = ws_url.replace("https", "wss", 1)
+
+ await self._proxy_websocket(scope, receive, send, ws_url)
+ return
+
+ if scope["type"] != "http":
+ return await self.app(scope, receive, send)
+
+ request = Request(scope, receive)
+ if not scope["path"].startswith(self.path):
+ await self.app(scope, receive, send)
+ return
+
+ target_base = self._get_target_url(request.url.path)
+ # Remove proxy path prefix for proxied request
+ target_path = request.url.path
+ if self.path_rewrite:
+ target_path = self.path_rewrite(target_path)
+ target_query = request.url.query.encode("utf-8")
+
+ # Create client if needed (for dynamic target URLs)
+ client = _AsyncHTTPClient(base_url=target_base)
+
+ # Construct the URL object with path and query
+ url = type("URL", (), {"path": target_path, "query": target_query})()
+
+ headers = {k.decode(): v.decode() for k, v in request.headers.raw}
+
+ rp_req = client.build_request(
+ request.method,
+ url,
+ headers=headers,
+ content=request.stream(),
+ )
+
+ rp_resp = await client.send(rp_req, stream=True)
+ response = StreamingResponse(
+ rp_resp.aiter_raw(),
+ status_code=rp_resp.status_code,
+ headers=rp_resp.headers,
+ background=BackgroundTask(rp_resp.aclose),
+ )
+ await response(scope, receive, send)
+
+ async def _proxy_websocket(
+ self, scope: Scope, receive: Receive, send: Send, ws_url: str
+ ) -> None:
+ websocket = WebSocket(scope, receive=receive, send=send)
+ original_params = websocket.query_params
+ if original_params:
+ ws_url = f"{ws_url}?{'&'.join(f'{k}={v}' for k,v in original_params.items())}"
+ await websocket.accept()
+
+ async with connect(ws_url) as ws_client:
+
+ async def client_to_upstream() -> None:
+ try:
+ while True:
+ msg = await websocket.receive()
+ if msg["type"] == "websocket.disconnect":
+ return
+
+ if "text" in msg:
+ await ws_client.send(msg["text"])
+ elif "bytes" in msg:
+ await ws_client.send(msg["bytes"])
+ except ConnectionClosed:
+ return
+ except Exception:
+ return
+
+ async def upstream_to_client() -> None:
+ try:
+ while True:
+ msg = await ws_client.recv()
+ if isinstance(msg, bytes):
+ await websocket.send_bytes(msg)
+ else:
+ await websocket.send_text(msg)
+ except ConnectionClosed:
+ return
+ except Exception:
+ return
+
+ # Run both relay loops concurrently
+ relay_tasks = [
+ asyncio.create_task(client_to_upstream()),
+ asyncio.create_task(upstream_to_client()),
+ ]
+
+ try:
+ await asyncio.gather(*relay_tasks)
+ except Exception as e:
+ raise e
+ finally:
+ try:
+ if websocket.client_state != WebSocketState.DISCONNECTED:
+ await websocket.close()
+ except Exception as e:
+ raise e
diff --git a/marimo/_server/main.py b/marimo/_server/main.py
index 13756455eb..82768335b8 100644
--- a/marimo/_server/main.py
+++ b/marimo/_server/main.py
@@ -19,6 +19,7 @@ from marimo._server.api.auth import (
from marimo._server.api.middleware import (
AuthBackend,
OpenTelemetryMiddleware,
+ ProxyMiddleware,
SkewProtectionMiddleware,
)
from marimo._server.api.router import build_routes
@@ -110,6 +111,7 @@ def create_starlette_app(
allow_headers=["*"],
),
Middleware(SkewProtectionMiddleware),
+ _create_mpl_proxy_middleware(),
]
)
@@ -126,3 +128,23 @@ def create_starlette_app(
MarimoHTTPException: handle_error,
},
)
+
+
+def _create_mpl_proxy_middleware() -> Middleware:
+ # MPL proxy logic
+ def mpl_target_url(path: str) -> str:
+ # Path format: /mpl/<port>/rest/of/path
+ port = path.split("/", 3)[2]
+ return f"http://localhost:{port}"
+
+ def mpl_path_rewrite(path: str) -> str:
+ # Remove the /mpl/<port>/ prefix
+ rest = path.split("/", 3)[3]
+ return f"/{rest}"
+
+ return Middleware(
+ ProxyMiddleware,
+ proxy_path="/mpl",
+ target_url=mpl_target_url,
+ path_rewrite=mpl_path_rewrite,
+ )
diff --git a/pyproject.toml b/pyproject.toml
index f9f8e17968..7348c2704f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -75,22 +75,19 @@ marimo = "marimo._cli.cli:main"
homepage = "https://github.com/marimo-team/marimo"
[project.optional-dependencies]
-sql = [
- "duckdb >= 1.0.0",
- "polars >= 1.9.0",
-]
+sql = ["duckdb >= 1.0.0", "polars >= 1.9.0"]
# List of deps that are recommended for most users
# in order to unlock all features in marimo
recommended = [
- "duckdb>=1.1.0", # SQL cells
- "altair>=5.4.0", # Plotting in datasource viewer
- "polars>=1.9.0", # SQL output back in Python
+ "duckdb>=1.1.0", # SQL cells
+ "altair>=5.4.0", # Plotting in datasource viewer
+ "polars>=1.9.0", # SQL output back in Python
"openai>=1.41.1", # AI features
- "ruff", # Formatting
+ "ruff", # Formatting
]
dev = [
- "click <8.1.4", # https://github.com/pallets/click/issues/2558
+ "click <8.1.4", # https://github.com/pallets/click/issues/2558
"black~=23.12.1",
# For tracing debugging
"opentelemetry-api~=1.26.0",
@@ -114,7 +111,7 @@ docs = [
"sphinx-design~=0.5.0",
"sphinx-autobuild~=2024.10.3",
"myst_parser~=3.0.1",
- "furo==2024.8.6"
+ "furo==2024.8.6",
]
[tool.hatch]
@@ -125,12 +122,22 @@ path = "marimo/__init__.py"
[tool.hatch.build.targets.sdist]
include = ["/marimo"]
-artifacts = ["marimo/_static/", "marimo/_lsp/", "third_party.txt", "third_party_licenses.txt"]
+artifacts = [
+ "marimo/_static/",
+ "marimo/_lsp/",
+ "third_party.txt",
+ "third_party_licenses.txt",
+]
exclude = ["marimo/_smoke_tests"]
[tool.hatch.build.targets.wheel]
include = ["/marimo"]
-artifacts = ["marimo/_static/", "marimo/_lsp/", "third_party.txt", "third_party_licenses.txt"]
+artifacts = [
+ "marimo/_static/",
+ "marimo/_lsp/",
+ "third_party.txt",
+ "third_party_licenses.txt",
+]
exclude = ["marimo/_smoke_tests"]
# Override the default uv version to use the latest version
@@ -179,6 +186,7 @@ extra-dependencies = [
"hypothesis~=6.102.1",
# For server testing
"httpx~=0.27.0",
+ "matplotlib~=3.9.2",
"pytest~=8.3.2",
"pytest-timeout~=2.3.1",
"pytest-codecov~=0.5.1",
@@ -186,7 +194,7 @@ extra-dependencies = [
]
[[tool.hatch.envs.test.matrix]]
-python = ["3.9","3.10", "3.11", "3.12"]
+python = ["3.9", "3.10", "3.11", "3.12"]
[tool.hatch.envs.test.scripts]
test = "pytest{env:HATCH_TEST_ARGS:} {args:tests}"
@@ -206,12 +214,12 @@ template = "test"
extra-dependencies = [
"hypothesis~=6.102.1",
"httpx~=0.27.0",
+ "matplotlib~=3.9.2",
"pytest~=8.3.2",
"pytest-timeout~=2.3.1",
"pytest-codecov~=0.5.1",
"pytest-asyncio~=0.23.8",
# For testing mo.ui.chart, table, ...
- "matplotlib",
"vl-convert-python",
"pyarrow",
"pyarrow_hotfix",
@@ -239,7 +247,7 @@ extra-dependencies = [
]
[[tool.hatch.envs.test-optional.matrix]]
-python = ["3.9","3.10", "3.11", "3.12"]
+python = ["3.9", "3.10", "3.11", "3.12"]
[tool.hatch.envs.docs]
features = ["docs"]
@@ -250,7 +258,7 @@ autobuild = "sphinx-autobuild {args:docs/ docs/_build}"
clean = "cd docs && make clean"
[tool.ruff]
-line-length=79
+line-length = 79
include = ["marimo/**/*.py", "tests/**/*.py", "dagger/**/*.py"]
exclude = [
"examples",
@@ -275,12 +283,12 @@ exclude = [
[tool.ruff.lint]
ignore = [
- "G004", # Logging statement uses f-string
+ "G004", # Logging statement uses f-string
"TCH001", # Move application import into a type-checking block
- "D301", # Use r""" if any backslashes in a docstring
+ "D301", # Use r""" if any backslashes in a docstring
# TODO: we should fix these, and enable this rule
"PT011", # `pytest.raises(ValueError)` is too broad, set the `match` parameter or use a more specific exception
- "E501", # Line too long, we still trim
+ "E501", # Line too long, we still trim
]
extend-select = [
# pyflakes
@@ -307,10 +315,10 @@ extend-select = [
"I001",
# Enable entire ruff rule section
"ASYNC", # subset of flake8-async rules
- "TCH", # Rules around TYPE_CHECKING blocks
- "G", # flake8-logging-format rules
- "LOG", # flake8-logging rules, most of them autofixable
- "PT", # flake8-pytest-style rules
+ "TCH", # Rules around TYPE_CHECKING blocks
+ "G", # flake8-logging-format rules
+ "LOG", # flake8-logging rules, most of them autofixable
+ "PT", # flake8-pytest-style rules
"TID25", # flake8-tidy-imports rules
# Per rule enables
# "RUF100", # Unused noqa (auto-fixable)
@@ -325,13 +333,13 @@ extend-select = [
"D403",
"D412",
"D419",
- "PGH004", # Use specific rule codes when using noqa
+ "PGH004", # Use specific rule codes when using noqa
"PGH005", # Invalid unittest.mock.Mock methods/attributes/properties
# "S101", # Checks use `assert` outside the test cases, test cases should be added into the exclusions
- "B004", # Checks for use of hasattr(x, "__call__") and replaces it with callable(x)
- "B006", # Checks for uses of mutable objects as function argument defaults.
- "B017", # Checks for pytest.raises context managers that catch Exception or BaseException.
- "B019", # Use of functools.lru_cache or functools.cache on methods can lead to memory leaks
+ "B004", # Checks for use of hasattr(x, "__call__") and replaces it with callable(x)
+ "B006", # Checks for uses of mutable objects as function argument defaults.
+ "B017", # Checks for pytest.raises context managers that catch Exception or BaseException.
+ "B019", # Use of functools.lru_cache or functools.cache on methods can lead to memory leaks
"TRY002", # Prohibit use of `raise Exception`, use specific exceptions instead.
]
@@ -357,7 +365,16 @@ docstring-code-format = true
ban-relative-imports = "all"
# Ban certain modules from being imported at module level, instead requiring
# that they're imported lazily (e.g., within a function definition).
-banned-module-level-imports = ["numpy", "pandas", "tomlkit", "polars", "altair", "ipython", "anywidget", "packaging"]
+banned-module-level-imports = [
+ "numpy",
+ "pandas",
+ "tomlkit",
+ "polars",
+ "altair",
+ "ipython",
+ "anywidget",
+ "packaging",
+]
[tool.ruff.lint.flake8-pytest-style]
mark-parentheses = false
@@ -377,22 +394,20 @@ exclude = [
'marimo/_snippets/data/',
'marimo/_smoke_tests/',
]
-warn_unused_ignores=false
+warn_unused_ignores = false
# tutorials shouldn't be type-checked (should be excluded), but they
# get included anyway, maybe due to import following; this is coarse but works
[[tool.mypy.overrides]]
-module= "marimo._tutorials.*"
+module = "marimo._tutorials.*"
ignore_errors = true
[tool.pytest.ini_options]
minversion = "6.0"
addopts = "-ra -q -v --ignore tests/_cli/ipynb_data --ignore tests/_ast/codegen_data --ignore tests/_ast/app_data"
-testpaths = [
- "tests",
-]
+testpaths = ["tests"]
asyncio_mode = "auto"
-timeout = 30 # seconds, per test
+timeout = 30 # seconds, per test
[tool.coverage.run]
omit = ["marimo/_tutorials/*"]
@@ -402,9 +417,9 @@ extend-ignore-re = ["[0-9a-zA-Z]{43}"]
[tool.typos.default.extend-words]
wheres = "wheres"
-Ue = "Ue" # Used in one of the cell IDs
-Nd = "Nd" # Confused with And
-pn = "pn" # Panel
+Ue = "Ue" # Used in one of the cell IDs
+Nd = "Nd" # Confused with And
+pn = "pn" # Panel
[tool.typos.files]
extend-exclude = [
diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.py
index 4f003bb630..f3552369cc 100644
--- a/tests/_server/api/test_middleware.py
+++ b/tests/_server/api/test_middleware.py
@@ -1,20 +1,38 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import TYPE_CHECKING, Any
+import io
+import json
+import time
+from multiprocessing import Process
+from typing import TYPE_CHECKING, Any, Tuple
import pytest
import uvicorn
+from starlette.applications import Starlette
+from starlette.responses import Response
+from starlette.routing import Route
from starlette.testclient import TestClient
+from starlette.websockets import WebSocket, WebSocketDisconnect
+from uvicorn import Config, Server
from marimo._config.manager import UserConfigManager
+from marimo._server.api.middleware import (
+ ProxyMiddleware,
+ _AsyncHTTPClient,
+ _URLRequest,
+)
from marimo._server.main import create_starlette_app
from marimo._server.model import SessionMode
from marimo._server.tokens import AuthToken
+from marimo._server.utils import find_free_port
from tests._server.mocks import get_mock_session_manager, token_header
if TYPE_CHECKING:
- from starlette.applications import Starlette
+ from pathlib import Path
+
+ from starlette.requests import Request
+ from starlette.types import ASGIApp, Receive, Scope, Send
def test_base_url() -> None:
@@ -227,15 +245,352 @@ class TestNoAuth:
assert response.headers.get("Set-Cookie") is None
def tets_any_query(self, no_auth_app: Starlette) -> None:
- # Test unauthorized access with bad auth token
client = TestClient(no_auth_app)
response = client.get("/?access_token=bad-token")
assert response.status_code == 200, response.text
assert response.headers.get("Set-Cookie") is None
def test_any_header(self, no_auth_app: Starlette) -> None:
- # Test unauthorized access with bad auth token
client = TestClient(no_auth_app)
response = client.get("/", headers=token_header("bad-token"))
assert response.status_code == 200, response.text
assert response.headers.get("Set-Cookie") is None
+
+
+async def target_app(scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] == "http":
+ response = Response(
+ json.dumps({"message": "response from proxied app"}),
+ media_type="application/json",
+ )
+ await response(scope, receive, send)
+ elif scope["type"] == "websocket":
+ websocket = WebSocket(scope, receive=receive, send=send)
+ await websocket.accept()
+ try:
+ while True:
+ await websocket.receive_json()
+ await websocket.send_json(
+ {"message": "ws response from proxied app"}
+ )
+ except WebSocketDisconnect:
+ print("Client disconnected")
+ return
+
+
+def run_target_server():
+ """Runs the target app with uvicorn."""
+ config = Config(
+ app=target_app, host="127.0.0.1", port=8765, log_level="info"
+ )
+ server = Server(config)
+ server.run()
+
+
+def run_mpl_server(host: str, port: int):
+ """Runs the matplotlib plugin server.
+ Defined at module level so it can be pickled."""
+ from marimo._plugins.stateless.mpl._mpl import (
+ create_application, # Import here to avoid circular imports
+ )
+
+ app = create_application()
+ app.state.host = host
+ app.state.port = port
+ app.state.secure = False
+ config = Config(app=app, host=host, port=port, log_level="info")
+ server = Server(config)
+ server.run()
+
+
+async def serve_static(request: Request) -> Response:
+ del request
+ content = "body { color: red; }"
+ return Response(content=content, media_type="text/css")
+
+
+async def serve_large_file(request: Request) -> Response:
+ del request
+ content = "x" * 1024 * 1024 # 1MB of 'x' characters
+ return Response(content=content, media_type="text/plain")
+
+
+target_static_app = Starlette(
+ routes=[
+ Route("/_static/css/page.css", serve_static),
+ Route("/_static/large-file.txt", serve_large_file),
+ ]
+)
+
+
+def run_static_server():
+ """Runs the static file server with uvicorn."""
+ config = Config(
+ app=target_static_app, host="127.0.0.1", port=8766, log_level="info"
+ )
+ server = Server(config)
+ server.run()
+
+
+class TestProxyMiddleware:
+ @pytest.fixture(scope="module")
+ def target_server(self):
+ """Start a separate `uvicorn` server for the target app."""
+ process = Process(target=run_target_server, daemon=True)
+ process.start()
+ time.sleep(1) # Ensure the server has started before tests run
+ yield None
+ process.terminate()
+ process.join()
+
+ @pytest.fixture
+ def app_with_proxy(
+ self, edit_app: Starlette, target_server: None
+ ) -> ASGIApp:
+ del target_server
+ """Create the app with ProxyMiddleware targeting the running server."""
+ edit_app.add_middleware(
+ ProxyMiddleware,
+ proxy_path="/proxy",
+ target_url="http://127.0.0.1:8765",
+ )
+ return edit_app
+
+ @pytest.fixture(scope="module")
+ def mpl_server(self):
+ """Start the matplotlib plugin server in a separate process."""
+ host = "127.0.0.1"
+ port = find_free_port(10_000)
+
+ process = Process(
+ target=run_mpl_server, args=(host, port), daemon=True
+ )
+ process.start()
+ time.sleep(1)
+ yield host, port
+ process.terminate()
+ process.join()
+
+ @pytest.fixture
+ def app_with_mpl_proxy(
+ self, edit_app: Starlette, mpl_server: Tuple[str, int]
+ ) -> ASGIApp:
+ """Create the app with ProxyMiddleware targeting the matplotlib plugin server."""
+ host, port = mpl_server
+ target_url = f"http://{host}:{port}"
+ edit_app.add_middleware(
+ ProxyMiddleware,
+ proxy_path="/mpl",
+ target_url=target_url,
+ )
+ return edit_app
+
+ @pytest.fixture(scope="module")
+ def static_server(self):
+ """Start a separate server for static files."""
+ process = Process(target=run_static_server, daemon=True)
+ process.start()
+ time.sleep(1) # Ensure the server has started
+ yield None
+ process.terminate()
+ process.join()
+
+ @pytest.fixture
+ def app_with_static_proxy(
+ self, edit_app: Starlette, static_server: None, tmp_path: Path
+ ) -> ASGIApp:
+ del static_server
+ """Create the app with ProxyMiddleware targeting the static server."""
+ # Create test static files
+ css_dir = tmp_path / "static" / "css"
+ css_dir.mkdir(parents=True)
+ css_file = css_dir / "page.css"
+ css_file.write_text("body { color: red; }")
+
+ large_file = tmp_path / "static" / "large-file.txt"
+ large_file.write_text("x" * 1024 * 1024) # 1MB file
+
+ edit_app.add_middleware(
+ ProxyMiddleware,
+ proxy_path="/_static",
+ target_url="http://127.0.0.1:8766",
+ )
+ return edit_app
+
+ def test_proxy_static_file(self, app_with_static_proxy: Starlette) -> None:
+ client = TestClient(app_with_static_proxy)
+ response = client.get("/_static/css/page.css")
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"].startswith("text/css")
+ assert "body { color: red; }" in response.text
+
+ def test_proxy_large_static_file(
+ self, app_with_static_proxy: Starlette
+ ) -> None:
+ client = TestClient(app_with_static_proxy)
+ response = client.get("/_static/large-file.txt")
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"].startswith("text/plain")
+ assert (
+ len(response.content) == 1024 * 1024
+ ) # Check full content length
+
+ def test_proxy_static_file_streaming(
+ self, app_with_static_proxy: Starlette
+ ) -> None:
+ client = TestClient(app_with_static_proxy)
+ with client.stream("GET", "/_static/large-file.txt") as response:
+ assert response.status_code == 200, response.text
+ content_length = 0
+ for chunk in response.iter_bytes():
+ content_length += len(chunk)
+ assert content_length == 1024 * 1024
+
+ @pytest.mark.asyncio
+ async def test_http_client_streaming(
+ self, app_with_proxy: Starlette
+ ) -> None:
+ del app_with_proxy
+ client = _AsyncHTTPClient(base_url="http://127.0.0.1:8765")
+
+ request = _URLRequest(
+ "http://127.0.0.1:8765/test",
+ method="POST",
+ headers={"Content-Type": "application/json"},
+ data=b"test string",
+ )
+ response = await client.send(request, stream=True)
+ assert response.status_code == 200
+ chunks = [chunk async for chunk in response.aiter_raw()]
+ assert len(chunks) > 0
+ await response.aclose()
+
+ @pytest.mark.asyncio
+ async def test_http_client_body_types(
+ self, app_with_proxy: Starlette
+ ) -> None:
+ del app_with_proxy
+ client = _AsyncHTTPClient(base_url="http://127.0.0.1:8765")
+
+ # Test with bytes data
+ request = _URLRequest(
+ "http://127.0.0.1:8765/test",
+ method="POST",
+ headers={"Content-Type": "application/json"},
+ data=b'{"test": "data"}',
+ )
+ response = await client.send(request)
+ assert response.status_code == 200
+ await response.aclose()
+
+ # Test with iterable of bytes using a file-like object
+ class BytesBuffer(io.BytesIO):
+ def read(self, size: int | None = -1) -> bytes:
+ return super().read(size)
+
+ buffer = BytesBuffer(b'{"test": "data"}')
+ request = _URLRequest(
+ "http://127.0.0.1:8765/test",
+ method="POST",
+ headers={"Content-Type": "application/json"},
+ data=buffer,
+ )
+ response = await client.send(request)
+ assert response.status_code == 200
+ await response.aclose()
+
+ @pytest.mark.asyncio
+ async def test_http_client_headers(
+ self, app_with_proxy: Starlette
+ ) -> None:
+ del app_with_proxy
+ client = _AsyncHTTPClient(base_url="http://127.0.0.1:8765")
+
+ custom_headers = {
+ "X-Test-Header": "test-value",
+ "Content-Type": "application/json",
+ }
+ request = _URLRequest(
+ "http://127.0.0.1:8765/test",
+ method="GET",
+ headers=custom_headers,
+ data=None, # Explicitly set to None for GET request
+ )
+ response = await client.send(request)
+ assert response.headers.get("content-type") == "application/json"
+ await response.aclose()
+
+ def test_http_client_url_building(self) -> None:
+ client = _AsyncHTTPClient(base_url="http://127.0.0.1:8765")
+
+ url = type(
+ "URL", (), {"path": "/test/path", "query": b"param=value"}
+ )()
+
+ request = client.build_request("GET", url, headers={}, content=None)
+ assert (
+ request.full_url == "http://127.0.0.1:8765/test/path?param=value"
+ )
+ assert "host" in request.headers
+
+ @pytest.mark.parametrize(
+ ("method", "payload"),
+ [
+ ("GET", None),
+ ("POST", {"data": "test"}),
+ ],
+ )
+ def test_proxy_basic_http_functionality(
+ self,
+ app_with_proxy: Starlette,
+ method: str,
+ payload: dict[str, Any] | None,
+ ) -> None:
+ client = TestClient(app_with_proxy)
+ response = client.request(
+ method,
+ "/proxy/api/test",
+ headers=token_header("fake-token"),
+ json=payload,
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["message"] == "response from proxied app"
+
+ def test_original_app_auth_still_works(
+ self, app_with_proxy: Starlette
+ ) -> None:
+ client = TestClient(app_with_proxy)
+ response = client.get("/api/status", headers=token_header("bad-token"))
+ assert response.status_code == 401, response.text
+ assert response.headers.get("Set-Cookie") is None
+
+ @pytest.mark.asyncio
+ async def test_proxy_websocket(self, app_with_proxy: Starlette) -> None:
+ client = TestClient(app_with_proxy)
+ with client.websocket_connect("/proxy/ws") as websocket:
+ websocket.send_json({"message": "hello there"})
+ response = websocket.receive_json()
+ assert response["message"] == "ws response from proxied app"
+ websocket.send_json({"message": "hello there again"})
+ response_2 = websocket.receive_json()
+ assert response_2["message"] == "ws response from proxied app"
+ websocket.send_json({"message": "hello there again"})
+ response_3 = websocket.receive_json()
+ assert response_3["message"] == "ws response from proxied app"
+
+ @pytest.mark.xfail(
+ reason="Returning 403 instead of invalid ID message",
+ )
+ def test_proxy_websocket_with_invalid_id(
+ self, app_with_mpl_proxy: Starlette
+ ) -> None:
+ client = TestClient(app_with_mpl_proxy)
+ with client.websocket_connect(
+ "/mpl/ws?figure=invalid_id",
+ ) as websocket:
+ websocket.send_json({"type": "supports_binary", "value": True})
+ message = websocket.receive_json()
+ assert message["type"] == "error"
+ assert "invalid" in message["message"].lower()
+
+ # Could be good to go on to test the happy path for mpl but we're already doing that with the test client above so leaving just this invalid ID test for