import Foundation import Synchronization struct CommandOutput: Codable, Sendable { let status: Int32 let output: String let errors: String } enum RealityProcess { @concurrent static func run( _ executable: String, _ arguments: [String], directory: URL, environment: [String: String]? = nil, timeout: Duration = .seconds(15) ) async throws -> CommandOutput { let stem = directory.appendingPathComponent("command-\(UUID().uuidString)") let outputURL = stem.appendingPathExtension("stdout") let errorURL = stem.appendingPathExtension("stderr") guard FileManager.default.createFile(atPath: outputURL.path, contents: nil), FileManager.default.createFile(atPath: errorURL.path, contents: nil) else { throw RealityError("Cannot create command output files") } let output = try FileHandle(forWritingTo: outputURL) let errors = try FileHandle(forWritingTo: errorURL) let process = Process() process.executableURL = URL(fileURLWithPath: executable) process.arguments = arguments process.environment = environment process.currentDirectoryURL = directory process.standardOutput = output process.standardError = errors // A delayed waiter must not turn a late child exit into success. let exited = Mutex(nil) process.terminationHandler = { _ in exited.withLock { $0 = .now } } try process.run() let clock = ContinuousClock() let deadline = clock.now.advanced(by: timeout) while exited.withLock({ $0 == nil }), clock.now < deadline { try await Task.sleep(for: .milliseconds(25)) } if !completedBeforeDeadline(exited.withLock({ $0 }), deadline: deadline) { if process.isRunning { process.terminate() } let terminationDeadline = clock.now.advanced(by: .seconds(1)) while process.isRunning, clock.now < terminationDeadline { try await Task.sleep(for: .milliseconds(25)) } if process.isRunning { kill(process.processIdentifier, SIGKILL) } let killedDeadline = clock.now.advanced(by: .seconds(2)) while process.isRunning, clock.now < killedDeadline { try await Task.sleep(for: .milliseconds(25)) } guard !process.isRunning else { throw RealityError("Owned command process did not exit after SIGKILL") } try output.close() try errors.close() throw RealityError("Command timed out: \(executable) \(arguments.joined(separator: " "))") } try output.close() try errors.close() return CommandOutput( status: process.terminationStatus, output: String(decoding: try Data(contentsOf: outputURL), as: UTF8.self), errors: String(decoding: try Data(contentsOf: errorURL), as: UTF8.self)) } static func completedBeforeDeadline(_ exit: ContinuousClock.Instant?, deadline: ContinuousClock.Instant) -> Bool { exit.map { $0 <= deadline } == true } static func quoted(_ text: String) -> String { "\"" + text.replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") .replacingOccurrences(of: "\n", with: "\\n") + "\"" } }