Skip to main content

binlog_inspect/
filter.rs

1// Copyright (c) 2026 houseme
2// SPDX-License-Identifier: Apache-2.0
3
4//! Event, table, range and GTID filters applied after parsing.
5use crate::event::{EventPayload, EventType, ParsedEvent};
6use std::collections::HashSet;
7/// Byte-offset and timestamp range filters (mysqlbinlog convention).
8///
9/// All bounds are optional; filtering happens after parsing, so it never
10/// changes parser state.
11#[derive(Debug, Default)]
12pub struct RangeFilter {
13    /// Keep events starting at or after this byte offset (inclusive).
14    pub start_position: Option<u64>,
15    /// Keep events starting before this byte offset (exclusive).
16    pub stop_position: Option<u64>,
17    /// Keep events with timestamp at or after this Unix second (inclusive).
18    ///
19    /// Events with a zero timestamp (heartbeat-style) fall before any real
20    /// datetime start bound, which matches mysqlbinlog.
21    pub start_datetime: Option<i64>,
22    /// Keep events with timestamp at or before this Unix second (inclusive).
23    pub stop_datetime: Option<i64>,
24}
25impl RangeFilter {
26    /// Returns whether the event header offset and timestamp are inside the
27    /// configured ranges.
28    fn keep(&self, event: &ParsedEvent) -> bool {
29        if let Some(start) = self.start_position
30            && event.offset < start
31        {
32            return false;
33        }
34        // mysqlbinlog convention: the stop position is exclusive.
35        if let Some(stop) = self.stop_position
36            && event.offset >= stop
37        {
38            return false;
39        }
40        let timestamp = i64::from(event.timestamp);
41        if let Some(start) = self.start_datetime
42            && timestamp < start
43        {
44            return false;
45        }
46        if let Some(stop) = self.stop_datetime
47            && timestamp > stop
48        {
49            return false;
50        }
51        true
52    }
53}
54/// Optional allow lists for event types and fully qualified tables, plus
55/// range bounds and an exact-match GTID allow list.
56#[derive(Default)]
57pub struct EventFilter {
58    /// Empty means all event types.
59    pub kinds: HashSet<EventType>,
60    /// Empty means all tables; non-table events are excluded when set.
61    ///
62    /// Entries are `(database, table)` pairs; the CLI splits `--table`
63    /// values at the first `.` at parse time (R16).
64    pub tables: HashSet<(String, String)>,
65    /// Byte-offset and timestamp range bounds (R26).
66    pub ranges: RangeFilter,
67    /// Empty means all GTIDs; when set, only events carrying one of these
68    /// exact GTID strings are kept (R26).
69    ///
70    /// Entries are canonical `uuid:gno` or `uuid:tag:gno` strings exactly as
71    /// they appear in [`ParsedEvent`] output; no interval or set algebra.
72    pub gtids: HashSet<String>,
73}
74impl EventFilter {
75    /// Returns whether the event matches all configured filters.
76    ///
77    /// Table matching is a scan over the `(database, table)` tuple set with no
78    /// per-event allocation; filter lists are small, so the scan is cheaper
79    /// than the string formatting it replaced.
80    pub fn keep(&self, event: &ParsedEvent) -> bool {
81        if !self.kinds.is_empty() && !self.kinds.contains(&event.event_type) {
82            return false;
83        }
84        if !self.ranges.keep(event) {
85            return false;
86        }
87        if !self.gtids.is_empty() {
88            match &event.payload {
89                EventPayload::Gtid { gtid, .. } if self.gtids.contains(gtid) => (),
90                // A GTID allow list only matches GTID payload events; every
91                // other event (and anonymous transactions, whose GTID is the
92                // placeholder "ANONYMOUS") is excluded.
93                _ => return false,
94            }
95        }
96        if self.tables.is_empty() {
97            return true;
98        }
99        match &event.payload {
100            EventPayload::Rows {
101                database, table, ..
102            }
103            | EventPayload::PartialUpdateRows {
104                database, table, ..
105            }
106            | EventPayload::TableMap {
107                database, table, ..
108            } => self
109                .tables
110                .iter()
111                .any(|(db, tbl)| db == database && tbl == table),
112            // Row events without a usable table map carry no table identity,
113            // so they never match a table filter.
114            _ => false,
115        }
116    }
117}
118#[cfg(test)]
119mod tests {
120    use super::*;
121    fn xid(offset: u64, timestamp: u32) -> ParsedEvent {
122        ParsedEvent {
123            offset,
124            timestamp,
125            event_type: EventType::Xid,
126            event_type_code: 16,
127            server_id: 1,
128            event_size: 27,
129            log_pos: u32::try_from(offset + 27).unwrap(),
130            payload: EventPayload::Xid { xid: 1 },
131        }
132    }
133    fn gtid(offset: u64, gtid: &str) -> ParsedEvent {
134        ParsedEvent {
135            offset,
136            timestamp: 1,
137            event_type: EventType::Gtid,
138            event_type_code: 33,
139            server_id: 1,
140            event_size: 42,
141            log_pos: u32::try_from(offset + 42).unwrap(),
142            payload: EventPayload::Gtid {
143                gtid: gtid.to_owned(),
144                tag: None,
145            },
146        }
147    }
148    #[test]
149    fn position_bounds_are_start_inclusive_and_stop_exclusive() {
150        let filter = EventFilter {
151            ranges: RangeFilter {
152                start_position: Some(4),
153                stop_position: Some(31),
154                ..Default::default()
155            },
156            ..Default::default()
157        };
158        assert!(filter.keep(&xid(4, 1)));
159        // Before the exclusive stop bound: kept.
160        assert!(filter.keep(&xid(30, 1)));
161        // At the exclusive stop bound: dropped.
162        assert!(!filter.keep(&xid(31, 1)));
163    }
164    #[test]
165    fn datetime_bounds_are_inclusive_on_both_ends() {
166        let filter = EventFilter {
167            ranges: RangeFilter {
168                start_datetime: Some(100),
169                stop_datetime: Some(200),
170                ..Default::default()
171            },
172            ..Default::default()
173        };
174        assert!(filter.keep(&xid(4, 100)));
175        assert!(filter.keep(&xid(4, 200)));
176        assert!(!filter.keep(&xid(4, 99)));
177        assert!(!filter.keep(&xid(4, 201)));
178        // A zero timestamp never satisfies a real datetime start bound.
179        assert!(!filter.keep(&xid(4, 0)));
180    }
181    #[test]
182    fn gtid_allow_list_matches_exact_strings_only() {
183        let filter = EventFilter {
184            gtids: ["11111111-1111-1111-1111-111111111111:1".to_owned()]
185                .into_iter()
186                .collect(),
187            ..Default::default()
188        };
189        assert!(filter.keep(&gtid(4, "11111111-1111-1111-1111-111111111111:1")));
190        assert!(!filter.keep(&gtid(4, "11111111-1111-1111-1111-111111111111:2")));
191        assert!(!filter.keep(&gtid(4, "ANONYMOUS")));
192        assert!(!filter.keep(&xid(4, 1)));
193    }
194}