-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.tsx
More file actions
230 lines (210 loc) · 6.32 KB
/
runtime.tsx
File metadata and controls
230 lines (210 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"use client";
import {
useState,
useRef,
useCallback,
ReactNode,
createContext,
useContext,
useEffect,
} from "react";
import { SyntaxStatus, ReplOutput, ReplCommand } from "../repl";
import { Mutex, MutexInterface } from "async-mutex";
import { useEmbedContext } from "../embedContext";
import { RuntimeContext } from "../runtime";
const PyodideContext = createContext<RuntimeContext>(null!);
export function usePyodide(): RuntimeContext {
const context = useContext(PyodideContext);
if (!context) {
throw new Error("usePyodide must be used within a PyodideProvider");
}
return context;
}
type MessageToWorker =
| {
type: "init";
payload: { interruptBuffer: Uint8Array };
}
| {
type: "runPython";
payload: { code: string };
}
| {
type: "checkSyntax";
payload: { code: string };
}
| {
type: "runFile";
payload: { name: string; files: Record<string, string> };
};
type MessageFromWorker =
| { id: number; payload: unknown }
| { id: number; error: string };
type InitPayloadFromWorker = { success: boolean };
type RunPayloadFromWorker = {
output: ReplOutput[];
updatedFiles: [string, string][]; // Recordではない
};
type StatusPayloadFromWorker = { status: SyntaxStatus };
export function PyodideProvider({ children }: { children: ReactNode }) {
const workerRef = useRef<Worker | null>(null);
const [ready, setReady] = useState<boolean>(false);
const mutex = useRef<MutexInterface>(new Mutex());
const { files, writeFile } = useEmbedContext();
const messageCallbacks = useRef<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Map<number, [(payload: any) => void, (error: string) => void]>
>(new Map());
const nextMessageId = useRef<number>(0);
const interruptBuffer = useRef<Uint8Array | null>(null);
function postMessage<T>({ type, payload }: MessageToWorker) {
const id = nextMessageId.current++;
return new Promise<T>((resolve, reject) => {
messageCallbacks.current.set(id, [resolve, reject]);
workerRef.current?.postMessage({ id, type, payload });
});
}
useEffect(() => {
const worker = new Worker("/pyodide.worker.js");
workerRef.current = worker;
interruptBuffer.current = new Uint8Array(new SharedArrayBuffer(1));
worker.onmessage = (event) => {
const data = event.data as MessageFromWorker;
if (messageCallbacks.current.has(data.id)) {
const [resolve, reject] = messageCallbacks.current.get(data.id)!;
if ("error" in data) {
reject(data.error);
} else {
resolve(data.payload);
}
messageCallbacks.current.delete(data.id);
}
};
postMessage<InitPayloadFromWorker>({
type: "init",
payload: { interruptBuffer: interruptBuffer.current },
}).then(({ success }) => {
if (success) {
setReady(true);
}
});
return () => {
workerRef.current?.terminate();
};
}, []);
const interrupt = useCallback(() => {
if (interruptBuffer.current) {
interruptBuffer.current[0] = 2;
}
}, []);
const runCommand = useCallback(
async (code: string): Promise<ReplOutput[]> => {
if (!mutex.current.isLocked()) {
throw new Error(
"mutex of PyodideContext must be locked for runCommand"
);
}
if (!workerRef.current || !ready) {
return [{ type: "error", message: "Pyodide is not ready yet." }];
}
if (interruptBuffer.current) {
interruptBuffer.current[0] = 0;
}
const { output, updatedFiles } = await postMessage<RunPayloadFromWorker>({
type: "runPython",
payload: { code },
});
for (const [name, content] of updatedFiles) {
writeFile(name, content);
}
return output;
},
[ready, writeFile]
);
const checkSyntax = useCallback(
async (code: string): Promise<SyntaxStatus> => {
if (!workerRef.current || !ready) return "invalid";
const { status } = await mutex.current.runExclusive(() =>
postMessage<StatusPayloadFromWorker>({
type: "checkSyntax",
payload: { code },
})
);
return status;
},
[ready]
);
const runFiles = useCallback(
async (filenames: string[]): Promise<ReplOutput[]> => {
if (filenames.length !== 1) {
return [
{
type: "error",
message: "Python execution requires exactly one filename",
},
];
}
// Incorporate runFile logic directly
if (!workerRef.current || !ready) {
return [{ type: "error", message: "Pyodide is not ready yet." }];
}
if (interruptBuffer.current) {
interruptBuffer.current[0] = 0;
}
return mutex.current.runExclusive(async () => {
const { output, updatedFiles } =
await postMessage<RunPayloadFromWorker>({
type: "runFile",
payload: { name: filenames[0], files },
});
for (const [newName, content] of updatedFiles) {
writeFile(newName, content);
}
return output;
});
},
[files, ready, writeFile]
);
const splitReplExamples = useCallback((content: string): ReplCommand[] => {
const initCommands: { command: string; output: ReplOutput[] }[] = [];
for (const line of content.split("\n")) {
if (line.startsWith(">>> ")) {
// Remove the prompt from the command
initCommands.push({ command: line.slice(4), output: [] });
} else if (line.startsWith("... ")) {
if (initCommands.length > 0) {
initCommands[initCommands.length - 1].command += "\n" + line.slice(4);
}
} else {
// Lines without prompt are output from the previous command
if (initCommands.length > 0) {
initCommands[initCommands.length - 1].output.push({
type: "stdout",
message: line,
});
}
}
}
return initCommands;
}, []);
const getCommandlineStr = useCallback(
(filenames: string[]) => `python ${filenames[0]}`,
[]
);
return (
<PyodideContext.Provider
value={{
ready,
runCommand,
checkSyntax,
mutex: mutex.current,
runFiles,
interrupt,
splitReplExamples,
getCommandlineStr,
}}
>
{children}
</PyodideContext.Provider>
);
}