|
| 1 | +// |
| 2 | +// PreConnectHookRunner.swift |
| 3 | +// TablePro |
| 4 | +// |
| 5 | + |
| 6 | +import Foundation |
| 7 | +import os |
| 8 | + |
| 9 | +/// Runs a shell script before establishing a database connection. |
| 10 | +/// Non-zero exit aborts the connection with an error. |
| 11 | +enum PreConnectHookRunner { |
| 12 | + private static let logger = Logger(subsystem: "com.TablePro", category: "PreConnectHookRunner") |
| 13 | + |
| 14 | + enum HookError: LocalizedError { |
| 15 | + case scriptFailed(exitCode: Int32, stderr: String) |
| 16 | + case timeout |
| 17 | + |
| 18 | + var errorDescription: String? { |
| 19 | + switch self { |
| 20 | + case let .scriptFailed(exitCode, stderr): |
| 21 | + let message = stderr.trimmingCharacters(in: .whitespacesAndNewlines) |
| 22 | + if message.isEmpty { |
| 23 | + return String(localized: "Pre-connect script failed with exit code \(exitCode)") |
| 24 | + } |
| 25 | + return String(localized: "Pre-connect script failed (exit \(exitCode)): \(message)") |
| 26 | + case .timeout: |
| 27 | + return String(localized: "Pre-connect script timed out after 10 seconds") |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + /// Run a shell script before connecting. Throws on non-zero exit or timeout. |
| 33 | + /// Executes on a background thread to avoid blocking the MainActor. |
| 34 | + static func run(script: String, environment: [String: String]? = nil) async throws { |
| 35 | + logger.info("Running pre-connect script") |
| 36 | + |
| 37 | + try await Task.detached { |
| 38 | + let process = Process() |
| 39 | + process.executableURL = URL(fileURLWithPath: "/bin/bash") |
| 40 | + process.arguments = ["-c", script] |
| 41 | + |
| 42 | + var env = ProcessInfo.processInfo.environment |
| 43 | + if let environment { |
| 44 | + for (key, value) in environment { |
| 45 | + env[key] = value |
| 46 | + } |
| 47 | + } |
| 48 | + process.environment = env |
| 49 | + |
| 50 | + let stderrPipe = Pipe() |
| 51 | + process.standardError = stderrPipe |
| 52 | + process.standardOutput = FileHandle.nullDevice |
| 53 | + |
| 54 | + // Drain stderr on a background thread to prevent pipe deadlock. |
| 55 | + // If the child writes >64KB to stderr without the parent reading, |
| 56 | + // the pipe buffer fills and the child blocks on write — deadlocking |
| 57 | + // with waitUntilExit() on the parent side. |
| 58 | + let stderrCollector = StderrCollector() |
| 59 | + stderrPipe.fileHandleForReading.readabilityHandler = { handle in |
| 60 | + let chunk = handle.availableData |
| 61 | + if !chunk.isEmpty { |
| 62 | + stderrCollector.append(chunk) |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + try process.run() |
| 67 | + |
| 68 | + // 10-second timeout on a separate detached task |
| 69 | + let timeoutTask = Task.detached { |
| 70 | + try await Task.sleep(nanoseconds: 10_000_000_000) |
| 71 | + if process.isRunning { |
| 72 | + process.terminate() |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + process.waitUntilExit() |
| 77 | + timeoutTask.cancel() |
| 78 | + |
| 79 | + stderrPipe.fileHandleForReading.readabilityHandler = nil |
| 80 | + let stderr = stderrCollector.result |
| 81 | + |
| 82 | + if process.terminationReason == .uncaughtSignal { |
| 83 | + throw HookError.timeout |
| 84 | + } |
| 85 | + |
| 86 | + if process.terminationStatus != 0 { |
| 87 | + throw HookError.scriptFailed(exitCode: process.terminationStatus, stderr: stderr) |
| 88 | + } |
| 89 | + }.value |
| 90 | + |
| 91 | + logger.info("Pre-connect script completed successfully") |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +/// Thread-safe collector for stderr output from a child process. |
| 96 | +private final class StderrCollector: @unchecked Sendable { |
| 97 | + private let lock = NSLock() |
| 98 | + private var data = Data() |
| 99 | + |
| 100 | + func append(_ chunk: Data) { |
| 101 | + lock.lock() |
| 102 | + data.append(chunk) |
| 103 | + lock.unlock() |
| 104 | + } |
| 105 | + |
| 106 | + var result: String { |
| 107 | + lock.lock() |
| 108 | + defer { lock.unlock() } |
| 109 | + return String(data: data, encoding: .utf8) ?? "" |
| 110 | + } |
| 111 | +} |
0 commit comments