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.

internal: add entrypoints registries (#4815)

Myles Scolnick390ca9ed62a9
diff --git a/marimo/_entrypoints/ids.py b/marimo/_entrypoints/ids.py
new file mode 100644
index 0000000000..f208155ecc
--- /dev/null
+++ b/marimo/_entrypoints/ids.py
@@ -0,0 +1,10 @@
+from typing import Literal
+
+# Internal entrypoints. Not user-facing as the API is not stable.
+KnownEntryPoint = Literal[
+ "marimo.cell.executor",
+ "marimo.cache.store",
+ "marimo.kernel.lifespan",
+ "marimo.server.asgi.lifespan",
+ "marimo.server.asgi.middleware",
+]
diff --git a/marimo/_entrypoints/registry.py b/marimo/_entrypoints/registry.py
new file mode 100644
index 0000000000..6a4b42bae0
--- /dev/null
+++ b/marimo/_entrypoints/registry.py
@@ -0,0 +1,106 @@
+from importlib.metadata import entry_points
+from typing import TYPE_CHECKING, Generic, Optional, TypeVar, cast
+
+from marimo._entrypoints.ids import KnownEntryPoint
+
+if TYPE_CHECKING:
+ from importlib.metadata import EntryPoints
+
+T = TypeVar("T")
+
+
+class EntryPointRegistry(Generic[T]):
+ """A registry for entry points.
+
+ This registry allows entry points to be loaded in two ways:
+ 1. Through an explicit call to `.register(name, value)`
+ 2. By looking for Python packages that provide a setuptools entry point group
+
+ Usage:
+ registry = EntryPointRegistry[MyType]("my_entrypoint_group")
+ """
+
+ def __init__(self, entry_point_group: KnownEntryPoint) -> None:
+ """Create an EntryPointRegistry for a named entry point group.
+
+ Args:
+ entry_point_group: The name of the entry point group.
+ """
+ self.entry_point_group: KnownEntryPoint = entry_point_group
+ self._plugins: dict[str, T] = {}
+
+ def register(self, name: str, value: T) -> None:
+ """Register a plugin by name and value.
+
+ Args:
+ name: The name of the plugin.
+ value: The actual plugin object to register.
+ """
+ self._plugins[name] = value
+
+ def unregister(self, name: str) -> Optional[T]:
+ """Unregister a plugin by name.
+
+ Args:
+ name: The name of the plugin to unregister.
+
+ Returns:
+ The plugin that was unregistered.
+ """
+ return self._plugins.pop(name, None)
+
+ def names(self) -> list[str]:
+ """List the names of the registered and entry points plugins.
+
+ Returns:
+ A sorted list of plugin names.
+ """
+ registered = list(self._plugins.keys())
+ entry_points_list = get_entry_points(self.entry_point_group)
+ entry_point_names = [ep.name for ep in entry_points_list]
+ return sorted(set(registered + entry_point_names))
+
+ def get(self, name: str) -> T:
+ """Get a plugin by name, loading it from entry points if necessary.
+
+ Args:
+ name: The name of the plugin to get.
+
+ Returns:
+ The requested plugin.
+
+ Raises:
+ KeyError: If the plugin cannot be found.
+ """
+ if name in self._plugins:
+ return self._plugins[name]
+
+ entry_points_list = get_entry_points(self.entry_point_group)
+ for ep in entry_points_list:
+ if ep.name == name:
+ value = ep.load()
+ self.register(name, value)
+ return cast(T, value)
+
+ raise KeyError(
+ f"No entry point named '{name}' found in group '{self.entry_point_group}'"
+ )
+
+ def get_all(self) -> list[T]:
+ """Get all registered and entry point plugins.
+
+ Returns:
+ A list of all registered and entry point plugins.
+ """
+ return [self.get(name) for name in self.names()]
+
+ def __repr__(self) -> str:
+ return f"{type(self).__name__}(group={self.entry_point_group!r}, registered={self.names()!r})"
+
+
+def get_entry_points(group: KnownEntryPoint) -> "EntryPoints":
+ ep = entry_points()
+ if hasattr(ep, "select"):
+ return ep.select(group=group)
+ else:
+ return ep.get(group, []) # type: ignore
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 82df2bacd1..2c750264fe 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -17,7 +17,13 @@ from copy import copy, deepcopy
from functools import cached_property
from multiprocessing import connection
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Callable, Optional, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Optional,
+ cast,
+)
from uuid import uuid4
from marimo import _loggers
@@ -35,6 +41,7 @@ from marimo._data.preview_column import (
)
from marimo._dependencies.dependencies import DependencyManager
from marimo._dependencies.errors import ManyModulesNotFoundError
+from marimo._entrypoints.registry import EntryPointRegistry
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.context import http_request_context, run_id_context
from marimo._messaging.errors import (
@@ -158,7 +165,9 @@ from marimo._sql.engines.types import SQLEngine
from marimo._sql.get_engines import get_engines_from_variables
from marimo._tracer import kernel_tracer
from marimo._types.ids import CellId_t, UIElementId, VariableName
+from marimo._types.lifespan import Lifespan
from marimo._utils.assert_never import assert_never
+from marimo._utils.lifespans import Lifespans
from marimo._utils.platform import is_pyodide
from marimo._utils.signals import restore_signals
from marimo._utils.typed_connection import TypedConnection
@@ -172,6 +181,10 @@ if TYPE_CHECKING:
LOGGER = _loggers.marimo_logger()
+_KERNEL_LIFESPAN_REGISTRY = EntryPointRegistry[Lifespan[None]](
+ "marimo.kernel.lifespan",
+)
+
@mddoc
def defs() -> tuple[str, ...]:
@@ -602,6 +615,14 @@ class Kernel:
exec("import marimo as __marimo__", self.globals)
+ # Lifespans
+ lifespan = Lifespans(_KERNEL_LIFESPAN_REGISTRY.get_all())
+ self._lifespan: Optional[
+ contextlib.AbstractAsyncContextManager[None]
+ ] = None
+ if lifespan.has_lifespans():
+ self._lifespan = lifespan(None)
+
def teardown(self) -> None:
"""Teardown resources owned by the kernel."""
if self.stdout is not None:
@@ -621,6 +642,10 @@ class Kernel:
# manually clear kernel memory.
self._module.__dict__.clear()
+ # Teardown lifespans
+ if self._lifespan is not None:
+ asyncio.run(self._lifespan.__aexit__(None, None, None))
+
def lazy(self) -> bool:
return self.reactive_execution_mode == "lazy"
@@ -1925,6 +1950,7 @@ class Kernel:
initial_value,
) in request.set_ui_element_value_request.ids_and_values:
self.ui_initializers[object_id] = initial_value
+
await self.run(request.execution_requests)
self.reset_ui_initializers()
else:
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index f0da02ab3f..5d2c851928 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -4,68 +4,31 @@ from __future__ import annotations
import asyncio
import contextlib
import socket
-import sys
-from collections.abc import AsyncIterator, Callable, Sequence
-from contextlib import AbstractAsyncContextManager
-
-from starlette.applications import Starlette
-
-from marimo._server.api.deps import AppState, AppStateBase
-from marimo._server.file_router import AppFileRouter
-from marimo._server.lsp import any_lsp_server_running
-from marimo._server.sessions import SessionManager
-from marimo._server.tokens import AuthToken
-
-if sys.version_info < (3, 10):
- from typing_extensions import TypeAlias
-else:
- from typing import TypeAlias
+from typing import TYPE_CHECKING
from marimo import _loggers
+from marimo._server.api.deps import AppState, AppStateBase
from marimo._server.api.interrupt import InterruptHandler
from marimo._server.api.utils import open_url_in_browser
+from marimo._server.file_router import AppFileRouter
+from marimo._server.lsp import any_lsp_server_running
from marimo._server.model import SessionMode
from marimo._server.print import (
print_experimental_features,
print_shutdown,
print_startup,
)
+from marimo._server.sessions import SessionManager
+from marimo._server.tokens import AuthToken
from marimo._server.utils import initialize_mimetypes
from marimo._server.uvicorn_utils import close_uvicorn
-LifespanList: TypeAlias = Sequence[
- Callable[[Starlette], AbstractAsyncContextManager[None]]
-]
-
-LOGGER = _loggers.marimo_logger()
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator
+ from starlette.applications import Starlette
-# Compound lifespans
-class Lifespans:
- def __init__(
- self,
- lifespans: LifespanList,
- ) -> None:
- self.lifespans = lifespans
-
- @contextlib.asynccontextmanager
- async def _manager(
- self,
- app: Starlette,
- lifespans: LifespanList,
- ) -> AsyncIterator[None]:
- exit_stack = contextlib.AsyncExitStack()
- try:
- async with exit_stack:
- for lifespan in lifespans:
- LOGGER.debug(f"Setup: {lifespan.__name__}")
- await exit_stack.enter_async_context(lifespan(app))
- yield
- except asyncio.CancelledError:
- pass
-
- def __call__(self, app: Starlette) -> AbstractAsyncContextManager[None]:
- return self._manager(app, lifespans=self.lifespans)
+LOGGER = _loggers.marimo_logger()
@contextlib.asynccontextmanager
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.py
index cff53e9b13..77ffa34f4b 100644
--- a/marimo/_server/asgi.py
+++ b/marimo/_server/asgi.py
@@ -15,6 +15,9 @@ from typing import (
Union,
)
+from marimo._server.registry import LIFESPAN_REGISTRY
+from marimo._utils.lifespans import Lifespans
+
if TYPE_CHECKING:
import sys
@@ -465,11 +468,12 @@ def create_asgi_app(
)
app = create_starlette_app(
base_url="",
- lifespan=lifespans.Lifespans(
+ lifespan=Lifespans(
[
# Not all lifespans are needed for run mode
lifespans.etc,
lifespans.signal_handler,
+ *LIFESPAN_REGISTRY.get_all(),
]
),
enable_auth=not AuthToken.is_empty(auth_token),
diff --git a/marimo/_server/main.py b/marimo/_server/main.py
index c78f247a10..cb729a939c 100644
--- a/marimo/_server/main.py
+++ b/marimo/_server/main.py
@@ -28,6 +28,7 @@ from marimo._server.api.status import (
)
from marimo._server.errors import handle_error
from marimo._server.lsp import LspServer
+from marimo._server.registry import MIDDLEWARE_REGISTRY
if TYPE_CHECKING:
from starlette.types import Lifespan
@@ -89,6 +90,8 @@ def create_starlette_app(
]
)
+ final_middlewares.extend(MIDDLEWARE_REGISTRY.get_all())
+
if lsp_servers is not None:
final_middlewares.extend(
_create_lsps_proxy_middleware(servers=lsp_servers)
diff --git a/marimo/_server/registry.py b/marimo/_server/registry.py
new file mode 100644
index 0000000000..62141e8ac0
--- /dev/null
+++ b/marimo/_server/registry.py
@@ -0,0 +1,13 @@
+from starlette.applications import Starlette
+from starlette.middleware import Middleware
+from starlette.types import Lifespan
+
+from marimo._entrypoints.registry import EntryPointRegistry
+
+MIDDLEWARE_REGISTRY = EntryPointRegistry[Middleware](
+ entry_point_group="marimo.server.asgi.middleware"
+)
+
+LIFESPAN_REGISTRY = EntryPointRegistry[Lifespan[Starlette]](
+ entry_point_group="marimo.server.asgi.lifespan"
+)
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 0d9b454d00..ebdfa6a3fd 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -15,6 +15,7 @@ from marimo._server.file_router import AppFileRouter
from marimo._server.lsp import CompositeLspServer, NoopLspServer
from marimo._server.main import create_starlette_app
from marimo._server.model import SessionMode
+from marimo._server.registry import LIFESPAN_REGISTRY
from marimo._server.sessions import SessionManager
from marimo._server.tokens import AuthToken
from marimo._server.utils import (
@@ -24,6 +25,7 @@ from marimo._server.utils import (
)
from marimo._server.uvicorn_utils import initialize_signals
from marimo._tracer import LOGGER
+from marimo._utils.lifespans import Lifespans
from marimo._utils.paths import marimo_package_path
DEFAULT_PORT = 2718
@@ -161,13 +163,14 @@ def start(
app = create_starlette_app(
base_url=base_url,
host=external_host,
- lifespan=lifespans.Lifespans(
+ lifespan=Lifespans(
[
lifespans.lsp,
lifespans.etc,
lifespans.signal_handler,
lifespans.logging,
lifespans.open_browser,
+ *LIFESPAN_REGISTRY.get_all(),
]
),
allow_origins=allow_origins,
diff --git a/marimo/_types/lifespan.py b/marimo/_types/lifespan.py
new file mode 100644
index 0000000000..a613511c9c
--- /dev/null
+++ b/marimo/_types/lifespan.py
@@ -0,0 +1,14 @@
+from collections.abc import (
+ Callable,
+ Mapping,
+)
+from contextlib import AbstractAsyncContextManager
+from typing import Any, TypeVar, Union
+
+AppType = TypeVar("AppType")
+
+StatelessLifespan = Callable[[AppType], AbstractAsyncContextManager[None]]
+StatefulLifespan = Callable[
+ [AppType], AbstractAsyncContextManager[Mapping[str, Any]]
+]
+Lifespan = Union[StatelessLifespan[AppType], StatefulLifespan[AppType]]
diff --git a/marimo/_utils/lifespans.py b/marimo/_utils/lifespans.py
new file mode 100644
index 0000000000..31e0968d1a
--- /dev/null
+++ b/marimo/_utils/lifespans.py
@@ -0,0 +1,60 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import sys
+from collections.abc import AsyncIterator, Sequence
+from contextlib import AbstractAsyncContextManager
+from typing import Any, Generic, TypeVar
+
+from marimo import _loggers
+from marimo._types.lifespan import Lifespan
+
+if sys.version_info < (3, 10):
+ from typing_extensions import TypeAlias
+else:
+ from typing import TypeAlias
+
+T = TypeVar("T", bound=Any)
+
+LifespanList: TypeAlias = Sequence[Lifespan[T]]
+
+LOGGER = _loggers.marimo_logger()
+
+
+class Lifespans(Generic[T]):
+ """
+ A compound lifespan that runs a list of lifespans in order.
+ """
+
+ def __init__(
+ self,
+ lifespans: LifespanList[T],
+ ) -> None:
+ self._lifespans = lifespans
+
+ def has_lifespans(self) -> bool:
+ return bool(self._lifespans)
+
+ @contextlib.asynccontextmanager
+ async def _manager(
+ self,
+ app: T,
+ lifespans: LifespanList[T],
+ ) -> AsyncIterator[None]:
+ exit_stack = contextlib.AsyncExitStack()
+ try:
+ async with exit_stack:
+ for lifespan in lifespans:
+ LOGGER.debug(f"Setup: {lifespan.__name__}")
+ await exit_stack.enter_async_context(lifespan(app))
+ yield
+ except asyncio.CancelledError:
+ pass
+
+ def __call__(self, app: T) -> AbstractAsyncContextManager[None]:
+ return self._manager(app, lifespans=self._lifespans)
+
+ def __repr__(self) -> str:
+ return f"Lifespans({self._lifespans})"
diff --git a/tests/_utils/test_lifespans.py b/tests/_utils/test_lifespans.py
new file mode 100644
index 0000000000..35e45ef5d8
--- /dev/null
+++ b/tests/_utils/test_lifespans.py
@@ -0,0 +1,127 @@
+import asyncio
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from typing import Callable
+
+import pytest
+
+from marimo._types.lifespan import Lifespan
+from marimo._utils.lifespans import Lifespans
+
+
+class MockApp:
+ def __init__(self) -> None:
+ self.setup_calls: list[str] = []
+ self.teardown_calls: list[str] = []
+
+
+def create_mock_lifespan() -> Callable[[str], Lifespan[MockApp]]:
+ def mock_lifespan(name: str) -> Lifespan[MockApp]:
+ @asynccontextmanager
+ async def lifespan(app: MockApp) -> AsyncIterator[None]:
+ app.setup_calls.append(name)
+ try:
+ yield
+ finally:
+ app.teardown_calls.append(name)
+
+ return lifespan
+
+ return mock_lifespan
+
+
+async def test_empty_lifespans() -> None:
+ app = MockApp()
+ lifespans: Lifespans[MockApp] = Lifespans([])
+ assert not lifespans.has_lifespans()
+
+ async with lifespans(app):
+ assert len(app.setup_calls) == 0
+ assert len(app.teardown_calls) == 0
+
+
+async def test_single_lifespan() -> None:
+ app = MockApp()
+ mock_lifespan = create_mock_lifespan()
+ lifespans: Lifespans[MockApp] = Lifespans([mock_lifespan("test1")])
+ assert lifespans.has_lifespans()
+
+ async with lifespans(app):
+ assert app.setup_calls == ["test1"]
+ assert len(app.teardown_calls) == 0
+
+ assert app.setup_calls == ["test1"]
+ assert app.teardown_calls == ["test1"]
+
+
+async def test_multiple_lifespans() -> None:
+ app = MockApp()
+ mock_lifespan = create_mock_lifespan()
+ lifespans: Lifespans[MockApp] = Lifespans(
+ [
+ mock_lifespan("test1"),
+ mock_lifespan("test2"),
+ mock_lifespan("test3"),
+ ]
+ )
+ assert lifespans.has_lifespans()
+
+ async with lifespans(app):
+ assert app.setup_calls == ["test1", "test2", "test3"]
+ assert len(app.teardown_calls) == 0
+
+ assert app.setup_calls == ["test1", "test2", "test3"]
+ assert app.teardown_calls == [
+ "test3",
+ "test2",
+ "test1",
+ ] # Teardown in reverse order
+
+
+async def test_lifespan_error_handling() -> None:
+ app = MockApp()
+ mock_lifespan = create_mock_lifespan()
+
+ def failing_lifespan(name: str) -> Lifespan[MockApp]:
+ @asynccontextmanager
+ async def lifespan(app: MockApp) -> AsyncIterator[None]:
+ app.setup_calls.append(name)
+ try:
+ yield
+ finally:
+ app.teardown_calls.append(name)
+ raise ValueError(f"Error in {name}")
+
+ return lifespan
+
+ lifespans: Lifespans[MockApp] = Lifespans(
+ [
+ mock_lifespan("test1"),
+ failing_lifespan("test2"),
+ mock_lifespan("test3"),
+ ]
+ )
+
+ with pytest.raises(ValueError, match="Error in test2"):
+ async with lifespans(app):
+ pass
+
+ # Even with errors, setup and teardown should be called in correct order
+ assert app.setup_calls == ["test1", "test2", "test3"]
+ assert app.teardown_calls == ["test3", "test2", "test1"]
+
+
+async def test_lifespan_cancellation() -> None:
+ app = MockApp()
+ mock_lifespan = create_mock_lifespan()
+ lifespans: Lifespans[MockApp] = Lifespans(
+ [mock_lifespan("test1"), mock_lifespan("test2")]
+ )
+
+ async with lifespans(app):
+ assert app.setup_calls == ["test1", "test2"]
+ # Simulate cancellation
+ raise asyncio.CancelledError()
+
+ # Teardown should still be called even on cancellation
+ assert app.teardown_calls == ["test2", "test1"]
diff --git a/tests/test_entrypoints.py b/tests/test_entrypoints.py
new file mode 100644
index 0000000000..4c8cfabed9
--- /dev/null
+++ b/tests/test_entrypoints.py
@@ -0,0 +1,89 @@
+from typing import cast
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from marimo._entrypoints.ids import KnownEntryPoint
+from marimo._entrypoints.registry import EntryPointRegistry, get_entry_points
+
+
+class TestEntryPointRegistry:
+ @pytest.fixture
+ def registry(self) -> EntryPointRegistry[str]:
+ return EntryPointRegistry[str](cast(KnownEntryPoint, "plugins"))
+
+ def test_register_and_get(self, registry: EntryPointRegistry[str]) -> None:
+ registry.register("test", "value")
+ assert registry.get("test") == "value"
+
+ def test_unregister(self, registry: EntryPointRegistry[str]) -> None:
+ registry.register("test", "value")
+ assert registry.unregister("test") == "value"
+ with pytest.raises(KeyError):
+ registry.get("test")
+
+ def test_names(self, registry: EntryPointRegistry[str]) -> None:
+ registry.register("test1", "value1")
+ registry.register("test2", "value2")
+ assert set(registry.names()) == {"test1", "test2"}
+
+ def test_get_nonexistent(self, registry: EntryPointRegistry[str]) -> None:
+ with pytest.raises(KeyError):
+ registry.get("nonexistent")
+
+ def test_repr(self, registry: EntryPointRegistry[str]) -> None:
+ registry.register("test", "value")
+ assert "EntryPointRegistry" in repr(registry)
+ assert "test" in repr(registry)
+
+ @patch("marimo._entrypoints.registry.entry_points")
+ def test_get_entry_points_modern(
+ self, mock_entry_points: MagicMock
+ ) -> None:
+ mock_eps = MagicMock()
+ mock_eps.select.return_value = ["ep1", "ep2"]
+ mock_entry_points.return_value = mock_eps
+
+ result = get_entry_points(cast(KnownEntryPoint, "plugins"))
+ assert result == ["ep1", "ep2"]
+ mock_eps.select.assert_called_once_with(
+ group=cast(KnownEntryPoint, "plugins")
+ )
+
+ def test_get_all(self, registry: EntryPointRegistry[str]) -> None:
+ registry.register("test1", "value1")
+ registry.register("test2", "value2")
+
+ with patch(
+ "marimo._entrypoints.registry.get_entry_points"
+ ) as mock_get_entry_points:
+ mock_get_entry_points.return_value = []
+ result = registry.get_all()
+
+ assert set(result) == {"value1", "value2"}
+
+ @patch("marimo._entrypoints.registry.get_entry_points")
+ def test_get_all_with_entry_points(
+ self, mock_get_entry_points: MagicMock
+ ) -> None:
+ registry = EntryPointRegistry[str](cast(KnownEntryPoint, "test_group"))
+
+ # Create mock entry points
+ ep1 = MagicMock()
+ ep1.name = "ep1"
+ ep1.load.return_value = "ep_value1"
+
+ ep2 = MagicMock()
+ ep2.name = "ep2"
+ ep2.load.return_value = "ep_value2"
+
+ mock_get_entry_points.return_value = [ep1, ep2]
+
+ # Register one plugin directly
+ registry.register("test1", "value1")
+
+ # Get all plugins
+ result = registry.get_all()
+
+ # Should include both registered and entry point plugins
+ assert set(result) == {"value1", "ep_value1", "ep_value2"}