flare_core/common/message/
processor.rs1use super::pipeline::{MessageContext, MessageProcessor};
6use crate::common::error::Result;
7use crate::common::protocol::Frame;
8use async_trait::async_trait;
9use std::sync::Arc;
10
11pub struct FunctionProcessor {
15 name: String,
16 #[allow(clippy::type_complexity)]
17 handler: Arc<
18 dyn Fn(
19 &MessageContext,
20 )
21 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Option<Frame>>> + Send>>
22 + Send
23 + Sync,
24 >,
25}
26
27impl FunctionProcessor {
28 pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
30 where
31 F: Fn(&MessageContext) -> Fut + Send + Sync + 'static,
32 Fut: std::future::Future<Output = Result<Option<Frame>>> + Send + 'static,
33 {
34 Self {
35 name: name.into(),
36 handler: Arc::new(move |ctx| Box::pin(handler(ctx))),
37 }
38 }
39}
40
41#[async_trait]
42impl MessageProcessor for FunctionProcessor {
43 async fn process(&self, ctx: &MessageContext) -> Result<Option<Frame>> {
44 (self.handler)(ctx).await
45 }
46
47 fn name(&self) -> &str {
48 &self.name
49 }
50}
51
52pub struct DelegateProcessor {
56 name: String,
57 #[allow(clippy::type_complexity)]
58 handler: Arc<
59 dyn Fn(
60 &Frame,
61 Option<&str>,
62 )
63 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Option<Frame>>> + Send>>
64 + Send
65 + Sync,
66 >,
67}
68
69impl DelegateProcessor {
70 pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
72 where
73 F: Fn(&Frame, Option<&str>) -> Fut + Send + Sync + 'static,
74 Fut: std::future::Future<Output = Result<Option<Frame>>> + Send + 'static,
75 {
76 Self {
77 name: name.into(),
78 handler: Arc::new(move |frame, conn_id| Box::pin(handler(frame, conn_id))),
79 }
80 }
81}
82
83#[async_trait]
84impl MessageProcessor for DelegateProcessor {
85 async fn process(&self, ctx: &MessageContext) -> Result<Option<Frame>> {
86 (self.handler)(&ctx.frame, ctx.connection_id.as_deref()).await
87 }
88
89 fn name(&self) -> &str {
90 &self.name
91 }
92}