Updated the Probe method in the Persistence package with a query deadline.

This commit is contained in:
2026-08-13 00:11:59 +02:00
parent 8303598244
commit d7465d03cc
4 changed files with 138 additions and 15 deletions
@@ -57,6 +57,46 @@ struct ProbeTests {
#expect(!isReachable)
}
@Test
func `reports a hanging database as unreachable within its timeout`() async throws {
// The silent server accepts the TCP connection and never answers, so the probe's query can only
// ever be resolved by its deadline without one, it would wait out the driver's own connect
// timeout (10 seconds) instead.
let server = try await SilentPostgresServer.start()
let service = try Service(
driver: .postgres(
.init(
host: "127.0.0.1",
port: server.port,
name: "hanging",
username: "nobody",
password: "nothing",
tls: .off,
maxConnectionsPerEventLoop: 1
)
),
logger: Logger(label: "test")
)
let fluent = service()
let probe = Probe(
fluent: fluent,
timeout: .milliseconds(100)
)
let clock = ContinuousClock()
let start = clock.now
let isReachable = await probe()
let elapsed = clock.now - start
try await fluent.shutdown()
try await server.stop()
#expect(!isReachable)
// Well past the 100-millisecond deadline to absorb scheduling noise, yet far below the driver's
// 10-second connect timeout only the deadline can answer this fast.
#expect(elapsed < .seconds(5))
}
@Test
func `reports a default database that is not an SQL database`() async throws {
let fluent = Fluent(logger: Logger(label: "test"))
@@ -0,0 +1,54 @@
import NIOCore
import NIOPosix
/// A fake server accepting connections and never answering.
///
/// A client connecting to it completes the TCP handshake and then waits forever for the first protocol byte the shape of a database that hangs rather
/// than refuses. This is what the probe's deadline test connects to, proving the probe answers within its timeout instead of hanging alongside the server.
final class SilentPostgresServer {
// MARK: Properties
/// The port the server listens on, assigned by the system at bind time.
let port: Int
/// The listening channel the server accepts connections through.
private let channel: Channel
// MARK: Initializers
private init(
channel: Channel,
port: Int
) {
self.channel = channel
self.port = port
}
// MARK: Functions
/// Starts a server on the loopback interface, on a system-assigned port.
/// - Returns: the running server, ready to be connected to at ``port``.
static func start() async throws -> SilentPostgresServer {
let channel = try await ServerBootstrap(group: MultiThreadedEventLoopGroup.singleton)
.bind(host: "127.0.0.1", port: 0)
.get()
guard let port = channel.localAddress?.port else {
throw ChannelError.unknownLocalAddress
}
return .init(
channel: channel,
port: port
)
}
/// Stops the server, closing its listening channel.
func stop() async throws {
try await channel
.close()
.get()
}
}