Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Be resilient about a read after connection closed; fixes #449 #452

Merged
merged 1 commit into from
Jan 31, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -624,21 +624,19 @@ struct ConnectionStateMachine {
mutating func readEventCaught() -> ConnectionAction {
switch self.state {
case .initialized:
preconditionFailure("Received a read event on a connection that was never opened.")
case .sslRequestSent:
return .read
case .sslNegotiated:
return .read
case .sslHandlerAdded:
return .read
case .waitingToStartAuthentication:
return .read
case .authenticating:
return .read
case .authenticated:
return .read
case .readyForQuery:
preconditionFailure("Invalid state: \(self.state). Read event before connection established?")

case .sslRequestSent,
.sslNegotiated,
.sslHandlerAdded,
.waitingToStartAuthentication,
.authenticating,
.authenticated,
.readyForQuery,
.closing:
// all states in which we definitely want to make further forward progress...
return .read

case .extendedQuery(var extendedQuery, let connectionContext):
self.state = .modifying // avoid CoW
let action = extendedQuery.readEventCaught()
Expand All @@ -651,12 +649,15 @@ struct ConnectionStateMachine {
self.state = .closeCommand(closeState, connectionContext)
return self.modify(with: action)

case .closing:
return .read
case .closed:
preconditionFailure("How can we receive a read, if the connection is closed")
// Generally we shouldn't see this event (read after connection closed?!).
// But truth is, adopters run into this, again and again. So preconditioning here leads
// to unnecessary crashes. So let's be resilient and just make more forward progress.
// If we really care, we probably need to dive deep into PostgresNIO and SwiftNIO.
return .read

case .modifying:
preconditionFailure("Invalid state")
preconditionFailure("Invalid state: \(self.state)")
}
}

Expand Down
Loading