flare_core/client/builder/
simple.rs1#[cfg(not(target_arch = "wasm32"))]
24use crate::client::HybridClient;
25#[cfg(target_arch = "wasm32")]
26use crate::client::WebSocketClient;
27use crate::client::builder::{BaseClientBuilderConfig, ClientWrapper};
28use crate::common::error::Result;
29use crate::common::protocol::Frame;
30use crate::transport::events::{ConnectionEvent, ConnectionObserver};
31use std::sync::Arc;
32
33pub type ClientMessageHandler = Box<dyn Fn(&Frame) -> Result<()> + Send + Sync>;
35
36pub type ClientEventHandler = Box<dyn Fn(&ConnectionEvent) + Send + Sync>;
38
39struct SimpleClientObserver {
41 message_handler: Option<ClientMessageHandler>,
42 event_handler: Option<ClientEventHandler>,
43}
44
45impl ConnectionObserver for SimpleClientObserver {
46 fn on_event(&self, event: &ConnectionEvent) {
47 if let Some(ref handler) = self.event_handler {
48 handler(event);
49 }
50
51 if let ConnectionEvent::Message(data) = event
52 && let Some(ref handler) = self.message_handler
53 && let Ok(frame) = crate::common::MessageParser::new(
54 crate::common::protocol::SerializationFormat::Protobuf,
55 crate::common::compression::CompressionAlgorithm::None,
56 crate::common::encryption::EncryptionAlgorithm::None,
57 )
58 .parse(data)
59 && let Err(e) = handler(&frame)
60 {
61 tracing::error!("消息处理错误: {:?}", e);
62 }
63 }
64}
65
66pub struct SimpleClient {
68 wrapper: ClientWrapper,
69 observer: Arc<SimpleClientObserver>,
70}
71
72impl SimpleClient {
73 pub async fn connect(&mut self) -> Result<()> {
75 self.wrapper
76 .add_observer(self.observer.clone() as Arc<dyn ConnectionObserver>)
77 .await;
78 self.wrapper.connect().await
79 }
80
81 pub async fn disconnect(&mut self) -> Result<()> {
83 self.wrapper.disconnect().await
84 }
85
86 pub async fn send_frame(&mut self, frame: &Frame) -> Result<()> {
88 self.wrapper.send_frame(frame).await
89 }
90
91 pub async fn send_frame_and_wait(
93 &mut self,
94 frame: &Frame,
95 timeout: std::time::Duration,
96 ) -> Result<Frame> {
97 self.wrapper.send_frame_and_wait(frame, timeout).await
98 }
99
100 pub async fn is_connected(&self) -> bool {
102 self.wrapper.is_connected_async().await
103 }
104
105 pub async fn connection_id(&self) -> Option<String> {
107 self.wrapper.connection_id_async().await
108 }
109
110 pub fn active_protocol(&self) -> crate::common::config_types::TransportProtocol {
112 self.wrapper.active_protocol()
113 }
114
115 pub async fn parser_snapshot(&self) -> crate::common::MessageParser {
117 self.wrapper.parser_snapshot().await
118 }
119
120 pub async fn wait_for_negotiation(&self, timeout: std::time::Duration) -> Result<()> {
122 self.wrapper.wait_for_negotiation(timeout).await
123 }
124}
125
126pub struct ClientBuilder {
140 base: BaseClientBuilderConfig,
141 message_handler: Option<ClientMessageHandler>,
142 event_handler: Option<ClientEventHandler>,
143}
144
145impl ClientBuilder {
146 pub fn new(server_url: impl Into<String>) -> Self {
151 Self {
152 base: BaseClientBuilderConfig::new(server_url),
153 message_handler: None,
154 event_handler: None,
155 }
156 }
157
158 pub fn on_message<F>(mut self, handler: F) -> Self
163 where
164 F: Fn(&Frame) -> Result<()> + Send + Sync + 'static,
165 {
166 self.message_handler = Some(Box::new(handler));
167 self
168 }
169
170 pub fn on_event<F>(mut self, handler: F) -> Self
175 where
176 F: Fn(&ConnectionEvent) + Send + Sync + 'static,
177 {
178 self.event_handler = Some(Box::new(handler));
179 self
180 }
181
182 pub fn with_protocol(
184 mut self,
185 protocol: crate::common::config_types::TransportProtocol,
186 ) -> Self {
187 self.base = self.base.with_protocol(protocol);
188 self
189 }
190
191 pub fn with_protocol_race(
195 mut self,
196 protocols: Vec<crate::common::config_types::TransportProtocol>,
197 ) -> Self {
198 self.base = self.base.with_protocol_race(protocols);
199 self
200 }
201
202 pub fn with_protocol_url(
204 mut self,
205 protocol: crate::common::config_types::TransportProtocol,
206 url: String,
207 ) -> Self {
208 self.base = self.base.with_protocol_url(protocol, url);
209 self
210 }
211
212 pub fn with_user_id(mut self, user_id: String) -> Self {
214 self.base = self.base.with_user_id(user_id);
215 self
216 }
217
218 pub fn with_device_info(mut self, device_info: crate::common::device::DeviceInfo) -> Self {
220 self.base = self.base.with_device_info(device_info);
221 self
222 }
223
224 pub fn with_token(mut self, token: String) -> Self {
226 self.base = self.base.with_token(token);
227 self
228 }
229
230 pub fn with_format(mut self, format: crate::common::protocol::SerializationFormat) -> Self {
232 self.base = self.base.with_format(format);
233 self
234 }
235
236 pub fn with_compression(
238 mut self,
239 compression: crate::common::compression::CompressionAlgorithm,
240 ) -> Self {
241 self.base = self.base.with_compression(compression);
242 self
243 }
244
245 pub fn with_heartbeat(
247 mut self,
248 heartbeat: crate::common::config_types::HeartbeatConfig,
249 ) -> Self {
250 self.base = self.base.with_heartbeat(heartbeat);
251 self
252 }
253
254 pub fn with_tls(mut self, tls: crate::common::config_types::TlsConfig) -> Self {
256 self.base = self.base.with_tls(tls);
257 self
258 }
259
260 pub fn with_connect_timeout(mut self, timeout: std::time::Duration) -> Self {
262 self.base = self.base.with_connect_timeout(timeout);
263 self
264 }
265
266 pub fn with_reconnect_interval(mut self, interval: std::time::Duration) -> Self {
268 self.base = self.base.with_reconnect_interval(interval);
269 self
270 }
271
272 pub fn with_max_reconnect_attempts(mut self, max: Option<u32>) -> Self {
274 self.base = self.base.with_max_reconnect_attempts(max);
275 self
276 }
277
278 pub fn enable_router(mut self) -> Self {
282 self.base = self.base.enable_router();
283 self
284 }
285
286 pub fn build(self) -> Result<SimpleClient> {
291 let observer = Arc::new(SimpleClientObserver {
292 message_handler: self.message_handler,
293 event_handler: self.event_handler,
294 });
295
296 let client = {
297 #[cfg(not(target_arch = "wasm32"))]
298 {
299 HybridClient::new(self.base.config)?
300 }
301 #[cfg(target_arch = "wasm32")]
302 {
303 WebSocketClient::new(self.base.config)
304 }
305 };
306 let wrapper = ClientWrapper::new(client);
307
308 Ok(SimpleClient { wrapper, observer })
309 }
310}