|
| 1 | +use std::convert::Infallible; |
| 2 | +use std::sync::atomic::{AtomicU64, Ordering}; |
| 3 | + |
| 4 | +use async_trait::async_trait; |
| 5 | +use once_cell::sync::Lazy; |
| 6 | + |
| 7 | +use crate::filter::{Context, FilterFactory, Options}; |
| 8 | +use crate::protocol::Message; |
| 9 | + |
| 10 | +use super::proto::Filter; |
| 11 | + |
| 12 | +static NOOP_SEQ: Lazy<(AtomicU64, AtomicU64)> = |
| 13 | + Lazy::new(|| (AtomicU64::new(0), AtomicU64::new(0))); |
| 14 | + |
| 15 | +#[derive(Default)] |
| 16 | +pub(crate) struct NoopFilter { |
| 17 | + next: Option<Box<dyn Filter>>, |
| 18 | +} |
| 19 | + |
| 20 | +impl NoopFilter { |
| 21 | + pub(crate) fn reset() { |
| 22 | + let (req, res) = &*NOOP_SEQ; |
| 23 | + req.store(0, Ordering::SeqCst); |
| 24 | + res.store(0, Ordering::SeqCst); |
| 25 | + } |
| 26 | + |
| 27 | + pub(crate) fn requests() -> u64 { |
| 28 | + let (seq, _) = &*NOOP_SEQ; |
| 29 | + seq.load(Ordering::SeqCst) |
| 30 | + } |
| 31 | + |
| 32 | + pub(crate) fn responses() -> u64 { |
| 33 | + let (_, seq) = &*NOOP_SEQ; |
| 34 | + seq.load(Ordering::SeqCst) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +#[async_trait] |
| 39 | +impl Filter for NoopFilter { |
| 40 | + async fn on_request( |
| 41 | + &self, |
| 42 | + ctx: &mut Context, |
| 43 | + req: &mut Message, |
| 44 | + ) -> crate::Result<Option<Message>> { |
| 45 | + let (seq, _) = &*NOOP_SEQ; |
| 46 | + |
| 47 | + let cnt = seq.fetch_add(1, Ordering::SeqCst) + 1; |
| 48 | + info!("call 'on_request' from noop filter ok: cnt={}", cnt); |
| 49 | + |
| 50 | + if let Some(next) = &self.next { |
| 51 | + return next.on_request(ctx, req).await; |
| 52 | + } |
| 53 | + |
| 54 | + Ok(None) |
| 55 | + } |
| 56 | + |
| 57 | + async fn on_response(&self, ctx: &mut Context, res: &mut Option<Message>) -> crate::Result<()> { |
| 58 | + let (_, seq) = &*NOOP_SEQ; |
| 59 | + |
| 60 | + let cnt = seq.fetch_add(1, Ordering::SeqCst) + 1; |
| 61 | + info!("call 'on_response' from noop filter ok: cnt={}", cnt); |
| 62 | + |
| 63 | + if let Some(next) = &self.next { |
| 64 | + return next.on_response(ctx, res).await; |
| 65 | + } |
| 66 | + |
| 67 | + Ok(()) |
| 68 | + } |
| 69 | + |
| 70 | + fn next(&self) -> Option<&dyn Filter> { |
| 71 | + self.next.as_deref() |
| 72 | + } |
| 73 | + |
| 74 | + fn set_next(&mut self, next: Box<dyn Filter>) { |
| 75 | + self.next.replace(next); |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +pub(crate) struct NoopFilterFactory; |
| 80 | + |
| 81 | +impl FilterFactory for NoopFilterFactory { |
| 82 | + type Item = NoopFilter; |
| 83 | + |
| 84 | + fn get(&self) -> crate::Result<Self::Item> { |
| 85 | + Ok(Default::default()) |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +impl TryFrom<&Options> for NoopFilterFactory { |
| 90 | + type Error = Infallible; |
| 91 | + |
| 92 | + fn try_from(value: &Options) -> Result<Self, Self::Error> { |
| 93 | + Ok(NoopFilterFactory) |
| 94 | + } |
| 95 | +} |
0 commit comments