Skip to main content

mysql_replication/events/
mod.rs

1//! Concrete protocol events share decoding and diagnostic output, not CDC semantics.
2mod control;
3mod gtid;
4mod header;
5mod rows;
6
7use crate::{BinlogFrame, Result};
8pub use control::{
9    ChecksumAlgorithm, FormatDescriptionEvent, HeartbeatEvent, PreviousGtidsEvent, QueryEvent,
10    RotateEvent, SidIntervals, XidEvent,
11};
12pub use gtid::{GtidEvent, TaggedGtidEvent};
13pub use header::EventHeader;
14pub use rows::{RowImages, RowsEvent, RowsKind, TableColumns, TableMapEvent};
15use std::{fmt::Debug, io::Write, ops::Range, sync::Arc};
16
17/// A decoder is bound to its file layout before receiving an event body.
18/// Borrowed fields remain valid for the input lifetime. Header decoding receives
19/// exactly 19 bytes; body decoding excludes the common header and checksum.
20pub trait Event<'a>: Debug {
21    fn decode(&mut self, data: &'a [u8]) -> Result<()>;
22    /// Writes diagnostics only. This does not serialize a binary event or CDC row.
23    fn dump(&self, writer: &mut dyn Write) -> Result<()>;
24}
25
26#[derive(Debug, Clone, Copy, Default)]
27pub struct RawEvent<'a> {
28    pub data: &'a [u8],
29}
30impl<'a> Event<'a> for RawEvent<'a> {
31    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
32        writeln!(writer, "Data: {:02x?}\n", self.data)?;
33        Ok(())
34    }
35    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
36        self.data = data;
37        Ok(())
38    }
39}
40
41/// An explicit variant retains typed access without downcasting.
42#[derive(Debug, Clone)]
43#[non_exhaustive]
44pub enum EventData<'a> {
45    FormatDescription(FormatDescriptionEvent<'a>),
46    Rotate(RotateEvent<'a>),
47    Query(QueryEvent<'a>),
48    TableMap(TableMapEvent<'a>),
49    Rows(RowsEvent<'a>),
50    Xid(XidEvent),
51    Gtid(GtidEvent),
52    AnonymousGtid(GtidEvent),
53    TaggedGtid(TaggedGtidEvent<'a>),
54    PreviousGtids(PreviousGtidsEvent<'a>),
55    Heartbeat(HeartbeatEvent<'a>),
56    /// Unknown or deliberately unimplemented body; never silently discarded.
57    Raw(RawEvent<'a>),
58}
59impl<'a> Event<'a> for EventData<'a> {
60    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
61        match self {
62            Self::FormatDescription(event) => event.dump(writer),
63            Self::Rotate(event) => event.dump(writer),
64            Self::Query(event) => event.dump(writer),
65            Self::TableMap(event) => event.dump(writer),
66            Self::Rows(event) => event.dump(writer),
67            Self::Xid(event) => event.dump(writer),
68            Self::TaggedGtid(event) => event.dump(writer),
69            Self::PreviousGtids(event) => event.dump(writer),
70            Self::Heartbeat(event) => event.dump(writer),
71            Self::Raw(event) => event.dump(writer),
72            Self::Gtid(event) | Self::AnonymousGtid(event) => event.dump(writer),
73        }
74    }
75
76    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
77        match self {
78            Self::FormatDescription(v) => v.decode(data),
79            Self::Rotate(v) => v.decode(data),
80            Self::Query(v) => v.decode(data),
81            Self::TableMap(v) => v.decode(data),
82            Self::Rows(v) => v.decode(data),
83            Self::Xid(v) => v.decode(data),
84            Self::Gtid(v) | Self::AnonymousGtid(v) => v.decode(data),
85            Self::TaggedGtid(v) => v.decode(data),
86            Self::PreviousGtids(v) => v.decode(data),
87            Self::Heartbeat(v) => v.decode(data),
88            Self::Raw(v) => v.decode(data),
89        }
90    }
91}
92
93/// One wire event, borrowing the reader's complete, unmodified event buffer.
94#[derive(Debug, Clone)]
95pub struct BinlogEvent<'a> {
96    pub raw_data: &'a [u8],
97    pub header: EventHeader,
98    pub event: EventData<'a>,
99    pub(crate) body: &'a [u8],
100}
101impl BinlogEvent<'_> {
102    pub fn frame(&self) -> BinlogFrame<'_> {
103        BinlogFrame {
104            raw_data: self.raw_data,
105            header: self.header,
106            body: self.body,
107        }
108    }
109    /// Retains one raw buffer and its layout; typed fields are borrowed on view().
110    pub fn into_owned(self) -> Result<OwnedBinlogEvent> {
111        let start = EventHeader::LEN;
112        let end = start + self.body.len();
113        if self.raw_data.get(start..end) != Some(self.body)
114            || EventHeader::parse(
115                self.raw_data
116                    .get(..start)
117                    .ok_or_else(|| crate::error::invalid("missing common header"))?,
118            )? != self.header
119        {
120            return Err(crate::error::invalid("event fields do not match raw data"));
121        }
122        Ok(OwnedBinlogEvent {
123            raw_data: Arc::from(self.raw_data),
124            header: self.header,
125            body: start..end,
126            template: self.event.layout(),
127        })
128    }
129}
130
131/// No self references: a view borrows this owned raw buffer when requested.
132#[derive(Debug, Clone)]
133pub struct OwnedBinlogEvent {
134    raw_data: Arc<[u8]>,
135    header: EventHeader,
136    body: Range<usize>,
137    template: EventData<'static>,
138}
139impl OwnedBinlogEvent {
140    pub fn raw_data(&self) -> &[u8] {
141        &self.raw_data
142    }
143    pub fn view(&self) -> Result<BinlogEvent<'_>> {
144        let body = &self.raw_data[self.body.clone()];
145        let mut event = self.template.clone();
146        event.decode(body)?;
147        Ok(BinlogEvent {
148            raw_data: &self.raw_data,
149            header: self.header,
150            event,
151            body,
152        })
153    }
154}
155impl EventData<'_> {
156    fn layout(&self) -> EventData<'static> {
157        match self {
158            Self::FormatDescription(v) => EventData::FormatDescription(FormatDescriptionEvent {
159                checksum_algorithm: v.checksum_algorithm,
160                ..Default::default()
161            }),
162            Self::Rotate(v) => EventData::Rotate(RotateEvent::with_post_header(v.post_header)),
163            Self::Query(v) => EventData::Query(QueryEvent::with_post_header(v.post_header)),
164            Self::TableMap(v) => {
165                EventData::TableMap(TableMapEvent::with_post_header(v.post_header))
166            }
167            Self::Rows(v) => EventData::Rows(RowsEvent::with_layout(v.kind, v.post_header, v.v2)),
168            Self::Xid(_) => EventData::Xid(Default::default()),
169            Self::Gtid(_) => EventData::Gtid(Default::default()),
170            Self::AnonymousGtid(_) => EventData::AnonymousGtid(Default::default()),
171            Self::TaggedGtid(_) => EventData::TaggedGtid(Default::default()),
172            Self::PreviousGtids(_) => EventData::PreviousGtids(Default::default()),
173            Self::Heartbeat(_) => EventData::Heartbeat(Default::default()),
174            Self::Raw(_) => EventData::Raw(Default::default()),
175        }
176    }
177}