Sources/OrgApp/BabelSessions.swift
124 lines · 6346 bytes
1import Foundation
2import OrgCore
3
4/// Interpreters kept running for `:session`, one per file folder, interpreter and session name.
5/// Each run sends the code, then a line that prints a marker; the output is what came before it.
6public final class BabelSessions: @unchecked Sendable {
7 public static let shared = BabelSessions()
8
9 private let lock = NSLock()
10 private var sessions: [String: Session] = [:]
11
12 final class Session: @unchecked Sendable {
13 let process = Process()
14 private let input: FileHandle
15 private let lock = NSLock()
16 private var stdout = Data()
17 private var stderr = Data()
18 private var waiting: (marker: String, continuation: CheckedContinuation<(String, String, Int32), Error>)?
19
20 init(executable: String, arguments: [String], directory: URL) throws {
21 let inPipe = Pipe(), outPipe = Pipe(), errPipe = Pipe()
22 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
23 process.arguments = [executable] + arguments
24 process.environment = BabelRunner.environment
25 process.currentDirectoryURL = directory
26 process.standardInput = inPipe
27 process.standardOutput = outPipe
28 process.standardError = errPipe
29 input = inPipe.fileHandleForWriting
30 outPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in self?.received(handle.availableData, error: false) }
31 errPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in self?.received(handle.availableData, error: true) }
32 process.terminationHandler = { [weak self] _ in self?.ended() }
33 try process.run()
34 }
35
36 /// Sends `code` and waits for `marker`, printed with the last status after it.
37 func run(_ code: String, marker: String) async throws -> (stdout: String, stderr: String, status: Int32) {
38 let result: (String, String, Int32) = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<(String, String, Int32), Error>) in
39 lock.withLock {
40 stdout = Data()
41 stderr = Data()
42 waiting = (marker, continuation)
43 }
44 do {
45 try input.write(contentsOf: Data(code.utf8))
46 } catch {
47 finish(.failure(error))
48 }
49 }
50 return (result.0, result.1, result.2)
51 }
52
53 private func received(_ data: Data, error: Bool) {
54 guard !data.isEmpty else { return }
55 var result: (String, String, Int32)?
56 lock.withLock {
57 if error { stderr.append(data) } else { stdout.append(data) }
58 guard let marker = waiting?.marker, !error else { return }
59 let text = String(decoding: stdout, as: UTF8.self)
60 guard let found = text.range(of: marker + " ", options: .backwards),
61 let lineEnd = text[found.upperBound...].firstIndex(of: "\n") else { return }
62 let status = Int32(text[found.upperBound..<lineEnd].trimmingCharacters(in: .whitespaces)) ?? 0
63 result = (String(text[..<found.lowerBound]), String(decoding: stderr, as: UTF8.self), status)
64 }
65 if let result { finish(.success(result)) }
66 }
67
68 private func ended() {
69 finish(.failure(BabelRunner.Failure(description: "The session ended.")))
70 }
71
72 private func finish(_ result: Result<(String, String, Int32), Error>) {
73 let continuation = lock.withLock { () -> CheckedContinuation<(String, String, Int32), Error>? in
74 defer { waiting = nil }
75 return waiting?.continuation
76 }
77 continuation?.resume(with: result)
78 }
79
80 func stop() { if process.isRunning { process.terminate() } }
81 }
82
83 /// Runs a session job: the session starts in `directory` the first time.
84 func run(_ job: BabelJob, name: String, executable: String, python: Bool, directory: URL, resultFile: URL) async throws -> BabelOutput {
85 let key = [directory.path, executable, name].joined(separator: "\u{1}")
86 let session: Session = try lock.withLock {
87 if let existing = sessions[key], existing.process.isRunning { return existing }
88 let created = try Session(executable: executable, arguments: python ? ["-u", "-i", "-q"] : [], directory: directory)
89 sessions[key] = created
90 return created
91 }
92 let marker = "__orgstar_done_\(UUID().uuidString.replacingOccurrences(of: "-", with: ""))__"
93 let program = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
94 let code: String
95 if python {
96 let file = resultFile.deletingLastPathComponent().appendingPathComponent("program.py")
97 try program.write(to: file, atomically: true, encoding: .utf8)
98 let path = file.path.replacingOccurrences(of: "'", with: "\\'")
99 code = "try:\n exec(compile(open('\(path)').read(), '<org-babel>', 'exec'), globals())\nfinally:\n print('\\n\(marker) 0', flush=True)\n\n"
100 } else {
101 code = program + (program.hasSuffix("\n") ? "" : "\n") + "printf '\\n%s %d\\n' \(marker) $?\n"
102 }
103 let (stdout, stderr, status) = try await withTaskCancellationHandler {
104 try await session.run(code, marker: marker)
105 } onCancel: {
106 session.stop()
107 }
108 // The marker starts on a line of its own; the newline before it isn't output.
109 var output = stdout
110 if output.hasSuffix("\n") { output.removeLast() }
111 // Interactive Python prompts go to standard error.
112 let problems = stderr.split(separator: "\n").filter { $0.range(of: "^(>>> |\\.\\.\\. )*$", options: .regularExpression) == nil }
113 return BabelOutput(stdout: output, resultFile: try? String(contentsOf: resultFile, encoding: .utf8),
114 stderr: problems.joined(separator: "\n"), status: status)
115 }
116
117 /// Stops every session, as when the app quits.
118 public func stopAll() {
119 lock.withLock {
120 sessions.values.forEach { $0.stop() }
121 sessions = [:]
122 }
123 }
124}