Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 31 additions & 17 deletions Sources/SwiftFTR/PublicIPResolver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ func askWithinDeadline(_ resolver: any PublicIPResolver, _ request: PublicIPRequ
let deadline = request.deadline
// Nothing is started for a caller already cancelled.
try Task.checkCancellation()
let race = DeadlineRace(deadline: deadline)
let race = DeadlineRace<PublicIPObservation?>(hasPassed: { ContinuousClock.now >= deadline })
let arm = TestSeams.armPublicIPDeadline ?? sleepUntilDeadline
return try await withTaskCancellationHandler {
let outcome = try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
race.attach(continuation)
let ask = Task {
Expand All @@ -197,6 +197,8 @@ func askWithinDeadline(_ resolver: any PublicIPResolver, _ request: PublicIPRequ
} onCancel: {
race.commit(.cancellation)
}
guard case .completed(let answer) = outcome else { return nil }
return answer
}

/// The default wake-up for ``askWithinDeadline(_:_:)``: a task sleeping until `deadline`.
Expand All @@ -213,26 +215,36 @@ func askWithinDeadline(_ resolver: any PublicIPResolver, _ request: PublicIPRequ
return { timer.cancel() }
}

/// The race behind ``askWithinDeadline(_:_:)``: resumes one continuation with the first outcome
/// committed, from any thread and in any order, then runs the cleanup once.
final class DeadlineRace: @unchecked Sendable {
/// How a wait raced against a deadline ended, when it was not cancelled: with the work's value,
/// committed in time, or at the deadline. Distinct from any value, so a legitimate `nil` is not
/// mistaken for expiry.
enum DeadlineOutcome<Value: Sendable>: Sendable {
case completed(Value)
case expired
}

/// The race behind ``askWithinDeadline(_:_:)`` and ``raceDeadline(until:arm:_:)``: resumes one
/// continuation with the first outcome committed, from any thread and in any order, then runs the
/// cleanup once.
final class DeadlineRace<Value: Sendable>: @unchecked Sendable {
enum Event {
case answer(Result<PublicIPObservation?, Error>)
case answer(Result<Value, Error>)
case wake
case cancellation
}

private let deadline: ContinuousClock.Instant
private let hasPassed: @Sendable () -> Bool
private let lock = NSLock()
private var continuation: CheckedContinuation<PublicIPObservation?, Error>?
private var outcome: Result<PublicIPObservation?, Error>?
private var continuation: CheckedContinuation<DeadlineOutcome<Value>, Error>?
private var outcome: Result<DeadlineOutcome<Value>, Error>?
private var cleanup: (@Sendable () -> Void)?

init(deadline: ContinuousClock.Instant) {
self.deadline = deadline
/// - Parameter hasPassed: Whether the deadline has passed, read under the race's lock.
init(hasPassed: @escaping @Sendable () -> Bool) {
self.hasPassed = hasPassed
}

func attach(_ newContinuation: CheckedContinuation<PublicIPObservation?, Error>) {
func attach(_ newContinuation: CheckedContinuation<DeadlineOutcome<Value>, Error>) {
lock.lock()
guard let outcome else {
continuation = newContinuation
Expand All @@ -244,15 +256,17 @@ final class DeadlineRace: @unchecked Sendable {
}

/// The one place an outcome is committed: the first committed is delivered. The clock is read
/// here, under the lock, for every event but cancellation (see ``askWithinDeadline(_:_:)``).
/// here, under the lock, for every event but cancellation, so an answer committed once the
/// deadline has passed is expiry, however late the wake-up runs; a wake-up that runs early
/// commits nothing.
func commit(_ event: Event) {
lock.lock()
guard outcome == nil else {
lock.unlock()
return
}
let passed = ContinuousClock.now >= deadline
let decided: Result<PublicIPObservation?, Error>
let passed = hasPassed()
let decided: Result<DeadlineOutcome<Value>, Error>
switch event {
case .cancellation:
decided = .failure(CancellationError())
Expand All @@ -261,9 +275,9 @@ final class DeadlineRace: @unchecked Sendable {
lock.unlock()
return
}
decided = .success(nil)
decided = .success(.expired)
case .answer(let answer):
decided = passed ? .success(nil) : answer
decided = passed ? .success(.expired) : answer.map { .completed($0) }
}
outcome = decided
let waiting = continuation
Expand Down
91 changes: 90 additions & 1 deletion Sources/SwiftFTR/RDNSCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,12 @@ actor RDNSCache {
/// A lookup that belongs to work admitted before a reset (a batch's later addresses) asks
/// nothing after it: its addresses are the old network's, and their timeouts are not evidence
/// about the new one.
func lookup(_ ip: String, admittedBy admission: Admission) async -> String? {
///
/// Past `deadline`, only a cached answer is returned: nothing is joined or started. That check
/// and the start of a query are one step on this actor, so no query starts after the instant.
func lookup(_ ip: String, admittedBy admission: Admission, until deadline: TraceDeadline? = nil)
async -> String?
{
// A caller cancelled already, or admitted before a reset, starts nothing and joins nothing.
guard !Task.isCancelled, admission.withLock({ $0 }),
let question = ReverseDNSQuestion(address: ip)
Expand All @@ -175,6 +180,7 @@ actor RDNSCache {
if let entry = cache[key], now < entry.timestamp + ttl {
return entry.hostname
}
if deadline?.hasPassed == true { return nil }

let task: Task<String?, Never>
if let running = inFlight[key] {
Expand Down Expand Up @@ -269,6 +275,53 @@ actor RDNSCache {
}
}

/// ``batchLookup(_:)``, ending its wait at `deadline` with every answer its lookups gave before
/// the instant: `cut` is whether an address was still unanswered when the instant ended the wait.
/// The queries themselves run on to their own timeouts, and each outcome is applied once, as for
/// any other lookup. No query starts after the instant; past it, only cached answers are given.
/// A `nil` deadline is ``batchLookup(_:)`` exactly. A cancelled caller is released at once with
/// what it has.
func batchLookup(_ ips: [String], until deadline: TraceDeadline?) async -> (
names: [String: String], cut: Bool
) {
guard let deadline else { return (await batchLookup(ips), false) }
let asked = Set(ips)
let admission = admitting
if deadline.hasPassed {
var names: [String: String] = [:]
for ip in asked {
names[ip] = await lookup(ip, admittedBy: admission, until: deadline)
}
return (names, names.count < asked.count)
}
// The answers live here rather than in the cache, which may be too small or too short-lived to
// hold them, and only those that arrive before the instant are kept.
let answers = BatchAnswers(deadline, observe: TestSeams.observeBatchAnswer)
let outcome = try? await raceDeadline(until: deadline) {
await withTaskGroup(of: Void.self) { group in
for ip in asked {
group.addTask {
answers.record(ip, await self.lookup(ip, admittedBy: admission, until: deadline))
}
}
}
}
var (names, _) = answers.snapshot
guard case .expired? = outcome else { return (names, false) }
// The instant ends the wait for missing answers; it does not discard one the cache already
// holds, whether it was there before the batch or arrived as the wait ended.
for ip in asked where names[ip] == nil { names[ip] = cachedHostname(ip) }
return (names, names.count < asked.count)
}

/// The unexpired cached answer for `ip`, read without asking anything.
private func cachedHostname(_ ip: String) -> String? {
guard let key = ReverseDNSQuestion(address: ip)?.key, let entry = cache[key],
now() < entry.timestamp + ttl
else { return nil }
return entry.hostname
}

/// Forgets every query in flight and cancels it, so a request from before a reset neither
/// goes out afterwards nor keeps a lookup slot from the new network's questions. Admission is
/// closed first: cancelling a query frees its slot, and one still waiting must not take it.
Expand Down Expand Up @@ -342,3 +395,39 @@ actor RDNSCache {
}
}
}

/// The answers one ``RDNSCache/batchLookup(_:until:)`` has gathered: each address once, and only
/// while its deadline has not passed, so what the batch returns at the instant is what arrived
/// before it.
private final class BatchAnswers: @unchecked Sendable {
private let deadline: TraceDeadline
private let lock = NSLock()
private var names: [String: String] = [:]
private var answered = 0
private let observe: (@Sendable (String) -> Void)?

init(_ deadline: TraceDeadline, observe: (@Sendable (String) -> Void)?) {
self.deadline = deadline
self.observe = observe
}

/// Records that `ip`'s lookup returned `hostname` (`nil`: no name), unless the instant has passed.
func record(_ ip: String, _ hostname: String?) {
lock.lock()
guard !deadline.hasPassed else {
lock.unlock()
return
}
answered += 1
if let hostname { names[ip] = hostname }
lock.unlock()
observe?(ip)
}

/// The names gathered, and how many addresses' lookups returned.
var snapshot: (names: [String: String], answered: Int) {
lock.lock()
defer { lock.unlock() }
return (names, answered)
}
}
41 changes: 29 additions & 12 deletions Sources/SwiftFTR/Segmentation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -242,20 +242,37 @@ public struct TraceClassifier: Sendable {
publicIP: String?,
vpnContext: VPNContext? = nil
) async throws -> ClassifiedTrace {
// Gather IPs
let hopIPs: [String] = trace.hops.compactMap { $0.ipAddress }
var allIPs = Set(hopIPs)
let addresses = asnLookupAddresses(
trace: trace, destinationIP: destinationIP, publicIP: publicIP)
let asnMap = try? await resolver.resolve(ipv4Addrs: addresses, timeout: timeout)
return categorize(
trace: trace, destinationIP: destinationIP, asnMap: asnMap, publicIP: publicIP,
vpnContext: vpnContext)
}

/// The addresses ``classify(trace:destinationIP:resolver:timeout:publicIP:vpnContext:)`` asks
/// its resolver about: every hop, the destination and the public address, each once, and only
/// the globally routable ones. Private and other non-global addresses have no meaningful origin
/// ASN and must not reach a network-backed resolver.
func asnLookupAddresses(trace: TraceResult, destinationIP: String, publicIP: String?)
-> [String]
{
var allIPs = Set(trace.hops.compactMap { $0.ipAddress })
allIPs.insert(destinationIP)
let resolvedPublicIP: String? = publicIP
if let providedIP = publicIP {
allIPs.insert(providedIP)
}
if let publicIP { allIPs.insert(publicIP) }
return Array(Set(allIPs.compactMap(asnLookupAddress)))
}

// Lookup only globally routable addresses. Private and other non-global
// addresses do not have meaningful origin ASN data and must not reach a
// network-backed resolver.
let resolverIPs = Set(allIPs.compactMap(asnLookupAddress))
let asnMap = try? await resolver.resolve(ipv4Addrs: Array(resolverIPs), timeout: timeout)
/// Categories and interpolation for `trace` from the ASN answers in hand, with no lookup:
/// `asnMap` is `nil` when the lookup failed, which classifies as if no address had an answer.
func categorize(
trace: TraceResult,
destinationIP: String,
asnMap: [String: ASNInfo]?,
publicIP: String?,
vpnContext: VPNContext?
) -> ClassifiedTrace {
let resolvedPublicIP: String? = publicIP
let clientAS = resolvedPublicIP.flatMap { ip in
asnLookupAddress(for: ip).flatMap { asnMap?[$0] }
}
Expand Down
4 changes: 4 additions & 0 deletions Sources/SwiftFTR/TestSeams.swift
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,8 @@ enum TestSeams {
/// Awaited by a `traceStream` producer once its trace has ended, just before it unregisters and
/// finishes the stream, so a test can order `cancelActiveTraces()` before or after that step.
@TaskLocal static var beforeStreamCommit: (@Sendable () async -> Void)?

/// Called with each address whose answer a deadline-bounded reverse-DNS batch has kept, so a
/// test can pass the deadline only once an answer is in.
@TaskLocal static var observeBatchAnswer: (@Sendable (_ address: String) -> Void)?
}
93 changes: 93 additions & 0 deletions Sources/SwiftFTR/TraceDeadline.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import Foundation

/// One operation's overall deadline: an absolute instant on one clock, taken once and never reset.
///
/// A wait bounded by it is either handed the instant and holds it itself, or raced against it by
/// ``raceDeadline(until:arm:_:)``, never both, so an answer the work is entitled to give at the
/// instant cannot lose to a second timer aimed at the same one.
struct TraceDeadline: Sendable {
/// The instant, on `clock`.
let instant: TimeInterval
/// The clock `instant` is on, captured where the deadline was taken: queues and workers cannot
/// read the task-local test clock.
let clock: DiscoveryClock

init(instant: TimeInterval, clock: DiscoveryClock) {
self.instant = instant
self.clock = clock
}

/// `total` seconds from now on `clock`, or `nil` for positive infinity, which is no deadline.
static func after(_ total: TimeInterval, clock: DiscoveryClock = .current) -> TraceDeadline? {
guard total != .infinity else { return nil }
return TraceDeadline(instant: clock.now() + total, clock: clock)
}

/// Whether the instant has passed.
var hasPassed: Bool { clock.hasPassed(instant) }

/// The cutoff for a phase whose own cap is `cap` seconds from now: the earlier of the two, and
/// whether it is this deadline's instant. A tie is the instant, so the overall deadline decides.
func cutoff(cap: TimeInterval) -> (instant: TimeInterval, overallBinds: Bool) {
let own = clock.now() + cap
return own < instant ? (own, false) : (instant, true)
}

/// Starts the wake-up for this deadline: `wake` runs once the instant has passed, unless the
/// returned stop is called first. A stopped wake-up never runs `wake`.
func armWake(_ wake: @escaping @Sendable () -> Void) -> @Sendable () -> Void {
let clock = clock
let instant = instant
let timer = Task {
await clock.sleep(until: instant)
if !Task.isCancelled { wake() }
}
return { timer.cancel() }
}
}

/// Starts a wake-up that calls its argument at the deadline, and returns the function that stops it.
typealias ArmDeadlineWake = (_ wake: @escaping @Sendable () -> Void) -> @Sendable () -> Void

/// `work`'s value if it is committed before `deadline`, else ``DeadlineOutcome/expired``.
///
/// The work runs in a task of its own that this does not wait for, so work that never returns, or
/// ignores cancellation, cannot hold the caller; it is cancelled once the outcome is committed, and
/// the wake-up is stopped. A deadline already passed starts no work. A value or error committed
/// once the deadline has passed is expiry, decided under the race's lock. The calling task's
/// cancellation wins over expiry, but not over a value committed in time.
///
/// - Parameter arm: Starts the wake-up; by default `deadline`'s own (``TraceDeadline/armWake(_:)``).
/// - Throws: `CancellationError` when the calling task is cancelled, or the work's own error when
/// it throws in time.
func raceDeadline<Value: Sendable>(
until deadline: TraceDeadline,
arm: ArmDeadlineWake? = nil,
_ work: @escaping @Sendable () async throws -> Value
) async throws -> DeadlineOutcome<Value> {
try Task.checkCancellation()
guard !deadline.hasPassed else { return .expired }
let race = DeadlineRace<Value>(hasPassed: { deadline.hasPassed })
let armWake = arm ?? deadline.armWake
let outcome = try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
race.attach(continuation)
let task = Task {
do {
race.commit(.answer(.success(try await work())))
} catch {
race.commit(.answer(.failure(error)))
}
}
let stopWake = armWake { race.commit(.wake) }
race.onFinish {
task.cancel()
stopWake()
}
}
} onCancel: {
race.commit(.cancellation)
}
if case .expired = outcome, Task.isCancelled { throw CancellationError() }
return outcome
}
Loading
Loading