Skip to content

Proper decoding logical replication messages #31

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
55 changes: 54 additions & 1 deletion postgres-replication/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub const PRIMARY_KEEPALIVE_TAG: u8 = b'k';

// logical replication message tags
const BEGIN_TAG: u8 = b'B';
const MESSAGE_TAG: u8 = b'M';
const COMMIT_TAG: u8 = b'C';
const ORIGIN_TAG: u8 = b'O';
const RELATION_TAG: u8 = b'R';
Expand Down Expand Up @@ -165,7 +166,9 @@ impl PrimaryKeepAliveBody {
pub enum LogicalReplicationMessage {
/// A BEGIN statement
Begin(BeginBody),
/// A BEGIN statement
/// A logical decoding message
Message(MessageBody),
/// A COMMIT statement
Commit(CommitBody),
/// An Origin replication message
/// Note that there can be multiple Origin messages inside a single transaction.
Expand Down Expand Up @@ -199,6 +202,21 @@ impl LogicalReplicationMessage {
timestamp: buf.read_i64::<BigEndian>()?,
xid: buf.read_u32::<BigEndian>()?,
}),
MESSAGE_TAG => Self::Message(MessageBody {
flags: buf.read_i8()?,
message_lsn: buf.read_u64::<BigEndian>()?,
prefix: buf.read_cstr()?,
content: match buf.read_i32::<BigEndian>()? {
len if len > 0 => buf.read_buf(len as usize)?,
0 => Bytes::new(),
len => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("unexpected message content length `{len}`"),
))
}
},
}),
COMMIT_TAG => Self::Commit(CommitBody {
flags: buf.read_i8()?,
commit_lsn: buf.read_u64::<BigEndian>()?,
Expand Down Expand Up @@ -491,6 +509,41 @@ impl BeginBody {
}
}

/// A logical decoding message
#[derive(Debug)]
pub struct MessageBody {
message_lsn: u64,
flags: i8,
prefix: Bytes,
content: Bytes,
}

impl MessageBody {
#[inline]
/// The LSN of the logical decoding message.
pub fn message_lsn(&self) -> Lsn {
self.message_lsn
}

#[inline]
/// Flags. Currently can be either 0 for no flags or 1 if the logical decoding message is transactional.
pub fn flags(&self) -> i8 {
self.flags
}

#[inline]
/// The prefix of the logical decoding message.
pub fn prefix(&self) -> io::Result<&str> {
get_str(&self.prefix)
}

#[inline]
/// The content of the logical decoding message.
pub fn content(&self) -> &Bytes {
&self.content
}
}

/// A COMMIT statement
#[derive(Debug)]
pub struct CommitBody {
Expand Down