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
344impl<'a, B> WebSocketConfig<'a, B>
345where
346 B: BroadcastTypeTrait,
347{
348 /// Sets the capacity for the broadcast sender.
349 ///
350 /// # Arguments
351 ///
352 /// - `Capacity` - The desired capacity.
353 ///
354 /// # Returns
355 ///
356 /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
357 #[inline(always)]
358 pub fn set_capacity(mut self, capacity: Capacity) -> Self {
359 self.capacity = capacity;
360 self
361 }
362
363 /// Sets the context for the WebSocket connection.
364 ///
365 /// # Arguments
366 ///
367 /// - `&'a mut Context` - The context object to associate with the WebSocket.
368 ///
369 /// # Returns
370 ///
371 /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
372 #[inline(always)]
373 pub fn set_context(mut self, context: &'a mut Context) -> Self {
374 self.context = context;
375 self
376 }
377
378 /// Sets the broadcast type for the WebSocket connection.
379 ///
380 /// # Arguments
381 ///
382 /// - `BroadcastType<B>` - The broadcast type to use for this WebSocket.
383 ///
384 /// # Returns
385 ///
386 /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
387 #[inline(always)]
388 pub fn set_broadcast_type(mut self, broadcast_type: BroadcastType<B>) -> Self {
389 self.broadcast_type = broadcast_type;
390 self
391 }
392
393 /// Sets the connected hook handler.
394 ///
395 /// This hook is executed when the WebSocket connection is established.
396 ///
397 /// # Type Parameters
398 ///
399 /// - `S`: The hook type, which must implement `ServerHook`.
400 ///
401 /// # Returns
402 ///
403 /// The modified `WebSocketConfig` instance.
404 ///
405 /// # Examples
406 ///
407 /// ```rust
408 /// use hyperlane::{Context, ServerHook, Status, Stream};
409 /// use hyperlane_plugin_websocket::WebSocketConfig;
410 /// # use hyperlane::{RequestConfig, Transport, tokio};
411 /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
412 /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
413 /// #
414 /// # #[derive(Debug)]
415 /// # struct MemoryTransport(DuplexStream);
416 /// #
417 /// # impl Transport for MemoryTransport {
418 /// # fn peer_addr(&self) -> io::Result<SocketAddr> {
419 /// # Err(io::ErrorKind::AddrNotAvailable.into())
420 /// # }
421 /// # fn local_addr(&self) -> io::Result<SocketAddr> {
422 /// # Err(io::ErrorKind::AddrNotAvailable.into())
423 /// # }
424 /// # }
425 /// #
426 /// # impl AsyncRead for MemoryTransport {
427 /// # fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
428 /// # Pin::new(&mut self.0).poll_read(cx, buf)
429 /// # }
430 /// # }
431 /// #
432 /// # impl AsyncWrite for MemoryTransport {
433 /// # fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
434 /// # Pin::new(&mut self.0).poll_write(cx, buf)
435 /// # }
436 /// # fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
437 /// # Pin::new(&mut self.0).poll_flush(cx)
438 /// # }
439 /// # fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
440 /// # Pin::new(&mut self.0).poll_shutdown(cx)
441 /// # }
442 /// # }
443 ///
444 /// struct MyConnectedHook;
445 ///
446 /// impl ServerHook for MyConnectedHook {
447 /// async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
448 /// Self
449 /// }
450 ///
451 /// async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
452 /// ctx.set_attribute("connected", true);
453 /// Status::Continue
454 /// }
455 /// }
456 ///
457 /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
458 /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
459 /// # let mut ctx: Context = Context::default();
460 /// // Register the hook with the stream and context for this connection.
461 /// let config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
462 /// .set_connected_hook::<MyConnectedHook>();
463 /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
464 /// # runtime.block_on(async {
465 /// # let status: Status = (config.connected_hook)(config.stream, config.context).await;
466 /// # assert!(matches!(status, Status::Continue));
467 /// # assert!(config.context.get_attribute::<bool, _>("connected"));
468 /// # });
469 /// ```
470 #[inline(always)]
471 pub fn set_connected_hook<S>(mut self) -> Self
472 where
473 S: ServerHook,
474 {
475 self.connected_hook = Hook::factory::<S>();
476 self
477 }
478
479 /// Sets the request hook handler.
480 ///
481 /// This hook is executed when a new request is received on the WebSocket.
482 ///
483 /// # Type Parameters
484 ///
485 /// - `S`: The hook type, which must implement `ServerHook`.
486 ///
487 /// # Returns
488 ///
489 /// The modified `WebSocketConfig` instance.
490 ///
491 /// # Examples
492 ///
493 /// ```rust
494 /// use hyperlane::{Context, ServerHook, Status, Stream};
495 /// use hyperlane_plugin_websocket::WebSocketConfig;
496 /// # use hyperlane::{RequestConfig, Transport, tokio};
497 /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
498 /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
499 /// #
500 /// # #[derive(Debug)]
501 /// # struct MemoryTransport(DuplexStream);
502 /// #
503 /// # impl Transport for MemoryTransport {
504 /// # fn peer_addr(&self) -> io::Result<SocketAddr> {
505 /// # Err(io::ErrorKind::AddrNotAvailable.into())
506 /// # }
507 /// # fn local_addr(&self) -> io::Result<SocketAddr> {
508 /// # Err(io::ErrorKind::AddrNotAvailable.into())
509 /// # }
510 /// # }
511 /// #
512 /// # impl AsyncRead for MemoryTransport {
513 /// # fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
514 /// # Pin::new(&mut self.0).poll_read(cx, buf)
515 /// # }
516 /// # }
517 /// #
518 /// # impl AsyncWrite for MemoryTransport {
519 /// # fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
520 /// # Pin::new(&mut self.0).poll_write(cx, buf)
521 /// # }
522 /// # fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
523 /// # Pin::new(&mut self.0).poll_flush(cx)
524 /// # }
525 /// # fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
526 /// # Pin::new(&mut self.0).poll_shutdown(cx)
527 /// # }
528 /// # }
529 ///
530 /// struct MyRequestHook;
531 ///
532 /// impl ServerHook for MyRequestHook {
533 /// async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
534 /// Self
535 /// }
536 ///
537 /// async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
538 /// ctx.set_attribute("request_received", true);
539 /// Status::Continue
540 /// }
541 /// }
542 ///
543 /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
544 /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
545 /// # let mut ctx: Context = Context::default();
546 /// // Register the hook with the stream and context for this connection.
547 /// let config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
548 /// .set_request_hook::<MyRequestHook>();
549 /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
550 /// # runtime.block_on(async {
551 /// # let status: Status = (config.request_hook)(config.stream, config.context).await;
552 /// # assert!(matches!(status, Status::Continue));
553 /// # assert!(config.context.get_attribute::<bool, _>("request_received"));
554 /// # });
555 /// ```
556 #[inline(always)]
557 pub fn set_request_hook<S>(mut self) -> Self
558 where
559 S: ServerHook,
560 {
561 self.request_hook = Hook::factory::<S>();
562 self
563 }
564
565 /// Sets the sended hook handler.
566 ///
567 /// This hook is executed after a message has been successfully sent over the WebSocket.
568 ///
569 /// # Type Parameters
570 ///
571 /// - `S`: The hook type, which must implement `ServerHook`.
572 ///
573 /// # Returns
574 ///
575 /// The modified `WebSocketConfig` instance.
576 ///
577 /// # Examples
578 ///
579 /// ```rust
580 /// use hyperlane::{Context, ServerHook, Status, Stream};
581 /// use hyperlane_plugin_websocket::WebSocketConfig;
582 /// # use hyperlane::{RequestConfig, Transport, tokio};
583 /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
584 /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
585 /// #
586 /// # #[derive(Debug)]
587 /// # struct MemoryTransport(DuplexStream);
588 /// #
589 /// # impl Transport for MemoryTransport {
590 /// # fn peer_addr(&self) -> io::Result<SocketAddr> {
591 /// # Err(io::ErrorKind::AddrNotAvailable.into())
592 /// # }
593 /// # fn local_addr(&self) -> io::Result<SocketAddr> {
594 /// # Err(io::ErrorKind::AddrNotAvailable.into())
595 /// # }
596 /// # }
597 /// #
598 /// # impl AsyncRead for MemoryTransport {
599 /// # fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
600 /// # Pin::new(&mut self.0).poll_read(cx, buf)
601 /// # }
602 /// # }
603 /// #
604 /// # impl AsyncWrite for MemoryTransport {
605 /// # fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
606 /// # Pin::new(&mut self.0).poll_write(cx, buf)
607 /// # }
608 /// # fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
609 /// # Pin::new(&mut self.0).poll_flush(cx)
610 /// # }
611 /// # fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
612 /// # Pin::new(&mut self.0).poll_shutdown(cx)
613 /// # }
614 /// # }
615 ///
616 /// struct MySendedHook;
617 ///
618 /// impl ServerHook for MySendedHook {
619 /// async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
620 /// Self
621 /// }
622 ///
623 /// async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
624 /// ctx.set_attribute("message_sent", true);
625 /// Status::Continue
626 /// }
627 /// }
628 ///
629 /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
630 /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
631 /// # let mut ctx: Context = Context::default();
632 /// // Register the hook with the stream and context for this connection.
633 /// let config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
634 /// .set_sended_hook::<MySendedHook>();
635 /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
636 /// # runtime.block_on(async {
637 /// # let status: Status = (config.sended_hook)(config.stream, config.context).await;
638 /// # assert!(matches!(status, Status::Continue));
639 /// # assert!(config.context.get_attribute::<bool, _>("message_sent"));
640 /// # });
641 /// ```
642 #[inline(always)]
643 pub fn set_sended_hook<S>(mut self) -> Self
644 where
645 S: ServerHook,
646 {
647 self.sended_hook = Hook::factory::<S>();
648 self
649 }
650
651 /// Sets the closed hook handler.
652 ///
653 /// This hook is executed when the WebSocket connection is closed.
654 ///
655 /// # Type Parameters
656 ///
657 /// - `S`: The hook type, which must implement `ServerHook`.
658 ///
659 /// # Returns
660 ///
661 /// The modified `WebSocketConfig` instance.
662 ///
663 /// # Examples
664 ///
665 /// ```rust
666 /// use hyperlane::{Context, ServerHook, Status, Stream};
667 /// use hyperlane_plugin_websocket::WebSocketConfig;
668 /// # use hyperlane::{RequestConfig, Transport, tokio};
669 /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
670 /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
671 /// #
672 /// # #[derive(Debug)]
673 /// # struct MemoryTransport(DuplexStream);
674 /// #
675 /// # impl Transport for MemoryTransport {
676 /// # fn peer_addr(&self) -> io::Result<SocketAddr> {
677 /// # Err(io::ErrorKind::AddrNotAvailable.into())
678 /// # }
679 /// # fn local_addr(&self) -> io::Result<SocketAddr> {
680 /// # Err(io::ErrorKind::AddrNotAvailable.into())
681 /// # }
682 /// # }
683 /// #
684 /// # impl AsyncRead for MemoryTransport {
685 /// # fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
686 /// # Pin::new(&mut self.0).poll_read(cx, buf)
687 /// # }
688 /// # }
689 /// #
690 /// # impl AsyncWrite for MemoryTransport {
691 /// # fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
692 /// # Pin::new(&mut self.0).poll_write(cx, buf)
693 /// # }
694 /// # fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
695 /// # Pin::new(&mut self.0).poll_flush(cx)
696 /// # }
697 /// # fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
698 /// # Pin::new(&mut self.0).poll_shutdown(cx)
699 /// # }
700 /// # }
701 ///
702 /// struct MyClosedHook;
703 ///
704 /// impl ServerHook for MyClosedHook {
705 /// async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
706 /// Self
707 /// }
708 ///
709 /// async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
710 /// ctx.set_attribute("closed", true);
711 /// Status::Continue
712 /// }
713 /// }
714 ///
715 /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
716 /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
717 /// # let mut ctx: Context = Context::default();
718 /// // Register the hook with the stream and context for this connection.
719 /// let config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
720 /// .set_closed_hook::<MyClosedHook>();
721 /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
722 /// # runtime.block_on(async {
723 /// # let status: Status = (config.closed_hook)(config.stream, config.context).await;
724 /// # assert!(matches!(status, Status::Continue));
725 /// # assert!(config.context.get_attribute::<bool, _>("closed"));
726 /// # });
727 /// ```
728 #[inline(always)]
729 pub fn set_closed_hook<S>(mut self) -> Self
730 where
731 S: ServerHook,
732 {
733 self.closed_hook = Hook::factory::<S>();
734 self
735 }
736}
737
738/// Inherent implementation of [`WebSocket`].
739impl WebSocket {
740 /// Creates a new WebSocket instance.
741 ///
742 /// Initializes with a default broadcast map.
743 ///
744 /// # Returns
745 ///
746 /// - `WebSocket` - A new WebSocket instance.
747 #[inline(always)]
748 pub fn new() -> Self {
749 Self::default()
750 }
751
752 /// Subscribes to a broadcast type or inserts a new one if it doesn't exist.
753 ///
754 /// # Type Parameters
755 ///
756 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
757 ///
758 /// # Arguments
759 ///
760 /// - `BroadcastType<B>` - The broadcast type to subscribe to.
761 /// - `Capacity` - The capacity for the broadcast sender if a new one is inserted.
762 ///
763 /// # Returns
764 ///
765 /// - `BroadcastMapReceiver<Vec<u8>>` - A broadcast map receiver for the specified broadcast type.
766 #[inline(always)]
767 fn subscribe_unwrap_or_insert<B>(
768 &self,
769 broadcast_type: BroadcastType<B>,
770 capacity: Capacity,
771 ) -> BroadcastMapReceiver<Vec<u8>>
772 where
773 B: BroadcastTypeTrait,
774 {
775 let key: String = BroadcastType::get_key(broadcast_type);
776 self.get_broadcast_map().subscribe_or_insert(&key, capacity)
777 }
778
779 /// Subscribes to a point-to-point broadcast.
780 ///
781 /// # Type Parameters
782 ///
783 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
784 ///
785 /// # Arguments
786 ///
787 /// - `&B` - The first identifier for the point-to-point communication.
788 /// - `&B` - The second identifier for the point-to-point communication.
789 /// - `Capacity` - The capacity for the broadcast sender.
790 ///
791 /// # Returns
792 ///
793 /// - `BroadcastMapReceiver<Vec<u8>>` - A broadcast map receiver for the point-to-point broadcast.
794 #[inline(always)]
795 fn point_to_point<B>(
796 &self,
797 key1: &B,
798 key2: &B,
799 capacity: Capacity,
800 ) -> BroadcastMapReceiver<Vec<u8>>
801 where
802 B: BroadcastTypeTrait,
803 {
804 self.subscribe_unwrap_or_insert(
805 BroadcastType::PointToPoint(key1.clone(), key2.clone()),
806 capacity,
807 )
808 }
809
810 /// Subscribes to a point-to-group broadcast.
811 ///
812 /// # Type Parameters
813 ///
814 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
815 ///
816 /// # Arguments
817 ///
818 /// - `&B` - The identifier for the group.
819 /// - `Capacity` - The capacity for the broadcast sender.
820 ///
821 /// # Returns
822 ///
823 /// - `BroadcastMapReceiver<Vec<u8>>` - A broadcast map receiver for the point-to-group broadcast.
824 #[inline(always)]
825 fn point_to_group<B>(&self, key: &B, capacity: Capacity) -> BroadcastMapReceiver<Vec<u8>>
826 where
827 B: BroadcastTypeTrait,
828 {
829 self.subscribe_unwrap_or_insert(BroadcastType::PointToGroup(key.clone()), capacity)
830 }
831
832 /// Retrieves the current receiver count for a given broadcast type.
833 ///
834 /// # Type Parameters
835 ///
836 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
837 ///
838 /// # Arguments
839 ///
840 /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
841 ///
842 /// # Returns
843 ///
844 /// - `ReceiverCount` - The number of active receivers for the broadcast type, or 0 if not found.
845 #[inline(always)]
846 pub fn receiver_count<B>(&self, broadcast_type: BroadcastType<B>) -> ReceiverCount
847 where
848 B: BroadcastTypeTrait,
849 {
850 let key: String = BroadcastType::get_key(broadcast_type);
851 self.get_broadcast_map().receiver_count(&key).unwrap_or(0)
852 }
853
854 /// Calculates the receiver count before a connection is established.
855 ///
856 /// Ensures the count does not exceed the maximum allowed value minus one.
857 ///
858 /// # Type Parameters
859 ///
860 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
861 ///
862 /// # Arguments
863 ///
864 /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
865 ///
866 /// # Returns
867 ///
868 /// - `ReceiverCount` - The receiver count after the connection is established.
869 #[inline(always)]
870 pub fn receiver_count_before_connected<B>(
871 &self,
872 broadcast_type: BroadcastType<B>,
873 ) -> ReceiverCount
874 where
875 B: BroadcastTypeTrait,
876 {
877 let count: ReceiverCount = self.receiver_count(broadcast_type);
878 count.clamp(0, ReceiverCount::MAX - 1) + 1
879 }
880
881 /// Calculates the receiver count after a connection is closed.
882 ///
883 /// Ensures the count does not go below 0.
884 ///
885 /// # Type Parameters
886 ///
887 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
888 ///
889 /// # Arguments
890 ///
891 /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
892 ///
893 /// # Returns
894 ///
895 /// - `ReceiverCount` - The receiver count after the connection is closed.
896 #[inline(always)]
897 pub fn receiver_count_after_closed<B>(&self, broadcast_type: BroadcastType<B>) -> ReceiverCount
898 where
899 B: BroadcastTypeTrait,
900 {
901 let count: ReceiverCount = self.receiver_count(broadcast_type);
902 count.clamp(1, ReceiverCount::MAX) - 1
903 }
904
905 /// Sends data to all active receivers for a given broadcast type.
906 ///
907 /// # Type Parameters
908 ///
909 /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
910 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
911 ///
912 /// # Arguments
913 ///
914 /// - `BroadcastType<B>` - The broadcast type to which to send the data.
915 /// - `T` - The data to send.
916 ///
917 /// # Returns
918 ///
919 /// - `Result<Option<ReceiverCount>, SendError<Vec<u8>>>` - A result indicating the success or failure of the send operation.
920 #[inline(always)]
921 pub fn try_send<T, B>(
922 &self,
923 broadcast_type: BroadcastType<B>,
924 data: T,
925 ) -> Result<Option<ReceiverCount>, SendError<Vec<u8>>>
926 where
927 T: Into<Vec<u8>>,
928 B: BroadcastTypeTrait,
929 {
930 let key: String = BroadcastType::get_key(broadcast_type);
931 self.get_broadcast_map().try_send(&key, data.into())
932 }
933
934 /// Sends data to all active receivers for a given broadcast type.
935 ///
936 /// This method panics if the send operation fails.
937 ///
938 /// # Type Parameters
939 ///
940 /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
941 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
942 ///
943 /// # Arguments
944 ///
945 /// - `BroadcastType<B>` - The broadcast type to which to send the data.
946 /// - `T` - The data to send.
947 ///
948 /// # Returns
949 ///
950 /// - `Option<ReceiverCount>` - The receiver count if the send operation succeeds.
951 ///
952 /// # Panics
953 ///
954 /// Panics if the send operation fails.
955 #[inline(always)]
956 pub fn send<T, B>(&self, broadcast_type: BroadcastType<B>, data: T) -> Option<ReceiverCount>
957 where
958 T: Into<Vec<u8>>,
959 B: BroadcastTypeTrait,
960 {
961 self.try_send(broadcast_type, data).unwrap()
962 }
963
964 /// Runs the WebSocket connection, handling incoming requests and outgoing messages.
965 ///
966 /// This asynchronous function continuously monitors for new WebSocket requests
967 /// and incoming broadcast messages, processing them according to the configured hooks.
968 ///
969 /// # Type Parameters
970 ///
971 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
972 ///
973 /// # Arguments
974 ///
975 /// - `WebSocketConfig<'_, B>` - The WebSocket configuration containing the configuration for this WebSocket instance.
976 ///
977 /// # Panics
978 ///
979 /// Panics if the context in the WebSocket configuration is not set (i.e., it's the default context).
980 /// Panics if the broadcast type in the WebSocket configuration is `BroadcastType::Unknown`.
981 pub async fn run<B>(&self, websocket_config: WebSocketConfig<'_, B>)
982 where
983 B: BroadcastTypeTrait,
984 {
985 let WebSocketConfig {
986 stream,
987 context: ctx,
988 capacity,
989 broadcast_type,
990 connected_hook,
991 request_hook,
992 sended_hook,
993 closed_hook,
994 }: WebSocketConfig<'_, B> = websocket_config;
995 let mut receiver: Receiver<Vec<u8>> = match &broadcast_type {
996 BroadcastType::PointToPoint(key1, key2) => self.point_to_point(key1, key2, capacity),
997 BroadcastType::PointToGroup(key) => self.point_to_group(key, capacity),
998 BroadcastType::Unknown => panic!("BroadcastType must be PointToPoint or PointToGroup"),
999 };
1000 let key: String = BroadcastType::get_key(broadcast_type);
1001 if connected_hook(stream, ctx).await.is_reject() {
1002 return;
1003 }
1004 let mut is_reject: bool;
1005 loop {
1006 tokio::select! {
1007 request_res = stream.try_get_websocket_request() => {
1008 if let Ok(body) = request_res {
1009 ctx.get_mut_request().set_body(body);
1010 is_reject = request_hook(stream, ctx).await.is_reject();
1011 } else {
1012 is_reject = true;
1013 closed_hook(stream, ctx).await;
1014 }
1015 let body: ResponseBody = ctx.get_response().get_body().clone();
1016 let is_err: bool = self.get_broadcast_map().try_send(&key, body).is_err();
1017 if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
1018 break;
1019 }
1020 },
1021 msg_res = receiver.recv() => {
1022 if let Ok(msg) = &msg_res {
1023 if stream.try_send_list(&WebSocketFrame::create_frame_list(msg)).await.is_ok() {
1024 continue;
1025 } else {
1026 break;
1027 }
1028 }
1029 break;
1030 }
1031 }
1032 }
1033 stream.set_closed(true);
1034 }
1035}