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
8 changes: 5 additions & 3 deletions apple/TablePro/Core/Database/ConnectionHealthMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,15 @@ actor ConnectionHealthMonitor {
try? await clock.sleep(for: .seconds(initialDelay))
guard !Task.isCancelled else { return }

// Read once per pass, after the sleep, so turning checks off stops the next ping and the answer also sets
// the sleep that follows it.
guard var interval = await intervalForPass() else { return }
while !Task.isCancelled {
guard let interval = await intervalForPass() else { break }
// The tolerance lets the system coalesce every open connection's ping into one wake.
try? await clock.sleep(for: interval, tolerance: interval / 4)
guard !Task.isCancelled else { break }
// Asked again after the sleep, so turning checks off stops the next one.
guard await intervalForPass() != nil else { break }
guard let next = await intervalForPass() else { break }
interval = next
await self.performHealthCheck()
guard await !self.hasHandedOff else { break }
}
Expand Down
36 changes: 36 additions & 0 deletions apple/TablePro/Core/Database/ConnectionNetworkMonitor.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//
// ConnectionNetworkMonitor.swift
// TablePro
//

import Foundation
import Network

/// What the Network framework reports of the Mac's route out, reduced to what a reconnect acts on.
struct NetworkPathSnapshot: Equatable, Sendable {
let isSatisfied: Bool
// A Wi-Fi rejoin or a VPN coming up keeps the path satisfied and changes these instead.
let interfaces: [String]
}

/// Watches the default network path with `NWPathMonitor`, the reachability API Apple documents, so a session that
/// lost its connection to an outage redials once the path is back instead of at its next backoff step.
final class ConnectionNetworkMonitor: @unchecked Sendable {
private let monitor = NWPathMonitor()

deinit {
monitor.cancel()
}

/// `onChange` runs on the main actor for every update, the first one included.
func start(onChange: @escaping @MainActor @Sendable (NetworkPathSnapshot) -> Void) {
monitor.pathUpdateHandler = { path in
let snapshot = NetworkPathSnapshot(
isSatisfied: path.status == .satisfied,
interfaces: path.availableInterfaces.map(\.name)
)
Task { @MainActor in onChange(snapshot) }
}
monitor.start(queue: DispatchQueue(label: "com.TablePro.connectionNetworkMonitor"))
}
}
78 changes: 59 additions & 19 deletions apple/TablePro/Core/Database/DatabaseManager+Health.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,10 @@ extension DatabaseManager {

let monitor = ConnectionHealthMonitor(
connectionId: connectionId,
pingInterval: { await AppSettingsManager.shared.general.connectionHealthCheck.interval },
pingInterval: { await Self.healthCheckInterval() },
pingHandler: { [weak self] in
guard let self else { return false }
await self.closeIdleOpenedLanes(for: connectionId)
if await self.queriesInFlight[connectionId] != nil {
Self.logger.debug("Ping skipped, operation in flight for \(connectionId)")
return true
}
guard let mainDriver = await self.activeSessions[connectionId]?.driver else {
Self.logger.debug("Ping skipped, no active driver for \(connectionId)")
return false
}
await self.notePinged(mainDriver, for: connectionId)
do {
try await mainDriver.ping()
await self.noteAnsweredPing(connectionId, driver: mainDriver)
return true
} catch {
Self.logger.debug("Ping failed for \(connectionId): \(error.publicLogShape, privacy: .public)")
return false
}
return await self.pingSessionDriver(connectionId)
},
onPingFailed: { [weak self] in
guard let self else { return .handedOff }
Expand All @@ -69,6 +52,63 @@ extension DatabaseManager {
await monitor.startMonitoring()
}

/// While the app is inactive nobody is waiting on an answer, and `verifyBeforeUse` checks a connection older
/// than `ConnectionHealthCheck.freshness` when the user comes back to it, so a ping more often than that only
/// wakes the network and keeps a serverless database billing.
internal static func healthCheckInterval(
setting: ConnectionHealthCheck = AppSettingsManager.shared.general.connectionHealthCheck,
appIsActive: Bool = NSApp?.isActive ?? true
) -> Duration? {
guard let interval = setting.interval else { return nil }
return appIsActive ? interval : max(interval, ConnectionHealthCheck.freshness)
}

/// The ping is a turn on the session driver's gate, so it never sits on the driver between two pieces of the
/// user's work. A held gate means the connection is busy, and the work holding it reports a dead connection
/// itself, so the ping is skipped rather than queued.
internal func pingSessionDriver(_ connectionId: UUID) async -> Bool {
await closeIdleOpenedLanes(for: connectionId)
let key = browsedGateKey(for: connectionId)
guard queriesInFlight[connectionId] == nil, !sessionDriverGate.isHeld(key) else {
Self.logger.debug("Ping skipped, the connection is in use for \(connectionId)")
return true
}
guard let mainDriver = activeSessions[connectionId]?.driver else {
Self.logger.debug("Ping skipped, no active driver for \(connectionId)")
return false
}
do {
return try await sessionDriverGate.withExclusiveAccess(key) {
// A switch or a reconnect that held the gate first replaced the driver, which needs no ping.
guard activeSessions[connectionId]?.driver === mainDriver else { return true }
notePinged(mainDriver, for: connectionId)
do {
// Counted as an operation, so a check before use skips instead of pinging the same driver beside it.
try await trackOperation(sessionId: connectionId) {
try await mainDriver.ping()
}
noteAnsweredPing(connectionId, driver: mainDriver)
return true
} catch {
Self.logger.debug("Ping failed for \(connectionId): \(error.publicLogShape, privacy: .public)")
return false
}
}
} catch {
// The gate was drained: the connection is going away, and nothing is left to report.
return true
}
}

/// Starts each running monitor again, so one that stretched its interval while the app was inactive pings on
/// the configured one from now on.
internal func restartHealthMonitors() async {
for connectionId in Array(healthMonitors.keys) {
guard let session = activeSessions[connectionId], session.liveness == .live else { continue }
await startHealthMonitor(for: connectionId)
}
}

internal func healthCheckFailed(_ connectionId: UUID) -> ConnectionHealthMonitor.FailureHandling {
// A monitor someone already stopped reports to nobody: whoever stopped it is dialing.
guard healthMonitors[connectionId] != nil else { return .handedOff }
Expand Down
103 changes: 103 additions & 0 deletions apple/TablePro/Core/Database/DatabaseManager+NetworkPath.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//
// DatabaseManager+NetworkPath.swift
// TablePro
//

import Foundation
import os
import TableProPluginKit
import TableProUtilities

// MARK: - Network path

extension DatabaseManager {
internal var isNetworkPathSatisfied: Bool {
networkPath?.isSatisfied ?? true
}

internal func startObservingNetworkPath() {
guard networkMonitor == nil else { return }
let monitor = ConnectionNetworkMonitor()
networkMonitor = monitor
monitor.start { [weak self] snapshot in
self?.networkPathChanged(to: snapshot)
}
}

/// A path that came back, or moved to other interfaces, wakes every waiting recovery loop so each retries at
/// once, and checks every live session: a socket that crossed the outage can be dead without having said so.
internal func networkPathChanged(to snapshot: NetworkPathSnapshot) {
let previous = networkPath
networkPath = snapshot
guard let previous, snapshot.isSatisfied else { return }
guard !previous.isSatisfied || previous.interfaces != snapshot.interfaces else { return }
Self.logger.info("Network path is back or changed, retrying reconnects and checking sessions")
wakeNetworkChangeWaiters()
Task { [weak self] in
guard let self else { return }
self.forgetAllVerifications()
await self.validateTunneledSessions()
await self.verifyLiveSessions()
}
}

/// Returns when the path next comes back or changes interface, or throws once the caller is cancelled.
internal func waitForNetworkChange() async throws {
let token = UUID()
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
networkChangeWaiters[token] = continuation
}
} onCancel: {
Task { @MainActor [weak self] in
self?.networkChangeWaiters.removeValue(forKey: token)?.resume(throwing: CancellationError())
}
}
}

/// Whether the connection needs the network path. Only one that provably stays on this Mac answers no: a local
/// socket, or a plain network engine whose Host field names loopback, answers with Wi-Fi and Ethernet both off,
/// and its loop must keep dialing. A tunnel, an empty Host (a host list or a seed field) or an engine that
/// reads its address from its own fields may leave the Mac, so it waits for the path.
internal func dialsThroughNetwork(_ connectionId: UUID) -> Bool {
guard let connection = activeSessions[connectionId]?.connection else { return true }
if connection.activeTunnelKind != nil { return true }
if connection.localSocketPath != nil { return false }
guard PluginMetadataRegistry.shared.snapshot(for: connection.type)?.connectionMode == .network else { return true }
return !LoopbackHost.isLoopback(connection.host)
}

/// Sleeps out a retry delay, cut short when the network comes back: the backoff is for a server that refuses,
/// not for a path that was down.
internal func waitBeforeRetry(_ delay: TimeInterval) async throws {
let clock = recoveryClock
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask { try await clock.sleep(for: .seconds(delay)) }
group.addTask { try await self.waitForNetworkChange() }
_ = try await group.next()
group.cancelAll()
}
}

private func wakeNetworkChangeWaiters() {
let waiters = networkChangeWaiters
networkChangeWaiters.removeAll()
for waiter in waiters.values {
waiter.resume()
}
}

/// Asks every live session the check a use would, at once: direct sessions too, which a tunnel check skips.
internal func verifyLiveSessions() async {
let live = activeSessions.filter { $0.value.isConnected && $0.value.liveness == .live }.map(\.key)
await withTaskGroup(of: Void.self) { group in
for connectionId in live {
group.addTask { await self.verifyBeforeUse(connectionId) }
}
}
}
}
20 changes: 14 additions & 6 deletions apple/TablePro/Core/Database/DatabaseManager+Recovery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ extension DatabaseManager {

let maxAttempts = ConnectionRecoveryProgress.maxAttempts
var lastFailure: ConnectionFailureInfo?
for attempt in 1...maxAttempts {
var attempt = 0
while attempt < maxAttempts {
attempt += 1
guard ownsRecovery(token, for: connectionId) else { return }
guard holdsRecoveringSession(connectionId, driver: driver) else {
await yieldRecovery(connectionId, outcome: .success)
Expand All @@ -175,12 +177,16 @@ extension DatabaseManager {
? 0
: ExponentialBackoff.delay(for: attempt, maxDelay: Self.maxRecoveryDelay)
Self.logger.info("Reconnect attempt \(attempt)/\(maxAttempts) in \(delay)s for \(connectionId, privacy: .public)")
if delay > 0 {
do {
try await recoveryClock.sleep(for: .seconds(delay))
} catch {
return
do {
if delay > 0 {
try await waitBeforeRetry(delay)
}
// With no route out, an attempt can only fail, so the loop waits for the path instead of spending one.
while !isNetworkPathSatisfied, dialsThroughNetwork(connectionId) {
try await waitForNetworkChange()
}
} catch {
return
}
guard ownsRecovery(token, for: connectionId) else { return }
guard holdsRecoveringSession(connectionId, driver: driver) else {
Expand Down Expand Up @@ -219,6 +225,8 @@ extension DatabaseManager {
if case .retry(let failure) = outcome {
lastFailure = failure
resumeRecoveryWaiters(connectionId, with: outcome)
// The path went down under the attempt, which says nothing about the server.
if !isNetworkPathSatisfied, dialsThroughNetwork(connectionId) { attempt -= 1 }
continue
}
giveUpRecovery(
Expand Down
17 changes: 16 additions & 1 deletion apple/TablePro/Core/Database/DatabaseManager+SystemEvents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,31 @@ extension DatabaseManager {
name: NSWorkspace.didWakeNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(handleAppDidBecomeActive),
name: NSApplication.didBecomeActiveNotification,
object: nil
)
startObservingNetworkPath()
}

@objc private func handleSystemDidWake(_ notification: Notification) {
Self.logger.info("System woke from sleep, validating tunneled sessions")
Self.logger.info("System woke from sleep, validating sessions")

Task { @MainActor [weak self] in
guard let self else { return }
// The clock moved while nothing observed it, so every answer held predates the sleep.
self.forgetAllVerifications()
await self.validateTunneledSessions()
await self.verifyLiveSessions()
}
}

// A monitor stretched its interval while the app was inactive; starting it again puts back the configured one.
@objc private func handleAppDidBecomeActive(_ notification: Notification) {
Task { @MainActor [weak self] in
await self?.restartHealthMonitors()
}
}

Expand Down
5 changes: 5 additions & 0 deletions apple/TablePro/Core/Database/DatabaseManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ final class DatabaseManager: ObservableObject {

// One reconnect loop per session, owned by DatabaseManager+Recovery.swift.
internal var recoveryLoops: [UUID: SessionRecoveryLoop] = [:]
/// The last network path the monitor reported; satisfied until it says otherwise, as in a test host.
internal var networkPath: NetworkPathSnapshot?
/// Recovery loops waiting for the network path to come back or change, woken together when it does.
internal var networkChangeWaiters: [UUID: CheckedContinuation<Void, Error>] = [:]
internal var networkMonitor: ConnectionNetworkMonitor?
internal let recoveryClock: any Clock<Duration>

/// Why a session was torn down, kept past the session entry so a window that only observes
Expand Down
Loading
Loading