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}
239/// PREVIOUS_GTIDS using the MySQL 8.4 tagged TSID encoding.
240#[derive(Debug, Clone, Copy, Default)]
241pub struct TaggedPreviousGtidsEvent<'a> {
242    pub sid_count: u64,
243    pub encoded_sids: &'a [u8],
244}
245
246#[derive(Debug, Clone, Copy)]
247pub struct TaggedSidIntervals<'a> {
248    pub sid: &'a [u8],
249    pub tag: Option<&'a str>,
250    pub intervals: &'a [u8],
251}
252
253fn read_sid<'a>(input: &mut Cursor<'a>, tagged: bool) -> Result<TaggedSidIntervals<'a>> {
254    let sid = input.take(16)?;
255    let tag = if tagged {
256        let len =
257            usize::try_from(input.varint()?).map_err(|_| invalid("GTID tag length overflow"))?;
258        let tag = std::str::from_utf8(input.take(len)?)?;
259        if tag.is_empty() {
260            None
261        } else {
262            mysql_common::packets::Tag::new(tag).map_err(|_| invalid("invalid GTID tag"))?;
263            Some(tag)
264        }
265    } else {
266        None
267    };
268    let count = usize::try_from(input.le(8)?).map_err(|_| invalid("interval count overflow"))?;
269    let bytes = count
270        .checked_mul(16)
271        .ok_or_else(|| invalid("interval size overflow"))?;
272    Ok(TaggedSidIntervals {
273        sid,
274        tag,
275        intervals: input.take(bytes)?,
276    })
277}
278
279fn sid_entries(
280    data: &[u8],
281    count: u64,
282    tagged: bool,
283) -> impl Iterator<Item = Result<TaggedSidIntervals<'_>>> {
284    let mut input = Cursor::new(data);
285    let mut remaining = count;
286    std::iter::from_fn(move || {
287        if remaining == 0 {
288            return None;
289        }
290        remaining -= 1;
291        let entry = read_sid(&mut input, tagged);
292        if entry.is_err() {
293            remaining = 0;
294        }
295        Some(entry)
296    })
297}
298
299fn previous_gtids(data: &[u8], tagged: bool) -> Result<(u64, &[u8])> {
300    let mut input = Cursor::new(data);
301    let header = input.le(8)?;
302    let count = match (header >> 56, tagged) {
303        (0, false) => header,
304        (1, true) if header as u8 == 1 => (header >> 8) & 0x0000_ffff_ffff_ffff,
305        _ => return Err(invalid("invalid PREVIOUS_GTIDS format")),
306    };
307    let encoded = input.remaining();
308    if count > (encoded.len() / 24) as u64 {
309        return Err(invalid("PREVIOUS_GTIDS SID count exceeds body"));
310    }
311    for _ in 0..count {
312        let entry = read_sid(&mut input, tagged)?;
313        let mut intervals = Cursor::new(entry.intervals);
314        let mut previous_end = 0;
315        while !intervals.remaining().is_empty() {
316            let start = intervals.le(8)?;
317            let end = intervals.le(8)?;
318            if start == 0 || start >= end || start < previous_end || end > i64::MAX as u64 + 1 {
319                return Err(invalid("invalid GTID interval"));
320            }
321            previous_end = end;
322        }
323    }
324    input.finish()?;
325    Ok((count, encoded))
326}
327impl PreviousGtidsEvent<'_> {
328    pub fn sids(&self) -> impl Iterator<Item = Result<SidIntervals<'_>>> {
329        sid_entries(self.encoded_sids, self.sid_count, false).map(|entry| {
330            entry.map(|e| SidIntervals {
331                sid: e.sid,
332                intervals: e.intervals,
333            })
334        })
335    }
336}
337impl TaggedPreviousGtidsEvent<'_> {
338    pub fn sids(&self) -> impl Iterator<Item = Result<TaggedSidIntervals<'_>>> {
339        sid_entries(self.encoded_sids, self.sid_count, true)
340    }
341}
342impl<'a> Event<'a> for PreviousGtidsEvent<'a> {
343    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
344        writeln!(writer, "SID count: {}", self.sid_count)?;
345        writeln!(writer, "Encoded SIDs: {:02x?}\n", self.encoded_sids)?;
346        Ok(())
347    }
348    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
349        (self.sid_count, self.encoded_sids) = previous_gtids(data, false)?;
350        Ok(())
351    }
352}
353impl<'a> Event<'a> for TaggedPreviousGtidsEvent<'a> {
354    fn dump(&self, writer: &mut dyn Write) -> Result<()> {
355        writeln!(writer, "Tagged SID count: {}", self.sid_count)?;
356        for entry in self.sids() {
357            let entry = entry?;
358            writeln!(
359                writer,
360                "SID: {:02x?}, tag: {:?}, intervals: {:02x?}",
361                entry.sid, entry.tag, entry.intervals
362            )?;
363        }
364        writeln!(writer)?;
365        Ok(())
366    }
367    fn decode(&mut self, data: &'a [u8]) -> Result<()> {
368        (self.sid_count, self.encoded_sids) = previous_gtids(data, true)?;
369        Ok(())
370    }
371}