Skip to main content

hyperlane_plugin_websocket/
impl.rs

1use super::*;
2
3/// Allows `String` to be used as a broadcast identifier.
4impl BroadcastTypeTrait for String {}
5
6/// Allows string slices to be used as broadcast identifiers.
7impl BroadcastTypeTrait for &str {}
8
9/// Allows `char` to be used as a broadcast identifier.
10impl BroadcastTypeTrait for char {}
11
12/// Allows `bool` to be used as a broadcast identifier.
13impl BroadcastTypeTrait for bool {}
14
15/// Allows `i8` to be used as a broadcast identifier.
16impl BroadcastTypeTrait for i8 {}
17
18/// Allows `i16` to be used as a broadcast identifier.
19impl BroadcastTypeTrait for i16 {}
20
21/// Allows `i32` to be used as a broadcast identifier.
22impl BroadcastTypeTrait for i32 {}
23
24/// Allows `i64` to be used as a broadcast identifier.
25impl BroadcastTypeTrait for i64 {}
26
27/// Allows `i128` to be used as a broadcast identifier.
28impl BroadcastTypeTrait for i128 {}
29
30/// Allows `isize` to be used as a broadcast identifier.
31impl BroadcastTypeTrait for isize {}
32
33/// Allows `u8` to be used as a broadcast identifier.
34impl BroadcastTypeTrait for u8 {}
35
36/// Allows `u16` to be used as a broadcast identifier.
37impl BroadcastTypeTrait for u16 {}
38
39/// Allows `u32` to be used as a broadcast identifier.
40impl BroadcastTypeTrait for u32 {}
41
42/// Allows `u64` to be used as a broadcast identifier.
43impl BroadcastTypeTrait for u64 {}
44
45/// Allows `u128` to be used as a broadcast identifier.
46impl BroadcastTypeTrait for u128 {}
47
48/// Allows `usize` to be used as a broadcast identifier.
49impl BroadcastTypeTrait for usize {}
50
51/// Allows `f32` to be used as a broadcast identifier.
52impl BroadcastTypeTrait for f32 {}
53
54/// Allows `f64` to be used as a broadcast identifier.
55impl BroadcastTypeTrait for f64 {}
56
57/// Allows `IpAddr` to be used as a broadcast identifier.
58impl BroadcastTypeTrait for IpAddr {}
59
60/// Allows `Ipv4Addr` to be used as a broadcast identifier.
61impl BroadcastTypeTrait for Ipv4Addr {}
62
63/// Allows `Ipv6Addr` to be used as a broadcast identifier.
64impl BroadcastTypeTrait for Ipv6Addr {}
65
66/// Allows `SocketAddr` to be used as a broadcast identifier.
67impl BroadcastTypeTrait for SocketAddr {}
68
69/// Allows `NonZeroU8` to be used as a broadcast identifier.
70impl BroadcastTypeTrait for NonZeroU8 {}
71
72/// Allows `NonZeroU16` to be used as a broadcast identifier.
73impl BroadcastTypeTrait for NonZeroU16 {}
74
75/// Allows `NonZeroU32` to be used as a broadcast identifier.
76impl BroadcastTypeTrait for NonZeroU32 {}
77
78/// Allows `NonZeroU64` to be used as a broadcast identifier.
79impl BroadcastTypeTrait for NonZeroU64 {}
80
81/// Allows `NonZeroU128` to be used as a broadcast identifier.
82impl BroadcastTypeTrait for NonZeroU128 {}
83
84/// Allows `NonZeroUsize` to be used as a broadcast identifier.
85impl BroadcastTypeTrait for NonZeroUsize {}
86
87/// Allows `NonZeroI8` to be used as a broadcast identifier.
88impl BroadcastTypeTrait for NonZeroI8 {}
89
90/// Allows `NonZeroI16` to be used as a broadcast identifier.
91impl BroadcastTypeTrait for NonZeroI16 {}
92
93/// Allows `NonZeroI32` to be used as a broadcast identifier.
94impl BroadcastTypeTrait for NonZeroI32 {}
95
96/// Allows `NonZeroI64` to be used as a broadcast identifier.
97impl BroadcastTypeTrait for NonZeroI64 {}
98
99/// Allows `NonZeroI128` to be used as a broadcast identifier.
100impl BroadcastTypeTrait for NonZeroI128 {}
101
102/// Allows `NonZeroIsize` to be used as a broadcast identifier.
103impl BroadcastTypeTrait for NonZeroIsize {}
104
105/// Allows `Infallible` to be used as a broadcast identifier.
106impl BroadcastTypeTrait for Infallible {}
107
108/// Allows references to `String` to be used as broadcast identifiers.
109impl BroadcastTypeTrait for &String {}
110
111/// Allows double references to string slices to be used as broadcast identifiers.
112impl BroadcastTypeTrait for &&str {}
113
114/// Allows references to `char` to be used as broadcast identifiers.
115impl BroadcastTypeTrait for &char {}
116
117/// Allows references to `bool` to be used as broadcast identifiers.
118impl BroadcastTypeTrait for &bool {}
119
120/// Allows references to `i8` to be used as broadcast identifiers.
121impl BroadcastTypeTrait for &i8 {}
122
123/// Allows references to `i16` to be used as broadcast identifiers.
124impl BroadcastTypeTrait for &i16 {}
125
126/// Allows references to `i32` to be used as broadcast identifiers.
127impl BroadcastTypeTrait for &i32 {}
128
129/// Allows references to `i64` to be used as broadcast identifiers.
130impl BroadcastTypeTrait for &i64 {}
131
132/// Allows references to `i128` to be used as broadcast identifiers.
133impl BroadcastTypeTrait for &i128 {}
134
135/// Allows references to `isize` to be used as broadcast identifiers.
136impl BroadcastTypeTrait for &isize {}
137
138/// Allows references to `u8` to be used as broadcast identifiers.
139impl BroadcastTypeTrait for &u8 {}
140
141/// Allows references to `u16` to be used as broadcast identifiers.
142impl BroadcastTypeTrait for &u16 {}
143
144/// Allows references to `u32` to be used as broadcast identifiers.
145impl BroadcastTypeTrait for &u32 {}
146
147/// Implements `BroadcastTypeTrait` for `&u64`.
148///
149/// This allows references to `u64` to be used as a broadcast identifier.
150impl BroadcastTypeTrait for &u64 {}
151
152/// Implements `BroadcastTypeTrait` for `&u128`.
153///
154/// This allows references to `u128` to be used as a broadcast identifier.
155impl BroadcastTypeTrait for &u128 {}
156
157/// Implements `BroadcastTypeTrait` for `&usize`.
158///
159/// This allows references to `usize` to be used as a broadcast identifier.
160impl BroadcastTypeTrait for &usize {}
161
162/// Implements `BroadcastTypeTrait` for `&f32`.
163///
164/// This allows references to `f32` to be used as a broadcast identifier.
165impl BroadcastTypeTrait for &f32 {}
166
167/// Implements `BroadcastTypeTrait` for `&f64`.
168///
169/// This allows references to `f64` to be used as a broadcast identifier.
170impl BroadcastTypeTrait for &f64 {}
171
172/// Implements `BroadcastTypeTrait` for `&IpAddr`.
173///
174/// This allows references to `IpAddr` to be used as a broadcast identifier.
175impl BroadcastTypeTrait for &IpAddr {}
176
177/// Implements `BroadcastTypeTrait` for `&Ipv4Addr`.
178///
179/// This allows references to `Ipv4Addr` to be used as a broadcast identifier.
180impl BroadcastTypeTrait for &Ipv4Addr {}
181
182/// Implements `BroadcastTypeTrait` for `&Ipv6Addr`.
183///
184/// This allows references to `Ipv6Addr` to be used as a broadcast identifier.
185impl BroadcastTypeTrait for &Ipv6Addr {}
186
187/// Implements `BroadcastTypeTrait` for `&SocketAddr`.
188///
189/// This allows references to `SocketAddr` to be used as a broadcast identifier.
190impl BroadcastTypeTrait for &SocketAddr {}
191
192/// Implements `BroadcastTypeTrait` for `&NonZeroU8`.
193///
194/// This allows references to `NonZeroU8` to be used as a broadcast identifier.
195impl BroadcastTypeTrait for &NonZeroU8 {}
196
197/// Implements `BroadcastTypeTrait` for `&NonZeroU16`.
198///
199/// This allows references to `NonZeroU16` to be used as a broadcast identifier.
200impl BroadcastTypeTrait for &NonZeroU16 {}
201
202/// Implements `BroadcastTypeTrait` for `&NonZeroU32`.
203///
204/// This allows references to `NonZeroU32` to be used as a broadcast identifier.
205impl BroadcastTypeTrait for &NonZeroU32 {}
206
207/// Implements `BroadcastTypeTrait` for `&NonZeroU64`.
208///
209/// This allows references to `NonZeroU64` to be used as a broadcast identifier.
210impl BroadcastTypeTrait for &NonZeroU64 {}
211
212/// Implements `BroadcastTypeTrait` for `&NonZeroU128`.
213///
214/// This allows references to `NonZeroU128` to be used as a broadcast identifier.
215impl BroadcastTypeTrait for &NonZeroU128 {}
216
217/// Implements `BroadcastTypeTrait` for `&NonZeroUsize`.
218///
219/// This allows references to `NonZeroUsize` to be used as a broadcast identifier.
220impl BroadcastTypeTrait for &NonZeroUsize {}
221
222/// Implements `BroadcastTypeTrait` for `&NonZeroI8`.
223///
224/// This allows references to `NonZeroI8` to be used as a broadcast identifier.
225impl BroadcastTypeTrait for &NonZeroI8 {}
226
227/// Implements `BroadcastTypeTrait` for `&NonZeroI16`.
228///
229/// This allows references to `NonZeroI16` to be used as a broadcast identifier.
230impl BroadcastTypeTrait for &NonZeroI16 {}
231
232/// Implements `BroadcastTypeTrait` for `&NonZeroI32`.
233///
234/// This allows references to `NonZeroI32` to be used as a broadcast identifier.
235impl BroadcastTypeTrait for &NonZeroI32 {}
236
237/// Implements `BroadcastTypeTrait` for `&NonZeroI64`.
238///
239/// This allows references to `NonZeroI64` to be used as a broadcast identifier.
240impl BroadcastTypeTrait for &NonZeroI64 {}
241
242/// Implements `BroadcastTypeTrait` for `&NonZeroI128`.
243///
244/// This allows references to `NonZeroI128` to be used as a broadcast identifier.
245impl BroadcastTypeTrait for &NonZeroI128 {}
246
247/// Implements `BroadcastTypeTrait` for `&NonZeroIsize`.
248///
249/// This allows references to `NonZeroIsize` to be used as a broadcast identifier.
250impl BroadcastTypeTrait for &NonZeroIsize {}
251
252/// Implements `BroadcastTypeTrait` for `&Infallible`.
253///
254/// This allows references to `Infallible` to be used as a broadcast identifier.
255impl BroadcastTypeTrait for &Infallible {}
256
257/// Implements the `Default` trait for `BroadcastType`.
258///
259/// The default value is `BroadcastType::Unknown`.
260///
261/// # Type Parameters
262///
263/// - `BroadcastTypeTrait`: The type parameter for `BroadcastType`, which must implement `BroadcastTypeTrait`.
264impl<B> Default for BroadcastType<B>
265where
266    B: BroadcastTypeTrait,
267{
268    /// Returns the default `BroadcastType`, which is `BroadcastType::Unknown`.
269    #[inline(always)]
270    fn default() -> Self {
271        BroadcastType::Unknown
272    }
273}
274
275impl<B> BroadcastType<B>
276where
277    B: BroadcastTypeTrait,
278{
279    /// Generates a unique key string for a given broadcast type.
280    ///
281    /// For point-to-point types, the keys are sorted to ensure consistent key generation
282    /// regardless of the order of the input keys.
283    ///
284    /// # Arguments
285    ///
286    /// - `BroadcastType<B>` - The broadcast type for which to generate the key.
287    ///
288    /// # Returns
289    ///
290    /// - `String` - The unique key string for the broadcast type.
291    #[inline(always)]
292    pub fn get_key(broadcast_type: BroadcastType<B>) -> String {
293        match broadcast_type {
294            BroadcastType::PointToPoint(key1, key2) => {
295                let (first_key, second_key) = if key1 <= key2 {
296                    (key1, key2)
297                } else {
298                    (key2, key1)
299                };
300                format!(
301                    "{}-{}-{}",
302                    POINT_TO_POINT_KEY,
303                    first_key.to_string(),
304                    second_key.to_string()
305                )
306            }
307            BroadcastType::PointToGroup(key) => {
308                format!("{}-{}", POINT_TO_GROUP_KEY, key.to_string())
309            }
310            BroadcastType::Unknown => String::new(),
311        }
312    }
313}
314
315impl<'a, B> WebSocketConfig<'a, B>
316where
317    B: BroadcastTypeTrait,
318{
319    /// Creates a new WebSocket configuration with the given context.
320    ///
321    /// # Arguments
322    ///
323    /// - `&'a mut Stream` - The stream object serving this WebSocket.
324    /// - `&'a mut Context` - The context object to associate with the WebSocket.
325    ///
326    /// # Returns
327    ///
328    /// - `WebSocketConfig<B>` - A new WebSocket configuration instance.
329    #[inline(always)]
330    pub fn new(stream: &'a mut Stream, context: &'a mut Context) -> Self {
331        Self {
332            stream,
333            context,
334            capacity: DEFAULT_BROADCAST_SENDER_CAPACITY,
335            broadcast_type: BroadcastType::default(),
336            connected_hook: Hook::default_handler(),
337            request_hook: Hook::default_handler(),
338            sended_hook: Hook::default_handler(),
339            closed_hook: Hook::default_handler(),
340        }
341    }
342
343    /// Hands out the stream and the context together.
344    ///
345    /// The two borrows live in the same configuration, so they have to be
346    /// taken together: a caller that wants to run a hook needs both, and the
347    /// borrow checker will not let it take them one at a time.
348    ///
349    /// # Returns
350    ///
351    /// - `(&'a mut Stream, &'a mut Context)` - The stream and the context.
352    #[inline(always)]
353    pub fn take_parts(self) -> (&'a mut Stream, &'a mut Context) {
354        // The destructuring pattern is the ยง17.13 escape hatch: it is not
355        // `self.field` access, and it hands out the two borrows together
356        // with the lifetime the struct holds them under.
357        let Self {
358            stream, context, ..
359        } = self;
360        (stream, context)
361    }
362}
363
364impl<'a, B> WebSocketConfig<'a, B>
365where
366    B: BroadcastTypeTrait,
367{
368    /// Sets the capacity for the broadcast sender.
369    ///
370    /// # Arguments
371    ///
372    /// - `Capacity` - The desired capacity.
373    ///
374    /// # Returns
375    ///
376    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
377    #[inline(always)]
378    pub fn set_capacity(mut self, capacity: Capacity) -> Self {
379        self.capacity = capacity;
380        self
381    }
382
383    /// Sets the context for the WebSocket connection.
384    ///
385    /// # Arguments
386    ///
387    /// - `&'a mut Context` - The context object to associate with the WebSocket.
388    ///
389    /// # Returns
390    ///
391    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
392    #[inline(always)]
393    pub fn set_context(mut self, context: &'a mut Context) -> Self {
394        self.context = context;
395        self
396    }
397
398    /// Sets the broadcast type for the WebSocket connection.
399    ///
400    /// # Arguments
401    ///
402    /// - `BroadcastType<B>` - The broadcast type to use for this WebSocket.
403    ///
404    /// # Returns
405    ///
406    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
407    #[inline(always)]
408    pub fn set_broadcast_type(mut self, broadcast_type: BroadcastType<B>) -> Self {
409        self.broadcast_type = broadcast_type;
410        self
411    }
412
413    /// Sets the connected hook handler.
414    ///
415    /// This hook is executed when the WebSocket connection is established.
416    ///
417    /// # Type Parameters
418    ///
419    /// - `S`: The hook type, which must implement `ServerHook`.
420    ///
421    /// # Returns
422    ///
423    /// The modified `WebSocketConfig` instance.
424    ///
425    /// # Examples
426    ///
427    /// ```rust
428    /// use hyperlane::{Context, ServerHook, Status, Stream};
429    /// use hyperlane_plugin_websocket::WebSocketConfig;
430    /// # use hyperlane::{RequestConfig, Transport, tokio};
431    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
432    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
433    /// #
434    /// # #[derive(Debug)]
435    /// # struct MemoryTransport(DuplexStream);
436    /// #
437    /// # impl Transport for MemoryTransport {
438    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
439    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
440    /// #     }
441    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
442    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
443    /// #     }
444    /// # }
445    /// #
446    /// # impl AsyncRead for MemoryTransport {
447    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
448    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
449    /// #     }
450    /// # }
451    /// #
452    /// # impl AsyncWrite for MemoryTransport {
453    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
454    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
455    /// #     }
456    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
457    /// #         Pin::new(&mut self.0).poll_flush(cx)
458    /// #     }
459    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
460    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
461    /// #     }
462    /// # }
463    ///
464    /// struct MyConnectedHook;
465    ///
466    /// impl ServerHook for MyConnectedHook {
467    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
468    ///         Self
469    ///     }
470    ///
471    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
472    ///         ctx.set_attribute("connected", true);
473    ///         Status::Continue
474    ///     }
475    /// }
476    ///
477    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
478    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
479    /// # let mut ctx: Context = Context::default();
480    /// // Register the hook with the stream and context for this connection.
481    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
482    ///     .set_connected_hook::<MyConnectedHook>();
483    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
484    /// # runtime.block_on(async {
485    /// #     let hook = config.get_connected_hook().clone();
486    /// #     let (stream, context) = config.take_parts();
487    /// #     let status: Status = hook(stream, context).await;
488    /// #     assert!(matches!(status, Status::Continue));
489    /// #     assert!(context.get_attribute::<bool, _>("connected"));
490    /// # });
491    /// ```
492    #[inline(always)]
493    pub fn set_connected_hook<S>(mut self) -> Self
494    where
495        S: ServerHook,
496    {
497        self.connected_hook = Hook::factory::<S>();
498        self
499    }
500
501    /// Sets the request hook handler.
502    ///
503    /// This hook is executed when a new request is received on the WebSocket.
504    ///
505    /// # Type Parameters
506    ///
507    /// - `S`: The hook type, which must implement `ServerHook`.
508    ///
509    /// # Returns
510    ///
511    /// The modified `WebSocketConfig` instance.
512    ///
513    /// # Examples
514    ///
515    /// ```rust
516    /// use hyperlane::{Context, ServerHook, Status, Stream};
517    /// use hyperlane_plugin_websocket::WebSocketConfig;
518    /// # use hyperlane::{RequestConfig, Transport, tokio};
519    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
520    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
521    /// #
522    /// # #[derive(Debug)]
523    /// # struct MemoryTransport(DuplexStream);
524    /// #
525    /// # impl Transport for MemoryTransport {
526    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
527    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
528    /// #     }
529    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
530    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
531    /// #     }
532    /// # }
533    /// #
534    /// # impl AsyncRead for MemoryTransport {
535    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
536    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
537    /// #     }
538    /// # }
539    /// #
540    /// # impl AsyncWrite for MemoryTransport {
541    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
542    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
543    /// #     }
544    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
545    /// #         Pin::new(&mut self.0).poll_flush(cx)
546    /// #     }
547    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
548    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
549    /// #     }
550    /// # }
551    ///
552    /// struct MyRequestHook;
553    ///
554    /// impl ServerHook for MyRequestHook {
555    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
556    ///         Self
557    ///     }
558    ///
559    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
560    ///         ctx.set_attribute("request_received", true);
561    ///         Status::Continue
562    ///     }
563    /// }
564    ///
565    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
566    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
567    /// # let mut ctx: Context = Context::default();
568    /// // Register the hook with the stream and context for this connection.
569    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
570    ///     .set_request_hook::<MyRequestHook>();
571    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
572    /// # runtime.block_on(async {
573    /// #     let hook = config.get_request_hook().clone();
574    /// #     let (stream, context) = config.take_parts();
575    /// #     let status: Status = hook(stream, context).await;
576    /// #     assert!(matches!(status, Status::Continue));
577    /// #     assert!(context.get_attribute::<bool, _>("request_received"));
578    /// # });
579    /// ```
580    #[inline(always)]
581    pub fn set_request_hook<S>(mut self) -> Self
582    where
583        S: ServerHook,
584    {
585        self.request_hook = Hook::factory::<S>();
586        self
587    }
588
589    /// Sets the sended hook handler.
590    ///
591    /// This hook is executed after a message has been successfully sent over the WebSocket.
592    ///
593    /// # Type Parameters
594    ///
595    /// - `S`: The hook type, which must implement `ServerHook`.
596    ///
597    /// # Returns
598    ///
599    /// The modified `WebSocketConfig` instance.
600    ///
601    /// # Examples
602    ///
603    /// ```rust
604    /// use hyperlane::{Context, ServerHook, Status, Stream};
605    /// use hyperlane_plugin_websocket::WebSocketConfig;
606    /// # use hyperlane::{RequestConfig, Transport, tokio};
607    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
608    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
609    /// #
610    /// # #[derive(Debug)]
611    /// # struct MemoryTransport(DuplexStream);
612    /// #
613    /// # impl Transport for MemoryTransport {
614    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
615    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
616    /// #     }
617    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
618    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
619    /// #     }
620    /// # }
621    /// #
622    /// # impl AsyncRead for MemoryTransport {
623    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
624    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
625    /// #     }
626    /// # }
627    /// #
628    /// # impl AsyncWrite for MemoryTransport {
629    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
630    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
631    /// #     }
632    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
633    /// #         Pin::new(&mut self.0).poll_flush(cx)
634    /// #     }
635    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
636    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
637    /// #     }
638    /// # }
639    ///
640    /// struct MySendedHook;
641    ///
642    /// impl ServerHook for MySendedHook {
643    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
644    ///         Self
645    ///     }
646    ///
647    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
648    ///         ctx.set_attribute("message_sent", true);
649    ///         Status::Continue
650    ///     }
651    /// }
652    ///
653    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
654    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
655    /// # let mut ctx: Context = Context::default();
656    /// // Register the hook with the stream and context for this connection.
657    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
658    ///     .set_sended_hook::<MySendedHook>();
659    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
660    /// # runtime.block_on(async {
661    /// #     let hook = config.get_sended_hook().clone();
662    /// #     let (stream, context) = config.take_parts();
663    /// #     let status: Status = hook(stream, context).await;
664    /// #     assert!(matches!(status, Status::Continue));
665    /// #     assert!(context.get_attribute::<bool, _>("message_sent"));
666    /// # });
667    /// ```
668    #[inline(always)]
669    pub fn set_sended_hook<S>(mut self) -> Self
670    where
671        S: ServerHook,
672    {
673        self.sended_hook = Hook::factory::<S>();
674        self
675    }
676
677    /// Sets the closed hook handler.
678    ///
679    /// This hook is executed when the WebSocket connection is closed.
680    ///
681    /// # Type Parameters
682    ///
683    /// - `S`: The hook type, which must implement `ServerHook`.
684    ///
685    /// # Returns
686    ///
687    /// The modified `WebSocketConfig` instance.
688    ///
689    /// # Examples
690    ///
691    /// ```rust
692    /// use hyperlane::{Context, ServerHook, Status, Stream};
693    /// use hyperlane_plugin_websocket::WebSocketConfig;
694    /// # use hyperlane::{RequestConfig, Transport, tokio};
695    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
696    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
697    /// #
698    /// # #[derive(Debug)]
699    /// # struct MemoryTransport(DuplexStream);
700    /// #
701    /// # impl Transport for MemoryTransport {
702    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
703    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
704    /// #     }
705    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
706    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
707    /// #     }
708    /// # }
709    /// #
710    /// # impl AsyncRead for MemoryTransport {
711    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
712    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
713    /// #     }
714    /// # }
715    /// #
716    /// # impl AsyncWrite for MemoryTransport {
717    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
718    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
719    /// #     }
720    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
721    /// #         Pin::new(&mut self.0).poll_flush(cx)
722    /// #     }
723    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
724    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
725    /// #     }
726    /// # }
727    ///
728    /// struct MyClosedHook;
729    ///
730    /// impl ServerHook for MyClosedHook {
731    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
732    ///         Self
733    ///     }
734    ///
735    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
736    ///         ctx.set_attribute("closed", true);
737    ///         Status::Continue
738    ///     }
739    /// }
740    ///
741    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
742    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
743    /// # let mut ctx: Context = Context::default();
744    /// // Register the hook with the stream and context for this connection.
745    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
746    ///     .set_closed_hook::<MyClosedHook>();
747    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
748    /// # runtime.block_on(async {
749    /// #     let hook = config.get_closed_hook().clone();
750    /// #     let (stream, context) = config.take_parts();
751    /// #     let status: Status = hook(stream, context).await;
752    /// #     assert!(matches!(status, Status::Continue));
753    /// #     assert!(context.get_attribute::<bool, _>("closed"));
754    /// # });
755    /// ```
756    #[inline(always)]
757    pub fn set_closed_hook<S>(mut self) -> Self
758    where
759        S: ServerHook,
760    {
761        self.closed_hook = Hook::factory::<S>();
762        self
763    }
764}
765
766/// Inherent implementation of [`WebSocket`].
767impl WebSocket {
768    /// Creates a new WebSocket instance.
769    ///
770    /// Initializes with a default broadcast map.
771    ///
772    /// # Returns
773    ///
774    /// - `WebSocket` - A new WebSocket instance.
775    #[inline(always)]
776    pub fn new() -> Self {
777        Self::default()
778    }
779
780    /// Subscribes to a broadcast type or inserts a new one if it doesn't exist.
781    ///
782    /// # Type Parameters
783    ///
784    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
785    ///
786    /// # Arguments
787    ///
788    /// - `BroadcastType<B>` - The broadcast type to subscribe to.
789    /// - `Capacity` - The capacity for the broadcast sender if a new one is inserted.
790    ///
791    /// # Returns
792    ///
793    /// - `BroadcastMapReceiver<Vec<u8>>` - A broadcast map receiver for the specified broadcast type.
794    #[inline(always)]
795    fn subscribe_unwrap_or_insert<B>(
796        &self,
797        broadcast_type: BroadcastType<B>,
798        capacity: Capacity,
799    ) -> BroadcastMapReceiver<Vec<u8>>
800    where
801        B: BroadcastTypeTrait,
802    {
803        let key: String = BroadcastType::get_key(broadcast_type);
804        self.get_broadcast_map().subscribe_or_insert(&key, capacity)
805    }
806
807    /// Subscribes to a point-to-point broadcast.
808    ///
809    /// # Type Parameters
810    ///
811    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
812    ///
813    /// # Arguments
814    ///
815    /// - `&B` - The first identifier for the point-to-point communication.
816    /// - `&B` - The second identifier for the point-to-point communication.
817    /// - `Capacity` - The capacity for the broadcast sender.
818    ///
819    /// # Returns
820    ///
821    /// - `BroadcastMapReceiver<Vec<u8>>` - A broadcast map receiver for the point-to-point broadcast.
822    #[inline(always)]
823    fn point_to_point<B>(
824        &self,
825        key1: &B,
826        key2: &B,
827        capacity: Capacity,
828    ) -> BroadcastMapReceiver<Vec<u8>>
829    where
830        B: BroadcastTypeTrait,
831    {
832        self.subscribe_unwrap_or_insert(
833            BroadcastType::PointToPoint(key1.clone(), key2.clone()),
834            capacity,
835        )
836    }
837
838    /// Subscribes to a point-to-group broadcast.
839    ///
840    /// # Type Parameters
841    ///
842    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
843    ///
844    /// # Arguments
845    ///
846    /// - `&B` - The identifier for the group.
847    /// - `Capacity` - The capacity for the broadcast sender.
848    ///
849    /// # Returns
850    ///
851    /// - `BroadcastMapReceiver<Vec<u8>>` - A broadcast map receiver for the point-to-group broadcast.
852    #[inline(always)]
853    fn point_to_group<B>(&self, key: &B, capacity: Capacity) -> BroadcastMapReceiver<Vec<u8>>
854    where
855        B: BroadcastTypeTrait,
856    {
857        self.subscribe_unwrap_or_insert(BroadcastType::PointToGroup(key.clone()), capacity)
858    }
859
860    /// Retrieves the current receiver count for a given broadcast type.
861    ///
862    /// # Type Parameters
863    ///
864    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
865    ///
866    /// # Arguments
867    ///
868    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
869    ///
870    /// # Returns
871    ///
872    /// - `ReceiverCount` - The number of active receivers for the broadcast type, or 0 if not found.
873    #[inline(always)]
874    pub fn receiver_count<B>(&self, broadcast_type: BroadcastType<B>) -> ReceiverCount
875    where
876        B: BroadcastTypeTrait,
877    {
878        let key: String = BroadcastType::get_key(broadcast_type);
879        self.get_broadcast_map().receiver_count(&key).unwrap_or(0)
880    }
881
882    /// Calculates the receiver count before a connection is established.
883    ///
884    /// Ensures the count does not exceed the maximum allowed value minus one.
885    ///
886    /// # Type Parameters
887    ///
888    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
889    ///
890    /// # Arguments
891    ///
892    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
893    ///
894    /// # Returns
895    ///
896    /// - `ReceiverCount` - The receiver count after the connection is established.
897    #[inline(always)]
898    pub fn receiver_count_before_connected<B>(
899        &self,
900        broadcast_type: BroadcastType<B>,
901    ) -> ReceiverCount
902    where
903        B: BroadcastTypeTrait,
904    {
905        let count: ReceiverCount = self.receiver_count(broadcast_type);
906        count.clamp(0, ReceiverCount::MAX - 1) + 1
907    }
908
909    /// Calculates the receiver count after a connection is closed.
910    ///
911    /// Ensures the count does not go below 0.
912    ///
913    /// # Type Parameters
914    ///
915    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
916    ///
917    /// # Arguments
918    ///
919    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
920    ///
921    /// # Returns
922    ///
923    /// - `ReceiverCount` - The receiver count after the connection is closed.
924    #[inline(always)]
925    pub fn receiver_count_after_closed<B>(&self, broadcast_type: BroadcastType<B>) -> ReceiverCount
926    where
927        B: BroadcastTypeTrait,
928    {
929        let count: ReceiverCount = self.receiver_count(broadcast_type);
930        count.clamp(1, ReceiverCount::MAX) - 1
931    }
932
933    /// Sends data to all active receivers for a given broadcast type.
934    ///
935    /// # Type Parameters
936    ///
937    /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
938    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
939    ///
940    /// # Arguments
941    ///
942    /// - `BroadcastType<B>` - The broadcast type to which to send the data.
943    /// - `T` - The data to send.
944    ///
945    /// # Returns
946    ///
947    /// - `Result<Option<ReceiverCount>, SendError<Vec<u8>>>` - A result indicating the success or failure of the send operation.
948    #[inline(always)]
949    pub fn try_send<T, B>(
950        &self,
951        broadcast_type: BroadcastType<B>,
952        data: T,
953    ) -> Result<Option<ReceiverCount>, SendError<Vec<u8>>>
954    where
955        T: Into<Vec<u8>>,
956        B: BroadcastTypeTrait,
957    {
958        let key: String = BroadcastType::get_key(broadcast_type);
959        self.get_broadcast_map().try_send(&key, data.into())
960    }
961
962    /// Sends data to all active receivers for a given broadcast type.
963    ///
964    /// This method panics if the send operation fails.
965    ///
966    /// # Type Parameters
967    ///
968    /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
969    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
970    ///
971    /// # Arguments
972    ///
973    /// - `BroadcastType<B>` - The broadcast type to which to send the data.
974    /// - `T` - The data to send.
975    ///
976    /// # Returns
977    ///
978    /// - `Option<ReceiverCount>` - The receiver count if the send operation succeeds.
979    ///
980    /// # Panics
981    ///
982    /// Panics if the send operation fails.
983    #[inline(always)]
984    pub fn send<T, B>(&self, broadcast_type: BroadcastType<B>, data: T) -> Option<ReceiverCount>
985    where
986        T: Into<Vec<u8>>,
987        B: BroadcastTypeTrait,
988    {
989        self.try_send(broadcast_type, data).unwrap()
990    }
991
992    /// Runs the WebSocket connection, handling incoming requests and outgoing messages.
993    ///
994    /// This asynchronous function continuously monitors for new WebSocket requests
995    /// and incoming broadcast messages, processing them according to the configured hooks.
996    ///
997    /// # Type Parameters
998    ///
999    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
1000    ///
1001    /// # Arguments
1002    ///
1003    /// - `WebSocketConfig<'_, B>` - The WebSocket configuration containing the configuration for this WebSocket instance.
1004    ///
1005    /// # Panics
1006    ///
1007    /// Panics if the context in the WebSocket configuration is not set (i.e., it's the default context).
1008    /// Panics if the broadcast type in the WebSocket configuration is `BroadcastType::Unknown`.
1009    pub async fn run<B>(&self, websocket_config: WebSocketConfig<'_, B>)
1010    where
1011        B: BroadcastTypeTrait,
1012    {
1013        let WebSocketConfig {
1014            stream,
1015            context: ctx,
1016            capacity,
1017            broadcast_type,
1018            connected_hook,
1019            request_hook,
1020            sended_hook,
1021            closed_hook,
1022        }: WebSocketConfig<'_, B> = websocket_config;
1023        let mut receiver: Receiver<Vec<u8>> = match &broadcast_type {
1024            BroadcastType::PointToPoint(key1, key2) => self.point_to_point(key1, key2, capacity),
1025            BroadcastType::PointToGroup(key) => self.point_to_group(key, capacity),
1026            BroadcastType::Unknown => panic!("BroadcastType must be PointToPoint or PointToGroup"),
1027        };
1028        let key: String = BroadcastType::get_key(broadcast_type);
1029        if connected_hook(stream, ctx).await.is_reject() {
1030            return;
1031        }
1032        let mut is_reject: bool;
1033        loop {
1034            tokio::select! {
1035                request_res = stream.try_get_websocket_request() => {
1036                    if let Ok(body) = request_res {
1037                        ctx.get_mut_request().set_body(body);
1038                        is_reject = request_hook(stream, ctx).await.is_reject();
1039                    } else {
1040                        is_reject = true;
1041                        closed_hook(stream, ctx).await;
1042                    }
1043                    let body: ResponseBody = ctx.get_response().get_body().clone();
1044                    let is_err: bool = self.get_broadcast_map().try_send(&key, body).is_err();
1045                    if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
1046                        break;
1047                    }
1048                },
1049                msg_res = receiver.recv() => {
1050                    if let Ok(msg) = &msg_res {
1051                        if stream.try_send_list(&WebSocketFrame::create_frame_list(msg)).await.is_ok() {
1052                            continue;
1053                        } else {
1054                            break;
1055                        }
1056                    }
1057                    break;
1058                }
1059            }
1060        }
1061        stream.set_closed(true);
1062    }
1063}