Sources/OrgApp/PythonBlocks.swift
317 lines · 15302 bytes
19 symbols in this file
1#if canImport(WebKit)
2import Foundation
3import OrgCore
4import WebKit
5
6/// python blocks in Pyodide (CPython compiled to WebAssembly), for the App Store builds, which
7/// can't start `python3`. Pyodide runs in a web worker of a hidden web view; the page and
8/// Pyodide's files come from the app through a URL scheme handler. Only the standard library is
9/// there: no packages, matplotlib included.
10///
11/// One worker runs every block. A block without a session gets new globals; a session keeps its
12/// own. Imported modules stay loaded until the worker goes: when a run is canceled or times
13/// out, since ending the worker is the only way to stop Python, and with the web view, after a
14/// minute without a run, or 15 minutes while a session exists.
15public enum PythonBlocks {
16 /// Pyodide's folder, which the App Store apps set from `OrgMathJax.pyodide`; python blocks
17 /// don't run here without it.
18 nonisolated(unsafe) public static var folder: URL?
19
20 static let scheme = "orgstar-python"
21 /// Where the block's value is written, in Pyodide's own file system.
22 static let resultPath = "/tmp/orgstar-result"
23
24 /// Runs `job` when it is a python block, in `directory` or its `:dir`; nil for other
25 /// languages. `:python` is ignored.
26 @MainActor
27 public static func run(_ job: BabelJob, directory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput? {
28 guard job.language == "python", let folder else { return nil }
29 let session: String
30 switch job.runner {
31 case .process: session = ""
32 case .session(let name, _, _): session = name
33 case .emacs: return nil
34 }
35 let dir = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
36 guard FileManager.default.fileExists(atPath: dir.path) else { throw Babel.Failure.message("No folder \(dir.path) for :dir.") }
37 if job.finish.params.contains("graphics") {
38 throw Babel.Failure.message(String(localized: "Python blocks can't draw graphics in this version of orgstar: matplotlib isn't included."))
39 }
40 let source = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultPath)
41 // One namespace per file folder and session name, as `python3` sessions are kept.
42 return try await evaluate(source, session: session.isEmpty ? "" : dir.path + "\u{1}" + session, folder: folder, timeout: timeout)
43 }
44
45 /// Unloads Pyodide, ending every session.
46 @MainActor
47 public static func stop() {
48 engine?.close()
49 engine = nil
50 }
51
52 @MainActor private static var engine: Engine?
53
54 @MainActor
55 static func evaluate(_ source: String, session: String, folder: URL, timeout: Duration) async throws -> BabelOutput {
56 let engine = self.engine ?? Engine(folder: folder)
57 self.engine = engine
58 engine.idle?.cancel()
59 defer { if self.engine === engine { engine.scheduleIdle() } }
60 if !session.isEmpty { engine.sessions.insert(session) }
61 let run = Run()
62 let reply: String
63 do {
64 reply = try await withTaskCancellationHandler {
65 try await withCheckedThrowingContinuation { continuation in
66 run.start(continuation, timeout: timeout)
67 Task { @MainActor in
68 do {
69 try await engine.loaded.value
70 let reply = try await engine.webView.callAsyncJavaScript(
71 "return await run({ source, session, result });",
72 arguments: ["source": source, "session": session, "result": resultPath],
73 contentWorld: .page
74 )
75 run.end(.success(reply as? String ?? ""))
76 } catch {
77 run.end(.failure(error))
78 }
79 }
80 }
81 } onCancel: {
82 run.end(.failure(CancellationError()))
83 }
84 } catch let error as NSError where error.domain == WKErrorDomain {
85 if self.engine === engine { stop() }
86 guard var message = error.userInfo["WKJavaScriptExceptionMessage"] as? String else {
87 throw Babel.Failure.message(String(localized: "Pyodide stopped: \(error.localizedDescription)"))
88 }
89 while message.hasPrefix("Error: ") { message.removeFirst("Error: ".count) }
90 throw Babel.Failure.message("Pyodide: " + message)
91 } catch let error where error is CancellationError || error is Babel.Failure {
92 // Canceled or timed out: the worker may still be running Python.
93 await engine.stopWorker()
94 throw error
95 } catch {
96 if self.engine === engine { stop() }
97 throw Babel.Failure.message(String(localized: "Pyodide stopped: \(error.localizedDescription)"))
98 }
99 guard let parts = try? JSONSerialization.jsonObject(with: Data(reply.utf8)) as? [Any], parts.count == 4,
100 let stdout = parts[0] as? String, let stderr = parts[1] as? String, let status = parts[2] as? Int
101 else { throw Babel.Failure.message("Pyodide returned nothing.") }
102 return BabelOutput(stdout: stdout, resultFile: parts[3] as? String, stderr: stderr, status: Int32(clamping: status))
103 }
104
105 /// A run, which ends once: with Python's reply, a cancel or the timeout.
106 final class Run: @unchecked Sendable {
107 private let lock = NSLock()
108 private var result: Result<String, Error>?
109 private var continuation: CheckedContinuation<String, Error>?
110 private var timer: Task<Void, Never>?
111
112 func start(_ continuation: CheckedContinuation<String, Error>, timeout: Duration) {
113 let ended: Result<String, Error>? = lock.withLock {
114 if result == nil { self.continuation = continuation }
115 return result
116 }
117 if let ended { return continuation.resume(with: ended) }
118 let timer = Task { [weak self] in
119 guard (try? await Task.sleep(for: timeout)) != nil else { return }
120 self?.end(.failure(Babel.Failure.message("The block took longer than \(timeout) and was stopped.")))
121 }
122 lock.withLock { self.timer = timer }
123 }
124
125 func end(_ outcome: Result<String, Error>) {
126 let (waiting, timer) = lock.withLock { () -> (CheckedContinuation<String, Error>?, Task<Void, Never>?) in
127 guard result == nil else { return (nil, nil) }
128 result = outcome
129 defer { continuation = nil; self.timer = nil }
130 return (continuation, self.timer)
131 }
132 timer?.cancel()
133 waiting?.resume(with: outcome)
134 }
135 }
136
137 /// The hidden web view, whose page starts the worker on the first run.
138 @MainActor
139 final class Engine: NSObject, WKNavigationDelegate {
140 let webView: WKWebView
141 var sessions: Set<String> = []
142 var idle: Task<Void, Never>?
143 private(set) var loaded: Task<Void, Error>!
144 private var loading: CheckedContinuation<Void, Error>?
145
146 init(folder: URL) {
147 let configuration = WKWebViewConfiguration()
148 configuration.setURLSchemeHandler(Files(folder: folder), forURLScheme: PythonBlocks.scheme)
149 configuration.websiteDataStore = .nonPersistent()
150 webView = WKWebView(frame: .zero, configuration: configuration)
151 super.init()
152 webView.navigationDelegate = self
153 loaded = Task {
154 try await withCheckedThrowingContinuation { continuation in
155 loading = continuation
156 webView.load(URLRequest(url: URL(string: "\(PythonBlocks.scheme)://pyodide/index.html")!))
157 }
158 }
159 }
160
161 /// Ends the worker, and with it every session.
162 func stopWorker() async {
163 sessions = []
164 _ = try? await webView.callAsyncJavaScript("stop();", contentWorld: .page)
165 }
166
167 func scheduleIdle() {
168 let wait: Duration = sessions.isEmpty ? .seconds(60) : .seconds(900)
169 idle = Task { [weak self] in
170 guard (try? await Task.sleep(for: wait)) != nil, let self else { return }
171 if PythonBlocks.engine === self { PythonBlocks.stop() }
172 }
173 }
174
175 func close() {
176 idle?.cancel()
177 webView.stopLoading()
178 webView.navigationDelegate = nil
179 finishLoading(.failure(CancellationError()))
180 }
181
182 private func finishLoading(_ result: Result<Void, Error>) {
183 loading?.resume(with: result)
184 loading = nil
185 }
186
187 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { finishLoading(.success(())) }
188 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { finishLoading(.failure(error)) }
189 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { finishLoading(.failure(error)) }
190 func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
191 if PythonBlocks.engine === self { PythonBlocks.stop() }
192 }
193 }
194
195 /// Serves the page, the worker and Pyodide's files, and nothing else.
196 @MainActor
197 final class Files: NSObject, WKURLSchemeHandler {
198 let folder: URL
199 static let types: [String: String] = [
200 "pyodide.mjs": "text/javascript", "pyodide.asm.mjs": "text/javascript", "pyodide.asm.wasm": "application/wasm",
201 "python_stdlib.zip": "application/zip", "pyodide-lock.json": "application/json",
202 ]
203
204 init(folder: URL) { self.folder = folder }
205
206 func webView(_ webView: WKWebView, start task: any WKURLSchemeTask) {
207 guard let url = task.request.url, url.host == "pyodide" else { return task.didFailWithError(URLError(.fileDoesNotExist)) }
208 let name = url.lastPathComponent
209 let file: (Data, String)?
210 switch name {
211 case "index.html": file = (Data(Self.page.utf8), "text/html")
212 case "worker.mjs": file = (Data(Self.worker.utf8), "text/javascript")
213 default: file = Self.types[name].flatMap { type in (try? Data(contentsOf: folder.appendingPathComponent(name))).map { ($0, type) } }
214 }
215 guard let (data, type) = file else { return task.didFailWithError(URLError(.fileDoesNotExist)) }
216 task.didReceive(HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1",
217 headerFields: ["Content-Type": type, "Content-Length": String(data.count)])!)
218 task.didReceive(data)
219 task.didFinish()
220 }
221
222 func webView(_ webView: WKWebView, stop task: any WKURLSchemeTask) {}
223
224 /// `run` sends a block to the worker, starting it when there is none; `stop` ends it.
225 static let page = """
226 <!doctype html><meta charset="utf-8"><script>
227 let worker = null, next = 0;
228 const pending = new Map();
229 function fail(message) {
230 for (const p of pending.values()) p.reject(new Error(message));
231 pending.clear();
232 }
233 function run(message) {
234 if (!worker) {
235 worker = new Worker("worker.mjs", { type: "module" });
236 worker.onmessage = e => {
237 const p = pending.get(e.data.id);
238 pending.delete(e.data.id);
239 if (e.data.error !== undefined) p.reject(new Error(e.data.error)); else p.resolve(e.data.reply);
240 };
241 worker.onerror = e => { worker = null; fail(e.message || "Pyodide didn't start."); };
242 }
243 return new Promise((resolve, reject) => {
244 const id = next++;
245 pending.set(id, { resolve, reject });
246 worker.postMessage({ id, ...message });
247 });
248 }
249 function stop() {
250 if (worker) worker.terminate();
251 worker = null;
252 fail("stopped");
253 }
254 </script>
255 """
256
257 static var worker: String {
258 let literal = String(data: try! JSONSerialization.data(withJSONObject: [setup]), encoding: .utf8)!.dropFirst().dropLast()
259 return """
260 import { loadPyodide } from "./pyodide.mjs";
261 const ready = loadPyodide({ indexURL: location.href.replace(/[^/]*$/, ""), stdout: () => {}, stderr: () => {} }).then(pyodide => {
262 pyodide.runPython(\(literal));
263 return pyodide.globals.get("__orgstar_run");
264 });
265 onmessage = async e => {
266 const { id, source, session, result } = e.data;
267 try {
268 const run = await ready;
269 postMessage({ id, reply: run(source, session, result) });
270 } catch (error) {
271 postMessage({ id, error: String(error && error.message || error) });
272 }
273 };
274 """
275 }
276
277 /// Runs a program as `python3` reads one on standard input, or in a session's
278 /// namespace, and returns its output, error output, exit status and value as JSON.
279 /// A traceback leaves out this function's frame; in a session an error doesn't change
280 /// the status, as the interactive interpreter goes on.
281 static let setup = """
282 import io, json, os, sys, traceback
283
284 __orgstar_sessions = {}
285
286 def __orgstar_run(source, session, result):
287 if session:
288 scope = __orgstar_sessions.setdefault(session, {'__name__': '__main__'})
289 else:
290 scope = {'__name__': '__main__'}
291 out, err = io.StringIO(), io.StringIO()
292 saved = sys.stdin, sys.stdout, sys.stderr
293 sys.stdin, sys.stdout, sys.stderr = io.StringIO(), out, err
294 status = 0
295 try:
296 exec(compile(source, '<org-babel>' if session else '<stdin>', 'exec'), scope)
297 except SystemExit as e:
298 if isinstance(e.code, int):
299 status = e.code
300 elif e.code is not None:
301 print(e.code, file=err)
302 status = 1
303 except BaseException as e:
304 traceback.print_exception(type(e), e, e.__traceback__.tb_next, file=err)
305 status = 0 if session else 1
306 finally:
307 sys.stdin, sys.stdout, sys.stderr = saved
308 value = None
309 if os.path.exists(result):
310 with open(result) as f:
311 value = f.read()
312 os.remove(result)
313 return json.dumps([out.getvalue(), err.getvalue(), status, value])
314 """
315 }
316}
317#endif