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 "chore: improves typings of webworker rpc (#952)" (#955)

Myles Scolnickfc57e847e4ed
diff --git a/frontend/package.json b/frontend/package.json
index c2a9cd0aea..97dd60cda8 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -110,7 +110,6 @@
"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",
@@ -159,7 +158,6 @@
"@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 03890bbfa0..64167bf136 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -299,9 +299,6 @@ 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
@@ -364,9 +361,6 @@ 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
@@ -6498,8 +6492,8 @@ packages:
resolution: {integrity: sha512-ZmiaE3wglXVWBM9fyVC17aGPkLo/UgaOjEiI2FXQfyczrCefORPxIe+2dVmnmk3zkVIbizjrlQzmPGhSYGXG5g==}
dev: true
- resolution: {integrity: sha512-TB/6hBkYQJxsZHSqyeuO1Jt0AB/bW6G7rHt9g7lML7SOF6lbgcHvw/Lr+69iqN0qxgXLhWKScAon73JNnptuDw==}
+ resolution: {integrity: sha512-H90aoynNhhkQP6DRweEjJp5vfUVdIj7tdPLsu7pq89vODD/lcugKfZOsfgwpvM6XUewEp2N5dCg1Uf3Qe55Dcg==}
dev: true
@@ -6550,16 +6544,6 @@ 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==}
@@ -6580,10 +6564,6 @@ packages:
'@types/node': 20.8.10
dev: true
- resolution: {integrity: sha512-RpQH4rXLuvTXKR0zqHq3go0RVXYv/YVqv4TnPH95VbwUxZdQlK1EtcMvQvMpDngHbt13Csh9Z4qT9AbkiQH5BA==}
- dev: false
-
resolution: {integrity: sha512-yaf7kan2Sq0goxpbcwTQ+8E9RP6HutFBPv74T/IA/ojcHKhuKVlk2YFYyHhWZeLvZPzzLE3aatuQB4h0iqyyUA==}
dev: false
@@ -6773,10 +6753,6 @@ 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
@@ -7356,7 +7332,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.10
+ '@types/emscripten': 1.39.6
tslib: 1.14.1
dev: true
@@ -8015,14 +7991,6 @@ 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:
@@ -15146,12 +15114,6 @@ 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 36c902a5f3..418af6c4ea 100644
--- a/frontend/src/core/pyodide/bridge.ts
+++ b/frontend/src/core/pyodide/bridge.ts
@@ -27,14 +27,19 @@ import {
import { IReconnectingWebSocket } from "../websocket/types";
import { fallbackFileStore, notebookFileStore } from "./store";
import { isPyodide } from "./utils";
-import { RawBridge } from "./worker/types";
+import {
+ RawBridge,
+ WorkerClientPayload,
+ WorkerServerPayload,
+} from "./worker/types";
+import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
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";
export type BridgeFunctionAndPayload = {
[P in keyof RawBridge]: {
@@ -46,78 +51,91 @@ export type BridgeFunctionAndPayload = {
export class PyodideBridge implements RunRequests, EditRequests {
static INSTANCE = new PyodideBridge();
- private rpc!: ReturnType<typeof getWorkerRPC>;
+ private worker!: Worker;
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()) {
- // Create a worker
- const worker = new Worker(
- // eslint-disable-next-line unicorn/relative-url-style
- new URL("./worker/worker.ts", import.meta.url),
- {
- type: "module",
- // Pass the version to the worker
- /* @vite-ignore */
- name: getMarimoVersion(),
- },
- );
-
- // 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);
+ this.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.",
+ );
+ }
}
}
-
- private async startSession() {
+ private setCode = async () => {
// 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();
- await this.rpc.proxy.request.startSession({
- code,
+ this.postMessage({
+ type: "set-code",
+ code: code,
fallbackCode: fallbackCode || "",
filename,
});
- }
+ };
- 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.",
- );
+ private handleWorkerMessage = async (
+ event: MessageEvent<WorkerClientPayload>,
+ ) => {
+ if (event.data.type === "ready") {
+ await this.setCode();
}
- }
+ if (event.data.type === "initialized") {
+ this.initialized.resolve();
+ }
+ 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.rpc.proxy.send.consumerReady({});
- }
+ this.postMessage({ type: "start-messages" });
+ };
sendRename = async (filename: string | null): Promise<null> => {
if (filename === null) {
@@ -127,7 +145,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
// so refreshing the page will keep the filename
PyodideRouter.setFilename(filename);
- await this.rpc.proxy.request.bridge({
+ await this.fetcher.request({
functionName: "rename_file",
payload: filename,
});
@@ -135,7 +153,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendSave = async (request: SaveKernelRequest): Promise<null> => {
- await this.rpc.proxy.request.bridge({
+ await this.fetcher.request({
functionName: "save",
payload: request,
});
@@ -147,7 +165,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendStdin = async (request: SendStdin): Promise<null> => {
- await this.rpc.proxy.request.bridge({
+ await this.fetcher.request({
functionName: "put_input",
payload: request.text,
});
@@ -155,7 +173,10 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendRun = async (cellIds: CellId[], codes: string[]): Promise<null> => {
- await this.rpc.proxy.request.loadPackages(codes.join("\n"));
+ await this.fetcher.request({
+ functionName: "load_packages",
+ payload: codes.join("\n"),
+ });
await this.putControlRequest({
execution_requests: cellIds.map((cellId, index) => ({
@@ -179,7 +200,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendFormat = async (
request: FormatRequest,
): Promise<Record<CellId, string>> => {
- const response = await this.rpc.proxy.request.bridge({
+ const response = await this.fetcher.request({
functionName: "format",
payload: request,
});
@@ -195,7 +216,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendCodeCompletionRequest = async (
request: CodeCompletionRequest,
): Promise<null> => {
- await this.rpc.proxy.request.bridge({
+ await this.fetcher.request({
functionName: "code_complete",
payload: request,
});
@@ -208,7 +229,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
saveAppConfig = async (request: SaveAppConfigRequest): Promise<null> => {
- await this.rpc.proxy.request.bridge({
+ await this.fetcher.request({
functionName: "save_app_config",
payload: request,
});
@@ -228,7 +249,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
readCode = async (): Promise<{ contents: string }> => {
- const response = await this.rpc.proxy.request.bridge({
+ const response = await this.fetcher.request({
functionName: "read_code",
payload: undefined,
});
@@ -250,7 +271,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendListFiles = async (
request: FileListRequest,
): Promise<FileListResponse> => {
- const response = await this.rpc.proxy.request.bridge({
+ const response = await this.fetcher.request({
functionName: "list_files",
payload: request,
});
@@ -278,7 +299,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendCreateFileOrFolder = async (
request: FileCreateRequest,
): Promise<FileOperationResponse> => {
- const response = await this.rpc.proxy.request.bridge({
+ const response = await this.fetcher.request({
functionName: "create_file_or_directory",
payload: request,
});
@@ -288,7 +309,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendDeleteFileOrFolder = async (
request: FileDeleteRequest,
): Promise<FileOperationResponse> => {
- const response = await this.rpc.proxy.request.bridge({
+ const response = await this.fetcher.request({
functionName: "delete_file_or_directory",
payload: request,
});
@@ -298,7 +319,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendRenameFileOrFolder = async (
request: FileUpdateRequest,
): Promise<FileOperationResponse> => {
- const response = await this.rpc.proxy.request.bridge({
+ const response = await this.fetcher.request({
functionName: "update_file_or_directory",
payload: request,
});
@@ -308,19 +329,19 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendFileDetails = async (request: {
path: string;
}): Promise<FileDetailsResponse> => {
- const response = await this.rpc.proxy.request.bridge({
+ const response = await this.fetcher.request({
functionName: "file_details",
payload: request,
});
return response as FileDetailsResponse;
};
- private async putControlRequest(operation: object) {
- await this.rpc.proxy.request.bridge({
+ private putControlRequest = async (operation: object) => {
+ await this.fetcher.request({
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
deleted file mode 100644
index 15c9bfdda2..0000000000
--- a/frontend/src/core/pyodide/rpc.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/* 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 3d11de56b0..40ebf61525 100644
--- a/frontend/src/core/pyodide/worker/bootstrap.ts
+++ b/frontend/src/core/pyodide/worker/bootstrap.ts
@@ -2,120 +2,99 @@
import type { PyodideInterface } from "pyodide";
import { mountFilesystem } from "./fs";
import { Logger } from "../../../utils/Logger";
-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;
- }
-
- 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;
+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");
}
- private async installDevMarimo(pyodide: PyodideInterface, version: string) {
+ // 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(version)}",
- ],
- deps=False,
- index_urls="https://test.pypi.org/pypi/{package_name}/json"
- );
- `);
- }
-
- private async installMarimoAndDeps(
- pyodide: PyodideInterface,
- version: string,
- ) {
- await pyodide.runPythonAsync(`
- import micropip
-
- await micropip.install(
- [
- "${getMarimoWheel(version)}",
- "markdown",
- "pymdown-extensions",
- ],
- deps=False,
- );
- `);
+ import micropip
+
+ await micropip.install(
+ [
+ "${getMarimoWheel()}",
+ ],
+ deps=False,
+ index_urls="https://test.pypi.org/pypi/{package_name}/json"
+ );
+ `);
}
- private installPatches(pyodide: PyodideInterface) {
- pyodide.runPython(`
- import pyodide_http
- pyodide_http.patch_urllib()
+ // 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,
+ );
`);
- }
- async startSession(opts: {
+ // Patch the built-in urllib
+ pyodide.runPython(`
+ import pyodide_http
+ pyodide_http.patch_urllib()
+ `);
+
+ return pyodide;
+}
+
+export async function startSession(
+ pyodide: PyodideInterface,
+ opts: {
code: string | null;
fallbackCode: string;
filename: string | null;
- 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(
- `
+ },
+ 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(
+ `
print("[py] Starting marimo...")
import asyncio
import js
@@ -128,13 +107,19 @@ export class DefaultWasmController implements WasmController {
asyncio.create_task(session.start())
bridge`,
- );
+ );
- return bridge;
- }
+ self.bridge = bridge;
+
+ return bridge;
+}
+
+function getMarimoVersion() {
+ return self.name; // We store the version in the worker name
}
-function getMarimoWheel(version: string) {
+function getMarimoWheel() {
+ const version = getMarimoVersion();
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
deleted file mode 100644
index fbe0e4c9cd..0000000000
--- a/frontend/src/core/pyodide/worker/constants.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-/* 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 f2362d4c6e..286857b560 100644
--- a/frontend/src/core/pyodide/worker/fs.ts
+++ b/frontend/src/core/pyodide/worker/fs.ts
@@ -3,10 +3,6 @@ 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;
@@ -17,22 +13,21 @@ 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 FS.mkdir(mountDir);
- await FS.mount(pyodide.FS.filesystems.IDBFS, { root: "." }, mountDir);
+ await pyodide.FS.mkdir(mountDir);
+ await pyodide.FS.mount(pyodide.FS.filesystems.IDBFS, { root: "." }, mountDir);
- await syncFileSystem(pyodide, true);
+ await syncFileSystem(pyodide, "start");
// Change to the mounted directory
- FS.chdir(mountDir);
+ await pyodide.FS.chdir(mountDir);
const readIfExist = (filename: string) => {
try {
- return FS.readFile(filename, { encoding: "utf8" });
+ return pyodide.FS.readFile(filename, { encoding: "utf8" });
} catch {
return null;
}
@@ -52,7 +47,7 @@ export async function mountFilesystem(opts: {
}
// If the filename does not exist in the FS, write the content to the file
- FS.writeFile(filename, content);
+ await pyodide.FS.writeFile(filename, content, { encoding: "utf8" });
return {
content,
filename,
@@ -60,7 +55,7 @@ export async function mountFilesystem(opts: {
}
// If there is no filename, write the code to the last used file
- FS.writeFile(FALLBACK_FILE, content);
+ await pyodide.FS.writeFile(FALLBACK_FILE, content, { encoding: "utf8" });
return {
content: content,
filename: FALLBACK_FILE,
@@ -69,12 +64,12 @@ export async function mountFilesystem(opts: {
export function syncFileSystem(
pyodide: PyodideInterface,
- populate: boolean,
+ type?: "start",
): 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) => {
- getFS(pyodide).syncfs(populate, (err: Error) => {
+ pyodide.FS.syncfs(type === "start", (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 1de7a551b4..6c201d578a 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 { PyodideInterface } from "pyodide";
+import type { RequestId } from "@/core/network/DeferredRequestRegistry";
import type {
CodeCompletionRequest,
FileCreateRequest,
@@ -15,26 +15,6 @@ 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>;
@@ -67,3 +47,46 @@ 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 6601212a4b..9b5c59b004 100644
--- a/frontend/src/core/pyodide/worker/worker.ts
+++ b/frontend/src/core/pyodide/worker/worker.ts
@@ -1,27 +1,21 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { DefaultWasmController } from "./bootstrap";
+import { bootstrap, startSession } from "./bootstrap";
import type { PyodideInterface } from "pyodide";
-import { RawBridge, SerializedBridge, WasmController } from "./types";
+import {
+ RawBridge,
+ SerializedBridge,
+ WorkerClientPayload,
+ WorkerServerPayload,
+} from "./types";
+import { invariant } from "../../../utils/invariant";
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
@@ -29,116 +23,93 @@ async function loadPyodideAndPackages() {
// @ts-expect-error ehh TypeScript
await import("https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js");
try {
- const version = getMarimoVersion();
- const controller = await getController(version);
- self.controller = controller;
- self.pyodide = await controller.bootstrap({
- version,
- });
+ self.pyodide = await bootstrap();
} catch (error) {
console.error("Error bootstrapping", error);
- rpc.send.initializedError({
- error: prettyError(error),
- });
+ postMessage({ type: "initialized-error", error: prettyError(error) });
}
}
+const pyodideReadyPromise = loadPyodideAndPackages();
+const messageBuffer = new MessageBuffer((m: string) =>
+ postMessage({ type: "message", message: m }),
+);
-// 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();
+// 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;
}
+ started = true;
+ startSession(self.pyodide, opts, messageBuffer.push).then((bridge) => {
+ bridgeReady.resolve(bridge);
+ postMessage({ type: "initialized" });
+ });
}
-const pyodideReadyPromise = loadPyodideAndPackages();
-const messageBuffer = new MessageBuffer((message: string) => {
- rpc.send.kernelMessage({ message });
-});
-const bridgeReady = new Deferred<SerializedBridge>();
-let started = false;
+async function getBridge() {
+ return bridgeReady.promise;
+}
-// 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;
- }
+self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {
+ // make sure loading is done
+ await pyodideReadyPromise;
- 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),
- });
- }
+ // Start the session
+ if (event.data.type === "set-code") {
+ startSessionWithCode(event.data);
return;
- },
+ }
- /**
- * Load packages
- */
- loadPackages: async (packages: string) => {
- await pyodideReadyPromise; // Make sure loading is done
+ if (event.data.type === "start-messages") {
+ // Flush the message buffer
+ messageBuffer.start();
- 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;
+ 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,
+ });
+
+ 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;
+ }
+ // 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
@@ -154,8 +125,7 @@ const requestHandler = createRPCRequestHandler({
}
// Perform the function call to the Python bridge
- const bridge = await bridgeReady.promise;
-
+ const bridge = await getBridge();
// Serialize the payload
const payloadString =
payload == null
@@ -163,7 +133,6 @@ const requestHandler = createRPCRequestHandler({
: typeof payload === "string"
? payload
: JSON.stringify(payload);
-
// Make the request
const response =
payloadString == null
@@ -172,49 +141,26 @@ const requestHandler = createRPCRequestHandler({
: // @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)) {
- void syncFileSystem(self.pyodide, false);
+ await syncFileSystem(self.pyodide);
}
-
- // 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();
-});
+ } 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 });
+ }
+ }
+};
const namesThatRequireSync = new Set<keyof RawBridge>([
"save",
@@ -224,6 +170,8 @@ const namesThatRequireSync = new Set<keyof RawBridge>([
"update_file_or_directory",
]);
-function getMarimoVersion() {
- return self.name; // We store the version in the worker name
+function postMessage(message: WorkerClientPayload) {
+ self.postMessage(message);
}
+
+postMessage({ type: "ready" });
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
index 65b81c2dd4..8ca62dd624 100644
--- a/frontend/tsconfig.json
+++ b/frontend/tsconfig.json
@@ -36,8 +36,7 @@
// "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",
- "@types/emscripten"
+ "vite/client"
] /* 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. */