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: proxy lsp through main server (#2911)

Myles Scolnicke87ecb38baa5
diff --git a/frontend/src/core/codemirror/copilot/__tests__/createWsUrl.test.ts b/frontend/src/core/codemirror/copilot/__tests__/createWsUrl.test.ts
deleted file mode 100644
index fcd1c5459b..0000000000
--- a/frontend/src/core/codemirror/copilot/__tests__/createWsUrl.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/no-explicit-any */
-import { beforeAll, afterAll, expect, describe, it, vi } from "vitest";
-import { createWsUrl } from "../client";
-
-vi.mock("@/core/config/config", () => ({
- parseAppConfig: () => ({}),
- parseUserConfig: () => ({}),
-}));
-
-describe("createWsUrl", () => {
- let originalWindow: Window & typeof globalThis;
-
- beforeAll(() => {
- // Save the original window object
- originalWindow = global.window;
- });
-
- afterAll(() => {
- // Restore the original window object after tests
- global.window = originalWindow;
- });
-
- it("should create a WebSocket URL based on the window location", () => {
- // Mock the window object
- global.window = {
- location: {
- protocol: "http:",
- hostname: "localhost",
- port: "3000",
- },
- } as any;
-
- const expectedUrl = "ws://localhost:30000/copilot";
- expect(createWsUrl()).toBe(expectedUrl);
- });
-
- it("should use wss protocol when window location protocol is https", () => {
- // Mock the window object
- global.window = {
- location: {
- protocol: "https:",
- hostname: "localhost",
- port: "3000",
- },
- } as any;
-
- const expectedUrl = "wss://localhost:30000/copilot";
- expect(createWsUrl()).toBe(expectedUrl);
- });
-});
diff --git a/frontend/src/core/codemirror/copilot/client.ts b/frontend/src/core/codemirror/copilot/client.ts
index 12d2b675b9..2019cad57c 100644
--- a/frontend/src/core/codemirror/copilot/client.ts
+++ b/frontend/src/core/codemirror/copilot/client.ts
@@ -79,15 +79,6 @@ export function copilotServer() {
});
}
-const DEVELOPMENT_WS_PORT = 27_180;
export function createWsUrl(): string {
- // TODO: this should be configurable, but instead we add a 0 and hope it is free
- // NOTE: window.location.port may also be empty if running behind a proxy
- // (plain 80 or 443 just gives a protocol), so default to the development port.
- const LSP_PORT =
- process.env.NODE_ENV === "development" || !window.location.port
- ? DEVELOPMENT_WS_PORT
- : `${window.location.port}0`;
- const protocol = window.location.protocol === "https:" ? "wss" : "ws";
- return `${protocol}://${window.location.hostname}:${LSP_PORT}/copilot`;
+ return "/lsp/copilot";
}
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 4beca79623..5e54366b9d 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -199,6 +199,14 @@ export default defineConfig({
origin: TARGET,
},
},
+ "/lsp": {
+ target: `ws://${HOST}:${SERVER_PORT}`,
+ ws: true,
+ changeOrigin: true,
+ headers: {
+ origin: TARGET,
+ },
+ },
"/terminal/ws": {
target: `ws://${HOST}:${SERVER_PORT}`,
ws: true,
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 0e655bee1a..47cc4c2f1d 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -29,9 +29,9 @@ from starlette.middleware.base import (
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 websockets import ConnectionClosed, connect
+from marimo import _loggers
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
from marimo._server.api.auth import validate_auth
@@ -43,6 +43,8 @@ if TYPE_CHECKING:
from starlette.requests import HTTPConnection
from starlette.types import ASGIApp, Receive, Scope, Send
+LOGGER = _loggers.marimo_logger()
+
class AuthBackend(AuthenticationBackend):
def __init__(self, should_authenticate: bool = True) -> None:
@@ -323,7 +325,9 @@ class ProxyMiddleware:
elif scope["scheme"] in ("https", "wss"):
ws_url = ws_url.replace("https", "wss", 1)
+ LOGGER.debug(f"Creating websocket proxy for {ws_url}")
await self._proxy_websocket(scope, receive, send, ws_url)
+ LOGGER.debug(f"Done with websocket proxy for {ws_url}")
return
if scope["type"] != "http":
@@ -381,6 +385,10 @@ class ProxyMiddleware:
while True:
msg = await websocket.receive()
if msg["type"] == "websocket.disconnect":
+ # Cancel the other task when client disconnects
+ for task in relay_tasks:
+ if not task.done():
+ task.cancel()
return
if "text" in msg:
@@ -401,6 +409,10 @@ class ProxyMiddleware:
else:
await websocket.send_text(msg)
except ConnectionClosed:
+ # Cancel the other task when connection closes
+ for task in relay_tasks:
+ if not task.done():
+ task.cancel()
return
except Exception:
return
@@ -413,11 +425,14 @@ class ProxyMiddleware:
try:
await asyncio.gather(*relay_tasks)
+ except asyncio.CancelledError:
+ pass
except Exception as e:
raise e
finally:
- try:
- if websocket.client_state != WebSocketState.DISCONNECTED:
- await websocket.close()
- except Exception as e:
- raise e
+ for task in relay_tasks:
+ if not task.done():
+ task.cancel()
+ if websocket.client_state != WebSocketState.DISCONNECTED:
+ await websocket.close()
+ await ws_client.close()
diff --git a/marimo/_server/main.py b/marimo/_server/main.py
index 82768335b8..623f20b358 100644
--- a/marimo/_server/main.py
+++ b/marimo/_server/main.py
@@ -77,6 +77,7 @@ def create_starlette_app(
lifespan: Optional[Lifespan[Starlette]] = None,
enable_auth: bool = True,
allow_origins: Optional[tuple[str, ...]] = None,
+ lsp_port: Optional[int] = None,
) -> Starlette:
final_middlewares: List[Middleware] = []
@@ -115,6 +116,9 @@ def create_starlette_app(
]
)
+ if lsp_port is not None:
+ final_middlewares.append(_create_lsp_proxy_middleware(lsp_port))
+
if middleware:
final_middlewares.extend(middleware)
@@ -148,3 +152,13 @@ def _create_mpl_proxy_middleware() -> Middleware:
target_url=mpl_target_url,
path_rewrite=mpl_path_rewrite,
)
+
+
+def _create_lsp_proxy_middleware(lsp_port: int) -> Middleware:
+ return Middleware(
+ ProxyMiddleware,
+ proxy_path="/lsp",
+ target_url=f"http://localhost:{lsp_port}",
+ # Remove the /lsp prefix
+ path_rewrite=lambda path: path.replace("/lsp", ""),
+ )
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 28abe060a7..1a9d47074d 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -89,6 +89,7 @@ def start(
# Find a free port if none is specified
# if the user specifies a port, we don't try to find a free one
port = port or find_free_port(DEFAULT_PORT)
+ lsp_port = find_free_port(DEFAULT_PORT + 200) # Add 200 to avoid conflicts
user_config_mgr = UserConfigManager()
session_manager = SessionManager(
@@ -97,7 +98,7 @@ def start(
development_mode=development_mode,
quiet=quiet,
include_code=include_code,
- lsp_server=LspServer(port * 10),
+ lsp_server=LspServer(lsp_port),
user_config_manager=user_config_mgr,
cli_args=cli_args,
auth_token=auth_token,
@@ -122,9 +123,11 @@ def start(
),
allow_origins=allow_origins,
enable_auth=not AuthToken.is_empty(session_manager.auth_token),
+ lsp_port=lsp_port,
)
app.state.port = external_port
+ app.state.lsp_port = lsp_port
app.state.host = external_host
app.state.headless = headless
diff --git a/marimo/_server/utils.py b/marimo/_server/utils.py
index 3a1742efed..04788f5d1c 100644
--- a/marimo/_server/utils.py
+++ b/marimo/_server/utils.py
@@ -36,6 +36,9 @@ def find_free_port(port: int, attempts: int = 100) -> int:
import socket
+ # Valid port range is 1-65535
+ port = max(1, min(port, 65535))
+
if attempts == 0:
raise RuntimeError("Could not find a free port")
@@ -47,7 +50,13 @@ def find_free_port(port: int, attempts: int = 100) -> int:
except OSError:
LOGGER.debug(f"Port {port} is already in use")
pass
- return find_free_port(port + 1, attempts - 1)
+
+ # Ensure we don't exceed valid port range
+ next_port = min(port + 1, 65535)
+ if next_port == port:
+ raise RuntimeError("No more ports available")
+
+ return find_free_port(next_port, attempts - 1)
def initialize_mimetypes() -> None: