Skip to content
Open
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
86 changes: 85 additions & 1 deletion apple/TablePro/Core/Database/DatabaseManager+Metadata.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<T: Sendable>(
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 {}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions apple/TablePro/Core/Database/DatabaseManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<UUID> = []

/// 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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<T: Sendable>(
Expand All @@ -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 {
Expand Down
119 changes: 96 additions & 23 deletions apple/TablePro/Core/Services/Query/MetadataConnectionPool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<T: Sendable>: Sendable {
case ran(T)
// The entry was left in a transaction and is closing, so the lease takes another.
Expand All @@ -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<Void, Never> = Task {}

init(driver: DatabaseDriver, schema: String?, forcesNextSwitch: Bool) {
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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<ObjectIdentifier>) -> Entry? {
private func claimEntry(forKey key: Key, schema: String?, excluding held: Set<ObjectIdentifier>) -> 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<ObjectIdentifier>
) -> 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<ObjectIdentifier>) -> 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.
Expand Down
Loading
Loading