diff --git a/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift b/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift index adf3ed4582..c9a66ee8bf 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift @@ -81,7 +81,11 @@ extension DatabaseManager { workload: MetadataConnectionPool.Workload = .interactive, _ body: @Sendable @escaping (DatabaseDriver) async throws -> T ) async throws -> T { - try await withScopedDriver( + if lendsSessionDriver(toMetadataReadOn: scope, workload: workload), + let value = try await onLentSessionDriver(scope: scope, body) { + return value + } + return try await withScopedDriver( scope: scope, route: metadataRoute(for: scope), workload: workload, @@ -91,4 +95,84 @@ extension DatabaseManager { body ) } + + // Nil when the session stopped being safe to lend while the read waited for its turn: a verification before the + // turn can suspend, and a user statement can take the gate meanwhile and open a transaction or move the session. + private func onLentSessionDriver( + scope: DatabaseScope, + _ body: @Sendable @escaping (DatabaseDriver) async throws -> T + ) async throws -> T? { + let connectionId = scope.connectionId + lentMetadataReads.insert(connectionId) + defer { lentMetadataReads.remove(connectionId) } + do { + return try await withScopedDriver( + scope: scope, + route: .sessionDriver, + cancellation: .untracked, + sessionWork: .independent, + readsOnly: true, + admit: { [self] in + guard sessionIsSafeToLend(for: scope, inItsTurn: true) else { throw LentSessionRefused() } + }, + body + ) + } catch is LentSessionRefused { + return nil + } + } + + /// Dials the browse scope's pooled connection once the session has logged in, so the catalog reads after the + /// first one, which the idle session serves, run beside it rather than behind a handshake. + func prewarmMetadataConnection(for connectionId: UUID) { + guard let scope = browseScope(for: connectionId), metadataRoute(for: scope) == .pooled else { return } + MetadataConnectionPool.shared.prewarm(scope: scope) + } + + /// Whether a metadata read takes the session connection instead of a pooled one. Right after connect the pool + /// holds nothing, and dialing an entry is a whole startup (TCP, TLS, authentication, the connect batch) in front + /// of the first table list while the session that just logged in sits idle. + /// + /// Only an idle session lends itself: no turn held or queued on its gate, no work in flight, no transaction or + /// protected write, and no other lent read. The read must leave nothing behind, so the session must already be + /// where the read goes: its database and its schema, since `pin` would otherwise move them for the user's next + /// statement. A catalog read pins its own search path for the one statement. A manual-commit session or one with + /// startup commands could open a transaction on a plain SELECT, which the user would then see as their own. + /// Bulk reads never lend: a row count or a column preload holds the gate long enough to delay the user's query. + func lendsSessionDriver( + toMetadataReadOn scope: DatabaseScope, + workload: MetadataConnectionPool.Workload + ) -> Bool { + let connectionId = scope.connectionId + return workload == .interactive + && metadataRoute(for: scope) == .pooled + && !lentMetadataReads.contains(connectionId) + && !sessionDriverGate.isHeld(browsedGateKey(for: connectionId)) + && sessionIsSafeToLend(for: scope, inItsTurn: false) + && !MetadataConnectionPool.shared.hasIdleEntry(for: scope, workload: workload) + } + + // Asked again inside the turn, where the lent read's own operation is the one in flight. Session state the user's + // statements set up, such as `SET IMPLICIT_TRANSACTIONS ON`, can make a plain SELECT open a transaction. + private func sessionIsSafeToLend(for scope: DatabaseScope, inItsTurn: Bool) -> Bool { + let connectionId = scope.connectionId + guard let session = activeSessions[connectionId], + let driver = session.driver, + isUsable(connectionId), + session.commitMode == .automatic, + !Self.hasStartupCommands(session.connection.startupCommands), + (queriesInFlight[connectionId] ?? 0) == (inItsTurn ? 1 : 0), + sessionTransactions.holds(for: connectionId).isEmpty, + sessionStateLedger.state(heldBy: driver, for: connectionId).isEmpty, + !holdsProtectedWrite(connectionId), + !MetadataConnectionPool.shared.isReplacingTransport(for: connectionId), + CatalogName.same(scope.database, session.resolvedBrowseDatabase), + let executing = executionDatabase(for: connectionId), + CatalogName.same(executing, scope.database) + else { return false } + guard let switchable = driver as? SchemaSwitchable else { return true } + return CatalogName.same(switchable.currentSchema, scope.schema) + } } + +private struct LentSessionRefused: Error {} diff --git a/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift b/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift index 81b2f41704..e04687318a 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift @@ -180,6 +180,7 @@ extension DatabaseManager { Telemetry.shared.connectionSucceeded(databaseType: connection.type.rawValue) AppEvents.shared.databaseDidConnect.send(DatabaseDidConnect(connectionId: connection.id)) + prewarmMetadataConnection(for: connection.id) await startHealthMonitor(for: connection.id) } catch { diff --git a/apple/TablePro/Core/Database/DatabaseManager.swift b/apple/TablePro/Core/Database/DatabaseManager.swift index 62588a26ab..fd0412b482 100644 --- a/apple/TablePro/Core/Database/DatabaseManager.swift +++ b/apple/TablePro/Core/Database/DatabaseManager.swift @@ -70,6 +70,9 @@ final class DatabaseManager: ObservableObject { internal var queriesInFlight: [UUID: Int] = [:] /// Tracks when the first query started for each session (used for staleness detection). internal var queryStartTimes: [UUID: Date] = [:] + /// Connections whose session driver is serving a metadata read the pool would have had to dial for. One at a + /// time, decided synchronously, so two reads that both find the session idle do not both queue on its gate. + internal var lentMetadataReads: Set = [] /// When each connection's server last answered, whether that was the connect itself, a health /// check, or a check made because the user was about to use it. diff --git a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift index e1364e31c0..9ba6facd7a 100644 --- a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift +++ b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift @@ -201,6 +201,28 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { databaseList[connectionId]?.value ?? [] } + /// The connection's database list, read once and shared: the tree, the database switcher and the quick + /// switcher show this one list rather than each reading their own. A list already loaded is answered + /// without a read, and one being read is joined. + func databaseNames(connectionId: UUID, databaseType: DatabaseType) async throws -> [String] { + switch databaseListState(for: connectionId) { + case .loaded(let list): + return list.map(\.name) + case .loading: + return try await fetchDatabaseList(connectionId: connectionId, databaseType: databaseType).map(\.name) + case .idle, .failed: + await loadDatabases(connectionId: connectionId, databaseType: databaseType) + switch databaseListState(for: connectionId) { + case .loaded(let list): + return list.map(\.name) + case .failed(let message): + throw DatabaseError.queryFailed(message) + case .idle, .loading: + return try await fetchDatabaseList(connectionId: connectionId, databaseType: databaseType).map(\.name) + } + } + } + func schemaListState(connectionId: UUID, database: String) -> MetadataLoadState<[String]> { schemaList[DatabaseKey(connectionId: connectionId, database: database)] ?? .idle } @@ -1087,7 +1109,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { .connection.type.supportsUserDefinedTypeBrowse ?? false } - /// Always a scoped driver, through `withMetadataDriver`, which alone knows which engines cannot + /// Always a scoped driver, through `withMetadataRead`, which alone knows which engines cannot /// answer on a second connection. The scope names the database only: a scope per schema took a /// pooled connection per expanded schema node. private func withDriver( @@ -1101,7 +1123,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { ) else { throw DatabaseError.notConnected } - return try await DatabaseManager.shared.withMetadataDriver(scope: scope, workload: workload, body) + return try await DatabaseManager.shared.withMetadataRead(scope: scope, workload: workload, body) } private static func objectsKey(connectionId: UUID, database: String, schema: String?) -> ObjectsKey { diff --git a/apple/TablePro/Core/Services/Query/MetadataConnectionPool.swift b/apple/TablePro/Core/Services/Query/MetadataConnectionPool.swift index 8b9b0296ea..d9c3220a6d 100644 --- a/apple/TablePro/Core/Services/Query/MetadataConnectionPool.swift +++ b/apple/TablePro/Core/Services/Query/MetadataConnectionPool.swift @@ -55,6 +55,18 @@ final class MetadataConnectionPool { slot = scope.schema == nil ? .home : .followsSchema } + private init(connectionId: UUID, database: String, workload: Workload, slot: Slot) { + self.connectionId = connectionId + self.database = database + self.workload = workload + self.slot = slot + } + + // The same database and slot under another workload: what an idle connection of one serves the other with. + func under(_ workload: Workload) -> Key { + Key(connectionId: connectionId, database: database, workload: workload, slot: slot) + } + // By bytes: a connection to one of two databases Swift's String equates never serves the other. static func == (lhs: Key, rhs: Key) -> Bool { lhs.connectionId == rhs.connectionId && CatalogName.same(lhs.database, rhs.database) @@ -86,6 +98,13 @@ final class MetadataConnectionPool { } } + // Where a lease runs: the entry and the key it is listed under, which is another workload's key when a bulk + // lease borrows an idle interactive entry. + private struct Placement { + let entry: Entry + let key: Key + } + private enum LeaseOutcome: Sendable { case ran(T) // The entry was left in a transaction and is closing, so the lease takes another. @@ -105,6 +124,9 @@ final class MetadataConnectionPool { // A startup command can move the search path after the driver read it, so the driver's cache is not trusted. var forcesNextSwitch: Bool var hasServedALease = false + // An interactive entry running a bulk lease it lent itself to. No interactive lease queues behind it, + // since a row count or a column preload can take far longer than the read that would wait. + var servesBulk = false private var tail: Task = Task {} init(driver: DatabaseDriver, schema: String?, forcesNextSwitch: Bool) { @@ -223,8 +245,8 @@ final class MetadataConnectionPool { ) async throws -> T { let key = Key(scope: scope, workload: workload) while true { - let entry = try await acquireEntry(forKey: key, schema: scope.schema, scope: scope) - if case .ran(let value) = try await run(body, on: entry, inKey: key, schema: scope.schema) { + let placed = try await acquireEntry(forKey: key, schema: scope.schema, scope: scope) + if case .ran(let value) = try await run(body, on: placed.entry, inKey: placed.key, schema: scope.schema) { return value } } @@ -347,6 +369,7 @@ final class MetadataConnectionPool { private func releaseEntry(_ entry: Entry, connectionId: UUID) { entry.inFlightCount -= 1 guard entry.inFlightCount == 0 else { return } + entry.servesBulk = false if entry.closeWhenIdle { entry.driver.disconnect() return @@ -415,13 +438,13 @@ final class MetadataConnectionPool { // In order: an idle entry on the schema, any idle entry, the busy entry on the schema, an open for the schema // already dialing, a new entry if there is room, else a place in the room line. A lease inside another lease's // work skips the busy entry and the open: two such leases nesting in opposite directions would wait on each other. - private func acquireEntry(forKey key: Key, schema: String?, scope: DatabaseScope) async throws -> Entry { + private func acquireEntry(forKey key: Key, schema: String?, scope: DatabaseScope) async throws -> Placement { let held = entriesHeldByThisTask() let openKey = OpenKey(key: key, schema: schema, owner: held.isEmpty ? nil : UUID()) while true { try await waitForTransport(for: scope) - if let entry = claimEntry(forKey: key, schema: schema, excluding: held) { - return entry + if let placed = claimEntry(forKey: key, schema: schema, excluding: held) { + return placed } if pending[openKey] == nil { try await waitForRoom(forKey: key, schema: schema, held: held) @@ -443,8 +466,9 @@ final class MetadataConnectionPool { throw failure } if let entry = open.entry, isListed(entry, inKey: key) { - claim(entry, for: schema) - return entry + let placed = Placement(entry: entry, key: key) + claim(placed, for: schema, workload: key.workload) + return placed } if open.withdrawal == .closed { throw DatabaseError.notConnected @@ -457,38 +481,87 @@ final class MetadataConnectionPool { Set(PooledLeaseContext.open.filter { $0.isOpen }.map { $0.entryId }) } - private func claimEntry(forKey key: Key, schema: String?, excluding held: Set) -> Entry? { + private func claimEntry(forKey key: Key, schema: String?, excluding held: Set) -> Placement? { // A Mac that slept comes back with entries the sweeper never reached and sockets the server already closed. - for entry in entries[key] ?? [] where !isUsable(entry) { - removeEntry(entry, fromKey: key) + for listed in Set([key, key.under(.interactive)]) { + for entry in entries[listed] ?? [] where !isUsable(entry) { + removeEntry(entry, fromKey: listed) + } } - guard let entry = placeWithoutOpening(forKey: key, schema: schema, excluding: held) else { return nil } - claim(entry, for: schema) - return entry + guard let placed = placeWithoutOpening(forKey: key, schema: schema, excluding: held) else { return nil } + claim(placed, for: schema, workload: key.workload) + return placed } - // At most one busy entry per schema, so two schemas share a connection only while one of them is idle. + // At most one busy entry per schema, so two schemas share a connection only while one of them is idle. A bulk + // lease takes an idle interactive entry before it dials one of its own: a fresh handshake costs more than the + // read, and the interactive side opens another entry if it needs one while the bulk read runs. private func placeWithoutOpening( forKey key: Key, schema: String?, excluding held: Set - ) -> Entry? { - let candidates = (entries[key] ?? []).filter { !held.contains(ObjectIdentifier($0)) && isUsable($0) } - let idle = candidates.filter { isIdle($0) } - if let onSchema = idle.first(where: { CatalogName.same($0.schema, schema) }) { - return onSchema + ) -> Placement? { + if let idle = idleEntry(inKey: key, schema: schema, excluding: held) { + return Placement(entry: idle, key: key) } - if let any = idle.min(by: { $0.lastUsed < $1.lastUsed }) { - return any + // Borrowing keeps bulk work's reserve: it never takes the last connection an interactive read could use. + if key.workload == .bulk, busyCount(for: key.connectionId) < Self.maxPerConnection - 1 { + let interactive = key.under(.interactive) + if let idle = idleEntry(inKey: interactive, schema: schema, excluding: held) { + return Placement(entry: idle, key: interactive) + } } guard held.isEmpty else { return nil } - return candidates.first { $0.inFlightCount > 0 && CatalogName.same($0.queuedSchema, schema) } + let busy = (entries[key] ?? []).first { entry in + !held.contains(ObjectIdentifier(entry)) && isUsable(entry) && entry.inFlightCount > 0 + && !entry.servesBulk && CatalogName.same(entry.queuedSchema, schema) + } + return busy.map { Placement(entry: $0, key: key) } + } + + private func idleEntry(inKey key: Key, schema: String?, excluding held: Set) -> Entry? { + let idle = (entries[key] ?? []).filter { !held.contains(ObjectIdentifier($0)) && isUsable($0) && isIdle($0) } + return idle.first { CatalogName.same($0.schema, schema) } ?? idle.min { $0.lastUsed < $1.lastUsed } } - private func claim(_ entry: Entry, for schema: String?) { + private func claim(_ placed: Placement, for schema: String?, workload: Workload) { + let entry = placed.entry entry.inFlightCount += 1 entry.lastUsed = Date() entry.queuedSchema = schema + if workload == .bulk, placed.key.workload == .interactive { + entry.servesBulk = true + } + } + + /// Whether a lease for `scope` would start at once on a pooled connection, without dialing one or queueing. + func hasIdleEntry(for scope: DatabaseScope, workload: Workload = .interactive) -> Bool { + let key = Key(scope: scope, workload: workload) + guard let placed = placeWithoutOpening(forKey: key, schema: scope.schema, excluding: entriesHeldByThisTask()) + else { return false } + return isIdle(placed.entry) + } + + /// Dials the scope's interactive connection in the background, once the session has logged in, so the reads + /// that follow the first one find it open. Never alongside the session's own login: a wrong password must count + /// as one failed login, not two. A connection already pooled or dialing for the scope, or a full pool, dials + /// nothing, and a failed dial is left to the first read that needs the pool, which reports it. + func prewarm(scope: DatabaseScope) { + let key = Key(scope: scope, workload: .interactive) + let openKey = OpenKey(key: key, schema: scope.schema, owner: nil) + guard !isReplacingTransport(for: key.connectionId), + (entries[key] ?? []).isEmpty, + pending[openKey] == nil, + heldCount(for: key.connectionId) < Self.maxPerConnection, + let open = try? startOpen(openKey) + else { return } + Task { [self] in + if let failure = await completion(of: open, for: openKey) { + Self.logger.info( + "Background pooled connection did not open: \(failure.publicLogShape, privacy: .public)" + ) + } + } } // Runs on the entry's queue before the lease's work, so the switch lands where the work reads. diff --git a/apple/TablePro/Core/Services/Query/SchemaService+CatalogLoad.swift b/apple/TablePro/Core/Services/Query/SchemaService+CatalogLoad.swift index e85314f6af..bc483ca9e5 100644 --- a/apple/TablePro/Core/Services/Query/SchemaService+CatalogLoad.swift +++ b/apple/TablePro/Core/Services/Query/SchemaService+CatalogLoad.swift @@ -11,7 +11,8 @@ import TableProPluginKit extension SchemaService { // One lease per read, so a column read asked for meanwhile goes before the next kind instead of after - // the whole catalog. The tables lease opens before any state moves: a refused lease leaves it untouched. + // the whole catalog, and a session lent to one read is never held across the catalog. The tables lease + // opens before any state moves: a refused lease leaves it untouched. func load( connectionId: UUID, connection: DatabaseConnection, @@ -37,7 +38,7 @@ extension SchemaService { if let started { endRefresh(connectionId, generation: started.generation) } } // A load queued for the same lease finds the catalog the one ahead of it committed. - let leased = try await provider.withMetadataDriver(scope: scope) { [self] driver -> LoadRun? in + let leased = try await provider.withMetadataRead(scope: scope, workload: .interactive) { [self] driver -> LoadRun? in guard await needsLoad(connectionId, scope: scope) else { return nil } var run = await beginLoad(connectionId: connectionId, driver: driver, connection: connection, scope: scope) let tables: Result<[TableInfo], any Error> @@ -65,6 +66,20 @@ extension SchemaService { generations[connectionId] ?? 0 } + func isRefreshing(connectionId: UUID) -> Bool { + refreshingConnections.contains(connectionId) + } + + /// The schema list read with `database`'s catalog, for a reader that would otherwise read it again; nil when the + /// catalog shown is another database's, is not current, or has no schema list. + func currentSchemas(for connectionId: UUID, database: String) -> [String]? { + guard let scope = loadedScope(for: connectionId), CatalogName.same(scope.database, database), + isCatalogCurrent(for: connectionId) + else { return nil } + let schemas = schemas(for: connectionId) + return schemas.isEmpty ? nil : schemas + } + func needsLoad(_ connectionId: UUID, scope: DatabaseScope?) -> Bool { guard case .loaded = state(for: connectionId) else { return true } return !((scope == nil || loadedScope(for: connectionId) == scope) && isCatalogCurrent(for: connectionId)) @@ -163,7 +178,7 @@ extension SchemaService { guard !order.isEmpty else { return } let reads: SideReads do { - reads = try await provider.withMetadataDriver(scope: scope) { [self] driver in + reads = try await provider.withMetadataRead(scope: scope, workload: .interactive) { [self] driver in await readSideKinds(run, driver: driver) } } catch { diff --git a/apple/TablePro/Core/Services/Query/SchemaService.swift b/apple/TablePro/Core/Services/Query/SchemaService.swift index 421aa775d6..3355094a23 100644 --- a/apple/TablePro/Core/Services/Query/SchemaService.swift +++ b/apple/TablePro/Core/Services/Query/SchemaService.swift @@ -156,10 +156,6 @@ final class SchemaService: ObservableObject { driverFacts[shownKey(connectionId)] } - func isRefreshing(connectionId: UUID) -> Bool { - refreshingConnections.contains(connectionId) - } - func loadedScope(for connectionId: UUID) -> DatabaseScope? { guard hasLoadedContent(for: connectionId) else { return nil } return shownCatalogs[connectionId]?.scope @@ -394,6 +390,13 @@ final class SchemaService: ObservableObject { schemasInOrder[shownKey(connectionId)] ?? [] } + /// A schema list read again for the catalog on screen, which every reader of that list then sees. + func noteSchemasRead(_ schemas: [String], for connectionId: UUID, database: String) { + guard currentSchemas(for: connectionId, database: database) != nil else { return } + schemasInOrder[shownKey(connectionId)] = schemas + bumpGeneration(connectionId) + } + func attachedSchemas(for connectionId: UUID) -> [String] { attachedSchemasInOrder[shownKey(connectionId)] ?? [] } diff --git a/apple/TablePro/ViewModels/DatabaseSwitcherViewModel.swift b/apple/TablePro/ViewModels/DatabaseSwitcherViewModel.swift index 29a5560f01..6788d4685d 100644 --- a/apple/TablePro/ViewModels/DatabaseSwitcherViewModel.swift +++ b/apple/TablePro/ViewModels/DatabaseSwitcherViewModel.swift @@ -105,6 +105,10 @@ final class DatabaseSwitcherViewModel: ObservableObject { /// A refresh never blanks the list it is refreshing, and a failed one never replaces data the /// popover is still showing. Only a load that has nothing to fall back on reports either state. func fetchDatabases() async { + await load(refreshing: false) + } + + private func load(refreshing: Bool) async { let token = UUID() loadToken = token if !hasLoadedOnce { @@ -113,12 +117,7 @@ final class DatabaseSwitcherViewModel: ObservableObject { do { let target = switchTarget - let names = try await services.databaseManager.withBrowseMetadataDriver(connectionId: connectionId) { driver in - switch target { - case .database: try await driver.fetchDatabases() - case .schema: try await driver.fetchSchemas() - } - } + let names = try await listedNames(refreshing: refreshing) guard loadToken == token else { return } let systemNames = services.pluginManager.systemContainerNames(for: databaseType, target: target) applyFetched(names.sorted().map { DatabaseMetadata.minimal(name: $0, isSystem: systemNames.contains($0)) }) @@ -142,7 +141,34 @@ final class DatabaseSwitcherViewModel: ObservableObject { } func refreshDatabases() async { - await fetchDatabases() + await load(refreshing: true) + } + + /// The lists have one owner each: the database list is the tree's, which the sidebar read on connect, and + /// the browsed database's schema list is the one the schema service read with its catalog. Opening the + /// switcher reads neither again; Refresh rereads through the owner, so every list it feeds moves together. + private func listedNames(refreshing: Bool) async throws -> [String] { + switch switchTarget { + case .database: + let tree = DatabaseTreeMetadataService.shared + if refreshing { + await tree.refreshDatabases(connectionId: connectionId, databaseType: databaseType) + } + return try await tree.databaseNames(connectionId: connectionId, databaseType: databaseType) + case .schema: + let database = services.databaseManager.browseScope(for: connectionId)?.database + if !refreshing, let database, + let held = services.schemaService.currentSchemas(for: connectionId, database: database) { + return held + } + let schemas = try await services.databaseManager.withBrowseMetadataDriver(connectionId: connectionId) { driver in + try await driver.fetchSchemas() + } + if let database { + services.schemaService.noteSchemasRead(schemas, for: connectionId, database: database) + } + return schemas + } } func loadCreateDatabaseForm() async throws -> CreateDatabaseFormSpec? { diff --git a/apple/TablePro/ViewModels/QuickSwitcherViewModel.swift b/apple/TablePro/ViewModels/QuickSwitcherViewModel.swift index b088926d4a..9438b15f7b 100644 --- a/apple/TablePro/ViewModels/QuickSwitcherViewModel.swift +++ b/apple/TablePro/ViewModels/QuickSwitcherViewModel.swift @@ -333,9 +333,10 @@ internal final class QuickSwitcherViewModel: ObservableObject { /// twice and the copy labelled "Database" failed with the driver's own error (#2262). if switchTarget != .schema { do { - let databases = try await services.databaseManager.withBrowseMetadataDriver(connectionId: connectionId) { driver in - try await driver.fetchDatabases() - } + // The tree's list, which the sidebar read on connect: the switcher reads it only when nothing has. + let databases = try await DatabaseTreeMetadataService.shared.databaseNames( + connectionId: connectionId, databaseType: databaseType + ) let databaseSubtitle = switchTarget == .database ? services.pluginManager.containerEntityName(for: databaseType) : String(localized: "Database") @@ -363,9 +364,7 @@ internal final class QuickSwitcherViewModel: ObservableObject { if services.pluginManager.supportsSchemaSwitching(for: databaseType) { do { - let schemas = try await services.databaseManager.withBrowseMetadataDriver(connectionId: connectionId) { driver in - try await driver.fetchSchemas() - } + let schemas = try await browsedSchemas() let schemaSubtitle = switchTarget == .schema ? services.pluginManager.containerEntityName(for: databaseType) : String(localized: "Schema") @@ -395,6 +394,17 @@ internal final class QuickSwitcherViewModel: ObservableObject { return (items, isComplete) } + /// The schema list the schema service read with the browsed catalog, read here only when it holds none current. + private func browsedSchemas() async throws -> [String] { + if let database = services.databaseManager.browseScope(for: connectionId)?.database, + let held = services.schemaService.currentSchemas(for: connectionId, database: database) { + return held + } + return try await services.databaseManager.withBrowseMetadataDriver(connectionId: connectionId) { driver in + try await driver.fetchSchemas() + } + } + /// The local part of the catalog store: saved queries and history. private func loadContentCatalog() async -> [QuickSwitcherItem] { var items: [QuickSwitcherItem] = [] diff --git a/apple/TableProTests/Core/Database/MetadataReadLendingTests.swift b/apple/TableProTests/Core/Database/MetadataReadLendingTests.swift new file mode 100644 index 0000000000..3e53a1ff35 --- /dev/null +++ b/apple/TableProTests/Core/Database/MetadataReadLendingTests.swift @@ -0,0 +1,102 @@ +// +// MetadataReadLendingTests.swift +// TableProTests +// +// Right after connect the pool holds nothing, so the first table list waited for a whole new +// connection while the session that had just logged in sat idle (#4542). +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import Testing + +@MainActor +struct MetadataReadLendingTests { + private func makeSession(commitMode: ConnectionCommitMode = .automatic) -> (DatabaseConnection, MockDatabaseDriver) { + let connection = TestFixtures.makeConnection(database: "app", type: .postgresql) + let driver = MockDatabaseDriver(connection: connection) + driver.currentSchema = "public" + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + session.browseDatabase = "app" + session.browseSchema = "public" + session.commitMode = commitMode + DatabaseManager.shared.injectSession(session, for: connection.id) + return (connection, driver) + } + + private func cleanUp(_ connectionId: UUID) { + MetadataConnectionPool.shared.closeAll(connectionId: connectionId) + DatabaseManager.shared.removeSession(for: connectionId) + } + + private func scope(_ connection: DatabaseConnection, database: String = "app", schema: String? = "public") -> DatabaseScope { + DatabaseScope(connectionId: connection.id, database: database, schema: schema) + } + + @Test("An idle session serves a catalog read when the pool holds no connection for it") + func idleSessionServesTheFirstRead() async throws { + let (connection, driver) = makeSession() + defer { cleanUp(connection.id) } + let place = scope(connection) + #expect(DatabaseManager.shared.metadataRoute(for: place) == .pooled) + + let served = try await DatabaseManager.shared.withMetadataRead(scope: place) { ObjectIdentifier($0) } + + #expect(served == ObjectIdentifier(driver)) + #expect(driver.switchSchemaCallCount == 0) + #expect(DatabaseManager.shared.lentMetadataReads.isEmpty) + } + + @Test("A session is not lent to a bulk read, or to a read on another database or schema") + func lendsOnlyWhereTheSessionAlreadyIs() { + let (connection, _) = makeSession() + defer { cleanUp(connection.id) } + let manager = DatabaseManager.shared + + #expect(manager.lendsSessionDriver(toMetadataReadOn: scope(connection), workload: .interactive)) + #expect(!manager.lendsSessionDriver(toMetadataReadOn: scope(connection), workload: .bulk)) + #expect(!manager.lendsSessionDriver(toMetadataReadOn: scope(connection, schema: "sales"), workload: .interactive)) + #expect(!manager.lendsSessionDriver(toMetadataReadOn: scope(connection, database: "billing"), workload: .interactive)) + } + + @Test("A pooled connection ready for the read keeps it off the session") + func idlePooledConnectionKeepsTheReadOffTheSession() async throws { + let (connection, driver) = makeSession() + defer { cleanUp(connection.id) } + let pooled = MockDatabaseDriver(connection: connection) + pooled.currentSchema = "public" + MetadataConnectionPool.shared.injectEntry(pooled, scope: scope(connection)) + + #expect(!DatabaseManager.shared.lendsSessionDriver(toMetadataReadOn: scope(connection), workload: .interactive)) + let served = try await DatabaseManager.shared.withMetadataRead(scope: scope(connection)) { ObjectIdentifier($0) } + #expect(served == ObjectIdentifier(pooled)) + #expect(served != ObjectIdentifier(driver)) + } + + @Test("A session holding a turn, or in manual commit, is not lent") + func busyOrManualCommitSessionIsNotLent() async throws { + let (connection, _) = makeSession() + defer { cleanUp(connection.id) } + let manager = DatabaseManager.shared + let release = AsyncGate() + let acquired = AsyncGate() + let holder = Task { @MainActor in + try await manager.sessionDriverGate.withExclusiveAccess(manager.browsedGateKey(for: connection.id)) { + await acquired.open() + await release.wait() + } + } + await acquired.wait() + #expect(!manager.lendsSessionDriver(toMetadataReadOn: scope(connection), workload: .interactive)) + await release.open() + try await holder.value + #expect(manager.lendsSessionDriver(toMetadataReadOn: scope(connection), workload: .interactive)) + + let (manual, _) = makeSession(commitMode: .manual) + defer { cleanUp(manual.id) } + #expect(!manager.lendsSessionDriver(toMetadataReadOn: scope(manual), workload: .interactive)) + } +} diff --git a/apple/TableProTests/Core/Services/Query/MetadataConnectionPoolSharingTests.swift b/apple/TableProTests/Core/Services/Query/MetadataConnectionPoolSharingTests.swift new file mode 100644 index 0000000000..2f68732d75 --- /dev/null +++ b/apple/TableProTests/Core/Services/Query/MetadataConnectionPoolSharingTests.swift @@ -0,0 +1,110 @@ +// +// MetadataConnectionPoolSharingTests.swift +// TableProTests +// +// Connecting to PostgreSQL and opening one table opened three server connections: the session and +// two pooled ones, the second only because a bulk read would not take the idle interactive one. Each +// is a whole startup in front of the read that waits for it (#4542). +// + +import Foundation +@testable import TablePro +import TableProTestSupport +import Testing + +@MainActor +private final class HeldLease { + private var continuation: CheckedContinuation? + private var isOpen = false + private(set) var hasArrived = false + + func wait() async { + hasArrived = true + guard !isOpen else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + isOpen = true + continuation?.resume() + continuation = nil + } +} + +@MainActor +struct MetadataConnectionPoolSharingTests { + private func makeSession() -> DatabaseConnection { + let connection = TestFixtures.makeConnection(database: "shop") + var session = ConnectionSession(connection: connection, driver: MockDatabaseDriver(connection: connection)) + session.status = .connected + DatabaseManager.shared.injectSession(session, for: connection.id) + return connection + } + + private func scope(_ connection: DatabaseConnection) -> DatabaseScope { + DatabaseScope(connectionId: connection.id, database: "shop", schema: nil) + } + + @Test("A bulk read runs on the idle interactive connection instead of dialing one of its own") + func bulkTakesIdleInteractiveEntry() async throws { + let connection = makeSession() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + let opener = CountingOpener() + let pool = MetadataConnectionPool.isolatedForTesting(openDriver: { try await opener.open($0) }) + defer { pool.closeAll(connectionId: connection.id) } + + let interactive = try await pool.withDriver(scope: scope(connection)) { ObjectIdentifier($0) } + let bulk = try await pool.withDriver(scope: scope(connection), workload: .bulk) { ObjectIdentifier($0) } + + #expect(opener.opened.count == 1) + #expect(bulk == interactive) + } + + @Test("An interactive read does not queue behind bulk work that borrowed its connection") + func interactiveSkipsEntryLentToBulk() async throws { + let connection = makeSession() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + let opener = CountingOpener() + let pool = MetadataConnectionPool.isolatedForTesting(openDriver: { try await opener.open($0) }) + defer { pool.closeAll(connectionId: connection.id) } + let place = scope(connection) + let first = try await pool.withDriver(scope: place) { ObjectIdentifier($0) } + + let held = HeldLease() + let bulk = Task { @MainActor in + try await pool.withDriver(scope: place, workload: .bulk) { driver -> ObjectIdentifier in + await held.wait() + return ObjectIdentifier(driver) + } + } + try await waitUntil { held.hasArrived } + let interactive = try await pool.withDriver(scope: place) { ObjectIdentifier($0) } + held.open() + let borrowed = try await bulk.value + + #expect(borrowed == first) + #expect(interactive != first) + #expect(opener.opened.count == 2) + } + + @Test("A prewarm dials the scope's connection once, and the first read takes it without dialing") + func prewarmDialsOnceAndIsTaken() async throws { + let connection = makeSession() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + let opener = CountingOpener() + let pool = MetadataConnectionPool.isolatedForTesting(openDriver: { try await opener.open($0) }) + defer { pool.closeAll(connectionId: connection.id) } + let place = scope(connection) + + pool.prewarm(scope: place) + pool.prewarm(scope: place) + try await waitUntil { pool.pooledDriverCount(for: connection.id) == 1 } + #expect(pool.hasIdleEntry(for: place)) + + let served = try await pool.withDriver(scope: place) { ObjectIdentifier($0) } + pool.prewarm(scope: place) + + #expect(opener.opened.count == 1) + #expect(served == opener.opened.first.map { ObjectIdentifier($0) }) + } +} diff --git a/apple/TableProTests/ViewModels/DatabaseSwitcherRefreshTests.swift b/apple/TableProTests/ViewModels/DatabaseSwitcherRefreshTests.swift index 62303cf3f3..e64e98b820 100644 --- a/apple/TableProTests/ViewModels/DatabaseSwitcherRefreshTests.swift +++ b/apple/TableProTests/ViewModels/DatabaseSwitcherRefreshTests.swift @@ -150,6 +150,21 @@ struct DatabaseSwitcherRefreshTests { #expect(viewModel.databases.map(\.name) == ["analytics", "testdb"]) } + // The sidebar read the list on connect, and the switcher read it again on open (#4542). + @Test("Opening the switcher after the sidebar listed the databases reads nothing") + func switcherTakesTheTreesList() async { + let (connection, driver) = connect(databaseNames: ["testdb", "analytics"]) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + await DatabaseTreeMetadataService.shared.loadDatabases(connectionId: connection.id, databaseType: .pglite) + driver.forgetReads() + let viewModel = makeConnectedViewModel(connection) + + await viewModel.fetchDatabases() + + #expect(driver.reads.isEmpty) + #expect(viewModel.databases.map(\.name) == ["analytics", "testdb"]) + } + @Test("A Teradata system database spelled in another case still lists under System") func namesOnlyListClassifiesLikeTheEngine() async { let (connection, _) = connect(databaseNames: ["dbc", "Sales"]) diff --git a/apple/changelog.d/4575.changed.md b/apple/changelog.d/4575.changed.md new file mode 100644 index 0000000000..9dc963de2e --- /dev/null +++ b/apple/changelog.d/4575.changed.md @@ -0,0 +1 @@ +Connecting opens fewer server connections, and the sidebar and switchers list their objects sooner.