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 @@ -79,7 +79,8 @@ final class ConnectionSessionModel {
@ObservationIgnored private var placementEpoch = 0
@ObservationIgnored private var switchesInFlight = 0
@ObservationIgnored private var placementRestored = false
@ObservationIgnored private var rememberedDatabaseHung = false
// Why the last dial into the remembered database failed with no fallback; the next open starts from the saved one.
@ObservationIgnored private var rememberedDialFailure: (any Error)?
@ObservationIgnored private var scenes: [WeakScene] = []

private let appState: AppState
Expand Down Expand Up @@ -136,6 +137,11 @@ final class ConnectionSessionModel {
record.type == .postgresql || record.type == .redshift
}

// MySQL, MariaDB and TiDB sign in apart from the database; SQL Server signs contained users in to the named one.
private var dialsRememberedDatabase: Bool {
redialsToSwitchDatabase || record.type == .mysql || record.type == .mariadb || record.type == .tidb
}

func adopt(_ record: DatabaseConnection) {
guard record.id == self.record.id, record != self.record else { return }
self.record = record
Expand Down Expand Up @@ -271,6 +277,10 @@ final class ConnectionSessionModel {
// The record changed how it dials, so the next window opens it again.
func reset() {
let attempt = state.attempt
// What failed was the old record's dial.
if !redialsToSwitchDatabase {
rememberedDialFailure = nil
}
enter(.cancel)
if attempt?.purpose == .open { attempt?.task?.cancel() }
leaveDial()
Expand Down Expand Up @@ -320,34 +330,43 @@ final class ConnectionSessionModel {
do {
let saved = record
// A remembered database that never answered may hang again, so the next open starts from the saved one and
// switches after, as opens did before.
let target = rememberedDatabaseHung ? record : openTarget(restoring: wanted)
rememberedDatabaseHung = false
// switches after, as opens did before. A USE engine does so after any failure it could not fall back from.
let failedBefore = rememberedDialFailure
rememberedDialFailure = nil
let target = failedBefore == nil ? openTarget(restoring: wanted) : record
let landed: OpenLanding
var restoring = wanted
var refused: RefusedDatabase?
// The saved database's list then says whether the remembered one is gone, as after a refused dial.
if let failedBefore, !redialsToSwitchDatabase, !wanted.database.isEmpty, wanted.database != saved.database {
refused = RefusedDatabase(name: wanted.database, error: failedBefore, reportedBySwitch: true)
}
do {
landed = try await dialForOpen(
target, schema: schemaRestored(by: target, restoring: wanted), by: attempt, joining: allowSignIn
)
} catch let thrown {
let listRefused = thrown as? TableListRefused
let error = listRefused?.error ?? thrown
if target.database != saved.database, case PostgreSQLError.unreachable = error {
rememberedDatabaseHung = true
if target.database != saved.database,
startsNextOpenFromSaved(after: error, listRefused: listRefused != nil, by: attempt) {
rememberedDialFailure = error
}
// A sign-in is the connection's, not the database's: the saved database would fail the same way.
guard target.database != saved.database, isCurrent(attempt),
listRefused != nil || Self.mayBlameDatabase(error),
listRefused != nil || blamesDatabase(error),
SignInOffer.method(for: error, connection: saved, secureStore: appState.secureStore) == nil
else { throw error }
Self.logger.warning("Failed to open remembered database \(target.database, privacy: .private(mask: .hash)): \(LogRedaction.publicDescription(of: error), privacy: .public) \(error.localizedDescription, privacy: .private)")
// A dial that landed and then refused its table list leaves a session to tear down first.
await appState.connectionManager.disconnect(connectionId)
guard isCurrent(attempt) else { return }
landed = try await dialForOpen(saved, schema: nil, by: attempt, joining: false)
restoring.database = saved.database
refused = RefusedDatabase(name: target.database, error: error)
// A USE engine still moves there with USE, which says why it fails, as its open always did.
if redialsToSwitchDatabase {
restoring.database = saved.database
}
refused = RefusedDatabase(name: target.database, error: error, reportedBySwitch: !redialsToSwitchDatabase)
}
guard isCurrent(attempt) else { return }
let newSession = landed.outcome.session
Expand Down Expand Up @@ -391,11 +410,9 @@ final class ConnectionSessionModel {
}
}

// Where the connection was, so the first table list is already the right one. Only PostgreSQL and Redshift, which
// need a second connection to change database. The others dial the saved one and move with USE, as before, so their
// refusals, which the app cannot always tell apart from a failed sign-in, never decide between two dials.
// Where the connection was, so the first table list is already the right one.
private func openTarget(restoring wanted: Placement) -> DatabaseConnection {
guard redialsToSwitchDatabase, !wanted.database.isEmpty else { return record }
guard dialsRememberedDatabase, !wanted.database.isEmpty else { return record }
var target = record
target.database = wanted.database
return target
Expand All @@ -419,6 +436,8 @@ final class ConnectionSessionModel {
private struct RefusedDatabase {
let name: String
let error: any Error
// The open's own USE tried it again and said why that failed.
let reportedBySwitch: Bool
}

nonisolated private struct TableListRefused: Error {
Expand All @@ -440,6 +459,22 @@ final class ConnectionSessionModel {
return !notAboutTheDatabase.contains { message.contains($0) }
}

// The MySQL driver types a refused database by its code.
private func blamesDatabase(_ error: any Error) -> Bool {
if redialsToSwitchDatabase { return Self.mayBlameDatabase(error) }
if case MySQLError.databaseRefused = error { return true }
return false
}

// A USE engine's other failure may still be the database's on a server that numbers it its own way.
private func startsNextOpenFromSaved(after error: any Error, listRefused: Bool, by attempt: ConnectionAttempt) -> Bool {
if redialsToSwitchDatabase {
if case PostgreSQLError.unreachable = error { return true }
return false
}
return isCurrent(attempt) && !listRefused && !blamesDatabase(error) && !(error is CancellationError)
}

private nonisolated static let notAboutTheDatabase = [
"password authentication failed", "authentication failed", "fe_sendauth", "no password supplied",
"could not connect", "connection refused", "timeout expired", "timed out", "could not translate host name",
Expand Down Expand Up @@ -502,6 +537,7 @@ final class ConnectionSessionModel {
reportingTo scene: ConnectionCoordinator?
) {
guard let listed, !listed.contains(refused.name) else {
guard !refused.reportedBySwitch else { return }
scene?.presentFailure(
title: ConnectionCoordinator.switchDatabaseFailedTitle,
message: classify(refused.error, operation: "switchDatabase").message
Expand Down
20 changes: 17 additions & 3 deletions apple/TableProMobile/TableProMobile/Drivers/MySQLDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,13 @@ nonisolated final class MySQLDriver: DatabaseDriver, SessionDatabaseReporting, @
}
}

// The sign-in went through and the database was refused as a USE there is (scripts/probes/check-mysql-dial-database-refusal.sh).
nonisolated enum MySQLDatabaseRefusal {
static func isRefusal(code: UInt32) -> Bool {
code == 1_044 || code == 1_049
}
}

nonisolated enum MySQLTokenSignIn {
// A token session refuses a server without TLS before the token is sent; this names that refusal.
static func connectFailure(
Expand Down Expand Up @@ -735,8 +742,13 @@ private actor MySQLActor {
) {
throw tokenFailure
}
throw MariaDBSSLClassifier.classifySSLError(code: failure.code, message: failure.message)
?? MySQLError.connectionFailed(failure.message)
if let tlsFailure = MariaDBSSLClassifier.classifySSLError(code: failure.code, message: failure.message) {
throw tlsFailure
}
if MySQLDatabaseRefusal.isRefusal(code: failure.code) {
throw MySQLError.databaseRefused(failure.message)
}
throw MySQLError.connectionFailed(failure.message)
}

guard MariaDBCharacterSet.establishSession(on: handle, encoding: encoding) else {
Expand Down Expand Up @@ -1258,13 +1270,15 @@ nonisolated private struct RawMySQLResult: Sendable {

nonisolated enum MySQLError: Error, LocalizedError {
case connectionFailed(String)
// The database the handshake named was refused; it reads as any failed connect.
case databaseRefused(String)
case notConnected
case queryFailed(String)
case unsupported(String)

var errorDescription: String? {
switch self {
case .connectionFailed(let msg): return "MySQL connection failed: \(msg)"
case .connectionFailed(let msg), .databaseRefused(let msg): return "MySQL connection failed: \(msg)"
case .notConnected: return "Not connected to MySQL database"
case .queryFailed(let msg): return "MySQL query failed: \(msg)"
case .unsupported(let msg): return msg
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,13 @@ struct ConnectionCoordinatorStatusTests {
#expect(ranUpdate(second))
}

// An open dials the remembered database first; this one refuses it as a dropped database.
private func goneStagingDriver() -> MockDatabaseDriver {
let gone = driver()
gone.connectError = MySQLError.databaseRefused("Unknown database 'app_staging'")
return gone
}

// A window on app_staging whose redial failed; `beforeLoss` runs while it is still connected.
private func lostOnStaging(
beforeLoss: (ConnectionCoordinator) -> Void = { _ in }
Expand All @@ -450,8 +457,9 @@ struct ConnectionCoordinatorStatusTests {
return coordinator
}

// Another window opens the connection, which dials the saved app_prod.
// Another window opens the connection once app_staging is gone, so it lands on the saved app_prod.
private func reconnectAnotherWindow() async -> MockDatabaseDriver {
factory.queue(goneStagingDriver())
let second = driver(tables: ["orders"])
factory.queue(second)
await ConnectionCoordinator(connection: connection, appState: appState).connect()
Expand Down Expand Up @@ -497,6 +505,7 @@ struct ConnectionCoordinatorStatusTests {
let second = driver(tables: ["orders"])
let loading = TestGate()
second.beforeFetchTables = { await loading.enter() }
factory.queue(goneStagingDriver())
factory.queue(second)
let other = ConnectionCoordinator(connection: connection, appState: appState)

Expand Down
Loading
Loading