-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathEmulator.swift
More file actions
73 lines (59 loc) · 1.62 KB
/
Emulator.swift
File metadata and controls
73 lines (59 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// Emulator.swift
// AndroidDeviceKit
//
// Created by Jared Hendry on 2020-09-10.
// Copyright © 2020 Shopify. All rights reserved.
//
import Foundation
import Network
import ShellKit
struct Emulator {
private static let portSequence = PortSequence()
/// - returns: The serial of the device that was booted.
static func start(name: String) async throws -> String {
let output = try await portSequence.withAvailablePort { reportConsolePort in
try run(
command: .emulator(.startDevice(name: name, reportConsolePort: reportConsolePort)),
log: log
)
}
guard let consolePort = Int(output.trimmingCharacters(in: .whitespacesAndNewlines)) else {
throw EmulatorError.failedToReadPort
}
return "emulator-\(consolePort)"
}
}
enum EmulatorError: Error {
case failedToReadPort
case noAvailablePort
}
private actor PortSequence {
private let startPort: UInt16 = 49152
private let maxAttempts = 20
private var inFlight: Set<UInt16> = []
func withAvailablePort<T>(_ body: (Int) async throws -> T) async throws -> T {
guard let port = reservePort() else {
throw EmulatorError.noAvailablePort
}
defer { inFlight.remove(port) }
return try await body(Int(port))
}
private func reservePort() -> UInt16? {
for attempt in 0..<maxAttempts {
let port = startPort + UInt16(attempt)
if !inFlight.contains(port), isAvailable(port) {
inFlight.insert(port)
return port
}
}
return nil
}
private func isAvailable(_ port: UInt16) -> Bool {
guard let listener = try? NWListener(using: .tcp, on: NWEndpoint.Port(rawValue: port)!) else {
return false
}
listener.cancel()
return true
}
}