diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Lifecycle.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Lifecycle.swift index 6724602bb0e5..722833b9c1c4 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Lifecycle.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Lifecycle.swift @@ -37,6 +37,7 @@ extension CmxIrohClientRuntime { return preparation } localBinding = nil + lastRegistrationRefreshState = nil lifecyclePhase = .inactive currentSnapshot = CmxIrohClientRuntimeSnapshot( state: .inactive, @@ -65,6 +66,7 @@ extension CmxIrohClientRuntime { registrationRefreshTask = nil registrationRefreshTaskID = nil registrationRefreshPending = false + registrationRefreshPendingRequiresDiscovery = false registrationRefreshEnabled = false supervisorEventTask?.cancel() supervisorEventTask = nil @@ -72,7 +74,10 @@ extension CmxIrohClientRuntime { relayCoordinator = nil await contextRouter.clear() authoritativeDiscovery = nil - if !preserveBinding { localBinding = nil } + if !preserveBinding { + localBinding = nil + lastRegistrationRefreshState = nil + } await connectivityEngine.stop() } diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Policy.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Policy.swift index b5c9a5754220..ed6d23a6c8bb 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Policy.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+Policy.swift @@ -6,7 +6,8 @@ extension CmxIrohClientRuntime { expectedEndpointID: CmxIrohPeerIdentity, revision: UInt64, prefetchedDiscovery: CmxIrohDiscoveryResponse? = nil, - brokerPreparationComplete: Bool = false + brokerPreparationComplete: Bool = false, + allowReadOnlyRegistrationRefresh: Bool = false ) async throws -> ResolvedPolicy { if !brokerPreparationComplete { try await preparePolicyResolution(revision: revision) @@ -34,11 +35,11 @@ extension CmxIrohClientRuntime { ) } - // The supervisor snapshot and the live endpoint address are separate - // actor reads. Re-verify identity before every cached or online policy - // path so an endpoint replacement cannot inherit the old tuple. - let address = try await connectivityEngine.endpointAddress() - guard address.identity == expectedEndpointID else { + // Cached discovery may return before a registration payload is built. + // Verify the live endpoint address first so a replaced driver cannot + // inherit the prior generation's broker tuple. + let liveAddress = try await connectivityEngine.endpointAddress() + guard liveAddress.identity == expectedEndpointID else { throw CmxIrohClientRuntimeError.invalidLocalBinding } @@ -74,26 +75,26 @@ extension CmxIrohClientRuntime { prefetchedDiscoveryRejectedCachedBinding = true } - let publicHints = Array(address.pathHints.compactMap { - $0.publicDisclosure(at: now()) - }.prefix(CmxAttachEndpoint.maximumIrohPathHintCount)) - let directPorts = CmxIrohDirectPorts( - localDirectAddresses: try await connectivityEngine.localDirectAddresses() + let payload = try await registrationPayload( + expectedEndpointID: expectedEndpointID ) - let payload = try CmxIrohRegistrationPayload( - deviceID: configuration.deviceID, - appInstanceID: configuration.appInstanceID, - tag: configuration.tag, - platform: .ios, - displayName: configuration.displayName, - endpointID: expectedEndpointID.endpointID, - identityGeneration: configuration.identity.generation, - pairingEnabled: false, - capabilities: configuration.capabilities, - pathHints: publicHints, - directPorts: directPorts, + let refreshState = Self.registrationRefreshState( + payload: payload, now: now() ) + if allowReadOnlyRegistrationRefresh, + shouldUseReadOnlyRegistrationRefresh(refreshState, at: now()) { + do { + return try await readOnlyResolvedPolicy( + expectation: expectation, + offlineExpectation: offlineExpectation + ) + } catch CmxIrohClientRuntimeError.localBindingMissingFromDiscovery { + // The server no longer has this binding. Fall through to a + // signed mutation so the client self-heals instead of staying + // read-only forever. + } + } let signer = try CmxIrohRegistrationSigner( identity: configuration.identity, endpointID: expectedEndpointID.endpointID @@ -129,6 +130,9 @@ extension CmxIrohClientRuntime { if let registration, !expectation.matches(registration.binding) { throw CmxIrohClientRuntimeError.invalidLocalBinding } + if registration != nil { + lastRegistrationRefreshState = refreshState + } let discovery: CmxIrohDiscoveryResponse do { if let embedded = registration?.discovery, @@ -197,6 +201,91 @@ extension CmxIrohClientRuntime { ) } + func readOnlyResolvedPolicy( + expectation: CmxIrohLocalBindingExpectation, + offlineExpectation: CmxIrohClientOfflinePolicyExpectation? + ) async throws -> ResolvedPolicy { + let discovery = try await discoverAuthoritatively() + guard discovery.routeContractVersion + == CmxIrohRegistrationPayload.currentRouteContractVersion else { + throw CmxIrohClientRuntimeError.routeContractMismatch + } + try validateRelayFleet(discovery.relayFleet) + let localMatches = discovery.bindings.filter(expectation.matches) + guard localMatches.count == 1, + let discovered = localMatches.first else { + throw CmxIrohClientRuntimeError.localBindingMissingFromDiscovery + } + return ResolvedPolicy( + registration: nil, + discovery: discovery, + binding: discovered, + expectation: expectation, + offlineExpectation: offlineExpectation, + cachedTargetBindings: [], + cachedLANRendezvous: nil + ) + } + + func shouldUseReadOnlyRegistrationRefresh( + _ state: CmxIrohRegistrationPublicationState, + at now: Date + ) -> Bool { + !state.requiresPublication(after: lastRegistrationRefreshState, now: now) + } + + func registrationRefreshState( + expectedEndpointID: CmxIrohPeerIdentity + ) async throws -> CmxIrohRegistrationPublicationState { + let timestamp = now() + return CmxIrohRegistrationPublicationState( + payload: try await registrationPayload( + expectedEndpointID: expectedEndpointID, + timestamp: timestamp + ), + now: timestamp + ) + } + + func registrationPayload( + expectedEndpointID: CmxIrohPeerIdentity, + timestamp: Date? = nil + ) async throws -> CmxIrohRegistrationPayload { + // The supervisor snapshot and live endpoint address are separate actor + // reads. Re-verify identity before comparing or publishing the tuple. + let address = try await connectivityEngine.endpointAddress() + guard address.identity == expectedEndpointID else { + throw CmxIrohClientRuntimeError.invalidLocalBinding + } + let payloadTime = timestamp ?? now() + let publicHints = Array(address.pathHints.compactMap { + $0.publicDisclosure(at: payloadTime) + }.prefix(CmxAttachEndpoint.maximumIrohPathHintCount)) + return try CmxIrohRegistrationPayload( + deviceID: configuration.deviceID, + appInstanceID: configuration.appInstanceID, + tag: configuration.tag, + platform: .ios, + displayName: configuration.displayName, + endpointID: expectedEndpointID.endpointID, + identityGeneration: configuration.identity.generation, + pairingEnabled: false, + capabilities: configuration.capabilities, + pathHints: publicHints, + directPorts: CmxIrohDirectPorts( + localDirectAddresses: try await connectivityEngine.localDirectAddresses() + ), + now: payloadTime + ) + } + + static func registrationRefreshState( + payload: CmxIrohRegistrationPayload, + now: Date + ) -> CmxIrohRegistrationPublicationState { + CmxIrohRegistrationPublicationState(payload: payload, now: now) + } + func preparePolicyResolution(revision: UInt64) async throws { try await pendingRevocations.revokePending( accountID: configuration.accountID, diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+PolicyRefresh.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+PolicyRefresh.swift index 965fa3098efc..aff4aeb8bc9e 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+PolicyRefresh.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime+PolicyRefresh.swift @@ -24,28 +24,36 @@ extension CmxIrohClientRuntime { scheduleRegistrationRefresh(revision: revision) } - func scheduleRegistrationRefresh(revision: UInt64) { + func scheduleRegistrationRefresh( + revision: UInt64, + requiresDiscovery: Bool = false + ) { guard lifecyclePhase == .active, lifecycleRevision == revision else { return } guard registrationRefreshTask == nil else { registrationRefreshPending = true + registrationRefreshPendingRequiresDiscovery = + registrationRefreshPendingRequiresDiscovery || requiresDiscovery return } registrationRefreshPending = false + registrationRefreshPendingRequiresDiscovery = false let refreshID = UUID() registrationRefreshTaskID = refreshID registrationRefreshTask = Task { [weak self] in guard let self else { return .failed(.superseded) } return try await self.refreshRegistration( revision: revision, - refreshID: refreshID + refreshID: refreshID, + requiresDiscovery: requiresDiscovery ) } } func refreshRegistration( revision: UInt64, - refreshID: UUID + refreshID: UUID, + requiresDiscovery: Bool ) async throws -> CmxIrohLiveDiscoveryRefreshOutcome { defer { if lifecycleRevision == revision, @@ -55,7 +63,12 @@ extension CmxIrohClientRuntime { if registrationRefreshEnabled, registrationRefreshPending, lifecyclePhase == .active { - scheduleRegistrationRefresh(revision: revision) + let pendingRequiresDiscovery = + registrationRefreshPendingRequiresDiscovery + scheduleRegistrationRefresh( + revision: revision, + requiresDiscovery: pendingRequiresDiscovery + ) } } } @@ -68,9 +81,19 @@ extension CmxIrohClientRuntime { } do { let endpointID = try await connectivityEngine.localEndpointIdentity() + if !requiresDiscovery { + let state = try await registrationRefreshState( + expectedEndpointID: endpointID + ) + guard state.requiresPublication( + after: lastRegistrationRefreshState, + now: now() + ) else { return .refreshed } + } let policy = try await resolvePolicy( expectedEndpointID: endpointID, - revision: revision + revision: revision, + allowReadOnlyRegistrationRefresh: requiresDiscovery ) guard policy.binding.bindingID == previousBinding.bindingID else { throw CmxIrohClientRuntimeError.invalidLocalBinding @@ -82,8 +105,7 @@ extension CmxIrohClientRuntime { endpointID: endpointID, bindingID: policy.binding.bindingID ) - if policy.registration != nil, - let discovery = policy.discovery { + if let discovery = policy.discovery { let published = await handleBinding(policy.binding, discovery) try requireCurrent(revision) guard published else { return .failed(.superseded) } diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime.swift index 98b50c1f7d23..3625fd243aee 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohClientRuntime.swift @@ -99,10 +99,12 @@ public actor CmxIrohClientRuntime { private var connectivityReconciliationOperation: ConnectivityReconciliationOperation? private var pendingConnectivityRevision: UInt64? var registrationRefreshPending = false + var registrationRefreshPendingRequiresDiscovery = false var registrationRefreshEnabled = false var liveDiscoveryGeneration: UInt64 = 0 var authoritativeDiscovery: CmxIrohDiscoveryResponse? var localBinding: CmxIrohBrokerBinding? + var lastRegistrationRefreshState: CmxIrohRegistrationPublicationState? var registryContextProvider: CmxIrohRegistryContextProvider? var currentSnapshot = CmxIrohClientRuntimeSnapshot( state: .inactive, @@ -401,7 +403,10 @@ public actor CmxIrohClientRuntime { var mayScheduleFreshRequest = registrationRefreshTask != nil var latestOutcome: CmxIrohLiveDiscoveryRefreshOutcome = .failed(.superseded) if registrationRefreshTask == nil { - scheduleRegistrationRefresh(revision: lifecycleRevision) + scheduleRegistrationRefresh( + revision: lifecycleRevision, + requiresDiscovery: true + ) } var lastAwaitedTaskID: UUID? while lifecyclePhase == .active, @@ -409,18 +414,24 @@ public actor CmxIrohClientRuntime { let refreshID = registrationRefreshTaskID, refreshID != lastAwaitedTaskID { lastAwaitedTaskID = refreshID - latestOutcome = try await refresh.value + let outcome = try await refresh.value guard lifecyclePhase == .active else { return .failed(.endpointUnavailable) } if liveDiscoveryGeneration > priorGeneration { return .refreshed } - if registrationRefreshTaskID != nil { - mayScheduleFreshRequest = false - continue - } + // A `.refreshed` outcome without a generation advance is an + // unchanged-fingerprint no-op that never read the broker. It can + // neither satisfy this live discovery nor mask a real failure, + // and a coalesced successor may no-op the same way, so the right + // to schedule one authoritative refresh must survive successors. + if outcome != .refreshed { latestOutcome = outcome } + if registrationRefreshTaskID != nil { continue } guard mayScheduleFreshRequest else { return latestOutcome } mayScheduleFreshRequest = false - scheduleRegistrationRefresh(revision: lifecycleRevision) + scheduleRegistrationRefresh( + revision: lifecycleRevision, + requiresDiscovery: true + ) } return lifecyclePhase == .active ? latestOutcome @@ -461,6 +472,7 @@ public actor CmxIrohClientRuntime { lifecycleRevision &+= 1 let revision = lifecycleRevision registrationRefreshPending = false + registrationRefreshPendingRequiresDiscovery = false registrationRefreshEnabled = false currentSnapshot = CmxIrohClientRuntimeSnapshot( state: .starting, @@ -597,6 +609,7 @@ public actor CmxIrohClientRuntime { } try requireCurrent(revision) registrationRefreshPending = false + registrationRefreshPendingRequiresDiscovery = false registrationRefreshEnabled = true _ = try await refreshLiveDiscoveryThrowing() try requireCurrent(revision) diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PolicyRefresh.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PolicyRefresh.swift index 5de065809937..34e7b161805b 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PolicyRefresh.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PolicyRefresh.swift @@ -72,8 +72,11 @@ extension CmxIrohHostRuntime { revision: UInt64, allowCachedFallback: Bool ) async throws -> ResolvedPolicy { - let address = try await engine.endpointAddress() - guard address.identity == expectedEndpointID else { + // Cached fallback may return before a registration payload is built. + // Verify the live endpoint first so a replaced driver cannot inherit + // the prior generation's broker tuple. + let liveAddress = try await engine.endpointAddress() + guard liveAddress.identity == expectedEndpointID else { throw CmxIrohHostRuntimeError.invalidLocalBinding } // Discovery follows registration in one trust round. Honor a restored @@ -91,25 +94,9 @@ extension CmxIrohHostRuntime { ) } try requireCurrent(revision) - let publicHints = Array(address.pathHints.compactMap { - $0.publicDisclosure(at: now()) - }.prefix(CmxAttachEndpoint.maximumIrohPathHintCount)) - let directPorts = CmxIrohDirectPorts( - localDirectAddresses: try await engine.localDirectAddresses() - ) - let payload = try CmxIrohRegistrationPayload( - deviceID: configuration.deviceID, - appInstanceID: configuration.appInstanceID, - tag: configuration.tag, - platform: .mac, - displayName: configuration.displayName, - endpointID: expectedEndpointID.endpointID, - identityGeneration: configuration.identity.generation, - pairingEnabled: configuration.pairingEnabled, - capabilities: configuration.capabilities, - pathHints: publicHints, - directPorts: directPorts, - now: now() + let payload = try await registrationPayload( + engine: engine, + expectedEndpointID: expectedEndpointID ) let signer = try CmxIrohRegistrationSigner( identity: configuration.identity, @@ -192,6 +179,10 @@ extension CmxIrohHostRuntime { bindingID: discovered.bindingID ) try requireCurrent(revision) + lastRegistrationRefreshState = CmxIrohRegistrationPublicationState( + payload: payload, + now: now() + ) return ResolvedPolicy( registration: registration, discovery: discovery, @@ -206,6 +197,52 @@ extension CmxIrohHostRuntime { ) } + func registrationPublicationState( + engine: CmxConnectivityEngine, + expectedEndpointID: CmxIrohPeerIdentity + ) async throws -> CmxIrohRegistrationPublicationState { + let timestamp = now() + return CmxIrohRegistrationPublicationState( + payload: try await registrationPayload( + engine: engine, + expectedEndpointID: expectedEndpointID, + timestamp: timestamp + ), + now: timestamp + ) + } + + func registrationPayload( + engine: CmxConnectivityEngine, + expectedEndpointID: CmxIrohPeerIdentity, + timestamp: Date? = nil + ) async throws -> CmxIrohRegistrationPayload { + let address = try await engine.endpointAddress() + guard address.identity == expectedEndpointID else { + throw CmxIrohHostRuntimeError.invalidLocalBinding + } + let payloadTime = timestamp ?? now() + let publicHints = Array(address.pathHints.compactMap { + $0.publicDisclosure(at: payloadTime) + }.prefix(CmxAttachEndpoint.maximumIrohPathHintCount)) + return try CmxIrohRegistrationPayload( + deviceID: configuration.deviceID, + appInstanceID: configuration.appInstanceID, + tag: configuration.tag, + platform: .mac, + displayName: configuration.displayName, + endpointID: expectedEndpointID.endpointID, + identityGeneration: configuration.identity.generation, + pairingEnabled: configuration.pairingEnabled, + capabilities: configuration.capabilities, + pathHints: publicHints, + directPorts: CmxIrohDirectPorts( + localDirectAddresses: try await engine.localDirectAddresses() + ), + now: payloadTime + ) + } + func discoverAuthoritatively( minimumRevision: UInt64? = nil ) async throws -> CmxIrohDiscoveryResponse { @@ -346,7 +383,10 @@ extension CmxIrohHostRuntime { scheduleRegistrationRefresh(revision: revision) } - func scheduleRegistrationRefresh(revision: UInt64) { + func scheduleRegistrationRefresh( + revision: UInt64, + forcePublication: Bool = false + ) { guard lifecyclePhase == .active, lifecycleRevision == revision else { return } guard registrationRefreshTask == nil else { @@ -354,11 +394,17 @@ extension CmxIrohHostRuntime { // is suspended. Preserve that newer snapshot as a dirty bit so the // running round cannot overwrite the final usable relay address. registrationRefreshPending = true + registrationRefreshPendingForcesPublication = + registrationRefreshPendingForcesPublication || forcePublication return } registrationRefreshPending = false + registrationRefreshPendingForcesPublication = false registrationRefreshTask = Task { [weak self] in - await self?.refreshRegistration(revision: revision) + await self?.refreshRegistration( + revision: revision, + forcePublication: forcePublication + ) } } @@ -394,7 +440,10 @@ extension CmxIrohHostRuntime { guard lifecyclePhase == .active, lifecycleRevision == revision, !Task.isCancelled else { return } - scheduleRegistrationRefresh(revision: revision) + scheduleRegistrationRefresh( + revision: revision, + forcePublication: true + ) await registrationRefreshTask?.value } @@ -447,7 +496,10 @@ extension CmxIrohHostRuntime { }.min() } - func refreshRegistration(revision: UInt64) async { + func refreshRegistration( + revision: UInt64, + forcePublication: Bool + ) async { var completedSuccessfully = false defer { if lifecycleRevision == revision { @@ -455,7 +507,12 @@ extension CmxIrohHostRuntime { if completedSuccessfully, registrationRefreshPending, lifecyclePhase == .active { - scheduleRegistrationRefresh(revision: revision) + let pendingForcesPublication = + registrationRefreshPendingForcesPublication + scheduleRegistrationRefresh( + revision: revision, + forcePublication: pendingForcesPublication + ) } } } @@ -466,6 +523,19 @@ extension CmxIrohHostRuntime { let previousBinding = localBinding else { return } do { let endpointID = try await connectivityEngine.localEndpointIdentity() + if !forcePublication { + let state = try await registrationPublicationState( + engine: connectivityEngine, + expectedEndpointID: endpointID + ) + guard state.requiresPublication( + after: lastRegistrationRefreshState, + now: now() + ) else { + completedSuccessfully = true + return + } + } let policy = try await resolvePolicy( engine: connectivityEngine, expectedEndpointID: endpointID, diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PublicAPI.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PublicAPI.swift index 75414a9ba1fd..315111c0a43c 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PublicAPI.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+PublicAPI.swift @@ -58,7 +58,10 @@ extension CmxIrohHostRuntime { public func requestRegistrationRefresh() async { guard lifecyclePhase == .active, registrationRefreshEnabled else { return } - scheduleRegistrationRefresh(revision: lifecycleRevision) + scheduleRegistrationRefresh( + revision: lifecycleRevision, + forcePublication: true + ) // Await across the coalesced replay, not just the round that was // running when this call arrived: a signal landing mid-round only // sets the pending bit, and the running round's completion schedules diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+SignOut.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+SignOut.swift index 730bca12df33..ad960082b53f 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+SignOut.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime+SignOut.swift @@ -37,6 +37,7 @@ extension CmxIrohHostRuntime { } localBinding = nil + lastRegistrationRefreshState = nil lifecyclePhase = .inactive currentSnapshot = CmxIrohHostRuntimeSnapshot( state: .inactive, @@ -80,6 +81,7 @@ extension CmxIrohHostRuntime { registrationRenewalTask?.cancel() registrationRenewalTask = nil registrationRefreshPending = false + registrationRefreshPendingForcesPublication = false registrationRefreshEnabled = false registrationRefreshFailureCount = 0 relayActivationTask?.cancel() @@ -104,6 +106,7 @@ extension CmxIrohHostRuntime { let bindingID = localBinding?.bindingID if !preserveBinding { localBinding = nil + lastRegistrationRefreshState = nil } endpointAttestation = nil lanRendezvous = nil diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime.swift index f9e1619dbd75..c70ac5fbb0a6 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohHostRuntime.swift @@ -98,9 +98,11 @@ public actor CmxIrohHostRuntime { var registrationRefreshTask: Task? var registrationRenewalTask: Task? var registrationRefreshPending = false + var registrationRefreshPendingForcesPublication = false var registrationRefreshEnabled = false var registrationRefreshFailureCount = 0 var localBinding: CmxIrohBrokerBindingMetadata? + var lastRegistrationRefreshState: CmxIrohRegistrationPublicationState? var managedRelayURLs: Set var currentEndpointRelayProfile: CmxIrohEndpointRelayProfile? var endpointAttestation: CmxIrohEndpointAttestationResponse? @@ -168,6 +170,7 @@ public actor CmxIrohHostRuntime { lifecycleRevision &+= 1 let revision = lifecycleRevision registrationRefreshPending = false + registrationRefreshPendingForcesPublication = false registrationRefreshEnabled = false registrationRefreshFailureCount = 0 currentSnapshot = CmxIrohHostRuntimeSnapshot( diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohRegistrationPublicationState.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohRegistrationPublicationState.swift new file mode 100644 index 000000000000..108350e8f9bb --- /dev/null +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohRegistrationPublicationState.swift @@ -0,0 +1,54 @@ +import CMUXMobileCore +import Foundation + +/// Identifies the externally visible reachability state last published to the broker. +struct CmxIrohRegistrationPublicationState: Equatable, Sendable { + private struct Fingerprint: Equatable, Sendable { + let routeKeys: [String] + let directPorts: CmxIrohDirectPorts? + + init(payload: CmxIrohRegistrationPayload) { + routeKeys = payload.pathHints.map(Self.routeKey).sorted() + directPorts = payload.directPorts + } + + private static func routeKey(_ hint: CmxIrohPathHint) -> String { + [ + hint.kind.rawValue, + hint.value, + hint.source.rawValue, + hint.privacyScope.rawValue, + hint.networkProfile?.source.rawValue ?? "", + hint.networkProfile?.profileID ?? "", + ].joined(separator: "\u{1F}") + } + } + + private static let maximumPublicationInterval: TimeInterval = 50 * 60 + private static let hintRefreshLeadTime: TimeInterval = 5 * 60 + + private let fingerprint: Fingerprint + private let refreshAfter: Date + + init(payload: CmxIrohRegistrationPayload, now: Date) { + let hintRefreshAfter = payload.pathHints.compactMap(\.expiresAt).min() + .map { $0.addingTimeInterval(-Self.hintRefreshLeadTime) } + let intervalRefreshAfter = now.addingTimeInterval( + Self.maximumPublicationInterval + ) + fingerprint = Fingerprint(payload: payload) + refreshAfter = min( + hintRefreshAfter ?? intervalRefreshAfter, + intervalRefreshAfter + ) + } + + func requiresPublication( + after previous: CmxIrohRegistrationPublicationState?, + now: Date + ) -> Bool { + guard let previous, + previous.fingerprint == fingerprint else { return true } + return now >= previous.refreshAfter + } +} diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeLifecycleRaceTests.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeLifecycleRaceTests.swift index 08afb90b3c19..563b0eb02379 100644 --- a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeLifecycleRaceTests.swift +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeLifecycleRaceTests.swift @@ -10,7 +10,10 @@ extension CmxIrohClientRuntimeTests { let staleEndpoint = ClientRuntimeBlockingCloseEndpoint( identity: fixture.endpointID ) - let replacementEndpoint = TestIrohEndpoint(identity: fixture.endpointID) + let replacementEndpoint = TestIrohEndpoint( + identity: fixture.endpointID, + directAddresses: ["0.0.0.0:50909"] + ) let factory = TestIrohEndpointFactory( endpoints: [staleEndpoint, replacementEndpoint] ) @@ -134,18 +137,21 @@ extension CmxIrohClientRuntimeTests { } @Test - func refreshAwaitsAlreadyScheduledSuccessorWithoutRequestingThirdRefresh() async throws { + func concurrentLiveDiscoveryRequestSchedulesOneSuccessor() async throws { let fixture = try ClientRuntimeTestFixture() let endpoint = TestIrohEndpoint(identity: fixture.endpointID) - let secondRegistration = HostRuntimeRegistrationGate() - let thirdRegistration = HostRuntimeRegistrationGate() + let secondDiscovery = HostRuntimeRegistrationGate() + let thirdDiscovery = HostRuntimeRegistrationGate() let broker = TestIrohClientBroker( binding: fixture.binding, discovery: fixture.discovery, relay: fixture.relayResponse(), - registrationHook: { count in - if count == 2 { await secondRegistration.waitOnce() } - if count == 3 { await thirdRegistration.waitOnce() } + discoveryErrorsByCount: [ + 2: CmxIrohTrustBrokerClientError.connectivity, + ], + discoveryHook: { count in + if count == 2 { await secondDiscovery.waitOnce() } + if count == 3 { await thirdDiscovery.waitOnce() } } ) let runtime = try CmxIrohClientRuntime( @@ -156,31 +162,26 @@ extension CmxIrohClientRuntimeTests { now: { fixture.now } ) try await runtime.start() - await broker.setRegistrationError( - CmxIrohTrustBrokerClientError.connectivity, - forRegistrationCount: 2 - ) let refresh = Task { await runtime.refreshLiveDiscovery() } - await broker.waitForRegistrationCount(2) - await runtime.handleSupervisorNetworkChange( - revision: await runtime.lifecycleRevision - ) - #expect(await runtime.registrationRefreshPending) + await broker.waitForDiscoveryCount(2) + let successor = Task { await runtime.refreshLiveDiscovery() } - await secondRegistration.open() - await broker.waitForRegistrationCount(3) + await secondDiscovery.open() + await broker.waitForDiscoveryCount(3) #expect(await runtime.registrationRefreshTaskID != nil) - await thirdRegistration.open() + await thirdDiscovery.open() - #expect(await refresh.value) + _ = await refresh.value + #expect(await successor.value) #expect(await runtime.registrationRefreshTaskID == nil) #expect(!(await runtime.registrationRefreshPending)) - #expect(await broker.observedRegistrations().count == 3) + #expect(await broker.observedRegistrations().count == 1) + #expect(await broker.observedDiscoveryCount() == 3) await runtime.stop() } @Test - func networkChangeDuringRegistrationRequestsRefreshAfterStartup() async throws { + func networkChangeDuringRegistrationDoesNotRequestBrokerRefreshAfterStartup() async throws { let fixture = try ClientRuntimeTestFixture() let endpoint = TestIrohEndpoint(identity: fixture.endpointID) let broker = TestIrohClientBroker( @@ -201,14 +202,74 @@ extension CmxIrohClientRuntimeTests { try await runtime.start() - #expect( - await broker.waitForRegistrationCount(2, timeout: .seconds(1)) + for _ in 0..<1_000 { await Task.yield() } + #expect(await broker.observedDiscoveryCount() == 1) + #expect(!(await broker.waitForRegistrationCount(2, timeout: .milliseconds(200)))) + await runtime.stop() + } + + @Test + func repeatedUnchangedNetworkEventsDoNotContactBroker() async throws { + let fixture = try ClientRuntimeTestFixture() + let endpoint = TestIrohEndpoint(identity: fixture.endpointID) + let broker = TestIrohClientBroker( + binding: fixture.binding, + discovery: fixture.discovery, + relay: fixture.relayResponse() + ) + let runtime = try CmxIrohClientRuntime( + factory: TestIrohEndpointFactory(endpoints: [endpoint]), + broker: broker, + configuration: fixture.configuration, + pendingRevocations: fixture.pendingRevocations(), + now: { fixture.now } + ) + try await runtime.start() + + for _ in 0..<1_000 { + await endpoint.emit(.networkChanged) + } + await withTaskGroup(of: Void.self) { group in + for _ in 0..<100 { + group.addTask { await endpoint.emit(.networkChanged) } + } + } + // A requested live discovery is the processing barrier. If it races + // the event refresh, the coalescer permits one successor read. + #expect(try await runtime.refreshLiveDiscoveryThrowing()) + + #expect(await broker.observedRegistrations().count == 1) + #expect(await broker.observedDiscoveryCount() <= 3) + await runtime.stop() + } + + @Test + func changedDirectPortPublishesImmediately() async throws { + let fixture = try ClientRuntimeTestFixture() + let endpoint = TestIrohEndpoint(identity: fixture.endpointID) + let broker = TestIrohClientBroker( + binding: fixture.binding, + discovery: fixture.discovery, + relay: fixture.relayResponse() + ) + let runtime = try CmxIrohClientRuntime( + factory: TestIrohEndpointFactory(endpoints: [endpoint]), + broker: broker, + configuration: fixture.configuration, + pendingRevocations: fixture.pendingRevocations(), + now: { fixture.now } ) + try await runtime.start() + + await endpoint.setDirectAddresses(["0.0.0.0:50909"]) + await endpoint.emit(.networkChanged) + + #expect(await broker.waitForRegistrationCount(2, timeout: .seconds(1))) await runtime.stop() } @Test - func networkChangeDuringActiveRefreshRequestsAnotherRegistration() async throws { + func networkChangeDuringActiveRefreshDoesNotRequestAnotherDiscovery() async throws { let fixture = try ClientRuntimeTestFixture() let endpoint = TestIrohEndpoint(identity: fixture.endpointID) let gate = HostRuntimeRegistrationGate() @@ -216,7 +277,7 @@ extension CmxIrohClientRuntimeTests { binding: fixture.binding, discovery: fixture.discovery, relay: fixture.relayResponse(), - registrationHook: { count in + discoveryHook: { count in if count == 2 { await gate.waitOnce() } } ) @@ -229,14 +290,15 @@ extension CmxIrohClientRuntimeTests { ) try await runtime.start() - await endpoint.emit(.networkChanged) - await broker.waitForRegistrationCount(2) + let refresh = Task { await runtime.refreshLiveDiscoveryOutcome() } + await broker.waitForDiscoveryCount(2) await endpoint.emit(.networkChanged) await gate.open() - #expect( - await broker.waitForRegistrationCount(3, timeout: .seconds(1)) - ) + #expect(await refresh.value == .refreshed) + for _ in 0..<1_000 { await Task.yield() } + #expect(await broker.observedDiscoveryCount() == 2) + #expect(!(await broker.waitForRegistrationCount(2, timeout: .milliseconds(200)))) await runtime.stop() } @@ -249,7 +311,7 @@ extension CmxIrohClientRuntimeTests { binding: fixture.binding, discovery: fixture.discovery, relay: fixture.relayResponse(), - registrationHook: { count in + discoveryHook: { count in if count == 2 { await gate.waitOnce() } } ) @@ -261,13 +323,12 @@ extension CmxIrohClientRuntimeTests { now: { fixture.now } ) try await runtime.start() - await endpoint.emit(.networkChanged) - await broker.waitForRegistrationCount(2) - let refresh = await runtime.registrationRefreshTask + let refresh = Task { await runtime.refreshLiveDiscoveryOutcome() } + await broker.waitForDiscoveryCount(2) await runtime.stop() await gate.open() - _ = try? await refresh?.value + _ = await refresh.value #expect(await runtime.snapshot().state == .inactive) #expect(await endpoint.observedCloseCallCount() == 1) @@ -282,7 +343,7 @@ extension CmxIrohClientRuntimeTests { binding: fixture.binding, discovery: fixture.discovery, relay: fixture.relayResponse(), - registrationHook: { count in + discoveryHook: { count in if count == 2 { await gate.waitOnce() } } ) @@ -294,18 +355,79 @@ extension CmxIrohClientRuntimeTests { now: { fixture.now } ) try await runtime.start() - await endpoint.emit(.networkChanged) - await broker.waitForRegistrationCount(2) - let refresh = await runtime.registrationRefreshTask + let refresh = Task { await runtime.refreshLiveDiscoveryOutcome() } + await broker.waitForDiscoveryCount(2) let preparation = await runtime.deactivateForSignOut() await gate.open() - _ = try? await refresh?.value + _ = await refresh.value #expect(preparation.wasPersisted) #expect(await runtime.snapshot().state == .inactive) #expect(await endpoint.observedCloseCallCount() == 1) } + + @Test + func liveDiscoveryRacingCoalescedUnchangedRefreshesStillReadsBroker() async throws { + let fixture = try ClientRuntimeTestFixture() + let endpoint = TestIrohEndpoint(identity: fixture.endpointID) + let broker = TestIrohClientBroker( + binding: fixture.binding, + discovery: fixture.discovery, + relay: fixture.relayResponse() + ) + let runtime = try CmxIrohClientRuntime( + factory: TestIrohEndpointFactory(endpoints: [endpoint]), + broker: broker, + configuration: fixture.configuration, + pendingRevocations: fixture.pendingRevocations(), + now: { fixture.now } + ) + try await runtime.start() + #expect(await broker.observedDiscoveryCount() == 1) + + // Hold every unchanged-fingerprint refresh at its payload read so the + // live discovery request is guaranteed to observe each one in flight. + await endpoint.armAddressGate() + let request = Task { + try await runtime.liveDiscoveryRacingCoalescedUnchangedRefreshes() + } + await endpoint.waitForBlockedAddressArrivals(1) + await endpoint.releaseOneBlockedAddressCall() + + await endpoint.waitForBlockedAddressArrivals(2) + await runtime.coalesceUnchangedRegistrationRefresh() + await endpoint.releaseOneBlockedAddressCall() + + await endpoint.waitForBlockedAddressArrivals(3) + await endpoint.disarmAddressGate() + + // The raced refreshes were all unchanged-fingerprint no-ops. Live + // discovery must still perform an authoritative broker read before + // reporting success. + #expect(try await request.value) + #expect(await broker.observedDiscoveryCount() == 2) + #expect(await broker.observedRegistrations().count == 1) + await runtime.stop() + } +} + +extension CmxIrohClientRuntime { + /// Schedules an unchanged-fingerprint refresh plus a coalesced successor, + /// then requests live discovery in the same actor turn so the request is + /// guaranteed to observe the first refresh still in flight. + fileprivate func liveDiscoveryRacingCoalescedUnchangedRefreshes() + async throws -> Bool + { + scheduleRegistrationRefresh(revision: lifecycleRevision) + scheduleRegistrationRefresh(revision: lifecycleRevision) + return try await refreshLiveDiscoveryThrowing() + } + + /// Coalesces one more unchanged-fingerprint refresh behind the in-flight one. + fileprivate func coalesceUnchangedRegistrationRefresh() { + scheduleRegistrationRefresh(revision: lifecycleRevision) + } } private actor ClientRuntimeBlockingCloseEndpoint: CmxIrohEndpoint { diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeTests.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeTests.swift index 1ee40c0f6fea..96e716d3f1a7 100644 --- a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeTests.swift +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohClientRuntimeTests.swift @@ -486,7 +486,8 @@ struct CmxIrohClientRuntimeTests { let initialProvider = try #require(await runtime.registryContextProvider) #expect(await runtime.refreshLiveDiscovery()) let refreshedProvider = try #require(await runtime.registryContextProvider) - #expect(await broker.observedRegistrations().count == 2) + #expect(await broker.observedRegistrations().count == 1) + #expect(await broker.observedDiscoveryCount() == 2) #expect(await recorder.observedBindingCount() == 2) #expect(initialProvider === refreshedProvider) await runtime.stop() @@ -498,7 +499,10 @@ struct CmxIrohClientRuntimeTests { let broker = TestIrohClientBroker( binding: fixture.binding, discovery: fixture.discovery, - relay: fixture.relayResponse() + relay: fixture.relayResponse(), + discoveryErrorsByCount: [ + 2: CmxIrohTrustBrokerClientError.connectivity, + ] ) let recorder = ClientRuntimeTestRecorder() let runtime = try CmxIrohClientRuntime( @@ -515,7 +519,6 @@ struct CmxIrohClientRuntimeTests { } ) try await runtime.start() - await broker.setRegistrationError(CmxIrohTrustBrokerClientError.connectivity) #expect( await runtime.refreshLiveDiscoveryOutcome() @@ -529,10 +532,15 @@ struct CmxIrohClientRuntimeTests { @Test func rateLimitedBrokerReportsPolicyUnavailableWithoutDroppingRuntime() async throws { let fixture = try ClientRuntimeTestFixture() + let rateLimit = CmxIrohTrustBrokerClientError.rateLimited( + code: nil, + retryAfterSeconds: 15 + ) let broker = TestIrohClientBroker( binding: fixture.binding, discovery: fixture.discovery, - relay: fixture.relayResponse() + relay: fixture.relayResponse(), + discoveryErrorsByCount: [2: rateLimit] ) let runtime = try CmxIrohClientRuntime( factory: TestIrohEndpointFactory(endpoints: [ @@ -544,12 +552,6 @@ struct CmxIrohClientRuntimeTests { now: { fixture.now } ) try await runtime.start() - await broker.setRegistrationError( - CmxIrohTrustBrokerClientError.rateLimited( - code: nil, - retryAfterSeconds: 15 - ) - ) #expect( await runtime.refreshLiveDiscoveryOutcome() @@ -773,7 +775,10 @@ struct CmxIrohClientRuntimeTests { let broker = TestIrohClientBroker( binding: fixture.binding, discovery: fixture.discovery, - relay: fixture.relayResponse() + relay: fixture.relayResponse(), + discoveryErrorsByCount: [ + 2: CmxIrohTrustBrokerClientError.connectivity, + ] ) let runtime = try CmxIrohClientRuntime( factory: factory, @@ -789,7 +794,8 @@ struct CmxIrohClientRuntimeTests { #expect(await endpoint.observedCloseCallCount() == 0) #expect(await factory.observedConfigurations().count == 1) - #expect(await broker.observedRegistrations().count == 2) + #expect(await broker.observedRegistrations().count == 1) + #expect(await broker.observedDiscoveryCount() == 2) #expect(await runtime.snapshot().state == .active) await runtime.stop() } @@ -798,7 +804,10 @@ struct CmxIrohClientRuntimeTests { func foregroundRecreatesStaleDriverWithStableIdentity() async throws { let fixture = try ClientRuntimeTestFixture() let staleEndpoint = TestIrohEndpoint(identity: fixture.endpointID) - let replacementEndpoint = TestIrohEndpoint(identity: fixture.endpointID) + let replacementEndpoint = TestIrohEndpoint( + identity: fixture.endpointID, + directAddresses: ["0.0.0.0:50909"] + ) let factory = TestIrohEndpointFactory( endpoints: [staleEndpoint, replacementEndpoint] ) @@ -833,10 +842,15 @@ struct CmxIrohClientRuntimeTests { func foregroundUnauthorizedBrokerFailurePreservesLocalPolicy() async throws { let fixture = try ClientRuntimeTestFixture() let endpoint = TestIrohEndpoint(identity: fixture.endpointID) + let terminal = CmxIrohTrustBrokerClientError.rejected( + statusCode: 401, + code: "unauthorized" + ) let broker = TestIrohClientBroker( binding: fixture.binding, discovery: fixture.discovery, - relay: fixture.relayResponse() + relay: fixture.relayResponse(), + discoveryErrorsByCount: [2: terminal] ) let offlineStore = TestSecureCredentialStore() let recorder = ClientRuntimeTestRecorder() @@ -854,11 +868,6 @@ struct CmxIrohClientRuntimeTests { } ) try await runtime.start() - let terminal = CmxIrohTrustBrokerClientError.rejected( - statusCode: 401, - code: "unauthorized" - ) - await broker.setRegistrationError(terminal) try await runtime.didBecomeActive() @@ -894,7 +903,6 @@ struct CmxIrohClientRuntimeTests { } ) try await runtime.start() - await broker.setRegistrationError(CmxIrohTrustBrokerClientError.connectivity) try await runtime.didBecomeActive() @@ -925,7 +933,8 @@ struct CmxIrohClientRuntimeTests { let broker = TestIrohClientBroker( binding: fixture.binding, discovery: fixture.discovery, - relay: fixture.relayResponse() + relay: fixture.relayResponse(), + discoveryErrorsByCount: [2: failure] ) let offlineStore = TestSecureCredentialStore() let recorder = ClientRuntimeTestRecorder() @@ -943,7 +952,6 @@ struct CmxIrohClientRuntimeTests { } ) try await runtime.start() - await broker.setRegistrationError(failure) try await runtime.didBecomeActive() diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleRaceTests.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleRaceTests.swift index 4e43707e6c39..df5fd369cfa4 100644 --- a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleRaceTests.swift +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleRaceTests.swift @@ -166,13 +166,12 @@ extension CmxIrohHostRuntimeTests { handleTransport: { session, _ in await session.close() } ) try await runtime.start() - await endpoint.emit(.networkChanged) + let refresh = Task { await runtime.requestRegistrationRefresh() } await broker.waitForRegistrationCount(2) - let refresh = await runtime.registrationRefreshTask await runtime.stop() await gate.open() - await refresh?.value + await refresh.value #expect(await runtime.snapshot().state == .inactive) #expect(await endpoint.observedCloseCallCount() == 1) @@ -196,13 +195,12 @@ extension CmxIrohHostRuntimeTests { handleTransport: { session, _ in await session.close() } ) try await runtime.start() - await endpoint.emit(.networkChanged) + let refresh = Task { await runtime.requestRegistrationRefresh() } await broker.waitForRegistrationCount(2) - let refresh = await runtime.registrationRefreshTask let preparation = await runtime.deactivateForSignOut() await gate.open() - await refresh?.value + await refresh.value #expect(preparation.wasPersisted) #expect(await runtime.snapshot().state == .inactive) diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleTests.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleTests.swift index d10755e2a8f5..8f49b82afef0 100644 --- a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleTests.swift +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimeLifecycleTests.swift @@ -225,7 +225,7 @@ extension CmxIrohHostRuntimeTests { await clock.waitUntilSleepCount(3) await broker.enqueueSubsequentRegistrationError(.connectivity) - await endpoint.emit(.networkChanged) + await runtime.requestRegistrationRefresh() await broker.waitForRegistrationCount(4) await clock.waitUntilSleepCount(4) let resetRetry = try #require(clock.observedSleepDeadlines().last) @@ -401,6 +401,33 @@ extension CmxIrohHostRuntimeTests { #expect(await runtime.snapshot().state == .inactive) } + @Test + func successfulSignOutClearsRegistrationPublicationState() async throws { + let fixture = try HostRuntimeFixture() + let endpoint = TestIrohEndpoint(identity: fixture.endpointID) + let store = TestControllableSecureCredentialStore() + let runtime = CmxIrohHostRuntime( + factory: TestIrohEndpointFactory(endpoints: [endpoint]), + broker: TestIrohHostBroker( + registrationBinding: fixture.binding, + discovery: fixture.discovery + ), + configuration: fixture.configuration, + pendingRevocations: CmxIrohPendingRevocationOutbox(secureStore: store), + handleTransport: { session, _ in await session.close() } + ) + try await runtime.start() + #expect(await runtime.lastRegistrationRefreshState != nil) + + let preparation = await runtime.deactivateForSignOut() + + #expect(preparation.wasPersisted) + #expect(await runtime.snapshot().state == .inactive) + // A stale fingerprint surviving sign-out could suppress the next + // account's non-forced publications when reachability matches. + #expect(await runtime.lastRegistrationRefreshState == nil) + } + @Test func requiredBindPolicyIsForwardedToTheEndpointGeneration() async throws { let fixture = try HostRuntimeFixture() @@ -624,6 +651,67 @@ extension CmxIrohHostRuntimeTests { await runtime.stop() } + @Test + func repeatedUnchangedNetworkEventsDoNotContactBroker() async throws { + let fixture = try HostRuntimeFixture() + let endpoint = TestIrohEndpoint(identity: fixture.endpointID) + let broker = TestIrohHostBroker( + registrationBinding: fixture.binding, + discovery: fixture.discovery + ) + let refreshes = HostRuntimeLANRefreshRecorder() + let runtime = CmxIrohHostRuntime( + factory: TestIrohEndpointFactory(endpoints: [endpoint]), + broker: broker, + configuration: fixture.configuration, + pendingRevocations: fixture.pendingRevocations(), + handleTransport: { session, _ in await session.close() }, + handleLANRefresh: { await refreshes.record() } + ) + try await runtime.start() + let initialDiscoveryCount = await broker.observedDiscoveryCount() + + for _ in 0..<1_000 { + await endpoint.emit(.networkChanged) + } + await withTaskGroup(of: Void.self) { group in + for _ in 0..<100 { + group.addTask { await endpoint.emit(.networkChanged) } + } + } + #expect(await refreshes.waitForCount(1_100, timeout: .seconds(5))) + + #expect(await broker.observedRegistrationCount() == 1) + #expect(await broker.observedDiscoveryCount() == initialDiscoveryCount) + await runtime.stop() + } + + @Test + func changedDirectPortPublishesImmediately() async throws { + let fixture = try HostRuntimeFixture() + let endpoint = TestIrohEndpoint(identity: fixture.endpointID) + let broker = TestIrohHostBroker( + registrationBinding: fixture.binding, + discovery: fixture.discovery + ) + let runtime = CmxIrohHostRuntime( + factory: TestIrohEndpointFactory(endpoints: [endpoint]), + broker: broker, + configuration: fixture.configuration, + pendingRevocations: fixture.pendingRevocations(), + handleTransport: { session, _ in await session.close() } + ) + try await runtime.start() + + await endpoint.setDirectAddresses(["0.0.0.0:50909"]) + await endpoint.emit(.networkChanged) + + #expect( + await broker.waitForRegistrationCount(2, timeout: .seconds(1)) + ) + await runtime.stop() + } + @Test func endpointOnlineRequestsImmediateReachabilityRefresh() async throws { let fixture = try HostRuntimeFixture() @@ -687,7 +775,7 @@ extension CmxIrohHostRuntimeTests { ) try await runtime.start() - await endpoint.emit(.networkChanged) + await runtime.requestRegistrationRefresh() await broker.waitForRegistrationCount(2) await runtime.waitForRegistrationRefreshForTesting() diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimePolicyTests.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimePolicyTests.swift index f0ad7b9ed8b0..85a22903ef54 100644 --- a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimePolicyTests.swift +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohHostRuntimePolicyTests.swift @@ -148,8 +148,7 @@ extension CmxIrohHostRuntimeTests { try await runtime.start() #expect(await runtime.connectivityEngine?.snapshot().routeRevision == 2) - await endpoint.emit(.networkChanged) - await broker.waitForRegistrationCount(2) + await runtime.requestRegistrationRefresh() for _ in 0..<1_000 { if await runtime.snapshot().state == .failed { break } await Task.yield() @@ -188,7 +187,7 @@ extension CmxIrohHostRuntimeTests { } @Test - func networkChangeDuringActiveRefreshRequestsAnotherRegistration() async throws { + func networkChangeDuringActiveRefreshDoesNotRequestAnotherRegistration() async throws { let fixture = try HostRuntimeFixture() let endpoint = TestIrohEndpoint(identity: fixture.endpointID) let gate = HostRuntimeRegistrationGate() @@ -208,17 +207,18 @@ extension CmxIrohHostRuntimeTests { ) try await runtime.start() - await endpoint.emit(.networkChanged) + let refresh = Task { await runtime.requestRegistrationRefresh() } await broker.waitForRegistrationCount(2) await endpoint.emit(.networkChanged) - #expect(await refreshes.waitForCount(2, timeout: .seconds(1))) + #expect(await refreshes.waitForCount(1, timeout: .seconds(1))) await gate.open() + await refresh.value let registeredAgain = await broker.waitForRegistrationCount( 3, - timeout: .seconds(1) + timeout: .milliseconds(200) ) - #expect(registeredAgain) + #expect(!registeredAgain) await runtime.stop() } @@ -253,7 +253,7 @@ extension CmxIrohHostRuntimeTests { } ) try await runtime.start() - await endpoint.emit(.networkChanged) + await runtime.requestRegistrationRefresh() await policies.waitForCount(2) #expect(await policies.contexts().map(\.rendezvous.generation) == [1, 2]) diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohRegistrationPublicationStateTests.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohRegistrationPublicationStateTests.swift new file mode 100644 index 000000000000..5e11b3aafea9 --- /dev/null +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/CmxIrohRegistrationPublicationStateTests.swift @@ -0,0 +1,140 @@ +import CMUXMobileCore +import Foundation +import Testing +@testable import CmuxIrohTransport + +@Suite("Iroh registration publication state") +struct CmxIrohRegistrationPublicationStateTests { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + @Test("path addition removal and replacement require publication") + func changedPathsRequirePublication() throws { + let first = try state(hints: [hint("https://relay-a.example/")]) + + #expect(try state(hints: []).requiresPublication(after: first, now: now)) + #expect( + try state(hints: [ + hint("https://relay-a.example/"), + hint("https://relay-b.example/"), + ]).requiresPublication(after: first, now: now) + ) + #expect( + try state(hints: [hint("https://relay-b.example/")]) + .requiresPublication(after: first, now: now) + ) + } + + @Test("path reorder and timestamp churn stay silent before renewal") + func metadataOnlyChangesStaySilent() throws { + let first = try state(hints: [ + hint("https://relay-a.example/"), + hint("https://relay-b.example/"), + ]) + let reordered = try state( + hints: [ + hint( + "https://relay-b.example/", + observedAt: now.addingTimeInterval(60), + expiresAt: now.addingTimeInterval(3_660) + ), + hint( + "https://relay-a.example/", + observedAt: now.addingTimeInterval(60), + expiresAt: now.addingTimeInterval(3_660) + ), + ], + payloadNow: now.addingTimeInterval(60) + ) + + #expect(!reordered.requiresPublication( + after: first, + now: now.addingTimeInterval(60) + )) + } + + @Test("unchanged paths renew before expiry and within fifty minutes") + func unchangedPathsRenewOnSchedule() throws { + let expiring = try state(hints: [ + hint( + "https://relay-a.example/", + expiresAt: now.addingTimeInterval(1_800) + ), + ]) + let unchanged = try state(hints: [ + hint( + "https://relay-a.example/", + expiresAt: now.addingTimeInterval(1_800) + ), + ]) + + #expect(!unchanged.requiresPublication( + after: expiring, + now: now.addingTimeInterval(1_499) + )) + #expect(unchanged.requiresPublication( + after: expiring, + now: now.addingTimeInterval(1_500) + )) + + let noHints = try state(hints: []) + #expect(!noHints.requiresPublication( + after: noHints, + now: now.addingTimeInterval(2_999) + )) + #expect(noHints.requiresPublication( + after: noHints, + now: now.addingTimeInterval(3_000) + )) + } + + @Test("direct port changes require publication") + func changedDirectPortsRequirePublication() throws { + let first = try state(hints: [], ipv4Port: 50_000, ipv6Port: 50_000) + let ipv4Changed = try state(hints: [], ipv4Port: 50_001, ipv6Port: 50_000) + let ipv6Changed = try state(hints: [], ipv4Port: 50_000, ipv6Port: 50_001) + + #expect(ipv4Changed.requiresPublication(after: first, now: now)) + #expect(ipv6Changed.requiresPublication(after: first, now: now)) + #expect(!first.requiresPublication(after: first, now: now)) + } + + private func state( + hints: [CmxIrohPathHint], + ipv4Port: UInt16? = nil, + ipv6Port: UInt16? = nil, + payloadNow: Date? = nil + ) throws -> CmxIrohRegistrationPublicationState { + let payloadNow = payloadNow ?? now + let payload = try CmxIrohRegistrationPayload( + deviceID: "123e4567-e89b-12d3-a456-426614174000", + appInstanceID: "123e4567-e89b-12d3-a456-426614174001", + tag: "verify", + platform: .ios, + endpointID: String(repeating: "0", count: 64), + identityGeneration: 1, + pairingEnabled: false, + capabilities: [], + pathHints: hints, + directPorts: ipv4Port == nil && ipv6Port == nil + ? nil + : try CmxIrohDirectPorts(ipv4: ipv4Port, ipv6: ipv6Port), + now: payloadNow + ) + return CmxIrohRegistrationPublicationState(payload: payload, now: payloadNow) + } + + private func hint( + _ value: String, + observedAt: Date? = nil, + expiresAt: Date? = nil + ) throws -> CmxIrohPathHint { + try CmxIrohPathHint( + kind: .relayURL, + value: value, + source: .native, + privacyScope: .publicInternet, + observedAt: observedAt ?? now, + expiresAt: expiresAt ?? now.addingTimeInterval(3_600) + ) + } +} diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohClientBroker.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohClientBroker.swift index 2a661c9be50e..e02657eb3187 100644 --- a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohClientBroker.swift +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohClientBroker.swift @@ -9,6 +9,7 @@ actor TestIrohClientBroker: CmxIrohClientBrokerServing { private let pairGrantResponse: CmxIrohPairGrantResponse? private let revokeError: (any Error)? private let registrationHook: (@Sendable (_ count: Int) async -> Void)? + private let discoveryHook: (@Sendable (_ count: Int) async -> Void)? private var registrationError: (any Error)? private var registrationErrorsByCount: [Int: any Error] = [:] private var preparedRegistrations: [CmxIrohPreparedRegistration] = [] @@ -19,6 +20,9 @@ actor TestIrohClientBroker: CmxIrohClientBrokerServing { private var registrationCountWaiters: [ UUID: (minimum: Int, continuation: CheckedContinuation) ] = [:] + private var discoveryCountWaiters: [ + UUID: (minimum: Int, continuation: CheckedContinuation) + ] = [:] init( binding: CmxIrohBrokerBinding, @@ -29,7 +33,8 @@ actor TestIrohClientBroker: CmxIrohClientBrokerServing { registrationError: (any Error)? = nil, discoveryErrorsByCount: [Int: any Error] = [:], revokeError: (any Error)? = nil, - registrationHook: (@Sendable (_ count: Int) async -> Void)? = nil + registrationHook: (@Sendable (_ count: Int) async -> Void)? = nil, + discoveryHook: (@Sendable (_ count: Int) async -> Void)? = nil ) { registration = CmxIrohRegistrationResponse( binding: binding, @@ -42,6 +47,7 @@ actor TestIrohClientBroker: CmxIrohClientBrokerServing { self.registrationError = registrationError self.discoveryErrorsByCount = discoveryErrorsByCount self.registrationHook = registrationHook + self.discoveryHook = discoveryHook } func register( @@ -64,8 +70,16 @@ actor TestIrohClientBroker: CmxIrohClientBrokerServing { return registration } - func discover() throws -> CmxIrohDiscoveryResponse { + func discover() async throws -> CmxIrohDiscoveryResponse { discoveryCount += 1 + let count = discoveryCount + let readyIDs = discoveryCountWaiters.compactMap { id, waiter in + count >= waiter.minimum ? id : nil + } + for id in readyIDs { + discoveryCountWaiters.removeValue(forKey: id)?.continuation.resume() + } + await discoveryHook?(count) if let error = discoveryErrorsByCount[discoveryCount] { throw error } @@ -156,7 +170,48 @@ actor TestIrohClientBroker: CmxIrohClientBrokerServing { } } + func waitForDiscoveryCount(_ minimum: Int) async { + if discoveryCount >= minimum { return } + let id = UUID() + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + if Task.isCancelled { + continuation.resume() + } else { + discoveryCountWaiters[id] = (minimum, continuation) + } + } + } onCancel: { + Task { await self.cancelDiscoveryWaiter(id) } + } + } + + func waitForDiscoveryCount(_ minimum: Int, timeout: Duration) async -> Bool { + if discoveryCount >= minimum { return true } + return await withTaskGroup(of: Bool.self) { group in + group.addTask { + await self.waitForDiscoveryCount(minimum) + return !Task.isCancelled + } + group.addTask { + do { + try await ContinuousClock().sleep(for: timeout) + } catch { + return false + } + return false + } + let result = await group.next() ?? false + group.cancelAll() + return result + } + } + private func cancelRegistrationWaiter(_ id: UUID) { registrationCountWaiters.removeValue(forKey: id)?.continuation.resume() } + + private func cancelDiscoveryWaiter(_ id: UUID) { + discoveryCountWaiters.removeValue(forKey: id)?.continuation.resume() + } } diff --git a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohEndpoint.swift b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohEndpoint.swift index 4ba37ba35df2..76a118005180 100644 --- a/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohEndpoint.swift +++ b/Packages/Shared/CmuxIrohTransport/Tests/CmuxIrohTransportTests/TestIrohEndpoint.swift @@ -4,7 +4,7 @@ import Foundation actor TestIrohEndpoint: CmxIrohEndpoint { private let peerIdentity: CmxIrohPeerIdentity - private let directAddresses: [String] + private var directAddresses: [String] private var pathHints: [CmxIrohPathHint] private let pathHintsAfterRelayReplacement: [CmxIrohPathHint]? private let healthStream: AsyncStream @@ -14,6 +14,10 @@ actor TestIrohEndpoint: CmxIrohEndpoint { private var relayProfileUpdates: [CmxIrohEndpointRelayProfile] = [] private var relayUpdateShouldFail = false private var healthy = true + private var addressGateArmed = false + private var blockedAddressArrivals = 0 + private var blockedAddressWaiters: [CheckedContinuation] = [] + private var addressArrivalWaiters: [CheckedContinuation] = [] init( identity: CmxIrohPeerIdentity, @@ -34,12 +38,47 @@ actor TestIrohEndpoint: CmxIrohEndpoint { peerIdentity } - func address() -> CmxIrohEndpointAddress { - CmxIrohEndpointAddress(identity: peerIdentity, pathHints: pathHints) + func address() async -> CmxIrohEndpointAddress { + if addressGateArmed { + blockedAddressArrivals += 1 + let arrivalWaiters = addressArrivalWaiters + addressArrivalWaiters.removeAll() + for waiter in arrivalWaiters { waiter.resume() } + await withCheckedContinuation { blockedAddressWaiters.append($0) } + } + return CmxIrohEndpointAddress(identity: peerIdentity, pathHints: pathHints) + } + + /// Blocks every subsequent `address()` read until released or disarmed, + /// so tests can hold a registration refresh in flight at its payload read. + func armAddressGate() { + addressGateArmed = true + } + + func disarmAddressGate() { + addressGateArmed = false + let blocked = blockedAddressWaiters + blockedAddressWaiters.removeAll() + for waiter in blocked { waiter.resume() } + } + + func releaseOneBlockedAddressCall() { + guard !blockedAddressWaiters.isEmpty else { return } + blockedAddressWaiters.removeFirst().resume() + } + + func waitForBlockedAddressArrivals(_ minimum: Int) async { + while blockedAddressArrivals < minimum { + await withCheckedContinuation { addressArrivalWaiters.append($0) } + } } func localDirectAddresses() -> [String] { directAddresses } + func setDirectAddresses(_ addresses: [String]) { + directAddresses = addresses + } + func connect( to _: CmxIrohEndpointAddress, alpn _: Data