Skip to content
Merged
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
15 changes: 13 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ Unreleased

### New public API

- **`SwiftFTRConfig.resolutionTimeout`** (default `SwiftFTRConfig.defaultResolutionTimeout`,
20 s; decision 7): how long `trace`, `traceClassified`, `traceStream`, `ping` and
`discoverPaths` wait for their destination to resolve. It must be finite and in (0, Int32.max]
seconds, as `PingConfig.timeout` must; any other value throws `invalidConfiguration` before
anything resolves, from `ping` too. The option comes as a further initializer, so existing
calls and stated function types keep their meaning.
- **`PublicIPResolver`**, and `SwiftFTRConfig.publicIPResolver` with a
`PublicIPResolverStrategy`: `.library` (the default: STUN only, see Behavior changes),
`.disabled` (send nothing) or `.custom(_:)` (the caller's resolver). A resolver answers a `PublicIPRequest` (one
Expand All @@ -48,10 +54,15 @@ Unreleased

### Behavior changes

- **`discoverPaths` resolves its target once, before its public-IP question,** and every flow
probes that one address, keeping the caller's name as its destination. A round-robin name could
give flows different addresses before. A name that does not resolve now fails the run before
any public-IP question (no STUN traffic, no caller resolver asked), and
`NetworkTopology.discoveryDuration` includes the lookup.
- **Forward resolution no longer runs on the tracer actor or a cooperative thread.** `trace`,
`traceClassified`, `traceStream`, `ping`, `tcpProbe`, `udpProbe` and multipath flows resolve
their destination in an executor slot. The wait ends at a deadline: 20 s for traces and ping,
`config.timeout` from entry for the probes, whose connect or receive window is what resolution
their destination in an executor slot. The wait ends at a deadline: `resolutionTimeout` (20 s by
default) for traces and ping, `config.timeout` from entry for the probes, whose connect or receive window is what resolution
leaves. A trace or ping whose lookup times out throws `resolutionFailed` with details
`"timed out"`; a probe reports its usual resolution failure and opens no socket. Cancelling the
task, `cancelActiveTraces()` or `networkChanged()` during resolution returns at once, and a
Expand Down
7 changes: 7 additions & 0 deletions Sources/SwiftFTR/ConfigurationValidation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ extension SwiftFTRConfig {
if case .hybrid(_, let fallbackTimeout) = asnResolverStrategy {
try validatePositiveTimeout(fallbackTimeout, named: "ASN fallbackTimeout")
}
try validateResolutionTimeout()
}

/// Validates ``resolutionTimeout`` alone: for `ping`, which uses only that field of its tracer's
/// configuration.
func validateResolutionTimeout() throws {
try validatePositiveTimeout(resolutionTimeout, named: "resolutionTimeout")
}

/// A safe cache TTL used while retaining invalid public input for operation-time validation.
Expand Down
3 changes: 0 additions & 3 deletions Sources/SwiftFTR/Hostname.swift
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,6 @@ internal func blockingResolution(
host: host, details: "No matching address for preferred family")
}

/// How long a trace or ping waits for its destination to resolve (docs/BLOCKING-IO.md, decision 7).
let forwardResolutionLimit: TimeInterval = 20

/// Whether `host` is numeric to the system resolver, so its lookup takes the Literal Lane. Wider
/// than a literal the library parses: the resolver also takes IPv4 shorthand ("127.1"), which
/// `inet_aton` recognizes and `inet_pton` does not. `inet_aton` stops at whitespace and accepts
Expand Down
35 changes: 23 additions & 12 deletions Sources/SwiftFTR/Multipath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ extension SwiftFTRConfig {
sourceIP: sourceIP,
asnResolverStrategy: asnResolverStrategy,
preferredFamily: .v4,
publicIPResolver: publicIPResolver
publicIPResolver: publicIPResolver,
resolutionTimeout: resolutionTimeout
)
}
}
Expand Down Expand Up @@ -641,21 +642,28 @@ extension SwiftFTR {

let outcome: Result<NetworkTopology, Error>
do {
// One question for the whole run, IPv4 by contract, before the first batch. Its answer, or
// its absence, is handed to every flow, so no flow asks again. It is asked on its own,
// before the race below, because both wait on the handle's one cancellation slot.
// One resolution and one question for the whole run, IPv4 by contract, before the first
// batch, each handed to every flow, so no flow resolves or asks again. Both run on their
// own, before the race below, because each waits on the handle's one cancellation slot. A
// name that does not resolve ends the run before the question is asked.
try validateBeforeQuestion(target: target)
let asked = monotonicNow()
let started = monotonicNow()
let clock = DiscoveryClock.current
let destination = try await resolveDestination(
target, prefer: .v4, until: clock.now() + swiftConfig.resolutionTimeout, clock: clock,
handle: handle)
try handle.checkCancellation()
let publicIP = try await publicIPObservation(for: .v4, handle: handle)
let worker = MultipathWorkerSpawner(
baseConfig: swiftConfig,
rdnsCache: self.rdnsCache,
asnResolver: self.asnResolver,
destination: destination,
publicIP: publicIP
)
let discovery = MultipathDiscovery(
worker: worker, config: swiftConfig, publicIP: publicIP,
elapsedBefore: monotonicNow() - asked)
elapsedBefore: monotonicNow() - started)
outcome = .success(
try await withThrowingTaskGroup(of: NetworkTopology?.self) { group in
group.addTask {
Expand Down Expand Up @@ -689,9 +697,9 @@ extension SwiftFTR {
}

/// Rejects, before the run's public-IP question, every input a flow would reject only after it:
/// the interface, the source address (its form, its family, and whether this host can bind it),
/// and a numeric destination of the wrong family. So an unusable binding never sends discovery
/// traffic. A destination name that does not resolve is found only by the flows.
/// the interface and the source address (its form, its family, and whether this host can bind
/// it). So an unusable binding never sends discovery traffic. The destination, a literal of the
/// wrong family included, is checked by the run's one resolution, which follows.
private func validateBeforeQuestion(target: String) throws {
if let name = config.interface { _ = try validateInterface(name) }
if let source = config.sourceIP {
Expand All @@ -703,15 +711,15 @@ extension SwiftFTR {
throw TracerouteError.sourceIPBindFailed(sourceIP: source, errno: errno, details: message)
}
}
// A literal, and a NUL, is decided without a resolver under the forced family.
_ = try inlineResolution(host: target, prefer: .v4)
}

/// Runs flow workers that reuse caches without escaping the caller's task group.
struct MultipathWorkerSpawner: MultipathFlowRunning {
let baseConfig: SwiftFTRConfig
let rdnsCache: RDNSCache
let asnResolver: ASNResolver
/// The parent's one resolution of the target, which every flow probes; a flow never resolves.
let destination: ResolvedHost
/// The parent's public address, or `nil` when it has none; a flow never asks for one.
let publicIP: PublicIPObservation?

Expand All @@ -726,6 +734,7 @@ extension SwiftFTR {
let trace = try await worker.performClassifiedTraceWithFlowID(
to: target,
flowIdentifier: flowID.icmpID,
destination: destination,
publicIP: publicIP
)
try Task.checkCancellation()
Expand All @@ -752,6 +761,7 @@ extension SwiftFTR {
fileprivate func performClassifiedTraceWithFlowID(
to host: String,
flowIdentifier: UInt16,
destination: ResolvedHost,
publicIP observation: PublicIPObservation?
) async throws -> ClassifiedTrace {
try config.validateForOperation()
Expand All @@ -771,7 +781,8 @@ extension SwiftFTR {

// Perform base trace with flow ID
let tr = try await withTaskCancellationHandler {
try await performTrace(to: host, handle: handle, flowIdentifier: flowIdentifier)
try await performTrace(
to: host, resolved: destination, handle: handle, flowIdentifier: flowIdentifier)
} onCancel: {
handle.cancel(for: .callerTask)
}
Expand Down
3 changes: 2 additions & 1 deletion Sources/SwiftFTR/Ping.swift
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,14 @@ struct PingExecutor: Sendable {
/// instance never share identifier/sequence space (downstream contract).
func ping(to target: String, config: PingConfig) async throws -> PingResult {
try config.validateForOperation()
try swiftFTRConfig.validateResolutionTimeout()
try Task.checkCancellation()

// 1. Resolve target, honoring PreferredFamily, off this thread, within the tracer's
// forward-resolution budget; `config.timeout` is the reply window and is not spent here.
let clock = DiscoveryClock.current
let resolved = try await resolveDestination(
target, prefer: config.preferredFamily, until: clock.now() + forwardResolutionLimit,
target, prefer: config.preferredFamily, until: clock.now() + swiftFTRConfig.resolutionTimeout,
clock: clock)
try Task.checkCancellation()

Expand Down
22 changes: 21 additions & 1 deletion Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,8 @@ let asns = try await resolver.resolve(ipv4Addrs: ips, timeout: 0.1)
**What changed.** A destination name is resolved in an executor slot rather than on the tracer
actor (`trace`, `traceClassified`, `traceStream`, multipath flows) or a cooperative thread
(`ping`, `tcpProbe`, `udpProbe`). The wait ends 20 s after a trace or ping starts resolving, and
`config.timeout` after a probe starts; a probe's connect or receive window is what resolution
`config.timeout` after a probe starts (traces and ping wait ``SwiftFTR/SwiftFTRConfig/resolutionTimeout``,
20 s by default); a probe's connect or receive window is what resolution
left. Forced-family literals, IPv4 loopback and unscoped IPv6 literals are answered without a
lookup; other `.auto` literals use a slot of their own, so stalled name lookups cannot delay them.
Which address is probed does not change.
Expand All @@ -774,3 +775,22 @@ Which address is probed does not change.
**What to change.** Nothing. A probe that resolves a slow name and needs its full connect or
receive window raises `timeout` by the time resolution takes.

## A multipath run resolves its target once, before its public-IP question

**What changed.** `discoverPaths` resolves its target once, as IPv4, within
``SwiftFTR/SwiftFTRConfig/resolutionTimeout``, before it asks for the public address, and gives
that address to every flow. In 0.18 each flow resolved the name for itself.

**What a caller sees.**

- Every path in a ``NetworkTopology`` was probed at one address. A name with rotating records could
give flows different addresses in 0.18, so paths to different hosts were compared as one
destination's. Each path's `destinationHost` is still the name the caller passed.
- A name that does not resolve fails the run with `TracerouteError.resolutionFailed` before the
public-IP question: no STUN traffic is sent, a custom ``SwiftFTR/PublicIPResolver`` is not asked,
and nothing is cached.
- ``NetworkTopology/discoveryDuration`` includes the lookup.

**What to change.** Nothing, unless code relied on flows reaching different addresses of a
rotating name: run `discoverPaths` once per address instead, passing each as a literal.

5 changes: 3 additions & 2 deletions Sources/SwiftFTR/SwiftFTR.docc/Tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ for hop in classified.hops {
address gets at most one second) and
``SwiftFTR/SwiftFTRConfig/publicIPDiscoveryTimeout`` bounds the one public-IP question a
classified trace asks, after its probes. Hops whose lookups run out of time report numerically, and
classification proceeds without a public address. Resolving a hostname destination is not
bounded by either setting.
classification proceeds without a public address. Resolving a hostname destination is
bounded by ``SwiftFTR/SwiftFTRConfig/resolutionTimeout`` (20 s by default), which a
`discoverPaths` run spends once for all its flows.
- Set ``SwiftFTR/SwiftFTRConfig/publicIP`` to use a known public address and bypass discovery for
classified-trace enrichment of its address family, or
``SwiftFTR/SwiftFTRConfig/publicIPResolver`` to answer the question with your own
Expand Down
62 changes: 58 additions & 4 deletions Sources/SwiftFTR/Traceroute.swift
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ public struct SwiftFTRConfig: Sendable {
/// resolvers.
public static let defaultRDNSLookupTimeout: TimeInterval = 5.0

/// Default ``resolutionTimeout``, in seconds: how long the system resolver itself waits has not
/// been measured, so this is a judgement (docs/BLOCKING-IO.md, decision 7).
public static let defaultResolutionTimeout: TimeInterval = 20

/// Maximum TTL/hops to probe (default: 40)
public let maxHops: Int
/// Maximum wait time per probe in milliseconds (default: 1000ms)
Expand Down Expand Up @@ -342,6 +346,15 @@ public struct SwiftFTRConfig: Sendable {
/// ``PublicIPResolverStrategy/library``.
public let publicIPResolver: PublicIPResolverStrategy

/// How long `trace`, `traceClassified`, `traceStream`, `ping` and `discoverPaths` wait for their
/// destination to resolve, in seconds (default: ``defaultResolutionTimeout``). The lookup runs
/// in an executor slot; when the wait ends first the operation throws
/// ``TracerouteError/resolutionFailed(host:details:)`` with details `"timed out"`, and a
/// `getaddrinfo` already running finishes on its own. Must be finite and in (0, `Int32.max`]:
/// any other value makes those operations throw ``TracerouteError/invalidConfiguration(reason:)``
/// before they resolve anything. `tcpProbe` and `udpProbe` spend their own `timeout` instead.
public let resolutionTimeout: TimeInterval

/// Creates a new SwiftFTR configuration.
///
/// - Parameters:
Expand Down Expand Up @@ -385,7 +398,8 @@ public struct SwiftFTRConfig: Sendable {
rdnsCacheSize: rdnsCacheSize, rdnsLookupTimeout: rdnsLookupTimeout,
publicIPDiscoveryTimeout: publicIPDiscoveryTimeout, interface: interface,
sourceIP: sourceIP, asnResolverStrategy: asnResolverStrategy,
preferredFamily: preferredFamily, publicIPResolver: .library)
preferredFamily: preferredFamily, publicIPResolver: .library,
resolutionTimeout: SwiftFTRConfig.defaultResolutionTimeout)
}

/// Creates a new SwiftFTR configuration: the parameters of the initializer above, plus
Expand All @@ -407,6 +421,37 @@ public struct SwiftFTRConfig: Sendable {
asnResolverStrategy: ASNResolverStrategy = .hybrid(.embedded),
preferredFamily: PreferredFamily = .auto,
publicIPResolver: PublicIPResolverStrategy = .library
) {
self.init(
maxHops: maxHops, maxWaitMs: maxWaitMs, payloadSize: payloadSize, publicIP: publicIP,
enableLogging: enableLogging, noReverseDNS: noReverseDNS, rdnsCacheTTL: rdnsCacheTTL,
rdnsCacheSize: rdnsCacheSize, rdnsLookupTimeout: rdnsLookupTimeout,
publicIPDiscoveryTimeout: publicIPDiscoveryTimeout, interface: interface,
sourceIP: sourceIP, asnResolverStrategy: asnResolverStrategy,
preferredFamily: preferredFamily, publicIPResolver: publicIPResolver,
resolutionTimeout: SwiftFTRConfig.defaultResolutionTimeout)
}

/// Creates a new SwiftFTR configuration: the parameters of the initializer above, plus
/// `resolutionTimeout`, how long an operation waits for its destination to resolve (default:
/// ``defaultResolutionTimeout``).
public init(
maxHops: Int = 40,
maxWaitMs: Int = 1000,
payloadSize: Int = 56,
publicIP: String? = nil,
enableLogging: Bool = false,
noReverseDNS: Bool = false,
rdnsCacheTTL: TimeInterval? = nil,
rdnsCacheSize: Int? = nil,
rdnsLookupTimeout: TimeInterval? = nil,
publicIPDiscoveryTimeout: TimeInterval? = nil,
interface: String? = nil,
sourceIP: String? = nil,
asnResolverStrategy: ASNResolverStrategy = .hybrid(.embedded),
preferredFamily: PreferredFamily = .auto,
publicIPResolver: PublicIPResolverStrategy = .library,
resolutionTimeout: TimeInterval = SwiftFTRConfig.defaultResolutionTimeout
) {
self.maxHops = maxHops
self.maxWaitMs = maxWaitMs
Expand All @@ -423,6 +468,7 @@ public struct SwiftFTRConfig: Sendable {
self.asnResolverStrategy = asnResolverStrategy
self.preferredFamily = preferredFamily
self.publicIPResolver = publicIPResolver
self.resolutionTimeout = resolutionTimeout
}
}

Expand Down Expand Up @@ -816,13 +862,13 @@ public actor SwiftFTR {
}

/// `host` resolved for this tracer's preferred family, waiting at most
/// ``forwardResolutionLimit`` and no longer than `handle` and the calling task allow.
/// ``SwiftFTRConfig/resolutionTimeout`` and no longer than `handle` and the calling task allow.
private func resolveTraceDestination(_ host: String, handle: TraceHandle) async throws
-> ResolvedHost
{
let clock = DiscoveryClock.current
return try await resolveDestination(
host, prefer: config.preferredFamily, until: clock.now() + forwardResolutionLimit,
host, prefer: config.preferredFamily, until: clock.now() + config.resolutionTimeout,
clock: clock, handle: handle)
}

Expand All @@ -848,8 +894,11 @@ public actor SwiftFTR {
}

// Internal implementation of trace with cancellation support
/// `resolved`, when given, is the destination already resolved for `host` (a multipath flow's,
/// from its parent); `host` is still what the result reports.
internal func performTrace(
to host: String,
resolved given: ResolvedHost? = nil,
handle: TraceHandle,
flowIdentifier: UInt16? = nil,
maxHopsOverride: Int? = nil
Expand Down Expand Up @@ -881,7 +930,12 @@ public actor SwiftFTR {
}
// Resolve host (dual-stack, honors config.preferredFamily), off this actor, then hand off to
// probing only if nothing has cancelled the trace meanwhile.
let resolved = try await resolveTraceDestination(host, handle: handle)
let resolved: ResolvedHost
if let given {
resolved = given
} else {
resolved = try await resolveTraceDestination(host, handle: handle)
}
try handle.checkCancellation()
if config.enableLogging {
let famName = resolved.family == AF_INET6 ? "v6" : "v4"
Expand Down
9 changes: 6 additions & 3 deletions Tests/SwiftFTRTests/MultipathWorkerConfigTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ struct MultipathWorkerConfigTests {
"maxHops", "maxWaitMs", "payloadSize", "publicIP", "enableLogging", "noReverseDNS",
"rdnsCacheTTL", "rdnsCacheSize", "rdnsLookupTimeout", "publicIPDiscoveryTimeout",
"interface", "sourceIP", "asnResolverStrategy", "preferredFamily", "publicIPResolver",
"resolutionTimeout",
]

/// A caller configuration with every field away from its default.
Expand All @@ -96,7 +97,8 @@ struct MultipathWorkerConfigTests {
sourceIP: "127.0.0.1",
asnResolverStrategy: .dns,
preferredFamily: .auto,
publicIPResolver: .disabled
publicIPResolver: .disabled,
resolutionTimeout: 3.5
)

static func fields(of config: SwiftFTRConfig) -> [String: String] {
Expand All @@ -109,7 +111,7 @@ struct MultipathWorkerConfigTests {
}

@Test("A flow's configuration is the caller's except the documented overrides")
func flowConfigCopiesEveryField() async {
func flowConfigCopiesEveryField() async throws {
let caller = Self.fields(of: Self.callerConfig)
let defaults = Self.fields(of: SwiftFTRConfig())
#expect(
Expand All @@ -123,7 +125,8 @@ struct MultipathWorkerConfigTests {
let rdns = RDNSCache { _, _ in .noSuchRecord }
let resolver = MultipathRecordingASNResolver(mapping: [:])
let spawner = SwiftFTR.MultipathWorkerSpawner(
baseConfig: Self.callerConfig, rdnsCache: rdns, asnResolver: resolver, publicIP: nil)
baseConfig: Self.callerConfig, rdnsCache: rdns, asnResolver: resolver,
destination: try resolveHost(host: "127.0.0.1", prefer: .v4), publicIP: nil)
let flow = spawner.makeFlowTracer(maxHops: 5, timeoutMs: 321)
let worker = Self.fields(of: flow.config)

Expand Down
Loading
Loading