Skip to main content

mysql_replication/events/
control.rs

1use super::Event;
2use std::{fmt, io::Write};
3
4/// The FDE trailer is supplied by the frame parser, outside the decoded body.
5#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
6pub enum ChecksumAlgorithm {
7    #[default]
8    Unknown,
9    None,
10    Crc32,
11}
12impl fmt::Display for ChecksumAlgorithm {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        f.write_str(match self {
15            Self::Unknown => "UNKNOWN",
16            Self::None => "NONE",
17            Self::Crc32 => "CRC32",
18        })
19    }
20}
21use crate::{Result, error::invalid, wire::Cursor};
22
23#[derive(Debug, Clone, Copy, Default)]
24pub struct FormatDescriptionEvent<'a> {
25    pub binlog_version: u16,
26    pub server_version: &'a str,
27    pub create_timestamp: u32,
28    pub header_length: u8,
29    pub post_header_lengths: &'a [u8],
30    pub checksum_algorithm: ChecksumAlgorithm,
31}
32impl<'a> Event<'a> for FormatDescriptionEvent<'a> {
33    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
34        writeln!(writer, "Version: {}", self.binlog_version)?;
35        writeln!(writer, "Server version: {}", self.server_version)?;
36        writeln!(writer, "Checksum algorithm: {}", self.checksum_algorithm)?;
37        writeln!(writer)?;
38        Ok(())
39    }
40
41    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
42        let mut input = Cursor::new(data);
43        let binlog_version = input.le(2)? as u16;
44        let version = input.take(50)?;
45        let end = version
46            .iter()
47            .position(|&b| b == 0)
48            .unwrap_or(version.len());
49        let server_version = std::str::from_utf8(&version[..end])?;
50        let create_timestamp = input.le(4)? as u32;
51        let header_length = input.byte()?;
52        if binlog_version != 4 || header_length != 19 {
53            return Err(crate::Error::Unsupported(
54                "requires binlog v4 with 19-byte common header".into(),
55            ));
56        }
57        *self = Self {
58            binlog_version,
59            server_version,
60            create_timestamp,
61            header_length,
62            post_header_lengths: input.remaining(),
63            checksum_algorithm: self.checksum_algorithm,
64        };
65        Ok(())
66    }
67}
68
69#[derive(Debug, Clone, Copy)]
70pub struct RotateEvent<'a> {
71    pub position: u64,
72    pub next_file: &'a [u8],
73    pub(crate) post_header: usize,
74}
75impl Default for RotateEvent<'_> {
76    fn default() -> Self {
77        Self::with_post_header(8)
78    }
79}
80impl RotateEvent<'_> {
81    pub fn with_post_header(post_header: usize) -> Self {
82        Self {
83            position: 0,
84            next_file: &[],
85            post_header,
86        }
87    }
88}
89impl<'a> Event<'a> for RotateEvent<'a> {
90    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
91        writeln!(writer, "Position: {}", self.position)?;
92        writeln!(
93            writer,
94            "Next file: {}",
95            String::from_utf8_lossy(self.next_file)
96        )?;
97        writeln!(writer)?;
98        Ok(())
99    }
100
101    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
102        if self.post_header < 8 {
103            return Err(invalid("short ROTATE post-header"));
104        }
105        let mut input = Cursor::new(data);
106        let position = Cursor::new(input.take(self.post_header)?).le(8)?;
107        let next_file = input.remaining();
108        if position < 4 || next_file.is_empty() {
109            return Err(invalid("invalid ROTATE file/position"));
110        }
111        self.position = position;
112        self.next_file = next_file;
113        Ok(())
114    }
115}
116
117/// SQL and names remain raw bytes; character-set and DDL policy belong upstairs.
118#[derive(Debug, Clone, Copy)]
119pub struct QueryEvent<'a> {
120    pub thread_id: u32,
121    pub execution_time: u32,
122    pub error_code: u16,
123    pub status_vars: &'a [u8],
124    pub schema: &'a [u8],
125    pub query: &'a [u8],
126    pub(crate) post_header: usize,
127}
128impl Default for QueryEvent<'_> {
129    fn default() -> Self {
130        Self::with_post_header(13)
131    }
132}
133impl QueryEvent<'_> {
134    pub fn with_post_header(post_header: usize) -> Self {
135        Self {
136            thread_id: 0,
137            execution_time: 0,
138            error_code: 0,
139            status_vars: &[],
140            schema: &[],
141            query: &[],
142            post_header,
143        }
144    }
145}
146impl<'a> Event<'a> for QueryEvent<'a> {
147    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
148        writeln!(writer, "Thread ID: {}", self.thread_id)?;
149        writeln!(writer, "Execution time: {}", self.execution_time)?;
150        writeln!(writer, "Error code: {}", self.error_code)?;
151        writeln!(writer, "Schema: {}", String::from_utf8_lossy(self.schema))?;
152        writeln!(writer, "Query: {}", String::from_utf8_lossy(self.query))?;
153        writeln!(writer, "Status variables: {:02x?}", self.status_vars)?;
154        writeln!(writer)?;
155        Ok(())
156    }
157
158    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
159        if self.post_header < 13 {
160            return Err(invalid("short QUERY post-header"));
161        }
162        let mut input = Cursor::new(data);
163        let mut header = Cursor::new(input.take(self.post_header)?);
164        let thread_id = header.le(4)? as u32;
165        let execution_time = header.le(4)? as u32;
166        let schema_len = usize::from(header.byte()?);
167        let error_code = header.le(2)? as u16;
168        let status_len = header.le(2)? as usize;
169        let status_vars = input.take(status_len)?;
170        let schema = input.take(schema_len)?;
171        if input.byte()? != 0 {
172            return Err(invalid("QUERY schema terminator"));
173        }
174        *self = Self {
175            thread_id,
176            execution_time,
177            error_code,
178            status_vars,
179            schema,
180            query: input.remaining(),
181            post_header: self.post_header,
182        };
183        Ok(())
184    }
185}
186
187#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
188pub struct XidEvent {
189    pub xid: u64,
190}
191impl<'a> Event<'a> for XidEvent {
192    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
193        writeln!(writer, "XID: {}", self.xid)?;
194        writeln!(writer)?;
195        Ok(())
196    }
197
198    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
199        let mut input = Cursor::new(data);
200        let xid = input.le(8)?;
201        input.finish()?;
202        self.xid = xid;
203        Ok(())
204    }
205}
206
207#[derive(Debug, Clone, Copy, Default)]
208pub struct HeartbeatEvent<'a> {
209    pub log_file: &'a [u8],
210}
211impl<'a> Event<'a> for HeartbeatEvent<'a> {
212    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
213        writeln!(
214            writer,
215            "Log file: {}",
216            String::from_utf8_lossy(self.log_file)
217        )?;
218        writeln!(writer)?;
219        Ok(())
220    }
221
222    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
223        self.log_file = data;
224        Ok(())
225    }
226}
227
228/// Intervals stay borrowed. Each interval is [start, end), encoded as two u64s.
229#[derive(Debug, Clone, Copy)]
230pub struct SidIntervals<'a> {
231    pub sid: &'a [u8],
232    pub intervals: &'a [u8],
233}
234#[derive(Debug, Clone, Copy, Default)]
235pub struct PreviousGtidsEvent<'a> {
236    pub sid_count: u64,
237    pub encoded_sids: &'a [u8],
238}
239impl PreviousGtidsEvent<'_> {
240    pub fn sids(&self) -> impl Iterator<Item = Result<SidIntervals<'_>>> {
241        let mut input = Cursor::new(self.encoded_sids);
242        let mut remaining = self.sid_count;
243        std::iter::from_fn(move || {
244            if remaining == 0 {
245                return None;
246            }
247            remaining -= 1;
248            let value = (|| {
249                let sid = input.take(16)?;
250                let count = usize::try_from(input.le(8)?)
251                    .map_err(|_| invalid("interval count overflow"))?;
252                let bytes = count
253                    .checked_mul(16)
254                    .ok_or_else(|| invalid("interval size overflow"))?;
255                Ok(SidIntervals {
256                    sid,
257                    intervals: input.take(bytes)?,
258                })
259            })();
260            if value.is_err() {
261                remaining = 0;
262            }
263            Some(value)
264        })
265    }
266}
267impl<'a> Event<'a> for PreviousGtidsEvent<'a> {
268    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
269        writeln!(writer, "SID count: {}", self.sid_count)?;
270        writeln!(writer, "Encoded SIDs: {:02x?}", self.encoded_sids)?;
271        writeln!(writer)?;
272        Ok(())
273    }
274
275    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
276        let mut input = Cursor::new(data);
277        let sid_count = input.le(8)?;
278        let encoded_sids = input.remaining();
279        if sid_count > (encoded_sids.len() / 24) as u64 {
280            return Err(invalid("PREVIOUS_GTIDS SID count exceeds body"));
281        }
282        for _ in 0..sid_count {
283            input.take(16)?;
284            let count =
285                usize::try_from(input.le(8)?).map_err(|_| invalid("interval count overflow"))?;
286            let bytes = count
287                .checked_mul(16)
288                .ok_or_else(|| invalid("interval size overflow"))?;
289            let mut intervals = Cursor::new(input.take(bytes)?);
290            let mut previous_end = 0;
291            for _ in 0..count {
292                let start = intervals.le(8)?;
293                let end = intervals.le(8)?;
294                if start == 0 || start >= end || start < previous_end || end > i64::MAX as u64 + 1 {
295                    return Err(invalid("invalid GTID interval"));
296                }
297                previous_end = end;
298            }
299        }
300        input.finish()?;
301        *self = Self {
302            sid_count,
303            encoded_sids,
304        };
305        Ok(())
306    }
307}