import Foundation #if DEBUG final class TestDeviceRestoreBackend: DeviceRestoreBackend, @unchecked Sendable { let stateDictionaries: [CFDictionary] let minTransitionIntervalMS: Int let maxTransitionIntervalMS: Int let simulatingFailure: Bool init( stateDictionaries: [CFDictionary]? = nil, simulatingFailure: Bool = false, minTransitionIntervalMS: Int = 5, maxTransitionIntervalMS: Int = 30 ) { self.stateDictionaries = stateDictionaries ?? (simulatingFailure ? DeviceRestoreState.testDictionariesError : DeviceRestoreState.testDictionaries) self.simulatingFailure = simulatingFailure self.minTransitionIntervalMS = minTransitionIntervalMS self.maxTransitionIntervalMS = maxTransitionIntervalMS } func restore(deviceECID: ECID, options: [String : AnyHashable], loggers: DeviceRestoreLoggers, progress: @escaping DeviceRestoreProgressClosure) throws { if simulatingFailure { try writeSimulatedFailureLogs(to: loggers) } Task { for dictionary in stateDictionaries { progress(dictionary) do { try await Task.sleep(for: .milliseconds(Int.random(in: minTransitionIntervalMS...maxTransitionIntervalMS))) } catch { break } } } } private func writeSimulatedFailureLogs(to loggers: DeviceRestoreLoggers) throws { let logs: [(RestoreLog?, String)] = [ (loggers.global, .simulatedGlobalRestoreFailureLog), (loggers.device, .simulatedDeviceRestoreFailureLog), (loggers.host, .simulatedHostRestoreFailureLog), (loggers.serial, .simulatedSerialRestoreFailureLog), ] for (log, contents) in logs { guard let log else { continue } try contents.write(to: log.fileURL, atomically: true, encoding: .utf8) } } } private extension String { static let testRestoreBackendLog: String = { guard let url = Bundle.virtualInstallation.url(forResource: "RestoreStates-VMA2", withExtension: "txt") else { fatalError("Missing RestoreStates-VMA2 file in VirtualInstallation bundle for test") } return try! String(contentsOf: url, encoding: .utf8) }() static let simulatedGlobalRestoreFailureLog = """ [12:00:00.000] (Info) - Starting simulated MobileDevice restore [12:00:01.000] (Default) - dumping CFError returned by restored: [12:00:01.000] (Default) - CFError domain:AMRestoreErrorDomain code:10 description:Simulated MobileDevice restore failure. This error was generated by VBSimulateInstallFailure. [12:00:01.000] (Default) - Restore failed (result = 10) """ static let simulatedDeviceRestoreFailureLog = """ restore-agent: Beginning simulated restore restore-agent: Reporting simulated terminal failure """ static let simulatedHostRestoreFailureLog = """ Host initiated a debug-only simulated MobileDevice restore. Host received AMRestoreErrorDomain error 10. """ static let simulatedSerialRestoreFailureLog = """ [serial] simulated restore boot [serial] simulated restore failure """ } extension DeviceRestoreState { nonisolated(unsafe) static var testDictionaries: [CFDictionary] = { let dictionaries = readRestoreStatesFromLog(String.testRestoreBackendLog) return dictionaries }() static let testStates: [DeviceRestoreState] = { return try! testDictionaries.map { try DeviceRestoreState(info: $0) } }() static let testStatesDistinctOperationsOnly: [DeviceRestoreState] = { return try! testDictionariesDistinctOperationsOnly.map { try DeviceRestoreState(info: $0) } }() static let testStatesError: [DeviceRestoreState] = { return try! testDictionariesError.map { try DeviceRestoreState(info: $0) } }() nonisolated(unsafe) static let testDictionariesDistinctOperationsOnly: [CFDictionary] = { var operations = Set() return testDictionaries.filter { dictionary in guard let state = try? DeviceRestoreState(info: dictionary), state.outcome == nil else { return false } return operations.insert(state.operation).inserted } }() nonisolated(unsafe) static let testDictionariesError: [CFDictionary] = { testDictionariesDistinctOperationsOnly + [DeviceRestoreState.testErrorDictionary] }() } // MARK: - Test Content private extension DeviceRestoreState { static let test1 = DeviceRestoreState( progress: 0.5, overallProgress: 0.34, operation: 200, operationName: AMRLocalizedCopyStringForAMROperation(200) as String, status: "Restoring", outcome: nil ) /// Intentionally omits the `Error` field so the terminal state exercises error extraction from `global.log`. nonisolated(unsafe) static let testErrorDictionary: CFDictionary = [ "DeviceState": 1, "Operation": RestoreOperation(0), "OverallProgress": 100, "Progress": 100, "Status": "Failed", ] as CFDictionary } /** Given a log string containing raw logged restore states from MobileDevice, constructs CFDictionary entries matching the restore states. Log format is expected to be the debug descriptions of CFDictionary as printed by RestoreBuddy when running, example: ``` PROGRESS: { DeviceState = 1; Operation = 208; OverallProgress = "-1"; Progress = "-1"; QueuePosition = 1; Status = Restoring; } PROGRESS: { DeviceState = 1; Operation = 2; OverallProgress = "-1"; Progress = 0; Status = Restoring; } ``` */ private func readRestoreStatesFromLog(_ log: String) -> [CFDictionary] { let regex = /\s{1,}?(.*)\s?\=\s?(.*);/ let valueCleanupRegex = /[=;\"]/ var output = [CFDictionary]() let entries = log.components(separatedBy: "}").filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } for entry in entries { var dict = [String: Any]() let matches = entry.matches(of: regex) for match in matches { let key = match.output.1.trimmingCharacters(in: .whitespacesAndNewlines) let value = match.output.2 .trimmingCharacters(in: .whitespacesAndNewlines) .replacing(valueCleanupRegex, with: { _ in "" }) switch key { case "DeviceState", "Progress", "OverallProgress", "QueuePosition": dict[key] = Int(value) case "Operation": dict[key] = RestoreOperation(value) default: dict[key] = value } } output.append(dict as CFDictionary) } return output } #endif