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.

Revert "Revert "chore: improves typings of webworker rpc"" (#956)

Myles Scolnickf7b0c2ad6de1
diff --git a/frontend/package.json b/frontend/package.json
index 97dd60cda8..c2a9cd0aea 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -110,6 +110,7 @@
"react-use-event-hook": "^0.9.6",
"react-vega": "^7.6.0",
"reactflow": "^11.10.4",
+ "rpc-anywhere": "^1.7.0",
"swiper": "^11.0.7",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7",
@@ -158,6 +159,7 @@
"@storybook/react-vite": "^7.6.14",
"@storybook/testing-library": "^0.2.2",
"@swc-jotai/react-refresh": "^0.1.0",
+ "@types/emscripten": "^1.39.10",
"@types/katex": "^0.16.7",
"@types/lodash-es": "^4.17.12",
"@types/react": "^18.2.58",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 64167bf136..03890bbfa0 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -299,6 +299,9 @@ dependencies:
reactflow:
specifier: ^11.10.4
+ rpc-anywhere:
+ specifier: ^1.7.0
+ version: 1.7.0
swiper:
specifier: ^11.0.7
version: 11.0.7
@@ -361,6 +364,9 @@ devDependencies:
'@swc-jotai/react-refresh':
specifier: ^0.1.0
version: 0.1.0
+ '@types/emscripten':
+ specifier: ^1.39.10
+ version: 1.39.10
'@types/katex':
specifier: ^0.16.7
version: 0.16.7
@@ -6492,8 +6498,8 @@ packages:
resolution: {integrity: sha512-ZmiaE3wglXVWBM9fyVC17aGPkLo/UgaOjEiI2FXQfyczrCefORPxIe+2dVmnmk3zkVIbizjrlQzmPGhSYGXG5g==}
dev: true
- resolution: {integrity: sha512-H90aoynNhhkQP6DRweEjJp5vfUVdIj7tdPLsu7pq89vODD/lcugKfZOsfgwpvM6XUewEp2N5dCg1Uf3Qe55Dcg==}
+ resolution: {integrity: sha512-TB/6hBkYQJxsZHSqyeuO1Jt0AB/bW6G7rHt9g7lML7SOF6lbgcHvw/Lr+69iqN0qxgXLhWKScAon73JNnptuDw==}
dev: true
@@ -6544,6 +6550,16 @@ packages:
fast-json-stable-stringify: 2.1.0
dev: false
+ resolution: {integrity: sha512-1eKvCaIBdrD2mmMgy5dwh564rVvfEhZTWVQQGRNn0Nt4ZEnJ0C8oSUCzvMKRA4lGde5oEVo+q2MrTTbV/GHDCQ==}
+ dependencies:
+ '@types/filewriter': 0.0.33
+ dev: false
+
+ resolution: {integrity: sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==}
+ dev: false
+
resolution: {integrity: sha512-frsJrz2t/CeGifcu/6uRo4b+SzAwT4NYCVPu1GN8IB9XTzrpPkGuV0tmh9mN+/L0PklAlsC3u5Fxt0ju00LXIw==}
@@ -6564,6 +6580,10 @@ packages:
'@types/node': 20.8.10
dev: true
+ resolution: {integrity: sha512-RpQH4rXLuvTXKR0zqHq3go0RVXYv/YVqv4TnPH95VbwUxZdQlK1EtcMvQvMpDngHbt13Csh9Z4qT9AbkiQH5BA==}
+ dev: false
+
resolution: {integrity: sha512-yaf7kan2Sq0goxpbcwTQ+8E9RP6HutFBPv74T/IA/ojcHKhuKVlk2YFYyHhWZeLvZPzzLE3aatuQB4h0iqyyUA==}
dev: false
@@ -6753,6 +6773,10 @@ packages:
resolution: {integrity: sha512-WUtIVRUZ9i5dYXefDEAI7sh9/O7jGvHg7Df/5O/gtH3Yabe5odI3UWopVR1qbPXQtvOxWu3mM4XxlYeZtMWF4g==}
dev: true
+ resolution: {integrity: sha512-10ql7A0qzBmFB+F+qAke/nP1PIonS0TXZAOMVOxEUsm+lGSW6uwVcISFNa0I4Oyj0884TZVWGGMIWeXOVSNFHw==}
+ dev: false
+
resolution: {integrity: sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==}
dev: true
@@ -7332,7 +7356,7 @@ packages:
resolution: {integrity: sha512-6xm38yGVIa6mKm/DUCF2zFFJhERh/QWp1ufm4cNUvxsONBmfPg8uZ9pZBdOmF6qFGr/HlT6ABBkCSx/dlEtvWg==}
engines: {node: '>=12 <14 || 14.2 - 14.9 || >14.10.0'}
dependencies:
- '@types/emscripten': 1.39.6
+ '@types/emscripten': 1.39.10
tslib: 1.14.1
dev: true
@@ -7991,6 +8015,14 @@ packages:
resolution: {integrity: sha512-nfulgvOR6S4gt9UKCeGJOuSGBPGiFT6oQ/2UBnvTY/5aQ1PnksW72fhZkM30DzoRRv2WpwZf1vHHEr3mtuXIWQ==}
dev: true
+ resolution: {integrity: sha512-9b4yNTNs+8HVPssSq8RSZMRunf+G4cVQ2PMtOTn+uEVFOW5C0Uo+eGXuJ5LfxS1UDph5oAdWj92thPyxVhpqXg==}
+ dependencies:
+ '@types/filesystem': 0.0.35
+ '@types/har-format': 1.2.15
+ '@types/webextension-polyfill': 0.10.7
+ dev: false
+
resolution: {integrity: sha512-19OEpq7vWgsH6WkvkBJQDFvJS1uPcbFOQ4v9CU839dO+ZZXUZO6XpE6hNCqvlIIj+4fZvRiJ6DsAQ382GwiyTQ==}
dependencies:
@@ -15114,6 +15146,12 @@ packages:
fsevents: 2.3.3
dev: true
+ resolution: {integrity: sha512-/MgRTK/5iOh7EmYz5uZAmHX0DNg9PdbyjVgDtLX4WwoWHmpI8uh9We877U6KizxPDlmeDslq/2MnS7kZXWR8Cw==}
+ dependencies:
+ browser-namespace: 1.4.0
+ dev: false
+
resolution: {integrity: sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==}
dev: true
diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.ts
index 418af6c4ea..3ae40e64b6 100644
--- a/frontend/src/core/pyodide/bridge.ts
+++ b/frontend/src/core/pyodide/bridge.ts
@@ -27,19 +27,15 @@ import {
import { IReconnectingWebSocket } from "../websocket/types";
import { fallbackFileStore, notebookFileStore } from "./store";
import { isPyodide } from "./utils";
-import {
- RawBridge,
- WorkerClientPayload,
- WorkerServerPayload,
-} from "./worker/types";
-import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
+import { RawBridge } from "./worker/types";
import { Deferred } from "@/utils/Deferred";
-import InlineWorker from "./worker/worker?worker&inline";
import { UserConfigLocalStorage } from "../config/config-schema";
import { createShareableLink } from "./share";
import { PyodideRouter } from "./router";
import { Paths } from "@/utils/paths";
import { getMarimoVersion } from "../dom/marimo-tag";
+import { getWorkerRPC } from "./rpc";
+import InlineWorker from "./worker/worker?worker&inline";
export type BridgeFunctionAndPayload = {
[P in keyof RawBridge]: {
@@ -51,91 +47,71 @@ export type BridgeFunctionAndPayload = {
export class PyodideBridge implements RunRequests, EditRequests {
static INSTANCE = new PyodideBridge();
- private worker!: Worker;
+ private rpc!: ReturnType<typeof getWorkerRPC>;
private interruptBuffer?: Uint8Array;
private messageConsumer: ((message: string) => void) | undefined;
- private fetcher = new DeferredRequestRegistry<
- BridgeFunctionAndPayload,
- unknown
- >("bridge", async (requestId, request) => {
- this.postMessage({
- type: "call-function",
- id: requestId,
- functionName: request.functionName,
- payload: request.payload,
- });
- });
public initialized = new Deferred<void>();
constructor() {
if (isPyodide()) {
- this.worker = new InlineWorker({
+ // Create a worker
+ const worker = new InlineWorker({
name: getMarimoVersion(),
});
- this.worker.onmessage = this.handleWorkerMessage;
- if (crossOriginIsolated) {
- // Pyodide handles interrupts through SharedArrayBuffers, which
- // only work in secure (crossOriginIsolated) contexts
- this.interruptBuffer = new Uint8Array(new SharedArrayBuffer(1));
- this.fetcher.request({
- functionName: "set_interrupt_buffer",
- payload: this.interruptBuffer,
- });
- } else {
- console.warn(
- "Not running in a secure context; interrupts are not available.",
- );
- }
+
+ // Create the RPC
+ this.rpc = getWorkerRPC(worker);
+
+ // Listeners
+ this.rpc.addMessageListener("ready", () => {
+ this.startSession();
+ });
+ this.rpc.addMessageListener("initialized", () => {
+ this.setInterruptBuffer();
+ this.initialized.resolve();
+ });
+ this.rpc.addMessageListener("initializedError", ({ error }) => {
+ this.initialized.reject(new Error(error));
+ });
+ this.rpc.addMessageListener("kernelMessage", ({ message }) => {
+ this.messageConsumer?.(message);
+ });
}
}
- private setCode = async () => {
+
+ private async startSession() {
// Pass the code to the worker
// If a filename is provided, it will be used to save the file
// If no filename is provided, the file will not be saved
const code = await notebookFileStore.readFile();
const fallbackCode = await fallbackFileStore.readFile();
const filename = PyodideRouter.getFilename();
- this.postMessage({
- type: "set-code",
- code: code,
+ await this.rpc.proxy.request.startSession({
+ code,
fallbackCode: fallbackCode || "",
filename,
});
- };
+ }
- private handleWorkerMessage = async (
- event: MessageEvent<WorkerClientPayload>,
- ) => {
- if (event.data.type === "ready") {
- await this.setCode();
- }
- if (event.data.type === "initialized") {
- this.initialized.resolve();
+ private setInterruptBuffer() {
+ // Set up the interrupt buffer
+ if (crossOriginIsolated) {
+ // Pyodide handles interrupts through SharedArrayBuffers, which
+ // only work in secure (crossOriginIsolated) contexts
+ this.interruptBuffer = new Uint8Array(new SharedArrayBuffer(1));
+ this.rpc.proxy.request.setInterruptBuffer(this.interruptBuffer);
+ } else {
+ Logger.warn(
+ "Not running in a secure context; interrupts are not available.",
+ );
}
- if (event.data.type === "initialized-error") {
- this.initialized.reject(new Error(event.data.error));
- }
- if (event.data.type === "message") {
- this.messageConsumer?.(event.data.message);
- }
- if (event.data.type === "error") {
- Logger.error(event.data.error);
- this.fetcher.reject(event.data.id, new Error(event.data.error));
- }
- if (event.data.type === "response") {
- this.fetcher.resolve(event.data.id, event.data.response);
- }
- };
-
- private postMessage = (message: WorkerServerPayload) => {
- this.worker.postMessage(message);
- };
+ }
- consumeMessages = (consumer: (message: string) => void) => {
+ consumeMessages(consumer: (message: string) => void) {
this.messageConsumer = consumer;
- this.postMessage({ type: "start-messages" });
- };
+ this.rpc.proxy.send.consumerReady({});
+ }
sendRename = async (filename: string | null): Promise<null> => {
if (filename === null) {
@@ -145,7 +121,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
// so refreshing the page will keep the filename
PyodideRouter.setFilename(filename);
- await this.fetcher.request({
+ await this.rpc.proxy.request.bridge({
functionName: "rename_file",
payload: filename,
});
@@ -153,7 +129,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendSave = async (request: SaveKernelRequest): Promise<null> => {
- await this.fetcher.request({
+ await this.rpc.proxy.request.bridge({
functionName: "save",
payload: request,
});
@@ -165,7 +141,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendStdin = async (request: SendStdin): Promise<null> => {
- await this.fetcher.request({
+ await this.rpc.proxy.request.bridge({
functionName: "put_input",
payload: request.text,
});
@@ -173,10 +149,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendRun = async (cellIds: CellId[], codes: string[]): Promise<null> => {
- await this.fetcher.request({
- functionName: "load_packages",
- payload: codes.join("\n"),
- });
+ await this.rpc.proxy.request.loadPackages(codes.join("\n"));
await this.putControlRequest({
execution_requests: cellIds.map((cellId, index) => ({
@@ -200,7 +173,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendFormat = async (
request: FormatRequest,
): Promise<Record<CellId, string>> => {
- const response = await this.fetcher.request({
+ const response = await this.rpc.proxy.request.bridge({
functionName: "format",
payload: request,
});
@@ -216,7 +189,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendCodeCompletionRequest = async (
request: CodeCompletionRequest,
): Promise<null> => {
- await this.fetcher.request({
+ await this.rpc.proxy.request.bridge({
functionName: "code_complete",
payload: request,
});
@@ -229,7 +202,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
saveAppConfig = async (request: SaveAppConfigRequest): Promise<null> => {
- await this.fetcher.request({
+ await this.rpc.proxy.request.bridge({
functionName: "save_app_config",
payload: request,
});
@@ -249,7 +222,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
readCode = async (): Promise<{ contents: string }> => {
- const response = await this.fetcher.request({
+ const response = await this.rpc.proxy.request.bridge({
functionName: "read_code",
payload: undefined,
});
@@ -271,7 +244,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendListFiles = async (
request: FileListRequest,
): Promise<FileListResponse> => {
- const response = await this.fetcher.request({
+ const response = await this.rpc.proxy.request.bridge({
functionName: "list_files",
payload: request,
});
@@ -299,7 +272,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendCreateFileOrFolder = async (
request: FileCreateRequest,
): Promise<FileOperationResponse> => {
- const response = await this.fetcher.request({
+ const response = await this.rpc.proxy.request.bridge({
functionName: "create_file_or_directory",
payload: request,
});
@@ -309,7 +282,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendDeleteFileOrFolder = async (
request: FileDeleteRequest,
): Promise<FileOperationResponse> => {
- const response = await this.fetcher.request({
+ const response = await this.rpc.proxy.request.bridge({
functionName: "delete_file_or_directory",
payload: request,
});
@@ -319,7 +292,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendRenameFileOrFolder = async (
request: FileUpdateRequest,
): Promise<FileOperationResponse> => {
- const response = await this.fetcher.request({
+ const response = await this.rpc.proxy.request.bridge({
functionName: "update_file_or_directory",
payload: request,
});
@@ -329,19 +302,19 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendFileDetails = async (request: {
path: string;
}): Promise<FileDetailsResponse> => {
- const response = await this.fetcher.request({
+ const response = await this.rpc.proxy.request.bridge({
functionName: "file_details",
payload: request,
});
return response as FileDetailsResponse;
};
- private putControlRequest = async (operation: object) => {
- await this.fetcher.request({
+ private async putControlRequest(operation: object) {
+ await this.rpc.proxy.request.bridge({
functionName: "put_control_request",
payload: operation,
});
- };
+ }
}
export class PyodideWebsocket implements IReconnectingWebSocket {
diff --git a/frontend/src/core/pyodide/rpc.ts b/frontend/src/core/pyodide/rpc.ts
new file mode 100644
index 0000000000..15c9bfdda2
--- /dev/null
+++ b/frontend/src/core/pyodide/rpc.ts
@@ -0,0 +1,29 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { createWorkerTransport, createRPC, type RPCSchema } from "rpc-anywhere";
+
+import type { WorkerSchema } from "./worker/worker";
+import { TRANSPORT_ID } from "./worker/constants";
+import { Logger } from "@/utils/Logger";
+
+export type ParentSchema = RPCSchema<{
+ messages: {
+ consumerReady: {};
+ };
+}>;
+
+export function getWorkerRPC(worker: Worker) {
+ return createRPC<ParentSchema, WorkerSchema>({
+ transport: createWorkerTransport(worker, {
+ transportId: TRANSPORT_ID,
+ }),
+ maxRequestTime: 20_000, // 20 seconds
+ _debugHooks: {
+ onSend: (message) => {
+ Logger.debug("[rpc] Parent -> Worker", message);
+ },
+ onReceive: (message) => {
+ Logger.debug("[rpc] Worker -> Parent", message);
+ },
+ },
+ });
+}
diff --git a/frontend/src/core/pyodide/worker/bootstrap.ts b/frontend/src/core/pyodide/worker/bootstrap.ts
index 40ebf61525..3d11de56b0 100644
--- a/frontend/src/core/pyodide/worker/bootstrap.ts
+++ b/frontend/src/core/pyodide/worker/bootstrap.ts
@@ -2,99 +2,120 @@
import type { PyodideInterface } from "pyodide";
import { mountFilesystem } from "./fs";
import { Logger } from "../../../utils/Logger";
-import { SerializedBridge } from "./types";
-
-declare let loadPyodide:
- | undefined
- | ((opts: {
- packages: string[];
- indexURL: string;
- }) => Promise<PyodideInterface>);
-
-export async function bootstrap() {
- if (!loadPyodide) {
- throw new Error("loadPyodide is not defined");
+import { SerializedBridge, WasmController } from "./types";
+import { invariant } from "../../../utils/invariant";
+
+declare let loadPyodide: (opts: {
+ packages: string[];
+ indexURL: string;
+}) => Promise<PyodideInterface>;
+
+export class DefaultWasmController implements WasmController {
+ private pyodide: PyodideInterface | null = null;
+
+ async bootstrap(opts: { version: string }): Promise<PyodideInterface> {
+ const pyodide = await this.loadPyoideAndPackages();
+
+ const { version } = opts;
+
+ // If is a dev release, we need to install from test.pypi.org
+ if (version.includes("dev")) {
+ await this.installDevMarimo(pyodide, version);
+ }
+
+ await this.installMarimoAndDeps(pyodide, version);
+ this.installPatches(pyodide);
+
+ return pyodide;
}
- // Load pyodide and packages
- const pyodide = await loadPyodide({
- // Perf: These get loaded while pyodide is being bootstrapped
- // The packages can be found here: https://pyodide.org/en/stable/usage/packages-in-pyodide.html
- packages: ["micropip", "docutils", "Pygments", "jedi"],
- // Without this, this fails in Firefox with
- // `Could not extract indexURL path from pyodide module`
- // This fixes for Firefox and does not break Chrome/others
- indexURL: "https://cdn.jsdelivr.net/pyodide/v0.25.0/full/",
- });
-
- // If is a dev release, we need to install from test.pypi.org
- if (getMarimoVersion().includes("dev")) {
- await pyodide.runPythonAsync(`
- import micropip
-
- await micropip.install(
- [
- "${getMarimoWheel()}",
- ],
- deps=False,
- index_urls="https://test.pypi.org/pypi/{package_name}/json"
- );
- `);
+ private async loadPyoideAndPackages(): Promise<PyodideInterface> {
+ if (!loadPyodide) {
+ throw new Error("loadPyodide is not defined");
+ }
+ // Load pyodide and packages
+ const pyodide = await loadPyodide({
+ // Perf: These get loaded while pyodide is being bootstrapped
+ // The packages can be found here: https://pyodide.org/en/stable/usage/packages-in-pyodide.html
+ packages: ["micropip", "docutils", "Pygments", "jedi", "pyodide-http"],
+ // Without this, this fails in Firefox with
+ // `Could not extract indexURL path from pyodide module`
+ // This fixes for Firefox and does not break Chrome/others
+ indexURL: "https://cdn.jsdelivr.net/pyodide/v0.25.0/full/",
+ });
+ this.pyodide = pyodide;
+ return pyodide;
}
- // Install marimo and its dependencies
- await pyodide.runPythonAsync(`
- import micropip
-
- await micropip.install(
- [
- # Subset of marimo requirements
- "${getMarimoWheel()}",
- "markdown",
- "pymdown-extensions",
- "pyodide_http",
- ],
- deps=False,
- );
- `);
+ private async installDevMarimo(pyodide: PyodideInterface, version: string) {
+ await pyodide.runPythonAsync(`
+ import micropip
+
+ await micropip.install(
+ [
+ "${getMarimoWheel(version)}",
+ ],
+ deps=False,
+ index_urls="https://test.pypi.org/pypi/{package_name}/json"
+ );
+ `);
+ }
- // Patch the built-in urllib
- pyodide.runPython(`
- import pyodide_http
- pyodide_http.patch_urllib()
- `);
+ private async installMarimoAndDeps(
+ pyodide: PyodideInterface,
+ version: string,
+ ) {
+ await pyodide.runPythonAsync(`
+ import micropip
+
+ await micropip.install(
+ [
+ "${getMarimoWheel(version)}",
+ "markdown",
+ "pymdown-extensions",
+ ],
+ deps=False,
+ );
+ `);
+ }
- return pyodide;
-}
+ private installPatches(pyodide: PyodideInterface) {
+ pyodide.runPython(`
+ import pyodide_http
+ pyodide_http.patch_urllib()
+ `);
+ }
-export async function startSession(
- pyodide: PyodideInterface,
- opts: {
+ async startSession(opts: {
code: string | null;
fallbackCode: string;
filename: string | null;
- },
- messageCallback: (data: string) => void,
-): Promise<SerializedBridge> {
- // Set up the filesystem
- const { filename, content } = await mountFilesystem({ pyodide, ...opts });
-
- // We pass down a messenger object to the code
- // This is used to have synchronous communication between the JS and Python code
- // Previously, we used a queue, but this would not properly flush the queue
- // during processing of a cell's code.
- //
- // This adds a messenger object to the global scope (import js; js.messenger.callback)
- self.messenger = { callback: messageCallback };
-
- // Load packages from the code
- await pyodide.loadPackagesFromImports(content, {
- messageCallback: Logger.log,
- errorCallback: Logger.error,
- });
-
- const bridge = await pyodide.runPythonAsync(
- `
+ onMessage: (message: string) => void;
+ }): Promise<SerializedBridge> {
+ invariant(this.pyodide, "Pyodide not loaded");
+
+ // Set up the filesystem
+ const { filename, content } = await mountFilesystem({
+ pyodide: this.pyodide,
+ ...opts,
+ });
+
+ // We pass down a messenger object to the code
+ // This is used to have synchronous communication between the JS and Python code
+ // Previously, we used a queue, but this would not properly flush the queue
+ // during processing of a cell's code.
+ //
+ // This adds a messenger object to the global scope (import js; js.messenger.callback)
+ self.messenger = { callback: opts.onMessage };
+
+ // Load packages from the code
+ await this.pyodide.loadPackagesFromImports(content, {
+ messageCallback: Logger.log,
+ errorCallback: Logger.error,
+ });
+
+ const bridge = await this.pyodide.runPythonAsync(
+ `
print("[py] Starting marimo...")
import asyncio
import js
@@ -107,19 +128,13 @@ export async function startSession(
asyncio.create_task(session.start())
bridge`,
- );
-
- self.bridge = bridge;
+ );
- return bridge;
-}
-
-function getMarimoVersion() {
- return self.name; // We store the version in the worker name
+ return bridge;
+ }
}
-function getMarimoWheel() {
- const version = getMarimoVersion();
+function getMarimoWheel(version: string) {
if (!version) {
return "marimo >= 0.3.0";
}
diff --git a/frontend/src/core/pyodide/worker/constants.ts b/frontend/src/core/pyodide/worker/constants.ts
new file mode 100644
index 0000000000..fbe0e4c9cd
--- /dev/null
+++ b/frontend/src/core/pyodide/worker/constants.ts
@@ -0,0 +1,2 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+export const TRANSPORT_ID = "marimo-transport";
diff --git a/frontend/src/core/pyodide/worker/fs.ts b/frontend/src/core/pyodide/worker/fs.ts
index 286857b560..f2362d4c6e 100644
--- a/frontend/src/core/pyodide/worker/fs.ts
+++ b/frontend/src/core/pyodide/worker/fs.ts
@@ -3,6 +3,10 @@ import type { PyodideInterface } from "pyodide";
const FALLBACK_FILE = "notebook.py";
+export function getFS(pyodide: PyodideInterface): typeof FS {
+ return pyodide.FS;
+}
+
export async function mountFilesystem(opts: {
pyodide: PyodideInterface;
code: string | null;
@@ -13,21 +17,22 @@ export async function mountFilesystem(opts: {
filename: string;
}> {
const { pyodide, filename, code, fallbackCode } = opts;
+ const FS = getFS(pyodide);
// This is our home directory
const mountDir = "/marimo";
// Mount the filesystem
- await pyodide.FS.mkdir(mountDir);
- await pyodide.FS.mount(pyodide.FS.filesystems.IDBFS, { root: "." }, mountDir);
+ await FS.mkdir(mountDir);
+ await FS.mount(pyodide.FS.filesystems.IDBFS, { root: "." }, mountDir);
- await syncFileSystem(pyodide, "start");
+ await syncFileSystem(pyodide, true);
// Change to the mounted directory
- await pyodide.FS.chdir(mountDir);
+ FS.chdir(mountDir);
const readIfExist = (filename: string) => {
try {
- return pyodide.FS.readFile(filename, { encoding: "utf8" });
+ return FS.readFile(filename, { encoding: "utf8" });
} catch {
return null;
}
@@ -47,7 +52,7 @@ export async function mountFilesystem(opts: {
}
// If the filename does not exist in the FS, write the content to the file
- await pyodide.FS.writeFile(filename, content, { encoding: "utf8" });
+ FS.writeFile(filename, content);
return {
content,
filename,
@@ -55,7 +60,7 @@ export async function mountFilesystem(opts: {
}
// If there is no filename, write the code to the last used file
- await pyodide.FS.writeFile(FALLBACK_FILE, content, { encoding: "utf8" });
+ FS.writeFile(FALLBACK_FILE, content);
return {
content: content,
filename: FALLBACK_FILE,
@@ -64,12 +69,12 @@ export async function mountFilesystem(opts: {
export function syncFileSystem(
pyodide: PyodideInterface,
- type?: "start",
+ populate: boolean,
): Promise<void> {
// Sync the filesystem. This brings IndexedDBFS up to date with the in-memory filesystem
// `true` when starting up, `false` when shutting down
return new Promise<void>((resolve, reject) => {
- pyodide.FS.syncfs(type === "start", (err: Error) => {
+ getFS(pyodide).syncfs(populate, (err: Error) => {
if (err) {
reject(err);
return;
diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.ts
index 6c201d578a..1de7a551b4 100644
--- a/frontend/src/core/pyodide/worker/types.ts
+++ b/frontend/src/core/pyodide/worker/types.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { RequestId } from "@/core/network/DeferredRequestRegistry";
+import type { PyodideInterface } from "pyodide";
import type {
CodeCompletionRequest,
FileCreateRequest,
@@ -15,6 +15,26 @@ import type {
SaveKernelRequest,
} from "../../network/types";
+export interface WasmController {
+ /**
+ * Prepare the wasm environment
+ * @param opts.version - The marimo version
+ */
+ bootstrap(opts: { version: string }): Promise<PyodideInterface>;
+ /**
+ * Start the session
+ * @param opts.code - The code to start with
+ * @param opts.fallbackCode - The code to fallback to
+ * @param opts.filename - The filename to start with
+ */
+ startSession(opts: {
+ code: string | null;
+ fallbackCode: string;
+ filename: string | null;
+ onMessage: (message: string) => void;
+ }): Promise<SerializedBridge>;
+}
+
export interface RawBridge {
put_control_request(operation: object): Promise<string>;
put_input(input: string): Promise<string>;
@@ -47,46 +67,3 @@ export type SerializedBridge = {
? (payload: string) => Promise<string>
: RawBridge[P];
};
-
-export type WorkerServerPayload =
- | {
- type: "start-messages";
- }
- | {
- type: "set-code";
- code: string | null;
- fallbackCode: string;
- filename: string | null;
- }
- | {
- type: "call-function";
- id: RequestId;
- functionName: keyof RawBridge | "load_packages" | "read_file";
- payload: {} | undefined | null;
- };
-
-export type WorkerClientPayload =
- | {
- type: "response";
- id: RequestId;
- response: unknown;
- }
- | {
- type: "ready";
- }
- | {
- type: "initialized";
- }
- | {
- type: "initialized-error";
- error: string;
- }
- | {
- type: "error";
- id: RequestId;
- error: string;
- }
- | {
- type: "message";
- message: string;
- };
diff --git a/frontend/src/core/pyodide/worker/worker.ts b/frontend/src/core/pyodide/worker/worker.ts
index 9b5c59b004..6601212a4b 100644
--- a/frontend/src/core/pyodide/worker/worker.ts
+++ b/frontend/src/core/pyodide/worker/worker.ts
@@ -1,21 +1,27 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { bootstrap, startSession } from "./bootstrap";
+import { DefaultWasmController } from "./bootstrap";
import type { PyodideInterface } from "pyodide";
-import {
- RawBridge,
- SerializedBridge,
- WorkerClientPayload,
- WorkerServerPayload,
-} from "./types";
-import { invariant } from "../../../utils/invariant";
+import { RawBridge, SerializedBridge, WasmController } from "./types";
import { Deferred } from "../../../utils/Deferred";
import { syncFileSystem } from "./fs";
import { MessageBuffer } from "./message-buffer";
import { prettyError } from "../../../utils/errors";
+import {
+ createWorkerParentTransport,
+ createRPC,
+ createRPCRequestHandler,
+ type RPCSchema,
+} from "rpc-anywhere";
+import { ParentSchema } from "../rpc";
+import { Logger } from "../../../utils/Logger";
+import { TRANSPORT_ID } from "./constants";
+import { invariant } from "../../../utils/invariant";
declare const self: Window & {
pyodide: PyodideInterface;
+ controller: WasmController;
+ rpc: ReturnType<typeof createRPC>;
};
// Initialize pyodide
@@ -23,93 +29,116 @@ async function loadPyodideAndPackages() {
// @ts-expect-error ehh TypeScript
await import("https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js");
try {
- self.pyodide = await bootstrap();
+ const version = getMarimoVersion();
+ const controller = await getController(version);
+ self.controller = controller;
+ self.pyodide = await controller.bootstrap({
+ version,
+ });
} catch (error) {
console.error("Error bootstrapping", error);
- postMessage({ type: "initialized-error", error: prettyError(error) });
+ rpc.send.initializedError({
+ error: prettyError(error),
+ });
}
}
-const pyodideReadyPromise = loadPyodideAndPackages();
-const messageBuffer = new MessageBuffer((m: string) =>
- postMessage({ type: "message", message: m }),
-);
-// Initialize the session
-const bridgeReady = new Deferred<SerializedBridge>();
-let started = false;
-function startSessionWithCode(opts: {
- code: string | null;
- fallbackCode: string;
- filename: string | null;
-}) {
- if (started) {
- return;
+// Load the controller
+// Falls back to the default controller
+async function getController(version: string) {
+ try {
+ const controller = await import(
+ /* @vite-ignore */ `/wasm/controller.js?version=${version}`
+ );
+ return controller;
+ } catch {
+ return new DefaultWasmController();
}
- started = true;
- startSession(self.pyodide, opts, messageBuffer.push).then((bridge) => {
- bridgeReady.resolve(bridge);
- postMessage({ type: "initialized" });
- });
}
-async function getBridge() {
- return bridgeReady.promise;
-}
-
-self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {
- // make sure loading is done
- await pyodideReadyPromise;
-
- // Start the session
- if (event.data.type === "set-code") {
- startSessionWithCode(event.data);
- return;
- }
+const pyodideReadyPromise = loadPyodideAndPackages();
+const messageBuffer = new MessageBuffer((message: string) => {
+ rpc.send.kernelMessage({ message });
+});
+const bridgeReady = new Deferred<SerializedBridge>();
+let started = false;
- if (event.data.type === "start-messages") {
- // Flush the message buffer
- messageBuffer.start();
+// Handle RPC requests
+const requestHandler = createRPCRequestHandler({
+ /**
+ * Start the session
+ */
+ startSession: async (opts: {
+ code: string | null;
+ fallbackCode: string;
+ filename: string | null;
+ }) => {
+ await pyodideReadyPromise; // Make sure loading is done
+
+ if (started) {
+ Logger.warn("Session already started");
+ return;
+ }
+ started = true;
+ try {
+ invariant(self.controller, "Controller not loaded");
+ const bridge = await self.controller.startSession({
+ ...opts,
+ onMessage: messageBuffer.push,
+ });
+ bridgeReady.resolve(bridge);
+ rpc.send.initialized({});
+ } catch (error) {
+ rpc.send.initializedError({
+ error: prettyError(error),
+ });
+ }
return;
- }
+ },
- const { id, functionName, payload } = event.data;
- try {
- // Special case for loading packages
- if (functionName === "load_packages") {
- invariant(
- typeof payload === "string",
- "Expected a string payload for load_packages",
- );
- await self.pyodide.loadPackagesFromImports(payload, {
- messageCallback: console.log,
- errorCallback: console.error,
- });
+ /**
+ * Load packages
+ */
+ loadPackages: async (packages: string) => {
+ await pyodideReadyPromise; // Make sure loading is done
- postMessage({ type: "response", response: null, id });
- return;
- }
- // Special case for reading a file
- if (functionName === "read_file") {
- invariant(
- typeof payload === "string",
- "Expected a string payload for read_file",
- );
- const file = self.pyodide.FS.readFile(payload, { encoding: "utf8" });
- postMessage({ type: "response", response: file, id });
- return;
- }
+ await self.pyodide.loadPackagesFromImports(packages, {
+ messageCallback: console.log,
+ errorCallback: console.error,
+ });
+ },
+
+ /**
+ * Read a file
+ */
+ readFile: async (filename: string) => {
+ await pyodideReadyPromise; // Make sure loading is done
+
+ const file = self.pyodide.FS.readFile(filename, { encoding: "utf8" });
+ return file;
+ },
+
+ /**
+ * Set the interrupt buffer
+ */
+ setInterruptBuffer: async (payload: Uint8Array) => {
+ await pyodideReadyPromise; // Make sure loading is done
+
+ self.pyodide.setInterruptBuffer(payload);
+ },
+
+ /**
+ * Call a function on the bridge
+ */
+ bridge: async (opts: {
+ functionName: keyof RawBridge;
+ payload: {} | undefined | null;
+ }) => {
+ await pyodideReadyPromise; // Make sure loading is done
+
+ const { functionName, payload } = opts;
- // Special case for installing the interrupt buffer
- if (functionName == "set_interrupt_buffer") {
- invariant(
- payload instanceof Uint8Array,
- "Expected a Uint8Array payload for interrupt",
- );
- self.pyodide.setInterruptBuffer(payload);
- postMessage({ type: "response", response: null, id });
- return;
- }
// Special case to lazily install black on format
// Don't return early; still need to ask the pyodide kernel to run
// the formatter
@@ -125,7 +154,8 @@ self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {
}
// Perform the function call to the Python bridge
- const bridge = await getBridge();
+ const bridge = await bridgeReady.promise;
+
// Serialize the payload
const payloadString =
payload == null
@@ -133,6 +163,7 @@ self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {
: typeof payload === "string"
? payload
: JSON.stringify(payload);
+
// Make the request
const response =
payloadString == null
@@ -141,26 +172,49 @@ self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {
: // @ts-expect-error ehh TypeScript
await bridge[functionName](payloadString);
- // Post the response back to the main thread
- postMessage({
- type: "response",
- response: typeof response === "string" ? JSON.parse(response) : response,
- id,
- });
-
// Sync the filesystem if we're saving, creating, deleting, or renaming a file
if (namesThatRequireSync.has(functionName)) {
- await syncFileSystem(self.pyodide);
- }
- } catch (error) {
- console.error("Error in worker", error);
- if (error instanceof Error) {
- postMessage({ type: "error", error: error.message, id });
- } else {
- postMessage({ type: "error", error: String(error), id });
+ void syncFileSystem(self.pyodide, false);
}
- }
-};
+
+ // Post the response back to the main thread
+ return typeof response === "string" ? JSON.parse(response) : response;
+ },
+});
+
+// create the iframe's schema
+export type WorkerSchema = RPCSchema<
+ {
+ messages: {
+ // Emitted when the worker is ready
+ ready: {};
+ // Emitted when the kernel sends a message
+ kernelMessage: { message: string };
+ // Emitted when the Pyodide is initialized
+ initialized: {};
+ // Emitted when the Pyodide fails to initialize
+ initializedError: { error: string };
+ };
+ },
+ typeof requestHandler
+>;
+
+const rpc = createRPC<WorkerSchema, ParentSchema>({
+ transport: createWorkerParentTransport({
+ transportId: TRANSPORT_ID,
+ }),
+ requestHandler,
+});
+
+self.rpc = rpc;
+rpc.send("ready", {});
+
+/// Listeners
+// When the consumer is ready, start the message buffer
+rpc.addMessageListener("consumerReady", async () => {
+ await pyodideReadyPromise; // Make sure loading is done
+ messageBuffer.start();
+});
const namesThatRequireSync = new Set<keyof RawBridge>([
"save",
@@ -170,8 +224,6 @@ const namesThatRequireSync = new Set<keyof RawBridge>([
"update_file_or_directory",
]);
-function postMessage(message: WorkerClientPayload) {
- self.postMessage(message);
+function getMarimoVersion() {
+ return self.name; // We store the version in the worker name
}
-
-postMessage({ type: "ready" });
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
index 8ca62dd624..65b81c2dd4 100644
--- a/frontend/tsconfig.json
+++ b/frontend/tsconfig.json
@@ -36,7 +36,8 @@
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
"types": [
- "vite/client"
+ "vite/client",
+ "@types/emscripten"
] /* Specify type package names to be included without being referenced in a source file. */,
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */