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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: add asgi middleware to create_asgi_app (#3095)
Myles Scolnick387b711e583f
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex ab4838e342..759a95b03b 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport abcimport loggingfrom asyncio import iscoroutine+from functools import partialfrom pathlib import Pathfrom typing import (TYPE_CHECKING,@@ -12,6 +13,7 @@ from typing import (Dict,List,Optional,+ Protocol,Tuple,Union,)@@ -23,6 +25,7 @@ if TYPE_CHECKING:from typing_extensions import TypeAliaselse:from typing import TypeAlias+from starlette.requests import Requestfrom starlette.responses import Responsefrom starlette.types import ASGIApp, Receive, Scope, Send@@ -30,31 +33,64 @@ if TYPE_CHECKING:LOGGER = logging.getLogger(__name__)+class MiddlewareFactory(Protocol):+ def __call__(self, app: ASGIApp) -> ASGIApp: ... # pragma: no cover++class ASGIAppBuilder(abc.ABC):"""Class for building ASGI applications.Methods:- with_app(path: str, root: str) -> ASGIAppBuilder:+ with_app(+ path: str,+ root: str,+ middleware: Optional[list[MiddlewareFactory]] = None,+ ) -> ASGIAppBuilder:Adds a static application to the ASGI app at the specified path.+ Args:+ path (str): The URL path where the application will be mounted.+ root (str): The root directory of the application.+ middleware (Optional[list[MiddlewareFactory]]): Middleware to apply to the application.+with_dynamic_directory(- path: str, directory: str, validate_callback: Optional[ValidateCallback] = None+ path: str,+ directory: str,+ validate_callback: Optional[ValidateCallback] = None,+ middleware: Optional[list[MiddlewareFactory]] = None,) -> ASGIAppBuilder:Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.+ Args:+ path (str): The URL path where the dynamic directory will be mounted.+ directory (str): The directory containing the applications.+ validate_callback (Optional[ValidateCallback]): A callback function to validate the application path.+ This is useful to plug in authentication or authorization checks.+ The validate_callback receives the application path and the scope,+ and returns a boolean indicating whether the application is valid.+ You may also raise an exception for a custom error message.+ middleware (Optional[list[MiddlewareFactory]]): Middleware to apply to sub app.+build() -> ASGIApp:Builds and returns the final ASGI application."""@abc.abstractmethod- def with_app(self, *, path: str, root: str) -> "ASGIAppBuilder":+ def with_app(+ self,+ *,+ path: str,+ root: str,+ middleware: Optional[list[MiddlewareFactory]] = None,+ ) -> "ASGIAppBuilder":"""Adds a static application to the ASGI app at the specified path.Args:path (str): The URL path where the application will be mounted.root (str): The root directory of the application.+ middleware (Optional[list[MiddlewareFactory]]): Middleware to apply to the application.Returns:ASGIAppBuilder: The builder instance for chaining.@@ -68,6 +104,7 @@ class ASGIAppBuilder(abc.ABC):path: str,directory: str,validate_callback: Optional[ValidateCallback] = None,+ middleware: Optional[list[MiddlewareFactory]] = None,) -> "ASGIAppBuilder":"""Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.@@ -80,6 +117,8 @@ class ASGIAppBuilder(abc.ABC):The validate_callback receives the application path and the scope,and returns a boolean indicating whether the application is valid.You may also raise an exception for a custom error message.+ middleware (Optional[list[MiddlewareFactory]]): Middleware to apply to sub app. `marimo_app_file`+ is added to the scope of the request, so middleware can access it.Returns:ASGIAppBuilder: The builder instance for chaining.@@ -236,11 +275,16 @@ class DynamicDirectoryMiddleware:await self.app(scope, receive, send)return- potential_file, remaining_path = match_result+ marimo_file, remaining_path = match_resultLOGGER.debug(- f"Found matching file: {potential_file} with remaining path: {remaining_path}"+ f"Found matching file: {marimo_file} with remaining path: {remaining_path}")+ # Add app_path to scope+ # This is considered public API, so downstream middleware can access it+ new_scope = dict(scope)+ new_scope["marimo_app_file"] = str(marimo_file)+# For HTTP requests without trailing slash, redirect only if there's no remaining pathif (scope["type"] == "http"@@ -250,12 +294,12 @@ class DynamicDirectoryMiddleware:LOGGER.debug("Path matches file but missing trailing slash, redirecting")- response = self._redirect_response(scope)- await response(scope, receive, send)+ response = self._redirect_response(new_scope)+ await response(new_scope, receive, send)return# Create or get cached app- cache_key = str(potential_file)+ cache_key = str(marimo_file)if cache_key not in self._app_cache:LOGGER.debug(f"Creating new app for {cache_key}")try:@@ -269,8 +313,7 @@ class DynamicDirectoryMiddleware:return# Update scope to use the remaining path- new_scope = dict(scope)- old_path = new_scope["path"]+ old_path = scope["path"]new_scope["path"] = f"/{remaining_path}" if remaining_path else "/"LOGGER.debug(f"Updated path: {old_path} -> {new_scope['path']}")@@ -405,14 +448,27 @@ def create_asgi_app(# support directories or code in the futureclass Builder(ASGIAppBuilder):def __init__(self) -> None:- self._mount_configs: List[Tuple[str, str]] = []+ self._mount_configs: List[+ Tuple[str, str, Optional[list[MiddlewareFactory]]]+ ] = []self._dynamic_directory_configs: List[- Tuple[str, str, Optional[ValidateCallback]]+ Tuple[+ str,+ str,+ Optional[ValidateCallback],+ Optional[list[MiddlewareFactory]],+ ]] = []self._app_cache: Dict[str, ASGIApp] = {}- def with_app(self, *, path: str, root: str) -> "ASGIAppBuilder":- self._mount_configs.append((path, root))+ def with_app(+ self,+ *,+ path: str,+ root: str,+ middleware: Optional[list[MiddlewareFactory]] = None,+ ) -> "ASGIAppBuilder":+ self._mount_configs.append((path, root, middleware))return selfdef with_dynamic_directory(@@ -421,9 +477,10 @@ def create_asgi_app(path: str,directory: str,validate_callback: Optional[ValidateCallback] = None,+ middleware: Optional[list[MiddlewareFactory]] = None,) -> "ASGIAppBuilder":self._dynamic_directory_configs.append(- (path, directory, validate_callback)+ (path, directory, validate_callback, middleware))return self@@ -477,11 +534,16 @@ def create_asgi_app(url=redirect_path, status_code=301)- for path, root in self._mount_configs:+ for path, root, middleware in self._mount_configs:if root not in self._app_cache:- self._app_cache[root] = self._create_app_for_file(+ single_asgi_app: ASGIApp = self._create_app_for_file(base_url=path, file_path=root)+ # Apply middleware if provided+ if middleware:+ for m in middleware:+ single_asgi_app = m(single_asgi_app)+ self._app_cache[root] = single_asgi_appbase_app.mount(path, self._app_cache[root])# If path is not empty,@@ -499,12 +561,29 @@ def create_asgi_app(path,directory,validate_callback,+ middleware,) in self._dynamic_directory_configs:++ def app_builder(+ middleware: list[MiddlewareFactory],+ path: str,+ file_path: str,+ ) -> ASGIApp:+ single_asgi_app: ASGIApp = self._create_app_for_file(+ base_url=path, file_path=file_path+ )+ # Apply middleware if provided.+ if middleware:+ for m in middleware:+ single_asgi_app = m(single_asgi_app)+ return single_asgi_app++ # This comes after the middleware, so it's applied first.app = DynamicDirectoryMiddleware(app=app,base_path=path,directory=directory,- app_builder=self._create_app_for_file,+ app_builder=partial(app_builder, middleware or []),validate_callback=validate_callback,)diff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.pyindex a0eb78169f..84bff5d237 100644--- a/tests/_server/test_asgi.py+++ b/tests/_server/test_asgi.py@@ -8,6 +8,7 @@ from starlette.applications import Starlettefrom starlette.requests import Requestfrom starlette.responses import PlainTextResponse, Responsefrom starlette.testclient import TestClient+from starlette.types import ASGIApp, Message, Receive, Scope, Sendfrom starlette.websockets import WebSocketfrom marimo._server.asgi import (@@ -141,6 +142,83 @@ class TestASGIAppBuilder(unittest.TestCase):response = client.get("/app1/health")assert response.status_code == 200, response.text+ def test_app_with_middleware(self):+ # Create a simple middleware+ class TestMiddleware:+ def __init__(self, app: ASGIApp):+ self.app = app++ async def __call__(+ self,+ scope: Scope,+ receive: Receive,+ send: Send,+ ) -> None:+ if scope["type"] == "http":++ async def wrapped_send(message: Message) -> None:+ if message["type"] == "http.response.start":+ headers: Any = dict(message.get("headers", []))+ headers[b"x-test-middleware"] = b"applied"+ message["headers"] = list(headers.items())+ await send(message)++ await self.app(scope, receive, wrapped_send)+ else:+ await self.app(scope, receive, send)++ builder = create_asgi_app(quiet=True, include_code=True)+ builder = builder.with_app(+ path="/app1", root=self.app1, middleware=[TestMiddleware]+ )+ app = builder.build()+ client = TestClient(app)+ response = client.get("/app1")+ assert response.status_code == 200+ assert response.headers["x-test-middleware"] == "applied"++ def test_multiple_middleware(self):+ def middleware1(app: ASGIApp) -> ASGIApp:+ async def middleware_app(+ scope: Scope, receive: Receive, send: Send+ ) -> None:+ async def wrapped_send(message: Message) -> None:+ if message["type"] == "http.response.start":+ headers: Any = dict(message.get("headers", []))+ headers[b"x-middleware-1"] = b"applied"+ message["headers"] = list(headers.items())+ await send(message)++ await app(scope, receive, wrapped_send)++ return middleware_app++ def middleware2(app: ASGIApp) -> ASGIApp:+ async def middleware_app(+ scope: Scope, receive: Receive, send: Send+ ) -> None:+ async def wrapped_send(message: Message) -> None:+ if message["type"] == "http.response.start":+ headers: Any = dict(message.get("headers", []))+ headers[b"x-middleware-2"] = b"applied"+ message["headers"] = list(headers.items())+ await send(message)++ await app(scope, receive, wrapped_send)++ return middleware_app++ builder = create_asgi_app(quiet=True, include_code=True)+ builder = builder.with_app(+ path="/app1", root=self.app1, middleware=[middleware1, middleware2]+ )+ app = builder.build()+ client = TestClient(app)+ response = client.get("/app1")+ assert response.status_code == 200+ assert response.headers["x-middleware-1"] == "applied"+ assert response.headers["x-middleware-2"] == "applied"+class TestDynamicDirectoryMiddleware(unittest.TestCase):def setUp(self):@@ -483,6 +561,63 @@ class TestDynamicDirectoryMiddleware(unittest.TestCase):assert response.status_code == 403assert response.text == "403: Forbidden"+ def test_dynamic_directory_middleware(self):+ # Create test files+ allowed_file = Path(self.temp_dir) / "my_app.py"+ allowed_file.write_text(contents)++ blocked_file = Path(self.temp_dir) / "nested/another_app.py"+ blocked_file.write_text(contents)++ class CustomMiddleware:+ def __init__(self, app: ASGIApp):+ self.app = app++ async def __call__(+ self, scope: Scope, receive: Receive, send: Send+ ) -> None:+ # Check the marimo app file as added to the scope prior.+ file = scope["marimo_app_file"]+ assert isinstance(file, str)+ assert file.endswith(str(allowed_file)) or file.endswith(+ str(blocked_file)+ )++ if scope["type"] == "http":++ async def wrapped_send(message: Message) -> None:+ if message["type"] == "http.response.start":+ headers: Any = dict(message.get("headers", []))+ headers[b"x-custom-middleware"] = b"applied"+ message["headers"] = list(headers.items())+ await send(message)++ await self.app(scope, receive, wrapped_send)+ else:+ await self.app(scope, receive, send)++ app = (+ create_asgi_app()+ .with_dynamic_directory(+ path="/apps",+ directory=self.temp_dir,+ middleware=[CustomMiddleware],+ )+ .build()+ )++ client = TestClient(app)++ # App+ response = client.get("/apps/my_app/")+ assert response.status_code == 200+ assert response.headers["x-custom-middleware"] == "applied"++ # Nested app+ response = client.get("/apps/nested/another_app/")+ assert response.status_code == 200+ assert response.headers["x-custom-middleware"] == "applied"+def default_app_builder(base_url: str, file_path: str) -> Starlette:del base_url