rocketmq-filter 1.1.0

A filter for RocketMQ messages
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use rocketmq_error::Result;
use std::convert::TryInto;

use super::invalid_filter;
use crate::utils::bits_array::BitsArray;
use crate::utils::bloom_filter_data::BloomFilterData;

/// Simple implementation of Bloom Filter.
///
/// This implementation follows the Java RocketMQ BloomFilter design:
/// - Uses double hashing technique (Kirsch-Mitzenmacher optimization)
/// - Configurable false positive rate
/// - Bit array size automatically calculated
///
/// # Examples
///
/// ```ignore
/// use rocketmq_filter::utils::bloom_filter::BloomFilter;
/// use rocketmq_filter::utils::bits_array::BitsArray;
///
/// let filter = BloomFilter::create_by_fn(10, 100).unwrap();
/// let mut bits = BitsArray::create(filter.m() as usize);
///
/// filter.hash_to_str("key1", &mut bits).unwrap();
/// assert!(filter.is_hit_str("key1", &bits).unwrap());
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BloomFilter {
    /// Error rate (f/100, e.g., 10 means 10%)
    f: i32,
    /// Expected number of elements
    n: i32,
    /// Number of hash functions
    k: i32,
    /// Total number of bits
    m: i32,
}

impl BloomFilter {
    /// Create a Bloom filter with specified error rate and expected element count.
    ///
    /// # Arguments
    ///
    /// * `f` - Error rate (1-99, representing percentage)
    /// * `n` - Expected number of elements
    ///
    /// # Formula
    ///
    /// - k = ceil(ln(0.5) / ln(error_rate))
    /// - m = ceil(n * ln(1/error_rate) / (ln(2)^2))
    /// - m adjusted to be multiple of 8
    pub fn create_by_fn(f: i32, n: i32) -> Result<Self> {
        if !(1..100).contains(&f) {
            return Err(invalid_filter("invalid_false_positive_rate"));
        }
        if n < 1 {
            return Err(invalid_filter("invalid_expected_element_count"));
        }

        let error_rate = f as f64 / 100.0;

        // Calculate optimal k: k = ln(2) * (m/n) ≈ 0.693 * (m/n)
        // Simplified: when p=0.5, k = ln(0.5) / ln(error_rate)
        let k = (Self::log_mn(0.5, error_rate)).ceil() as i32;

        if k < 1 {
            return Err(invalid_filter("invalid_hash_function_count"));
        }

        // Calculate m: m = n * ln(1/error_rate) / (ln(2))^2
        let m = (n as f64 * Self::log_mn(2.0, 1.0 / error_rate) * Self::log_mn(2.0, std::f64::consts::E)).ceil() as i32;

        // Ensure m is multiple of 8 (byte alignment)
        let m = 8 * ((m + 7) / 8);

        Ok(BloomFilter { f, n, k, m })
    }

    /// Calculate bit positions for a string using double hashing.
    ///
    /// Implements the Kirsch-Mitzenmacher optimization:
    /// "Less Hashing, Same Performance: Building a Better Bloom Filter"
    ///
    /// Uses two hash values (h1, h2) to generate k hash positions:
    /// g(i) = h1 + i * h2 (mod m)
    pub fn calc_bit_positions(&self, s: &str) -> Vec<i32> {
        let mut bit_positions = vec![0i32; self.k as usize];

        // Match Java RocketMQ exactly: Hashing.murmur3_128().hashString(str, UTF_8).asLong()
        let hash64 = Self::hash_string(s);

        let hash1 = hash64 as i32;
        let hash2 = (hash64 >> 32) as i32;

        for i in 1..=self.k {
            let mut combined_hash = hash1.wrapping_add(i.wrapping_mul(hash2));

            // Flip bits if negative to ensure positive
            if combined_hash < 0 {
                combined_hash = !combined_hash;
            }

            bit_positions[(i - 1) as usize] = combined_hash % self.m;
        }

        bit_positions
    }

    /// Generate BloomFilterData for a string.
    pub fn generate(&self, s: &str) -> BloomFilterData {
        let bit_positions = self.calc_bit_positions(s);
        BloomFilterData::new(bit_positions, self.m as u32)
    }

    /// Hash a string to bit array (by string).
    pub fn hash_to_str(&self, s: &str, bits: &mut BitsArray) -> Result<()> {
        let bit_positions = self.calc_bit_positions(s);
        self.hash_to_positions(&bit_positions, bits)
    }

    /// Hash to bit array using pre-calculated positions.
    pub fn hash_to_positions(&self, bit_positions: &[i32], bits: &mut BitsArray) -> Result<()> {
        self.check(bits)?;

        for &pos in bit_positions {
            bits.set_bit(pos as usize, true)?;
        }

        Ok(())
    }

    /// Hash to bit array using BloomFilterData.
    pub fn hash_to(&self, filter_data: &BloomFilterData, bits: &mut BitsArray) -> Result<()> {
        if !self.is_valid(Some(filter_data)) {
            return Err(invalid_filter("filter_data_mismatch"));
        }

        self.hash_to_positions(filter_data.bit_pos(), bits)
    }

    /// Check if a string might be in the set (by string).
    pub fn is_hit_str(&self, s: &str, bits: &BitsArray) -> Result<bool> {
        let bit_positions = self.calc_bit_positions(s);
        self.is_hit_positions(&bit_positions, bits)
    }

    /// Check if all bit positions are set.
    pub fn is_hit_positions(&self, bit_positions: &[i32], bits: &BitsArray) -> Result<bool> {
        self.check(bits)?;

        // Check first position
        let mut result = bits.get_bit(bit_positions[0] as usize)?;

        // AND with remaining positions
        for &pos in &bit_positions[1..] {
            result &= bits.get_bit(pos as usize)?;
        }

        Ok(result)
    }

    /// Check if BloomFilterData might be in the set.
    pub fn is_hit(&self, filter_data: &BloomFilterData, bits: &BitsArray) -> Result<bool> {
        if !self.is_valid(Some(filter_data)) {
            return Err(invalid_filter("filter_data_mismatch"));
        }

        self.is_hit_positions(filter_data.bit_pos(), bits)
    }

    /// Check if BloomFilterData might be in the set using a raw byte slice.
    ///
    /// This avoids constructing a temporary [`BitsArray`] on hot consume-queue paths.
    pub fn is_hit_bytes(&self, filter_data: &BloomFilterData, bits: &[u8]) -> Result<bool> {
        if !self.is_valid(Some(filter_data)) {
            return Err(invalid_filter("filter_data_mismatch"));
        }

        self.check_bytes(bits)?;
        for &pos in filter_data.bit_pos() {
            let bit_pos = pos as usize;
            let byte_index = bit_pos / 8;
            let bit_mask = 1u8 << (bit_pos % 8);
            if bits[byte_index] & bit_mask == 0 {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Check if positions would result in a false positive.
    ///
    /// Returns true if all positions are already occupied.
    pub fn check_false_hit(&self, bit_positions: &[i32], bits: &BitsArray) -> Result<bool> {
        for &pos in bit_positions {
            if !bits.get_bit(pos as usize)? {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Validate bit array length matches filter configuration.
    #[inline]
    fn check(&self, bits: &BitsArray) -> Result<()> {
        if bits.bit_length() != self.m as usize {
            return Err(invalid_filter("bit_length_mismatch"));
        }
        Ok(())
    }

    #[inline]
    fn check_bytes(&self, bits: &[u8]) -> Result<()> {
        if bits.len() * 8 != self.m as usize {
            return Err(invalid_filter("bit_length_mismatch"));
        }
        Ok(())
    }

    /// Validate BloomFilterData belongs to this filter.
    pub fn is_valid(&self, filter_data: Option<&BloomFilterData>) -> bool {
        match filter_data {
            Some(data) => {
                data.bit_num() == self.m as u32 && !data.bit_pos().is_empty() && data.bit_pos().len() == self.k as usize
            }
            None => false,
        }
    }

    /// Hash string using MurmurHash3 x64 128, matching the Java implementation.
    #[inline]
    fn hash_string(s: &str) -> u64 {
        let (h1, _) = Self::murmur3_x64_128(s.as_bytes(), 0);
        h1
    }

    fn murmur3_x64_128(bytes: &[u8], seed: u32) -> (u64, u64) {
        const C1: u64 = 0x87c3_7b91_1142_53d5;
        const C2: u64 = 0x4cf5_ad43_2745_937f;

        let mut h1 = seed as u64;
        let mut h2 = seed as u64;

        let block_count = bytes.len() / 16;
        for index in 0..block_count {
            let offset = index * 16;
            let mut k1 = u64::from_le_bytes(bytes[offset..offset + 8].try_into().expect("slice is exactly 8 bytes"));
            let mut k2 = u64::from_le_bytes(
                bytes[offset + 8..offset + 16]
                    .try_into()
                    .expect("slice is exactly 8 bytes"),
            );

            k1 = k1.wrapping_mul(C1);
            k1 = k1.rotate_left(31);
            k1 = k1.wrapping_mul(C2);
            h1 ^= k1;

            h1 = h1.rotate_left(27);
            h1 = h1.wrapping_add(h2);
            h1 = h1.wrapping_mul(5).wrapping_add(0x52dc_e729);

            k2 = k2.wrapping_mul(C2);
            k2 = k2.rotate_left(33);
            k2 = k2.wrapping_mul(C1);
            h2 ^= k2;

            h2 = h2.rotate_left(31);
            h2 = h2.wrapping_add(h1);
            h2 = h2.wrapping_mul(5).wrapping_add(0x3849_5ab5);
        }

        let tail = &bytes[block_count * 16..];
        let mut k1 = 0u64;
        let mut k2 = 0u64;

        for (index, byte) in tail.iter().enumerate() {
            if index < 8 {
                k1 |= (*byte as u64) << (index * 8);
            } else {
                k2 |= (*byte as u64) << ((index - 8) * 8);
            }
        }

        if tail.len() > 8 {
            k2 = k2.wrapping_mul(C2);
            k2 = k2.rotate_left(33);
            k2 = k2.wrapping_mul(C1);
            h2 ^= k2;
        }

        if !tail.is_empty() {
            k1 = k1.wrapping_mul(C1);
            k1 = k1.rotate_left(31);
            k1 = k1.wrapping_mul(C2);
            h1 ^= k1;
        }

        h1 ^= bytes.len() as u64;
        h2 ^= bytes.len() as u64;

        h1 = h1.wrapping_add(h2);
        h2 = h2.wrapping_add(h1);

        h1 = Self::fmix64(h1);
        h2 = Self::fmix64(h2);

        h1 = h1.wrapping_add(h2);
        h2 = h2.wrapping_add(h1);

        (h1, h2)
    }

    #[inline]
    fn fmix64(mut value: u64) -> u64 {
        value ^= value >> 33;
        value = value.wrapping_mul(0xff51_afd7_ed55_8ccd);
        value ^= value >> 33;
        value = value.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
        value ^= value >> 33;
        value
    }

    /// Calculate log base m of n: log_m(n)
    #[inline]
    fn log_mn(m: f64, n: f64) -> f64 {
        n.ln() / m.ln()
    }

    // Getters

    /// Get error rate (percentage).
    #[inline]
    pub fn f(&self) -> i32 {
        self.f
    }

    /// Get expected element count.
    #[inline]
    pub fn n(&self) -> i32 {
        self.n
    }

    /// Get number of hash functions.
    #[inline]
    pub fn k(&self) -> i32 {
        self.k
    }

    /// Get total number of bits.
    #[inline]
    pub fn m(&self) -> i32 {
        self.m
    }
}

impl std::fmt::Display for BloomFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "BloomFilter {{ f: {}, n: {}, k: {}, m: {} }}",
            self.f, self.n, self.k, self.m
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_create_by_fn() {
        let filter = BloomFilter::create_by_fn(10, 100).unwrap();
        assert_eq!(filter.f(), 10);
        assert_eq!(filter.n(), 100);
        assert!(filter.k() > 0);
        assert!(filter.m() > 0);
        assert_eq!(filter.m() % 8, 0); // Must be multiple of 8
    }

    #[test]
    fn test_invalid_parameters() {
        assert!(BloomFilter::create_by_fn(0, 100).is_err());
        assert!(BloomFilter::create_by_fn(100, 100).is_err());
        assert!(BloomFilter::create_by_fn(10, 0).is_err());
    }

    #[test]
    fn test_calc_bit_positions() {
        let filter = BloomFilter::create_by_fn(10, 100).unwrap();
        let positions = filter.calc_bit_positions("test_key");

        assert_eq!(positions.len(), filter.k() as usize);

        // All positions should be within bounds
        for &pos in &positions {
            assert!(pos >= 0 && pos < filter.m());
        }

        // Same input should produce same positions
        let positions2 = filter.calc_bit_positions("test_key");
        assert_eq!(positions, positions2);
    }

    #[test]
    fn test_empty_string_matches_java_zero_hash() {
        let filter = BloomFilter::create_by_fn(10, 100).unwrap();
        assert_eq!(filter.calc_bit_positions(""), vec![0; filter.k() as usize]);
    }

    #[test]
    fn test_hash_and_hit() {
        let filter = BloomFilter::create_by_fn(10, 100).unwrap();
        let mut bits = BitsArray::create(filter.m() as usize);

        // Hash a key
        filter.hash_to_str("key1", &mut bits).unwrap();

        // Should hit
        assert!(filter.is_hit_str("key1", &bits).unwrap());

        // Should not hit (most likely)
        assert!(!filter.is_hit_str("key2", &bits).unwrap());
    }

    #[test]
    fn test_is_hit_bytes_matches_bits_array_behavior() {
        let filter = BloomFilter::create_by_fn(10, 100).unwrap();
        let filter_data = filter.generate("key1");
        let mut bits = BitsArray::create(filter.m() as usize);
        filter.hash_to(&filter_data, &mut bits).unwrap();

        assert_eq!(
            filter.is_hit(&filter_data, &bits).unwrap(),
            filter.is_hit_bytes(&filter_data, bits.bytes()).unwrap()
        );
        assert!(!filter.is_hit_bytes(&filter.generate("key2"), bits.bytes()).unwrap());
    }

    #[test]
    fn test_multiple_keys() {
        let filter = BloomFilter::create_by_fn(5, 200).unwrap();
        let mut bits = BitsArray::create(filter.m() as usize);

        let keys = vec!["key1", "key2", "key3", "key4", "key5"];

        // Add all keys
        for key in &keys {
            filter.hash_to_str(key, &mut bits).unwrap();
        }

        // All keys should hit
        for key in &keys {
            assert!(filter.is_hit_str(key, &bits).unwrap());
        }
    }

    #[test]
    fn test_generate() {
        let filter = BloomFilter::create_by_fn(10, 100).unwrap();
        let data = filter.generate("test_key");

        assert_eq!(data.bit_num(), filter.m() as u32);
        assert_eq!(data.bit_pos().len(), filter.k() as usize);
        assert!(filter.is_valid(Some(&data)));
    }

    #[test]
    fn test_is_valid() {
        let filter = BloomFilter::create_by_fn(10, 100).unwrap();

        // Valid data
        let valid_data = BloomFilterData::new(vec![1, 2, 3], filter.m() as u32);
        if valid_data.bit_pos().len() == filter.k() as usize {
            assert!(filter.is_valid(Some(&valid_data)));
        }

        // Invalid: wrong bit count
        let invalid_data = BloomFilterData::new(vec![1, 2, 3], (filter.m() + 1) as u32);
        assert!(!filter.is_valid(Some(&invalid_data)));

        // None
        assert!(!filter.is_valid(None));
    }

    #[test]
    fn test_check_false_hit() {
        let filter = BloomFilter::create_by_fn(1, 300).unwrap();
        let mut bits = BitsArray::create(filter.m() as usize);

        let mut false_hits = 0;

        for i in 0..filter.n() {
            let key = format!("key_{}", i);
            let positions = filter.calc_bit_positions(&key);

            if filter.check_false_hit(&positions, &bits).unwrap() {
                false_hits += 1;
            }

            filter.hash_to_positions(&positions, &mut bits).unwrap();
        }

        // False positive rate should be within expected range
        let actual_rate = (false_hits as f64 / filter.n() as f64) * 100.0;
        assert!(actual_rate <= filter.f() as f64);
    }

    #[test]
    fn test_equality() {
        let filter1 = BloomFilter::create_by_fn(10, 100).unwrap();
        let filter2 = BloomFilter::create_by_fn(10, 100).unwrap();
        let filter3 = BloomFilter::create_by_fn(20, 100).unwrap();

        assert_eq!(filter1, filter2);
        assert_ne!(filter1, filter3);
    }
}