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
fix: don't block when writing auto-export files (#5254)
Myles Scolnick7b4ed54cdf6a
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex dd71910f54..340248090c 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -29,6 +29,8 @@ LOGGER = _loggers.marimo_logger()# Router for export endpointsrouter = APIRouter()+auto_exporter = AutoExporter()+@router.post("/html")@requires("read")@@ -135,7 +137,7 @@ async def auto_export_as_html()# Save the HTML file to disk, at `.marimo/<filename>.html`- AutoExporter().save_html(+ await auto_exporter.save_html(file_manager=session.app_file_manager,html=html,)@@ -283,7 +285,7 @@ async def auto_export_as_markdown()# Save the Markdown file to disk, at `.marimo/<filename>.md`- AutoExporter().save_md(+ await auto_exporter.save_md(file_manager=session.app_file_manager,markdown=markdown,)@@ -339,7 +341,7 @@ async def auto_export_as_ipynb()# Save the IPYNB file to disk, at `.marimo/<filename>.ipynb`- AutoExporter().save_ipynb(+ await auto_exporter.save_ipynb(file_manager=session.app_file_manager,ipynb=ipynb,)diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 83fd4610c7..76440f1b7a 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -1,9 +1,11 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import asyncioimport base64import ioimport mimetypes+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import (TYPE_CHECKING,@@ -476,51 +478,65 @@ class Exporter:class AutoExporter:EXPORT_DIR = "__marimo__"- def save_html(self, file_manager: AppFileManager, html: str) -> None:- # get filename+ def __init__(self) -> None:+ # Cache directories we've already created to avoid redundant checks+ self._created_dirs: set[Path] = set()+ # Thread pool for blocking I/O operations+ self._executor = ThreadPoolExecutor(+ max_workers=4, thread_name_prefix="export"+ )++ async def _save_file(+ self, file_manager: AppFileManager, content: str, extension: str+ ) -> None:directory = Path(get_filename(file_manager.filename)).parent- filename = get_download_filename(file_manager.filename, "html")+ filename = get_download_filename(file_manager.filename, extension)- # make directory if it doesn't exist- self._make_export_dir(directory)+ await self._ensure_export_dir_async(directory)filepath = directory / self.EXPORT_DIR / filename- # save html to .marimo directory- filepath.write_text(html, encoding="utf-8")+ # Run blocking file I/O in thread pool+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(+ self._executor, self._write_file_sync, filepath, content+ )- def save_md(self, file_manager: AppFileManager, markdown: str) -> None:- # get filename- directory = Path(get_filename(file_manager.filename)).parent- filename = get_download_filename(file_manager.filename, "md")+ async def save_html(self, file_manager: AppFileManager, html: str) -> None:+ await self._save_file(file_manager, html, "html")- # make directory if it doesn't exist- self._make_export_dir(directory)- filepath = directory / self.EXPORT_DIR / filename+ async def save_md(+ self, file_manager: AppFileManager, markdown: str+ ) -> None:+ await self._save_file(file_manager, markdown, "md")- # save md to .marimo directory- filepath.write_text(markdown, encoding="utf-8")+ async def save_ipynb(+ self, file_manager: AppFileManager, ipynb: str+ ) -> None:+ await self._save_file(file_manager, ipynb, "ipynb")- def save_ipynb(self, file_manager: AppFileManager, ipynb: str) -> None:- # get filename- directory = Path(get_filename(file_manager.filename)).parent- filename = get_download_filename(file_manager.filename, "ipynb")+ def _write_file_sync(self, filepath: Path, content: str) -> None:+ """Synchronous file write (runs in thread pool)"""+ filepath.write_text(content, encoding="utf-8")- # make directory if it doesn't exist- self._make_export_dir(directory)- filepath = directory / self.EXPORT_DIR / filename+ async def _ensure_export_dir_async(self, directory: Path) -> None:+ """Async directory creation with caching to avoid redundant checks"""+ export_dir = directory / self.EXPORT_DIR- # save ipynb to .marimo directory- filepath.write_text(ipynb, encoding="utf-8")+ # Fast path: already created this directory+ if export_dir in self._created_dirs:+ return- def _make_export_dir(self, directory: Path) -> None:- # make .marimo dir if it doesn't exist- # don't make the other directoriesif not directory.exists():raise FileNotFoundError(f"Directory {directory} does not exist")- export_dir = directory / self.EXPORT_DIR- if not export_dir.exists():- export_dir.mkdir(parents=True, exist_ok=True)+ export_dir.mkdir(parents=True, exist_ok=True)++ # Cache that we've created this directory+ self._created_dirs.add(export_dir)++ def cleanup(self) -> None:+ """Cleanup resources"""+ self._executor.shutdown(wait=False)def hash_code(code: str) -> str: