Skip to content

Error "How can we receive a read, if the connection is closed" #435

@notcome

Description

@notcome

Describe the bug

I am very new to Swift Server Side and Vapor, and I am confused by this migration to Swift concurrency. I saw AsyncKit being deprecated and decided to give the new ConnectionPool a try.

I found that seconds after I read the database, I saw this preconditionFailure:

PostgresNIO/ConnectionStateMachine.swift:657: Fatal error: How can we receive a read, if the connection is closed

To Reproduce

I have done a little bit wrapping around Vapor. My reading activity mostly happens inside this extension:

extension Request {
    func readingDB<Result>(closure: @escaping @Sendable (PostgresConnectionSource.Connection) async throws -> Result) async throws -> Result {
        try await application.postgresClient.withConnection { connection in
            try await connection.sql().raw("BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED").run()
            do {
                let result = try await closure(connection)
                try await connection.sql().raw("COMMIT").run()
                return result
            } catch {
                try await connection.sql().raw("COMMIT").run()
                throw error
            }
        }
    }
}

and helpers:

enum PostgresClientKey: StorageKey {
    typealias Value = PostgresClient
}

extension Application {
    var postgresClient: PostgresClient! {
        get { self.storage[PostgresClientKey.self] }
        set { self.storage[PostgresClientKey.self] = newValue }
    }
}

The client starts with:

 let postgresConfiguration = PostgresClient.Configuration(
    host: hostname,
    port: port,
    username: username,
    password: password,
    database: databaseName,
    tls: .require(tlsConfiguration))
let postgresClient = PostgresClient(configuration: postgresConfiguration, backgroundLogger: Logger(label: "postgres"))
Task {
    await postgresClient.run()
}

Expected behavior

No error.

Environment

  • Vapor Framework version: 4.84.6
  • Vapor Toolbox version: 18.7.4
  • OS version: macOS 14.0 (23A344)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions