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
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ public final class ConnectionManager: @unchecked Sendable {
let driver = try driverFactory.createDriver(
for: effectiveConnection,
password: password,
preTunnelHost: preTunnelHost
preTunnelHost: preTunnelHost,
refreshPassword: Self.passwordRefresh(
for: connection, stored: stored, factory: driverFactory, secureStore: secureStore
)
)
try await driver.connect()

Expand Down Expand Up @@ -407,6 +410,16 @@ public final class ConnectionManager: @unchecked Sendable {
return catalogs[connectionId] === connection
}

// Resolves for the connection as saved: behind a tunnel the driver's own connection names the loopback.
private static func passwordRefresh(
for saved: DatabaseConnection,
stored: String?,
factory: DriverFactory,
secureStore: SecureStore
) -> @Sendable () async throws -> String? {
{ try await factory.resolvePassword(for: saved, stored: stored, secureStore: secureStore) }
}

private static func openCatalogDriver(
dial: SessionDial,
database: String,
Expand All @@ -420,7 +433,12 @@ public final class ConnectionManager: @unchecked Sendable {
// An IAM token is minted for the saved host and expires, so each catalog connection gets its own.
let stored = try secureStore.retrieve(forKey: passwordKey(for: dial.saved.id))
let password = try await factory.resolvePassword(for: dial.saved, stored: stored, secureStore: secureStore)
let driver = try factory.createDriver(for: target, password: password, preTunnelHost: dial.preTunnelHost)
let driver = try factory.createDriver(
for: target,
password: password,
preTunnelHost: dial.preTunnelHost,
refreshPassword: passwordRefresh(for: dial.saved, stored: stored, factory: factory, secureStore: secureStore)
)
try await driver.connect()
do {
try await factory.prepareCatalogDriver(driver, for: target)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ public extension DriverFactory {
try createDriver(for: connection, password: password)
}

func createDriver(
for connection: DatabaseConnection,
password: String?,
preTunnelHost: String?,
refreshPassword: (@Sendable () async throws -> String?)?
) throws -> any DatabaseDriver {
try createDriver(for: connection, password: password, preTunnelHost: preTunnelHost)
}

func resolvePassword(
for connection: DatabaseConnection,
stored: String?,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ public protocol DriverFactory: Sendable {
password: String?,
preTunnelHost: String?
) throws -> any DatabaseDriver
// `refreshPassword` resolves the password again for the connection as saved, whose endpoint a tunnel hides from
// `connection`. A driver that signs in a second time later, such as to stop a statement, calls it once a minted
// token may have expired.
func createDriver(
for connection: DatabaseConnection,
password: String?,
preTunnelHost: String?,
refreshPassword: (@Sendable () async throws -> String?)?
) throws -> any DatabaseDriver
// Runs before the tunnel, on the connection as saved, so a sign-in failure comes before any SSH prompt.
func resolvePassword(
for connection: DatabaseConnection,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ private struct DriverRequest: Sendable {
let port: Int
let password: String?
let preTunnelHost: String?
let refreshPassword: (@Sendable () async throws -> String?)?
}

private final class SigningDriverFactory: DriverFactory, @unchecked Sendable {
var mint: @Sendable (String?) async throws -> String? = { stored in stored }
var opensCatalogs = false
private(set) var mintRequests: [MintRequest] = []
private(set) var driverRequests: [DriverRequest] = []

Expand All @@ -43,17 +45,29 @@ private final class SigningDriverFactory: DriverFactory, @unchecked Sendable {
for connection: DatabaseConnection,
password: String?,
preTunnelHost: String?
) throws -> any DatabaseDriver {
try createDriver(for: connection, password: password, preTunnelHost: preTunnelHost, refreshPassword: nil)
}

func createDriver(
for connection: DatabaseConnection,
password: String?,
preTunnelHost: String?,
refreshPassword: (@Sendable () async throws -> String?)?
) throws -> any DatabaseDriver {
driverRequests.append(DriverRequest(
host: connection.host,
port: connection.port,
password: password,
preTunnelHost: preTunnelHost
preTunnelHost: preTunnelHost,
refreshPassword: refreshPassword
))
return MockDatabaseDriver()
}

func supportedTypes() -> [DatabaseType] { [mockType] }

func opensCatalogConnections(for connection: DatabaseConnection) -> Bool { opensCatalogs }
}

private final class PasswordRecordingFactory: DriverFactory, @unchecked Sendable {
Expand Down Expand Up @@ -179,6 +193,52 @@ struct ConnectionManagerSignInTests {
#expect(driver.preTunnelHost == connection.host)
}

@Test("Through a tunnel, a driver signing in again later mints for the saved endpoint, not the tunnel's")
func tunneledRefreshMintsForTheSavedEndpoint() async throws {
let factory = SigningDriverFactory()
let manager = ConnectionManager(
driverFactory: factory,
secureStore: MockSecureStore(),
sshProvider: MockSSHProvider()
)
let connection = rdsConnection(tunneled: true)
_ = try await manager.connect(connection)
let refresh = try #require(factory.driverRequests.first?.refreshPassword)
factory.mint = { _ in "fresh-token" }

let token = try await refresh()

let mint = try #require(factory.mintRequests.last)
#expect(token == "fresh-token")
#expect(factory.mintRequests.count == 2)
#expect(mint.host == connection.host)
#expect(mint.port == connection.port)
}

@Test("A catalog connection behind a tunnel mints again for the saved endpoint too")
func tunneledCatalogRefreshMintsForTheSavedEndpoint() async throws {
let factory = SigningDriverFactory()
factory.opensCatalogs = true
let manager = ConnectionManager(
driverFactory: factory,
secureStore: MockSecureStore(),
sshProvider: MockSSHProvider()
)
let connection = rdsConnection(tunneled: true)
_ = try await manager.connect(connection)
_ = try #require(await manager.catalogDriver(for: connection.id, database: ""))
let catalog = try #require(factory.driverRequests.last)
let refresh = try #require(catalog.refreshPassword)

_ = try await refresh()

let mint = try #require(factory.mintRequests.last)
#expect(factory.driverRequests.count == 2)
#expect(catalog.host == "127.0.0.1")
#expect(mint.host == connection.host)
#expect(mint.port == connection.port)
}

@Test("Without a tunnel, the driver dials the saved host and gets no preTunnelHost")
func directConnectHasNoPreTunnelHost() async throws {
let factory = SigningDriverFactory()
Expand Down
12 changes: 12 additions & 0 deletions apple/TableProMobile/TableProMobile/CBridges/CMariaDB/CMariaDB.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@
#undef MARIADB_TLS
#include <ma_tls.h>

// MYSQL_OPT_READ_TIMEOUT is read once at connect, so a live session's socket timeout is set on its pvio. 0 is none.
static inline my_bool tablepro_mysql_set_io_timeout(MYSQL *mysql, unsigned int seconds) {
if (mysql == NULL || mysql->net.pvio == NULL) {
return 1;
}
mysql->options.read_timeout = seconds;
mysql->options.write_timeout = seconds;
my_bool read_result = ma_pvio_set_timeout(mysql->net.pvio, PVIO_READ_TIMEOUT, (int)seconds);
my_bool write_result = ma_pvio_set_timeout(mysql->net.pvio, PVIO_WRITE_TIMEOUT, (int)seconds);
return read_result || write_result;
}

// The server name a tunneled connection's certificate is checked against, kept as handle user data.
static const char *const tablepro_mysql_server_name_key = "com.TablePro.tls.serverName";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,10 @@ final class ConnectionCoordinator {
case duringWork
// The transaction is gone either way, which is what was asked for.
case duringRollBack
// The app closed a database file as it went to the background, which rolled the transaction back.
case inBackground
// The app closed the file once a running statement ended, and that statement may have ended the transaction.
case inBackgroundAfterStatement
}

// True when the redial dropped a held transaction and the outcome is already settled for the user.
Expand Down Expand Up @@ -405,7 +409,10 @@ final class ConnectionCoordinator {
}

workWasRunning = workWasRunning || appState.sessionTransactions.isRunningStatements(connection.id)
let heldTransaction = transactionHold != nil
let ended = appState.sessionTransactions.endedHold(for: connection.id, on: held?.driver)
workWasRunning = workWasRunning || ended?.duringWork == true
let heldTransaction = transactionHold != nil || ended != nil
let released = ended.flatMap { releasedLoss($0, on: held, asked: loss) }
isReconnecting = true
defer { isReconnecting = false }
do {
Expand All @@ -419,12 +426,12 @@ final class ConnectionCoordinator {
guard attemptToken == token else { return false }
await takeSession(outcome.session, token: token, dialedHere: outcome.dialedHere)
guard attemptToken == token else { return false }
let dropped = heldTransaction ? settledLoss(loss, workWasRunning: workWasRunning) : unsettledLoss
let dropped = heldTransaction ? released ?? settledLoss(loss, workWasRunning: workWasRunning) : unsettledLoss
return reportDroppedTransaction(dropped)
} catch {
guard attemptToken == token else { return false }
if heldTransaction {
unsettledLoss = settledLoss(loss, workWasRunning: workWasRunning)
unsettledLoss = released ?? settledLoss(loss, workWasRunning: workWasRunning)
}
phase = .lost(classify(error, operation: "reconnect"))
self.session = nil
Expand All @@ -436,6 +443,17 @@ final class ConnectionCoordinator {
workWasRunning || statementFailedDuringCheck ? .duringWork : loss
}

// The release closed the file once its running statement ended, so a later failure on the closed file decides nothing.
private func releasedLoss(
_ ended: SessionTransactionMonitor.EndedHold,
on held: ConnectionSession?,
asked loss: SessionLoss
) -> SessionLoss? {
guard held?.driver.holdsSuspensionBlockingResource == true else { return nil }
if ended.duringWork { return .inBackgroundAfterStatement }
return loss == .duringRollBack ? .duringRollBack : .inBackground
}

// True when the transaction a redial ended is settled for the user.
@discardableResult
private func reportDroppedTransaction(_ loss: SessionLoss?) -> Bool {
Expand Down Expand Up @@ -685,6 +703,20 @@ final class ConnectionCoordinator {
)
case .duringRollBack:
nil
case .inBackground:
String(
format: String(
localized: "TablePro closed %@ when it went to the background, which rolled back its open transaction. It has been reopened; run the statements again, and commit before you leave the app."
),
connectionName
)
case .inBackgroundAfterStatement:
String(
format: String(
localized: "TablePro closed %@ when it went to the background while a statement was running, so its open transaction may have been committed or rolled back. It has been reopened; check which of its changes were saved before running them again."
),
connectionName
)
}
}

Expand Down
Loading
Loading