Sources/OrgPrograms/BabelSessions.swift

176 lines · 9037 bytes

9 symbols in this file
  1#if os(macOS)
  2import Foundation
  3import OrgCore
  4
  5/// Interpreters kept running for `:session`, one per file folder, interpreter and session name.
  6/// Each run sends the code, then a line that prints a marker; the output is what came before it.
  7public final class BabelSessions: @unchecked Sendable {
  8    public static let shared = BabelSessions()
  9
 10    private let lock = NSLock()
 11    private var sessions: [String: Session] = [:]
 12
 13    final class Session: @unchecked Sendable {
 14        let process = Process()
 15        private let input: FileHandle
 16        private let lock = NSLock()
 17        private var stdout = Data()
 18        private var stderr = Data()
 19        private var waiting: (marker: String, continuation: CheckedContinuation<(String, String, Int32), Error>)?
 20
 21        init(executable: String, arguments: [String], directory: URL) throws {
 22            let inPipe = Pipe(), outPipe = Pipe(), errPipe = Pipe()
 23            process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
 24            process.arguments = [executable] + arguments
 25            process.environment = BabelRunner.environment
 26            process.currentDirectoryURL = directory
 27            process.standardInput = inPipe
 28            process.standardOutput = outPipe
 29            process.standardError = errPipe
 30            input = inPipe.fileHandleForWriting
 31            outPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in self?.received(handle.availableData, error: false) }
 32            errPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in self?.received(handle.availableData, error: true) }
 33            process.terminationHandler = { [weak self] _ in self?.ended() }
 34            try process.run()
 35        }
 36
 37        /// Sends `code` and waits for `marker`, printed with the last status after it.
 38        func run(_ code: String, marker: String) async throws -> (stdout: String, stderr: String, status: Int32) {
 39            let result: (String, String, Int32) = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<(String, String, Int32), Error>) in
 40                lock.withLock {
 41                    stdout = Data()
 42                    stderr = Data()
 43                    waiting = (marker, continuation)
 44                }
 45                do {
 46                    try input.write(contentsOf: Data(code.utf8))
 47                } catch {
 48                    finish(.failure(error))
 49                }
 50            }
 51            return (result.0, result.1, result.2)
 52        }
 53
 54        private func received(_ data: Data, error: Bool) {
 55            guard !data.isEmpty else { return }
 56            var result: (String, String, Int32)?
 57            lock.withLock {
 58                if error { stderr.append(data) } else { stdout.append(data) }
 59                guard let marker = waiting?.marker, !error else { return }
 60                let text = String(decoding: stdout, as: UTF8.self)
 61                guard let found = text.range(of: marker + " ", options: .backwards),
 62                      let lineEnd = text[found.upperBound...].firstIndex(of: "\n") else { return }
 63                let status = Int32(text[found.upperBound..<lineEnd].trimmingCharacters(in: .whitespaces)) ?? 0
 64                result = (String(text[..<found.lowerBound]), String(decoding: stderr, as: UTF8.self), status)
 65            }
 66            if let result { finish(.success(result)) }
 67        }
 68
 69        private func ended() {
 70            finish(.failure(BabelRunner.Failure(description: "The session ended.")))
 71        }
 72
 73        private func finish(_ result: Result<(String, String, Int32), Error>) {
 74            let continuation = lock.withLock { () -> CheckedContinuation<(String, String, Int32), Error>? in
 75                defer { waiting = nil }
 76                return waiting?.continuation
 77            }
 78            continuation?.resume(with: result)
 79        }
 80
 81        func stop() { if process.isRunning { process.terminate() } }
 82    }
 83
 84    /// The Ruby and Node sessions' loops: each line names a program file, the marker and the
 85    /// file the value goes to (empty for output), and the program runs where earlier ones left
 86    /// their variables. The value is written as the non-session wrappers write it.
 87    static let rubyDriver = #"""
 88        $stdout.sync = true
 89        $stderr.sync = true
 90        __orgstar_binding = binding
 91        while (__orgstar_line = $stdin.gets)
 92          __orgstar_file, __orgstar_marker, __orgstar_result = __orgstar_line.chomp.split("\t", 3)
 93          begin
 94            __orgstar_value = eval(File.read(__orgstar_file), __orgstar_binding, "org-babel")
 95            if __orgstar_result && !__orgstar_result.empty?
 96              File.open(__orgstar_result, "w") { |f| f.write(__orgstar_value.class == String ? __orgstar_value : __orgstar_value.inspect) }
 97            end
 98          rescue Exception => __orgstar_error
 99            $stderr.puts __orgstar_error.full_message(highlight: false)
100          end
101          $stdout.print "\n#{__orgstar_marker} 0\n"
102        end
103        """#
104    static let nodeDriver = #"""
105        const vm = require('vm'), fs = require('fs'), util = require('util');
106        globalThis.require = require;
107        require('readline').createInterface({ input: process.stdin }).on('line', line => {
108          const [file, marker, result] = line.split('\t');
109          try {
110            const value = vm.runInThisContext(fs.readFileSync(file, 'utf8'), { filename: 'org-babel' });
111            if (result) fs.writeFileSync(result, util.inspect(value));
112          } catch (e) {
113            process.stderr.write(String(e && e.stack || e) + '\n');
114          }
115          process.stdout.write('\n' + marker + ' 0\n');
116        });
117        """#
118
119    /// Runs a session job: the session starts in `directory` the first time.
120    func run(_ job: BabelJob, name: String, executable: String, kind: BabelJob.SessionKind, directory: URL, resultFile: URL) async throws -> BabelOutput {
121        let key = [directory.path, executable, name].joined(separator: "\u{1}")
122        let session: Session = try lock.withLock {
123            if let existing = sessions[key], existing.process.isRunning { return existing }
124            let arguments: [String] = switch kind {
125            case .shell: []
126            case .python: ["-u", "-i", "-q"]
127            case .ruby: ["-e", Self.rubyDriver]
128            case .node: ["-e", Self.nodeDriver]
129            case .r: ["--slave", "--no-save", "--no-restore"]
130            }
131            let created = try Session(executable: executable, arguments: arguments, directory: directory)
132            sessions[key] = created
133            return created
134        }
135        let marker = "__orgstar_done_\(UUID().uuidString.replacingOccurrences(of: "-", with: ""))__"
136        let program = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
137        let file = resultFile.deletingLastPathComponent().appendingPathComponent("program")
138        let code: String
139        switch kind {
140        case .python:
141            try program.write(to: file, atomically: true, encoding: .utf8)
142            let path = file.path.replacingOccurrences(of: "'", with: "\\'")
143            code = "try:\n    exec(compile(open('\(path)').read(), '<org-babel>', 'exec'), globals())\nfinally:\n    print('\\n\(marker) 0', flush=True)\n\n"
144        case .ruby, .node:
145            try program.write(to: file, atomically: true, encoding: .utf8)
146            code = [file.path, marker, job.finish.output ? "" : resultFile.path].joined(separator: "\t") + "\n"
147        case .r:
148            try program.write(to: file, atomically: true, encoding: .utf8)
149            let path = file.path.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
150            code = "tryCatch(source(\"\(path)\", echo = FALSE, print.eval = TRUE), error = function(e) message(\"Error: \", conditionMessage(e)))\ncat(\"\\n\(marker) 0\\n\")\n"
151        case .shell:
152            code = program + (program.hasSuffix("\n") ? "" : "\n") + "printf '\\n%s %d\\n' \(marker) $?\n"
153        }
154        let (stdout, stderr, status) = try await withTaskCancellationHandler {
155            try await session.run(code, marker: marker)
156        } onCancel: {
157            session.stop()
158        }
159        // The marker starts on a line of its own; the newline before it isn't output.
160        var output = stdout
161        if output.hasSuffix("\n") { output.removeLast() }
162        // Interactive Python prompts go to standard error.
163        let problems = stderr.split(separator: "\n").filter { $0.range(of: "^(>>> |\\.\\.\\. )*$", options: .regularExpression) == nil }
164        return BabelOutput(stdout: output, resultFile: try? String(contentsOf: resultFile, encoding: .utf8),
165                           stderr: problems.joined(separator: "\n"), status: status)
166    }
167
168    /// Stops every session, as when the app quits.
169    public func stopAll() {
170        lock.withLock {
171            sessions.values.forEach { $0.stop() }
172            sessions = [:]
173        }
174    }
175}
176#endif