Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/src/ws/tap.rs

5.4 KiB, 1 run

created by r1870400018:65650, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A seam for watching a websocket's messages, in both directions, at no cost when nobody is.
2//!
3//! A [`FrameTap`] is handed every message that crosses a socket, with a context of the caller's
4//! choosing (a connection's session and device, say), and cannot change what it sees or hold it
5//! up: the hooks return nothing. [`NoTap`] is the tap that is not there. It is zero-sized, so is
6//! its context, and its hooks are empty and inlined, so a socket that installs none is the same
7//! code as before the seam existed. The seam is a trait with a type parameter on
8//! [`WebSocket`](crate::ws::core::WebSocket), not a boxed callback, so a tap that is installed is
9//! called without dynamic dispatch.
10//!
11//! Two layers, because the crate offers two ways in. [`WebSocket`](crate::ws::core::WebSocket)
12//! carries a tap and a context of its own (`with_tap`). A caller that owns its two stream halves
13//! and calls [`read_message`] and [`encode_message`] itself, as an application's gateway does,
14//! calls [`read_message_tapped`] and [`encode_message_tapped`] instead, passing its tap and
15//! context by reference. Both layers tap a whole message, after reassembly on the way in and as
16//! it is framed on the way out, which is where a caller's filter can understand it.
17
18use crate::ws::core::{
19 encode_message,
20 read_message,
21 WebSocketLimits,
22 WebSocketMessage,
23};
24
25use oxedyne_fe2o3_core::prelude::*;
26
27use std::sync::Arc;
28
29use tokio::io::AsyncRead;
30
31
32/// Watches the messages of a websocket. Both hooks see a message once, after the fact.
33pub trait FrameTap {
34 type Ctx; // what the caller knows of the connection, handed to every call
35
36 /// A message has been read, its frames reassembled.
37 fn inbound(&self, ctx: &Self::Ctx, msg: &WebSocketMessage);
38
39 /// A message has been framed for the wire. This is called whether or not the write that
40 /// follows succeeds, since the point is to see what was sent, or tried.
41 fn outbound(&self, ctx: &Self::Ctx, msg: &WebSocketMessage);
42}
43
44/// The tap that watches nothing: no bytes of its own, none in its context, and hooks that compile
45/// to nothing.
46#[derive(Clone, Copy, Debug, Default)]
47pub struct NoTap;
48
49impl FrameTap for NoTap {
50 type Ctx = ();
51
52 #[inline(always)]
53 fn inbound(&self, _ctx: &(), _msg: &WebSocketMessage) {}
54
55 #[inline(always)]
56 fn outbound(&self, _ctx: &(), _msg: &WebSocketMessage) {}
57}
58
59impl<X: FrameTap> FrameTap for &X {
60 type Ctx = X::Ctx;
61
62 #[inline]
63 fn inbound(&self, ctx: &Self::Ctx, msg: &WebSocketMessage) { (**self).inbound(ctx, msg) }
64
65 #[inline]
66 fn outbound(&self, ctx: &Self::Ctx, msg: &WebSocketMessage) { (**self).outbound(ctx, msg) }
67}
68
69impl<X: FrameTap> FrameTap for Arc<X> {
70 type Ctx = X::Ctx;
71
72 #[inline]
73 fn inbound(&self, ctx: &Self::Ctx, msg: &WebSocketMessage) { (**self).inbound(ctx, msg) }
74
75 #[inline]
76 fn outbound(&self, ctx: &Self::Ctx, msg: &WebSocketMessage) { (**self).outbound(ctx, msg) }
77}
78
79/// [`read_message`], and the message it returns is shown to `tap` as inbound. A close of the
80/// connection (`Ok(None)`) and an error are not messages and are not shown.
81pub async fn read_message_tapped<R: AsyncRead + Unpin, X: FrameTap>(
82 stream: &mut R,
83 buffer: &mut Vec<u8>,
84 chunk_size: usize,
85 limits: WebSocketLimits,
86 tap: &X,
87 ctx: &X::Ctx,
88)
89 -> Outcome<Option<WebSocketMessage>>
90{
91 let msg = res!(read_message(stream, buffer, chunk_size, limits).await);
92 if let Some(m) = &msg {
93 tap.inbound(ctx, m);
94 }
95 Ok(msg)
96}
97
98/// [`encode_message`], and the message is shown to `tap` as outbound once it has been framed. A
99/// message that cannot be framed is not shown.
100pub fn encode_message_tapped<X: FrameTap>(
101 message: &WebSocketMessage,
102 mask: bool,
103 chunk_size: usize,
104 chunk_thresh: usize,
105 tap: &X,
106 ctx: &X::Ctx,
107)
108 -> Outcome<Vec<u8>>
109{
110 let byts = res!(encode_message(message, mask, chunk_size, chunk_thresh));
111 tap.outbound(ctx, message);
112 Ok(byts)
113}
114
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 use std::sync::atomic::{
121 AtomicUsize,
122 Ordering,
123 };
124
125 // Adds its context to one counter per direction, so a call to the wrong hook, or to none, shows.
126 #[derive(Default)]
127 struct Count {
128 ins: AtomicUsize,
129 outs: AtomicUsize,
130 }
131
132 impl FrameTap for Count {
133 type Ctx = usize;
134
135 fn inbound(&self, ctx: &usize, _msg: &WebSocketMessage) {
136 self.ins.fetch_add(*ctx, Ordering::SeqCst);
137 }
138
139 fn outbound(&self, ctx: &usize, _msg: &WebSocketMessage) {
140 self.outs.fetch_add(*ctx, Ordering::SeqCst);
141 }
142 }
143
144 #[test]
145 fn no_tap_and_its_context_occupy_no_bytes() {
146 assert_eq!(std::mem::size_of::<NoTap>(), 0);
147 assert_eq!(std::mem::size_of::<<NoTap as FrameTap>::Ctx>(), 0);
148 // And it can be called, to no effect.
149 NoTap.inbound(&(), &WebSocketMessage::Ping(Vec::new()));
150 NoTap.outbound(&(), &WebSocketMessage::Pong(Vec::new()));
151 }
152
153 #[test]
154 fn a_reference_and_an_arc_forward_each_hook_to_its_own_counter() {
155 let c = Arc::new(Count::default());
156 let m = WebSocketMessage::Text("x".to_string());
157 (&*c).inbound(&2, &m);
158 (&*c).outbound(&5, &m);
159 c.inbound(&10, &m);
160 c.outbound(&20, &m);
161 assert_eq!(c.ins.load(Ordering::SeqCst), 12);
162 assert_eq!(c.outs.load(Ordering::SeqCst), 25);
163 }
164}