refactor(proto): reuse code in handshakes

This commit is contained in:
Jindřich Moravec 2023-12-23 00:52:53 +01:00
parent 7b2dce4dfb
commit c1744711d3
9 changed files with 111 additions and 88 deletions

View file

@ -0,0 +1,34 @@
use crate::handshake::errors::ClientHandshakeError;
use crate::handshake::request::HandshakeRequest;
use crate::handshake::response::HandshakeResponse;
use crate::message::backend::{AuthenticationOkData, BackendMessage};
use crate::message::special::StartupMessageData;
use crate::reader::backend::BackendProtoReader;
use crate::writer::frontend::FrontendProtoWriter;
use crate::writer::protowriter::ProtoFlush;
pub async fn do_client_handshake(
writer: &mut (impl FrontendProtoWriter + ProtoFlush),
reader: &mut impl BackendProtoReader,
request: HandshakeRequest,
) -> Result<HandshakeResponse, ClientHandshakeError> {
let startup_message: StartupMessageData = request.into();
writer.write_startup_message(startup_message).await?;
let auth = reader.read_proto().await?;
if !matches!(auth, BackendMessage::AuthenticationOk(AuthenticationOkData { status: 0 })) {
return Err(ClientHandshakeError::UnexpectedAuthResponse(auth));
}
let mut messages = Vec::new();
loop {
let msg = reader.read_proto().await?;
if matches!(msg, BackendMessage::ReadyForQuery(_)) {
break;
}
messages.push(msg);
}
HandshakeResponse::try_from(messages.as_slice())
}