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