49 lines
1.7 KiB
Swift
49 lines
1.7 KiB
Swift
import HummingbirdFluent
|
|
import SQLKit
|
|
|
|
/// A readiness probe reporting whether the database behind a `Fluent` service is reachable.
|
|
///
|
|
/// Built once around the application's `Fluent` service and called as a function whenever a fresh answer is needed — typically from a readiness endpoint:
|
|
/// `let ready = await probe()`.
|
|
public struct Probe: Sendable {
|
|
|
|
// MARK: Properties
|
|
|
|
/// The `Fluent` service whose default database is probed.
|
|
private let fluent: Fluent
|
|
|
|
// MARK: Initializers
|
|
|
|
/// Creates a probe for the default database of the given `Fluent` service.
|
|
/// - Parameter fluent: the `Fluent` service whose default database is probed.
|
|
public init(
|
|
fluent: Fluent
|
|
) {
|
|
self.fluent = fluent
|
|
}
|
|
|
|
// MARK: Methods
|
|
|
|
/// Reports whether the database behind the `Fluent` service is reachable.
|
|
///
|
|
/// Runs a trivial `SELECT 1` against the default database — the cheapest statement both the PostgreSQL and SQLite backends understand — so
|
|
/// a readiness check does not depend on any particular schema or model. Any failure (connection refused, authentication error, pool exhausted) is
|
|
/// reported as not reachable rather than thrown, so callers can map it straight onto a readiness response. A default database that is not an SQL
|
|
/// database is likewise reported as not reachable.
|
|
/// - Returns: `true` when the database answers the probe, `false` otherwise.
|
|
public func callAsFunction() async -> Bool {
|
|
guard let database = fluent.db() as? any SQLDatabase else {
|
|
return false
|
|
}
|
|
|
|
do {
|
|
try await database.raw("SELECT 1").run()
|
|
|
|
return true
|
|
} catch {
|
|
return false
|
|
}
|
|
|
|
}
|
|
}
|