Skip to main content

rustfs_notify/rules/
pattern.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/// Create new pattern string based on prefix and suffix。
16///
17/// The rule is similar to event.NewPattern in the Go version:
18/// - If a prefix is provided and does not end with '*', '*' is appended.
19/// - If a suffix is provided and does not start with '*', then prefix '*'.
20/// - Replace "**" with "*".
21pub fn new_pattern(prefix: Option<&str>, suffix: Option<&str>) -> String {
22    let mut pattern = String::new();
23
24    // Process the prefix part
25    if let Some(p) = prefix
26        && !p.is_empty()
27    {
28        pattern.push_str(p);
29        if !p.ends_with('*') {
30            pattern.push('*');
31        }
32    }
33
34    // Process the suffix part
35    if let Some(s) = suffix
36        && !s.is_empty()
37    {
38        let mut s_to_append = s.to_string();
39        if !s.starts_with('*') {
40            s_to_append.insert(0, '*');
41        }
42
43        // If the pattern is empty (only suffixes are provided), then the pattern is the suffix
44        // Otherwise, append the suffix to the pattern
45        if pattern.is_empty() {
46            pattern = s_to_append;
47        } else {
48            pattern.push_str(&s_to_append);
49        }
50    }
51
52    // Replace "**" with "*"
53    pattern = pattern.replace("**", "*");
54
55    pattern
56}
57
58/// Simple matching object names and patterns。
59pub fn match_simple(pattern_str: &str, object_name: &str) -> bool {
60    if pattern_str == "*" {
61        // AWS S3 docs: A single asterisk (*) in the rule matches all objects.
62        return true;
63    }
64    // An empty pattern matches nothing, which is usually desired: an empty
65    // pattern_str means no specific filter was supplied. Go's NewRulesMap
66    // defaults to "*", so an empty pattern reaching here is unlikely to mean
67    // "match all" — treat it as no match unless it is explicitly "*".
68    if pattern_str.is_empty() {
69        return false; // Or true if an empty pattern means "match all" in some contexts.
70        // Given Go's NewRulesMap defaults to "*", an empty pattern from Filter is unlikely to mean "match all".
71    }
72    glob_match_star_only(pattern_str, object_name)
73}
74
75/// Matches `object_name` against a glob `pattern` using **S3 filter semantics**:
76/// only `*` is a wildcard (matching any run of characters, including none), and
77/// every other character — crucially including `?` — is matched literally.
78///
79/// S3 event notification prefix/suffix filters treat `*` as the only wildcard;
80/// AWS does not assign any special meaning to `?`. A generic glob matcher that
81/// interprets `?` as a single-character wildcard would let a literal `?` in a
82/// prefix/suffix filter (or object key) over-match and misroute events
83/// (backlog#979), so this matcher is hand-rolled to keep `?` literal.
84fn glob_match_star_only(pattern: &str, text: &str) -> bool {
85    let pattern: Vec<char> = pattern.chars().collect();
86    let text: Vec<char> = text.chars().collect();
87
88    let mut p = 0usize; // cursor into `pattern`
89    let mut t = 0usize; // cursor into `text`
90    // Backtracking state: the last `*` we saw and where in `text` we matched it.
91    let mut star_at: Option<usize> = None;
92    let mut star_match_t = 0usize;
93
94    while t < text.len() {
95        if p < pattern.len() && pattern[p] == '*' {
96            // Record the star and tentatively let it consume nothing.
97            star_at = Some(p);
98            star_match_t = t;
99            p += 1;
100        } else if p < pattern.len() && pattern[p] == text[t] {
101            // Literal match (any non-`*` char, including `?`).
102            p += 1;
103            t += 1;
104        } else if let Some(star_p) = star_at {
105            // Mismatch: let the previous `*` absorb one more character and retry.
106            p = star_p + 1;
107            star_match_t += 1;
108            t = star_match_t;
109        } else {
110            return false;
111        }
112    }
113
114    // Consume any trailing `*` in the pattern.
115    while p < pattern.len() && pattern[p] == '*' {
116        p += 1;
117    }
118
119    p == pattern.len()
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn test_new_pattern() {
128        assert_eq!(new_pattern(Some("images/"), Some(".jpg")), "images/*.jpg");
129        assert_eq!(new_pattern(Some("images/"), None), "images/*");
130        assert_eq!(new_pattern(None, Some(".jpg")), "*.jpg");
131        assert_eq!(new_pattern(Some("foo"), Some("bar")), "foo*bar"); // foo* + *bar -> foo**bar -> foo*bar
132        assert_eq!(new_pattern(Some("foo*"), Some("bar")), "foo*bar"); // foo* + *bar -> foo**bar -> foo*bar
133        assert_eq!(new_pattern(Some("foo"), Some("*bar")), "foo*bar"); // foo* + *bar -> foo**bar -> foo*bar
134        assert_eq!(new_pattern(Some("foo*"), Some("*bar")), "foo*bar"); // foo* + *bar -> foo**bar -> foo*bar
135        assert_eq!(new_pattern(Some("*"), Some("*")), "*"); // * + * -> ** -> *
136        assert_eq!(new_pattern(Some("a"), Some("")), "a*");
137        assert_eq!(new_pattern(Some(""), Some("b")), "*b");
138        assert_eq!(new_pattern(None, None), "");
139        assert_eq!(new_pattern(Some("prefix"), Some("suffix")), "prefix*suffix");
140        assert_eq!(new_pattern(Some("prefix/"), Some("/suffix")), "prefix/*/suffix"); // prefix/* + */suffix -> prefix/**/suffix -> prefix/*/suffix
141    }
142
143    #[test]
144    fn test_match_simple() {
145        assert!(match_simple("foo*", "foobar"));
146        assert!(!match_simple("foo*", "barfoo"));
147        assert!(match_simple("*.jpg", "photo.jpg"));
148        assert!(!match_simple("*.jpg", "photo.png"));
149        assert!(match_simple("*", "anything.anything"));
150        assert!(match_simple("foo*bar", "foobazbar"));
151        assert!(!match_simple("foo*bar", "foobar_baz"));
152        assert!(match_simple("a*b*c", "axbyc"));
153        assert!(match_simple("a*b*c", "abc"));
154        assert!(match_simple("a*b*c", "axbc"));
155    }
156
157    /// Regression test for backlog#979 (c): S3 filter semantics treat `*` as the
158    /// only wildcard. `?` must be matched literally, not as a single-character
159    /// wildcard (the way a generic glob matcher would treat it).
160    #[test]
161    fn question_mark_is_literal_not_single_char_wildcard() {
162        // `?` is a literal: it only matches a literal `?`, never an arbitrary char.
163        assert!(!match_simple("a?c", "abc"));
164        assert!(match_simple("a?c", "a?c"));
165
166        // Prefix-derived pattern containing a literal `?`.
167        let prefix_pattern = new_pattern(Some("foo?"), None);
168        assert_eq!(prefix_pattern, "foo?*");
169        assert!(!match_simple(&prefix_pattern, "fooX/bar")); // `?` must not match `X`
170        assert!(match_simple(&prefix_pattern, "foo?bar")); // literal `?` matches
171        assert!(!match_simple(&prefix_pattern, "foobar")); // `?` is required literally
172
173        // Suffix-derived pattern containing a literal `?`.
174        let suffix_pattern = new_pattern(None, Some("?.log"));
175        assert_eq!(suffix_pattern, "*?.log");
176        assert!(match_simple(&suffix_pattern, "app?.log"));
177        assert!(!match_simple(&suffix_pattern, "appX.log"));
178
179        // `*` continues to work as a multi-character wildcard alongside literal `?`.
180        assert!(match_simple("a?*c", "a?bbbc"));
181        assert!(!match_simple("a?*c", "aXbbbc"));
182    }
183}