209 lines
9.1 KiB
Swift
209 lines
9.1 KiB
Swift
// The set of machines this one knows about: name, id and when each was last
|
|
// heard from, in the persisted `Name:Id,…` form. See docs/protocol.md §4.1.
|
|
//
|
|
// Ported from App/Class/MachinePool.cs, App/Class/MachinePoolHelpers.cs and
|
|
// App/Core/MachineStuff.cs AddToMachinePool (712-777).
|
|
|
|
import Foundation
|
|
|
|
/// One machine in the pool (`MachineInf`, `MachineInf.cs`).
|
|
public struct MachineInfo: Sendable, Equatable {
|
|
/// The machine's name, as it appears in a packet's `MachineName` field.
|
|
public var name: String
|
|
/// Its id, or `MachineID.none` while unknown.
|
|
public var id: UInt32
|
|
/// When it was last heard from, in the caller's time base (seconds).
|
|
public var lastSeen: TimeInterval
|
|
|
|
/// A pool entry.
|
|
public init(name: String, id: UInt32 = MachineID.none, lastSeen: TimeInterval = 0) {
|
|
self.name = name
|
|
self.id = id
|
|
self.lastSeen = lastSeen
|
|
}
|
|
}
|
|
|
|
/// Up to four machines, keyed by name, with best-effort updates.
|
|
///
|
|
/// A value type: the Windows class is a locked list because every thread
|
|
/// touches one global (`MachinePool.cs:40-49`); here the app owns one copy on
|
|
/// the queue that owns the sessions. Every mutation is "try to", as on Windows:
|
|
/// a full pool simply refuses to learn a fifth machine.
|
|
public struct MachinePool: Sendable, Equatable {
|
|
/// The most machines a matrix can hold (`MAX_MACHINE`, `MachineStuff.cs:30`).
|
|
public static let maxMachines = 4
|
|
|
|
/// How long a machine stays alive without a heartbeat: 1 500 000 ms
|
|
/// (`HEARTBEAT_TIMEOUT`, `MachineStuff.cs:32` — 25 minutes, despite the
|
|
/// comment there saying 30).
|
|
public static let heartbeatTimeout: TimeInterval = 1500
|
|
|
|
private var machines: [MachineInfo]
|
|
|
|
/// An empty pool.
|
|
public init() {
|
|
machines = []
|
|
}
|
|
|
|
/// The pool as persisted in the `MachinePool` setting.
|
|
///
|
|
/// `MachinePoolHelpers.cs:16-43`: comma-separated `Name:Id` fields, at least
|
|
/// four of them. A field that is not exactly `Name:Id` is skipped; an
|
|
/// unparsable id reads as `ID.NONE` and back-dates the entry past the
|
|
/// heartbeat timeout so it starts out dead. A string with fewer than four
|
|
/// fields throws on Windows and is caught into an empty pool
|
|
/// (`InitAndCleanup.cs:47-64`), which is what an empty pool here means.
|
|
public init(string: String, now: TimeInterval) {
|
|
machines = []
|
|
let fields = string.components(separatedBy: ",")
|
|
guard fields.count >= MachinePool.maxMachines else { return }
|
|
for field in fields.prefix(MachinePool.maxMachines) {
|
|
let parts = field.components(separatedBy: ":")
|
|
guard parts.count == 2 else { continue }
|
|
let name = parts[0].trimmingCharacters(in: .whitespaces) // InitAndCleanup.cs:53
|
|
guard !name.isEmpty else { continue } // MachinePool.cs:178-181
|
|
let id = UInt32(parts[1]) ?? MachineID.none
|
|
let seen = id == MachineID.none ? now - MachinePool.heartbeatTimeout : now
|
|
machines.append(MachineInfo(name: name, id: id, lastSeen: seen))
|
|
}
|
|
}
|
|
|
|
/// The `Name:Id,…` string for the `MachinePool` setting
|
|
/// (`MachinePool.cs:287-301`), padded with empty `:` fields to four.
|
|
public var string: String {
|
|
var text = machines.map { "\($0.name):\($0.id)" }.joined(separator: ",")
|
|
for _ in machines.count..<MachinePool.maxMachines {
|
|
text += ",:"
|
|
}
|
|
return text
|
|
}
|
|
|
|
/// Every machine, in insertion order (`ListAllMachines`, `MachinePool.cs:130`).
|
|
public var all: [MachineInfo] { machines }
|
|
|
|
/// The machine with this name, compared case-insensitively as Windows does
|
|
/// (`NamesAreEqual`, `MachinePool.cs:309-312`).
|
|
public func machine(named name: String) -> MachineInfo? {
|
|
machines.first { MachinePool.namesAreEqual($0.name, name) }
|
|
}
|
|
|
|
/// This machine's id, or `nil` when it is unknown (`ID.NONE` on Windows,
|
|
/// `ResolveID`, `MachinePool.cs:264-267`).
|
|
public func resolveID(name: String) -> UInt32? {
|
|
guard let found = machine(named: name), found.id != MachineID.none else { return nil }
|
|
return found.id
|
|
}
|
|
|
|
/// The first machine holding this id, as `NameFromID` does
|
|
/// (`MachineStuff.cs:1085-1096`); `nil` for `MachineID.none`.
|
|
public func name(for id: UInt32) -> String? {
|
|
guard id != MachineID.none else { return nil }
|
|
return machines.first { $0.id == id }?.name
|
|
}
|
|
|
|
/// Adds a machine, initially disconnected (`LearnMachine`,
|
|
/// `MachinePool.cs:195-243`). `false` if it is already known, if the name is
|
|
/// blank, or if the pool is full of machines the matrix still wants.
|
|
///
|
|
/// When the pool is full, the first machine that is *not* in `matrix` is
|
|
/// evicted to make room — that is the only thing the matrix is consulted
|
|
/// for here (`MachinePool.cs:217-238`, `MachineStuff.InMachineMatrix`).
|
|
public mutating func learn(_ name: String, keeping matrix: Matrix) -> Bool {
|
|
let trimmed = name.trimmingCharacters(in: .whitespaces)
|
|
guard !trimmed.isEmpty else { return false }
|
|
guard machine(named: name) == nil else { return false }
|
|
|
|
if machines.count >= MachinePool.maxMachines {
|
|
guard let slot = machines.firstIndex(where: { !matrix.contains($0.name) }) else {
|
|
return false
|
|
}
|
|
machines.remove(at: slot)
|
|
}
|
|
|
|
machines.append(MachineInfo(name: name))
|
|
return true
|
|
}
|
|
|
|
/// Points a known name at an id, and clears that id from any other machine
|
|
/// that was holding it (`TryUpdateMachineID`, `MachinePool.cs:52-89`).
|
|
///
|
|
/// `false` when no machine has that name. `updateTimestamp` marks the
|
|
/// machine alive; the duplicate-id reset uses the same flag, as Windows does.
|
|
@discardableResult
|
|
public mutating func updateID(
|
|
name: String, id: UInt32, updateTimestamp: Bool, now: TimeInterval
|
|
) -> Bool {
|
|
var updated = false
|
|
for i in machines.indices {
|
|
if MachinePool.namesAreEqual(name, machines[i].name) {
|
|
machines[i].id = id
|
|
if updateTimestamp { machines[i].lastSeen = now }
|
|
updated = true
|
|
} else if machines[i].id == id {
|
|
// Duplicate id? Reset the old machine's (MachinePool.cs:75-84).
|
|
machines[i].id = MachineID.none
|
|
if updateTimestamp { machines[i].lastSeen = now }
|
|
}
|
|
}
|
|
return updated
|
|
}
|
|
|
|
/// Back-dates a machine's timestamp so it reads as dead after a socket
|
|
/// error (`SetMachineDisconnected`, `MachinePool.cs:101-127`).
|
|
///
|
|
/// Returns whether it was already past the timeout, which is the Windows
|
|
/// signal that control should come back to the local machine.
|
|
@discardableResult
|
|
public mutating func setDisconnected(name: String, now: TimeInterval) -> Bool {
|
|
let floor = now - MachinePool.heartbeatTimeout + 10 // 10 000 ms, MachinePool.cs:118
|
|
var foundAndTimedOut = false
|
|
for i in machines.indices where MachinePool.namesAreEqual(name, machines[i].name) {
|
|
machines[i].lastSeen = min(machines[i].lastSeen, floor)
|
|
foundAndTimedOut = machines[i].lastSeen < floor - 5 // 5 000 ms, MachinePool.cs:121
|
|
}
|
|
return foundAndTimedOut
|
|
}
|
|
|
|
/// Back-dates every machine holding this id, used when a connection drops
|
|
/// (`RemoveDeadMachines(ID)`, `MachineStuff.cs:675-694`).
|
|
@discardableResult
|
|
public mutating func setDisconnected(id: UInt32, now: TimeInterval) -> Bool {
|
|
var changed = false
|
|
for info in machines where info.id == id {
|
|
if setDisconnected(name: info.name, now: now) { changed = true }
|
|
}
|
|
return changed
|
|
}
|
|
|
|
/// Whether a machine counts as alive: it has an id, and either its last
|
|
/// heartbeat is inside the timeout or a socket to it is up
|
|
/// (`IsAlive`, `MachinePool.cs:304-307`).
|
|
public func isAlive(_ info: MachineInfo, now: TimeInterval, connectedIDs: Set<UInt32>) -> Bool {
|
|
guard info.id != MachineID.none else { return false }
|
|
return now - info.lastSeen <= MachinePool.heartbeatTimeout || connectedIDs.contains(info.id)
|
|
}
|
|
|
|
/// Clears the id of every machine that the matrix no longer lists or that
|
|
/// has gone quiet, leaving the local machine alone
|
|
/// (`ResetIPAddressesForDeadMachines`, `MachinePool.cs:320-343`).
|
|
public mutating func resetDeadMachineIDs(
|
|
localName: String, matrix: Matrix, now: TimeInterval, connectedIDs: Set<UInt32>,
|
|
firstLoaded: Bool
|
|
) {
|
|
for i in machines.indices {
|
|
let info = machines[i]
|
|
if !info.name.isEmpty && info.name == localName { continue } // MachinePool.cs:326
|
|
let inMatrix = matrix.contains(info.name)
|
|
let drop =
|
|
firstLoaded
|
|
? !inMatrix
|
|
: !inMatrix || !isAlive(info, now: now, connectedIDs: connectedIDs)
|
|
if drop { machines[i].id = MachineID.none }
|
|
}
|
|
}
|
|
|
|
private static func namesAreEqual(_ a: String, _ b: String) -> Bool {
|
|
a.caseInsensitiveCompare(b) == .orderedSame
|
|
}
|
|
}
|