Skip to content

Commit e012dde

Browse files
authored
perf(ios): open a MySQL, MariaDB or TiDB connection straight into the database it was last on (#4252)
1 parent 1274fa2 commit e012dde

8 files changed

Lines changed: 573 additions & 27 deletions

File tree

‎apple/TableProMobile/TableProMobile/Coordinators/ConnectionSessionModel.swift‎

Lines changed: 49 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ final class ConnectionSessionModel {
7979
@ObservationIgnored private var placementEpoch = 0
8080
@ObservationIgnored private var switchesInFlight = 0
8181
@ObservationIgnored private var placementRestored = false
82-
@ObservationIgnored private var rememberedDatabaseHung = false
82+
// Why the last dial into the remembered database failed with no fallback; the next open starts from the saved one.
83+
@ObservationIgnored private var rememberedDialFailure: (any Error)?
8384
@ObservationIgnored private var scenes: [WeakScene] = []
8485

8586
private let appState: AppState
@@ -136,6 +137,11 @@ final class ConnectionSessionModel {
136137
record.type == .postgresql || record.type == .redshift
137138
}
138139

140+
// MySQL, MariaDB and TiDB sign in apart from the database; SQL Server signs contained users in to the named one.
141+
private var dialsRememberedDatabase: Bool {
142+
redialsToSwitchDatabase || record.type == .mysql || record.type == .mariadb || record.type == .tidb
143+
}
144+
139145
func adopt(_ record: DatabaseConnection) {
140146
guard record.id == self.record.id, record != self.record else { return }
141147
self.record = record
@@ -271,6 +277,10 @@ final class ConnectionSessionModel {
271277
// The record changed how it dials, so the next window opens it again.
272278
func reset() {
273279
let attempt = state.attempt
280+
// What failed was the old record's dial.
281+
if !redialsToSwitchDatabase {
282+
rememberedDialFailure = nil
283+
}
274284
enter(.cancel)
275285
if attempt?.purpose == .open { attempt?.task?.cancel() }
276286
leaveDial()
@@ -320,34 +330,43 @@ final class ConnectionSessionModel {
320330
do {
321331
let saved = record
322332
// A remembered database that never answered may hang again, so the next open starts from the saved one and
323-
// switches after, as opens did before.
324-
let target = rememberedDatabaseHung ? record : openTarget(restoring: wanted)
325-
rememberedDatabaseHung = false
333+
// switches after, as opens did before. A USE engine does so after any failure it could not fall back from.
334+
let failedBefore = rememberedDialFailure
335+
rememberedDialFailure = nil
336+
let target = failedBefore == nil ? openTarget(restoring: wanted) : record
326337
let landed: OpenLanding
327338
var restoring = wanted
328339
var refused: RefusedDatabase?
340+
// The saved database's list then says whether the remembered one is gone, as after a refused dial.
341+
if let failedBefore, !redialsToSwitchDatabase, !wanted.database.isEmpty, wanted.database != saved.database {
342+
refused = RefusedDatabase(name: wanted.database, error: failedBefore, reportedBySwitch: true)
343+
}
329344
do {
330345
landed = try await dialForOpen(
331346
target, schema: schemaRestored(by: target, restoring: wanted), by: attempt, joining: allowSignIn
332347
)
333348
} catch let thrown {
334349
let listRefused = thrown as? TableListRefused
335350
let error = listRefused?.error ?? thrown
336-
if target.database != saved.database, case PostgreSQLError.unreachable = error {
337-
rememberedDatabaseHung = true
351+
if target.database != saved.database,
352+
startsNextOpenFromSaved(after: error, listRefused: listRefused != nil, by: attempt) {
353+
rememberedDialFailure = error
338354
}
339355
// A sign-in is the connection's, not the database's: the saved database would fail the same way.
340356
guard target.database != saved.database, isCurrent(attempt),
341-
listRefused != nil || Self.mayBlameDatabase(error),
357+
listRefused != nil || blamesDatabase(error),
342358
SignInOffer.method(for: error, connection: saved, secureStore: appState.secureStore) == nil
343359
else { throw error }
344360
Self.logger.warning("Failed to open remembered database \(target.database, privacy: .private(mask: .hash)): \(LogRedaction.publicDescription(of: error), privacy: .public) \(error.localizedDescription, privacy: .private)")
345361
// A dial that landed and then refused its table list leaves a session to tear down first.
346362
await appState.connectionManager.disconnect(connectionId)
347363
guard isCurrent(attempt) else { return }
348364
landed = try await dialForOpen(saved, schema: nil, by: attempt, joining: false)
349-
restoring.database = saved.database
350-
refused = RefusedDatabase(name: target.database, error: error)
365+
// A USE engine still moves there with USE, which says why it fails, as its open always did.
366+
if redialsToSwitchDatabase {
367+
restoring.database = saved.database
368+
}
369+
refused = RefusedDatabase(name: target.database, error: error, reportedBySwitch: !redialsToSwitchDatabase)
351370
}
352371
guard isCurrent(attempt) else { return }
353372
let newSession = landed.outcome.session
@@ -391,11 +410,9 @@ final class ConnectionSessionModel {
391410
}
392411
}
393412

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

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

462+
// The MySQL driver types a refused database by its code.
463+
private func blamesDatabase(_ error: any Error) -> Bool {
464+
if redialsToSwitchDatabase { return Self.mayBlameDatabase(error) }
465+
if case MySQLError.databaseRefused = error { return true }
466+
return false
467+
}
468+
469+
// A USE engine's other failure may still be the database's on a server that numbers it its own way.
470+
private func startsNextOpenFromSaved(after error: any Error, listRefused: Bool, by attempt: ConnectionAttempt) -> Bool {
471+
if redialsToSwitchDatabase {
472+
if case PostgreSQLError.unreachable = error { return true }
473+
return false
474+
}
475+
return isCurrent(attempt) && !listRefused && !blamesDatabase(error) && !(error is CancellationError)
476+
}
477+
443478
private nonisolated static let notAboutTheDatabase = [
444479
"password authentication failed", "authentication failed", "fe_sendauth", "no password supplied",
445480
"could not connect", "connection refused", "timeout expired", "timed out", "could not translate host name",
@@ -502,6 +537,7 @@ final class ConnectionSessionModel {
502537
reportingTo scene: ConnectionCoordinator?
503538
) {
504539
guard let listed, !listed.contains(refused.name) else {
540+
guard !refused.reportedBySwitch else { return }
505541
scene?.presentFailure(
506542
title: ConnectionCoordinator.switchDatabaseFailedTitle,
507543
message: classify(refused.error, operation: "switchDatabase").message

‎apple/TableProMobile/TableProMobile/Drivers/MySQLDriver.swift‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,13 @@ nonisolated final class MySQLDriver: DatabaseDriver, SessionDatabaseReporting, @
438438
}
439439
}
440440

441+
// The sign-in went through and the database was refused as a USE there is (scripts/probes/check-mysql-dial-database-refusal.sh).
442+
nonisolated enum MySQLDatabaseRefusal {
443+
static func isRefusal(code: UInt32) -> Bool {
444+
code == 1_044 || code == 1_049
445+
}
446+
}
447+
441448
nonisolated enum MySQLTokenSignIn {
442449
// A token session refuses a server without TLS before the token is sent; this names that refusal.
443450
static func connectFailure(
@@ -735,8 +742,13 @@ private actor MySQLActor {
735742
) {
736743
throw tokenFailure
737744
}
738-
throw MariaDBSSLClassifier.classifySSLError(code: failure.code, message: failure.message)
739-
?? MySQLError.connectionFailed(failure.message)
745+
if let tlsFailure = MariaDBSSLClassifier.classifySSLError(code: failure.code, message: failure.message) {
746+
throw tlsFailure
747+
}
748+
if MySQLDatabaseRefusal.isRefusal(code: failure.code) {
749+
throw MySQLError.databaseRefused(failure.message)
750+
}
751+
throw MySQLError.connectionFailed(failure.message)
740752
}
741753

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

12591271
nonisolated enum MySQLError: Error, LocalizedError {
12601272
case connectionFailed(String)
1273+
// The database the handshake named was refused; it reads as any failed connect.
1274+
case databaseRefused(String)
12611275
case notConnected
12621276
case queryFailed(String)
12631277
case unsupported(String)
12641278

12651279
var errorDescription: String? {
12661280
switch self {
1267-
case .connectionFailed(let msg): return "MySQL connection failed: \(msg)"
1281+
case .connectionFailed(let msg), .databaseRefused(let msg): return "MySQL connection failed: \(msg)"
12681282
case .notConnected: return "Not connected to MySQL database"
12691283
case .queryFailed(let msg): return "MySQL query failed: \(msg)"
12701284
case .unsupported(let msg): return msg

‎apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorStatusTests.swift‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,13 @@ struct ConnectionCoordinatorStatusTests {
434434
#expect(ranUpdate(second))
435435
}
436436

437+
// An open dials the remembered database first; this one refuses it as a dropped database.
438+
private func goneStagingDriver() -> MockDatabaseDriver {
439+
let gone = driver()
440+
gone.connectError = MySQLError.databaseRefused("Unknown database 'app_staging'")
441+
return gone
442+
}
443+
437444
// A window on app_staging whose redial failed; `beforeLoss` runs while it is still connected.
438445
private func lostOnStaging(
439446
beforeLoss: (ConnectionCoordinator) -> Void = { _ in }
@@ -450,8 +457,9 @@ struct ConnectionCoordinatorStatusTests {
450457
return coordinator
451458
}
452459

453-
// Another window opens the connection, which dials the saved app_prod.
460+
// Another window opens the connection once app_staging is gone, so it lands on the saved app_prod.
454461
private func reconnectAnotherWindow() async -> MockDatabaseDriver {
462+
factory.queue(goneStagingDriver())
455463
let second = driver(tables: ["orders"])
456464
factory.queue(second)
457465
await ConnectionCoordinator(connection: connection, appState: appState).connect()
@@ -497,6 +505,7 @@ struct ConnectionCoordinatorStatusTests {
497505
let second = driver(tables: ["orders"])
498506
let loading = TestGate()
499507
second.beforeFetchTables = { await loading.enter() }
508+
factory.queue(goneStagingDriver())
500509
factory.queue(second)
501510
let other = ConnectionCoordinator(connection: connection, appState: appState)
502511

0 commit comments

Comments
 (0)