|
| 1 | +// Copyright 2026 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import Foundation |
| 16 | + |
| 17 | +struct TestServerOptions { |
| 18 | + let configPath: String |
| 19 | + let recordingDir: String |
| 20 | + let mode: String // "record" or "replay" |
| 21 | + let binaryPath: String |
| 22 | + let testServerSecrets: String? |
| 23 | +} |
| 24 | + |
| 25 | +class TestServer { |
| 26 | + private var process: Process? |
| 27 | + private let options: TestServerOptions |
| 28 | + |
| 29 | + init(options: TestServerOptions) { |
| 30 | + self.options = options |
| 31 | + } |
| 32 | + |
| 33 | + func start() async throws { |
| 34 | + let binaryURL: URL |
| 35 | + let fileManager = FileManager.default |
| 36 | + |
| 37 | + if fileManager.fileExists(atPath: options.binaryPath) { |
| 38 | + binaryURL = URL(fileURLWithPath: options.binaryPath) |
| 39 | + } else { |
| 40 | + let targetDir = URL(fileURLWithPath: options.binaryPath).deletingLastPathComponent() |
| 41 | + print("[TestServerSdk] Installing binary to \(targetDir.path)...") |
| 42 | + binaryURL = try await BinaryInstaller.ensureBinary(at: targetDir) |
| 43 | + } |
| 44 | + |
| 45 | + let arguments = [ |
| 46 | + options.mode, |
| 47 | + "--config", options.configPath, |
| 48 | + "--recording-dir", options.recordingDir |
| 49 | + ] |
| 50 | + |
| 51 | + let process = Process() |
| 52 | + process.executableURL = binaryURL |
| 53 | + process.arguments = arguments |
| 54 | + |
| 55 | + if let secrets = options.testServerSecrets { |
| 56 | + var env = ProcessInfo.processInfo.environment |
| 57 | + env["TEST_SERVER_SECRETS"] = secrets |
| 58 | + process.environment = env |
| 59 | + } |
| 60 | + |
| 61 | + let pipe = Pipe() |
| 62 | + process.standardOutput = pipe |
| 63 | + process.standardError = pipe |
| 64 | + |
| 65 | + pipe.fileHandleForReading.readabilityHandler = { handle in |
| 66 | + if let data = try? handle.read(upToCount: handle.availableData.count), |
| 67 | + let str = String(data: data, encoding: .utf8), !str.isEmpty { |
| 68 | + print("[TestServer] \(str)", terminator: "") |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + try process.run() |
| 73 | + self.process = process |
| 74 | + |
| 75 | + try await awaitHealthyTestServer() |
| 76 | + } |
| 77 | + |
| 78 | + func stop() { |
| 79 | + process?.terminate() |
| 80 | + process = nil |
| 81 | + } |
| 82 | + |
| 83 | + private func awaitHealthyTestServer() async throws { |
| 84 | + let healthURLString = try extractHealthURL(from: options.configPath) |
| 85 | + guard let url = URL(string: healthURLString) else { |
| 86 | + throw NSError(domain: "TestServer", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid health URL"]) |
| 87 | + } |
| 88 | + |
| 89 | + print("[TestServer] Waiting for healthy server at \(url)...") |
| 90 | + try await checkHealth(url: url) |
| 91 | + } |
| 92 | + |
| 93 | + private func extractHealthURL(from configPath: String) throws -> String { |
| 94 | + let content = try String(contentsOfFile: configPath, encoding: .utf8) |
| 95 | + let fullRange = NSRange(content.startIndex..., in: content) |
| 96 | + |
| 97 | + // Find the first 'source_port', looks for "source_port: 1234" |
| 98 | + let portPattern = #"source_port:\s*(\d+)"# |
| 99 | + let portRegex = try NSRegularExpression(pattern: portPattern) |
| 100 | + let portMatch = portRegex.firstMatch(in: content, range: fullRange) |
| 101 | + |
| 102 | + guard let portRange = portMatch?.range(at: 1), |
| 103 | + let portRangeInString = Range(portRange, in: content) else { |
| 104 | + print("[TestServer] Warning: Could not parse source_port from config. Defaulting to 9000.") |
| 105 | + return "http://localhost:9000/health" |
| 106 | + } |
| 107 | + let port = String(content[portRangeInString]) |
| 108 | + |
| 109 | + var healthPath = "/health" // Default |
| 110 | + let healthPattern = #"health:\s*([\w/]+)"# |
| 111 | + |
| 112 | + if let healthRegex = try? NSRegularExpression(pattern: healthPattern), |
| 113 | + let healthMatch = healthRegex.firstMatch(in: content, range: fullRange), |
| 114 | + let healthRangeInString = Range(healthMatch.range(at: 1), in: content) { |
| 115 | + healthPath = String(content[healthRangeInString]) |
| 116 | + } |
| 117 | + |
| 118 | + return "http://localhost:\(port)\(healthPath)" |
| 119 | + } |
| 120 | + |
| 121 | + |
| 122 | + |
| 123 | + private func checkHealth(url: URL) async throws { |
| 124 | + let session = URLSession.shared |
| 125 | + let maxRetries = 20 |
| 126 | + let delay = 0.5 |
| 127 | + |
| 128 | + for _ in 0..<maxRetries { |
| 129 | + if let process = process, !process.isRunning { |
| 130 | + throw NSError(domain: "TestServer", code: -1, |
| 131 | + userInfo: [NSLocalizedDescriptionKey: "Server process died unexpectedly during startup."]) |
| 132 | + } |
| 133 | + |
| 134 | + do { |
| 135 | + let (_, response) = try await session.data(from: url) |
| 136 | + if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 { |
| 137 | + return |
| 138 | + } |
| 139 | + } catch { /* retry */ } |
| 140 | + |
| 141 | + try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) |
| 142 | + } |
| 143 | + throw NSError(domain: "TestServer", code: -1, userInfo: [NSLocalizedDescriptionKey: "Health check failed"]) |
| 144 | + } |
| 145 | + |
| 146 | +} |
0 commit comments