Skip to content
25 changes: 21 additions & 4 deletions apple/TablePro/Core/CloudSQL/CloudSQLProxyManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ actor CloudSQLProxyManager: TunnelManaging {
}

private var tunnels: [UUID: TunnelState] = [:]
private var creations = TunnelCreationGenerations()
private var pidRecords: [UUID: CloudSQLProxyPidRecord] = [:]
private let runnerFactory: () -> any SupervisedProcessRunner
private let managedBinary: @Sendable () async throws -> String
Expand Down Expand Up @@ -65,16 +66,18 @@ actor CloudSQLProxyManager: TunnelManaging {
deadline: ConnectionDeadline = ConnectionDeadline(configuredSeconds: nil)
) async throws -> Int {
guard config.isValid else { throw CloudSQLProxyError.invalidInstanceConnectionName }
let generation = creations.begin(connectionId)
defer { creations.finish(generation, for: connectionId) }
let timeoutEndpoint = ConnectionTimeoutEndpoint.proxy(config.instanceConnectionName)
try deadline.check(endpoint: timeoutEndpoint)

/// A `cloud-sql-proxy` a crashed session left behind still owns the port this is about to
/// ask for, and a configuration with a fixed `localPort` gets exactly one attempt at it.
// A `cloud-sql-proxy` a crashed session left behind still owns the port this is about to
// ask for, and a configuration with a fixed `localPort` gets exactly one attempt at it.
await sweepStalePidsIfNeeded()
try deadline.check(endpoint: timeoutEndpoint)

if tunnels[connectionId] != nil {
try await closeTunnel(connectionId: connectionId)
try await discardTunnel(connectionId: connectionId)
}

let binaryPath = try await resolveBinaryPath(config: config)
Expand Down Expand Up @@ -154,6 +157,12 @@ actor CloudSQLProxyManager: TunnelManaging {
throw error
}

// A newer createTunnel or a close for this connection came while this one dialed, so it must not adopt.
guard creations.isNewest(generation, for: connectionId) else {
runner.stop()
deleteCredentialsFile(at: credentialsFilePath)
throw CancellationError()
}
register(
connectionId: connectionId,
runner: runner,
Expand All @@ -169,7 +178,13 @@ actor CloudSQLProxyManager: TunnelManaging {
throw lastError
}

// Also ends a creation still dialing, so nothing it builds is adopted after the close returned.
func closeTunnel(connectionId: UUID) async throws {
creations.invalidate(connectionId)
try await discardTunnel(connectionId: connectionId)
}

private func discardTunnel(connectionId: UUID) async throws {
guard let state = tunnels.removeValue(forKey: connectionId) else { return }
Self.runnerRegistry.withLock { $0[connectionId] = nil }
pidRecords.removeValue(forKey: connectionId)
Expand All @@ -180,6 +195,7 @@ actor CloudSQLProxyManager: TunnelManaging {
}

func closeAllTunnels() async {
creations.invalidateAll()
let current = tunnels
tunnels.removeAll()
pidRecords.removeAll()
Expand Down Expand Up @@ -368,7 +384,8 @@ actor CloudSQLProxyManager: TunnelManaging {
throw CloudSQLProxyError.credentialsWriteFailed
}
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("\(Self.credentialsFilePrefix)\(connectionId.uuidString).json")
// One file per creation: two creations for one connection would otherwise share and delete one path.
.appendingPathComponent("\(Self.credentialsFilePrefix)\(connectionId.uuidString)-\(UUID().uuidString).json")
do {
try data.write(to: url, options: .atomic)
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
Expand Down
23 changes: 18 additions & 5 deletions apple/TablePro/Core/Cloudflare/CloudflareTunnelManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ actor CloudflareTunnelManager: TunnelManaging {
}

private var tunnels: [UUID: TunnelState] = [:]
private var creations = TunnelCreationGenerations()
private var pidRecords: [UUID: CloudflaredPidRecord] = [:]
private let runnerFactory: () -> any SupervisedProcessRunner
private var staleSweep: Task<Void, Never>?
Expand All @@ -43,24 +44,24 @@ actor CloudflareTunnelManager: TunnelManaging {
self.reaperTimings = reaperTimings
}

/// Create a Cloudflare Access TCP tunnel for a database connection.
/// Returns the local loopback port the database driver should connect to.
func createTunnel(
connectionId: UUID,
config: CloudflareConfiguration,
tokenId: String? = nil,
tokenSecret: String? = nil,
deadline: ConnectionDeadline = ConnectionDeadline(configuredSeconds: nil)
) async throws -> Int {
let generation = creations.begin(connectionId)
defer { creations.finish(generation, for: connectionId) }
let timeoutEndpoint = ConnectionTimeoutEndpoint.tunnel(config.accessHostname)
try deadline.check(endpoint: timeoutEndpoint)
/// A `cloudflared` a crashed session left behind still owns the port this is about to ask
/// for, and a configuration with a fixed `localPort` gets exactly one attempt at it.
// A `cloudflared` a crashed session left behind still owns the port this is about to ask
// for, and a configuration with a fixed `localPort` gets exactly one attempt at it.
await sweepStalePidsIfNeeded()
try deadline.check(endpoint: timeoutEndpoint)

if tunnels[connectionId] != nil {
try await closeTunnel(connectionId: connectionId)
try await discardTunnel(connectionId: connectionId)
}

let binaryPath = try resolveBinaryPath(config: config)
Expand Down Expand Up @@ -114,6 +115,11 @@ actor CloudflareTunnelManager: TunnelManaging {
throw error
}

// A newer createTunnel or a close for this connection came while this one dialed, so it must not adopt.
guard creations.isNewest(generation, for: connectionId) else {
runner.stop()
throw CancellationError()
}
register(connectionId: connectionId, runner: runner, port: port, binaryPath: binaryPath)
Self.logger.info("Cloudflare tunnel ready for \(connectionId.uuidString, privacy: .public) on 127.0.0.1:\(port)")
return port
Expand All @@ -122,7 +128,13 @@ actor CloudflareTunnelManager: TunnelManaging {
throw lastError
}

// Also ends a creation still dialing, so nothing it builds is adopted after the close returned.
func closeTunnel(connectionId: UUID) async throws {
creations.invalidate(connectionId)
try await discardTunnel(connectionId: connectionId)
}

private func discardTunnel(connectionId: UUID) async throws {
guard let state = tunnels.removeValue(forKey: connectionId) else { return }
Self.runnerRegistry.withLock { $0[connectionId] = nil }
pidRecords.removeValue(forKey: connectionId)
Expand All @@ -132,6 +144,7 @@ actor CloudflareTunnelManager: TunnelManaging {
}

func closeAllTunnels() async {
creations.invalidateAll()
let current = tunnels
tunnels.removeAll()
pidRecords.removeAll()
Expand Down
53 changes: 53 additions & 0 deletions apple/TablePro/Core/DataWrite/Rewind/RewindAvailability.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//
// RewindAvailability.swift
// TablePro
//

import Combine
import Foundation

struct RewindAvailability: Equatable, Sendable {
struct Target: Hashable, Sendable {
let connectionId: UUID
let database: String
let schema: String?
let table: String
}

let revision: Int
let targets: Set<Target>
let historyIds: Set<UUID>

static let empty = RewindAvailability(revision: -1, targets: [], historyIds: [])
}

// Menu and toolbar validation is synchronous, so the main actor keeps the history actor's last answer.
@MainActor
final class RewindAvailabilityCache: ObservableObject {
@Published private(set) var availability = RewindAvailability.empty

nonisolated init(storage: QueryHistoryStorage) {
// Weak, so the subscription never keeps the store alive: its deinit finishes the stream.
Task { @MainActor [weak self, weak storage] in
guard let updates = await storage?.rewindAvailabilityUpdates() else { return }
for await next in updates {
guard let self else { return }
adopt(next)
}
}
}

func hasSnapshot(for target: RewindAvailability.Target) -> Bool {
availability.targets.contains(target)
}

func hasSnapshot(forHistoryId historyId: UUID) -> Bool {
availability.historyIds.contains(historyId)
}

// Readings can reach the main actor out of order, so only a newer revision replaces the current one.
func adopt(_ next: RewindAvailability) {
guard next.revision > availability.revision else { return }
availability = next
}
}
82 changes: 79 additions & 3 deletions apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,27 @@ internal actor DatabaseAccessBridge {

internal func disconnect(connectionId: UUID) async throws {
let manager = await databaseManager
let sessionExists = await MainActor.run {
manager.activeSessions[connectionId] != nil
try await Self.disconnectUnlessWorkIsLost(connectionId, manager: manager)
}

// TablePro asks the user before a disconnect that loses work; a caller that is not a person gets a refusal.
@MainActor
private static func disconnectUnlessWorkIsLost(_ connectionId: UUID, manager: DatabaseManager) async throws {
guard manager.activeSessions[connectionId] != nil else { throw DatabaseAccessError.notConnected(connectionId) }
let turnRevisionBefore = manager.sessionTransactions.turnRevision(for: connectionId)
let probed = await manager.transactionSafety(for: connectionId)
// Read after the probe and with no suspension before the disconnect, so work that started meanwhile counts.
guard manager.activeSessions[connectionId] != nil else { throw DatabaseAccessError.notConnected(connectionId) }
let transactions = manager.settledTransactionSafety(
probed, for: connectionId, turnRevisionBefore: turnRevisionBefore
)
if let refusal = ExternalDisconnectRefusal.message(
work: RunningWorkRegistry.shared.items(in: .connection(connectionId)),
transactions: transactions,
hasUnsavedWork: MainContentCoordinator.hasUnsavedWork(forConnection: connectionId)
) {
throw DatabaseAccessError.forbidden(refusal)
}
guard sessionExists else { throw DatabaseAccessError.notConnected(connectionId) }
await manager.disconnectSession(connectionId)
}

Expand Down Expand Up @@ -694,3 +711,62 @@ internal actor DatabaseAccessBridge {
internal protocol StatementCancellationSignal: Sendable {
func onCancelRequested(_ handler: @escaping @Sendable () async -> Void) async
}

// Kinds only: a line naming the work could name a tab, a file or another connection the caller cannot see.
@MainActor
internal enum ExternalDisconnectRefusal {
internal enum Loss: Hashable, CaseIterable {
case query
case transfer
case agentReply
case comparison
case transaction
case unsavedChanges

internal var noun: String {
switch self {
case .query: return String(localized: "a running query")
case .transfer: return String(localized: "an import, export, backup, restore or copy")
case .agentReply: return String(localized: "an agent reply")
case .comparison: return String(localized: "a comparison or sync")
case .transaction: return String(localized: "an open transaction")
case .unsavedChanges: return String(localized: "unsaved changes")
}
}
}

internal static func message(
work: [RunningWork],
transactions: SessionTransactionSafety,
hasUnsavedWork: Bool
) -> String? {
var losses = Set(work.map { loss(for: $0.kind) })
if transactions == .holding { losses.insert(.transaction) }
if hasUnsavedWork { losses.insert(.unsavedChanges) }
if let message = message(for: losses) { return message }
guard transactions == .unknown else { return nil }
return String(
localized: "TablePro cannot tell whether this connection holds an open transaction, so it stays connected. Try again once its work is done, or disconnect in TablePro."
)
}

internal static func message(for losses: Set<Loss>) -> String? {
let nouns = Loss.allCases.filter { losses.contains($0) }.map { $0.noun }
guard !nouns.isEmpty else { return nil }
return String(
format: String(
localized: "This connection has %@ in TablePro, which disconnecting would stop or discard. Finish it first, or disconnect in TablePro, which asks the user."
),
ListFormatter.localizedString(byJoining: nouns)
)
}

private static func loss(for kind: RunningWorkKind) -> Loss {
switch kind {
case .query: return .query
case .restore, .dataImport, .dataExport, .backup, .tableTransfer, .objectCopy: return .transfer
case .agentReply: return .agentReply
case .compareRun, .compareApply: return .comparison
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,57 @@ extension DatabaseManager {
return holding
}

// Unlike the probe above, a busy session, a timeout or an engine that cannot say is never read as safe.
// The probe suspends, so a lane can take a turn meanwhile; what the tracker learned since, or a turn still
// running, outranks a stale idle answer.
internal func settledTransactionSafety(
_ probed: SessionTransactionSafety,
for connectionId: UUID,
turnRevisionBefore: Int
) -> SessionTransactionSafety {
guard activeSessions[connectionId]?.driver?.supportsTransactions ?? true else { return probed }
if probed == .holding || !sessionTransactions.holds(for: connectionId).isEmpty { return .holding }
guard probed == .noTransaction else { return probed }
let laneKeys = [browsedGateKey(for: connectionId)] + sessionLanes.parkedDatabases(for: connectionId).map {
SessionDriverGate.Key(connectionId: connectionId, database: $0)
}
if laneKeys.contains(where: { sessionDriverGate.isHeld($0) }) { return .unknown }
return sessionTransactions.turnRevision(for: connectionId) == turnRevisionBefore ? .noTransaction : .unknown
}

internal func transactionSafety(
for connectionId: UUID,
clock: any Clock<Duration> = ContinuousClock()
) async -> SessionTransactionSafety {
guard let session = activeSessions[connectionId] else { return .noTransaction }
guard session.driver?.supportsTransactions ?? true else { return .noTransaction }
var drivers: [DatabaseDriver] = []
var isBusy = false
if let driver = session.driver {
if sessionDriverGate.isHeld(browsedGateKey(for: connectionId)) { isBusy = true } else { drivers.append(driver) }
}
for database in sessionLanes.parkedDatabases(for: connectionId).sorted() {
guard let driver = sessionLanes.parkedDriver(for: connectionId, database: database) else { continue }
let key = SessionDriverGate.Key(connectionId: connectionId, database: database)
if sessionDriverGate.isHeld(key) { isBusy = true } else { drivers.append(driver) }
}
let reads = drivers.map { driver in Task { await Self.boundedTransactionState(of: driver, clock: clock) } }
var safety: SessionTransactionSafety = isBusy ? .unknown : .noTransaction
for read in reads {
switch await read.value {
case .inTransaction, .abortedTransaction:
safety = .holding
case .idle, .holdsSessionLocks:
break
case .unknown:
if safety == .noTransaction { safety = .unknown }
@unknown default:
if safety == .noTransaction { safety = .unknown }
}
}
return safety
}

/// Ends the transaction a hold shows, on the connection that holds it. Refused when that
/// connection was replaced, or when other work ran there after the hold was read: the user
/// confirmed what they saw, not a transaction someone opened since.
Expand Down Expand Up @@ -122,3 +173,10 @@ internal enum SessionTransactionActionError: Error, LocalizedError, Equatable {
}
}
}

internal enum SessionTransactionSafety: Equatable, Sendable {
case noTransaction
case holding
// Busy, timed out, or an engine that cannot report its transaction state.
case unknown
}
7 changes: 7 additions & 0 deletions apple/TablePro/Core/Database/SessionTransactionTracker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ internal final class SessionTransactionTracker: ObservableObject {
return states.isEmpty ? nil : .open
}

// Moves with every turn recorded on any of the connection's lanes.
internal func turnRevision(for connectionId: UUID) -> Int {
revisions.reduce(0) { total, entry in
entry.key.connectionId == connectionId ? total &+ entry.value : total
}
}

internal func driver(for hold: Hold) -> DatabaseDriver? {
guard let entry = drivers[hold.key], let driver = entry.driver as? DatabaseDriver else { return nil }
return driver
Expand Down
Loading
Loading