rocket_ws/lib.rs
1//! WebSocket support for Rocket.
2//!
3//! This crate implements support for WebSockets via Rocket's [connection
4//! upgrade API](rocket::Response#upgrading) and
5//! [tungstenite](tokio_tungstenite).
6//!
7//! # Usage
8//!
9//! Depend on the crate. Here, we rename the dependency to `ws` for convenience:
10//!
11//! ```toml
12//! [dependencies]
13//! ws = { package = "rocket_ws", version = "=0.3.0-rc.1" }
14//! ```
15//!
16//! Then, use [`WebSocket`] as a request guard in any route and either call
17//! [`WebSocket::channel()`] or return a stream via [`Stream!`] or
18//! [`WebSocket::stream()`] in the handler. The examples below are equivalent:
19//!
20//! ```rust
21//! # use rocket::get;
22//! # use rocket_ws as ws;
23//! #
24//! #[get("/echo?channel")]
25//! fn echo_channel(ws: ws::WebSocket) -> ws::Channel<'static> {
26//! use rocket::futures::{SinkExt, StreamExt};
27//!
28//! ws.channel(move |mut stream| Box::pin(async move {
29//! while let Some(message) = stream.next().await {
30//! let _ = stream.send(message?).await;
31//! }
32//!
33//! Ok(())
34//! }))
35//! }
36//!
37//! #[get("/echo?stream")]
38//! fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
39//! ws::Stream! { ws =>
40//! for await message in ws {
41//! yield message?;
42//! }
43//! }
44//! }
45//!
46//! #[get("/echo?compose")]
47//! fn echo_compose(ws: ws::WebSocket) -> ws::Stream!['static] {
48//! ws.stream(|io| io)
49//! }
50//! ```
51//!
52//! WebSocket connections are configurable via [`WebSocket::config()`]:
53//!
54//! ```rust
55//! # use rocket::get;
56//! # use rocket_ws as ws;
57//! #
58//! #[get("/echo")]
59//! fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
60//! let config = ws::Config::default()
61//! .max_message_size(Some(4 << 20))
62//! .read_buffer_size(8 * 1024);
63//!
64//! let ws = ws.config(config);
65//!
66//! ws::Stream! { ws =>
67//! for await message in ws {
68//! yield message?;
69//! }
70//! }
71//! }
72//! ```
73
74#![doc(html_root_url = "https://api.rocket.rs/v0.6-rc/rocket_ws")]
75#![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")]
76#![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")]
77
78mod tungstenite {
79 #[doc(inline)] pub use tokio_tungstenite::tungstenite::*;
80}
81
82mod duplex;
83mod websocket;
84
85pub use self::websocket::{WebSocket, Channel};
86pub use self::tungstenite::{Bytes, Utf8Bytes};
87
88/// A WebSocket message.
89///
90/// A value of this type is typically constructed by calling `.into()` on a
91/// supported message type. This includes strings via `&str` and `String` and
92/// bytes via `&[u8]` and `Vec<u8>`:
93///
94/// ```rust
95/// # use rocket::get;
96/// # use rocket_ws as ws;
97/// #
98/// #[get("/echo")]
99/// fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
100/// ws::Stream! { ws =>
101/// yield "Hello".into();
102/// yield String::from("Hello").into();
103/// yield (&[1u8, 2, 3][..]).into();
104/// yield vec![1u8, 2, 3].into();
105/// }
106/// }
107/// ```
108///
109/// Other kinds of messages can be constructed directly:
110///
111/// ```rust
112/// # use rocket::get;
113/// # use rocket_ws as ws;
114/// #
115/// #[get("/echo")]
116/// fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
117/// ws::Stream! { ws =>
118/// yield ws::Message::Ping(vec![b'h', b'i'].into())
119/// }
120/// }
121/// ```
122pub use self::tungstenite::Message;
123
124/// WebSocket connection configuration.
125///
126/// The default configuration for a [`WebSocket`] can be changed by calling
127/// [`WebSocket::config()`] with a value of this type, which replaces the
128/// default configuration entirely. Values are obtained via
129/// [`Default::default()`] and changed with builder methods.
130///
131/// By default, each connection allocates an 8KiB read buffer when it is
132/// created. `Config::default()`, however, uses a 128KiB read buffer. Unless
133/// [`Config::read_buffer_size()`] is used to set a smaller size, applications
134/// with many mostly idle connections may use considerably more memory with a
135/// custom configuration. Larger buffers can improve performance when reading
136/// many messages.
137///
138/// The read buffer size does not limit the size of incoming messages. Use
139/// [`Config::max_message_size()`] and [`Config::max_frame_size()`] to set
140/// limits.
141///
142/// # Example
143///
144/// ```rust
145/// # use rocket::get;
146/// # use rocket_ws as ws;
147/// use rocket::data::ToByteUnit;
148///
149/// #[get("/echo")]
150/// fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
151/// let config = ws::Config::default()
152/// // Keep the 8KiB read buffer that is used by default.
153/// .read_buffer_size(8.kibibytes().as_u64() as usize)
154/// // Decrease the maximum (complete) message size to 4MiB.
155/// .max_message_size(Some(4.mebibytes().as_u64() as usize))
156/// // Decrease the maximum size of _one_ frame (not message) to 1MiB.
157/// .max_frame_size(Some(1.mebibytes().as_u64() as usize));
158/// let ws = ws.config(config);
159///
160/// ws::Stream! { ws =>
161/// for await message in ws {
162/// yield message?;
163/// }
164/// }
165/// }
166/// ```
167///
168/// **Original `tungstenite` Documentation Follows**
169///
170pub use self::tungstenite::protocol::WebSocketConfig as Config;
171
172/// Structures for constructing raw WebSocket frames.
173pub mod frame {
174 #[doc(hidden)] pub use crate::Message;
175 pub use crate::tungstenite::protocol::frame::{CloseFrame, Frame};
176 pub use crate::tungstenite::protocol::frame::coding::CloseCode;
177}
178
179/// Types representing incoming and/or outgoing `async` [`Message`] streams.
180pub mod stream {
181 pub use crate::duplex::DuplexStream;
182 pub use crate::websocket::MessageStream;
183}
184
185/// Library [`Error`](crate::result::Error) and
186/// [`Result`](crate::result::Result) types.
187pub mod result {
188 pub use crate::tungstenite::error::{Result, Error};
189}
190
191/// Type and expression macro for `async` WebSocket [`Message`] streams.
192///
193/// This macro can be used both where types are expected or
194/// where expressions are expected.
195///
196/// # Type Position
197///
198/// When used in a type position, the macro invoked as `Stream['r]` expands to:
199///
200/// - [`MessageStream`]`<'r, impl `[`Stream`]`<Item = `[`Result`]`<`[`Message`]`>>> + 'r>`
201///
202/// The lifetime need not be specified as `'r`. For instance, `Stream['request]`
203/// is valid and expands as expected:
204///
205/// - [`MessageStream`]`<'request, impl `[`Stream`]`<Item = `[`Result`]`<`[`Message`]`>>> + 'request>`
206///
207/// As a convenience, when the macro is invoked as `Stream![]`, the lifetime
208/// defaults to `'static`. That is, `Stream![]` is equivalent to
209/// `Stream!['static]`.
210///
211/// [`MessageStream`]: crate::stream::MessageStream
212/// [`Stream`]: rocket::futures::stream::Stream
213/// [`Result`]: crate::result::Result
214/// [`Message`]: crate::Message
215///
216/// # Expression Position
217///
218/// When invoked as an expression, the macro behaves similarly to Rocket's
219/// [`stream!`](rocket::response::stream::stream) macro. Specifically, it
220/// supports `yield` and `for await` syntax. It is invoked as follows:
221///
222/// ```rust
223/// # use rocket::get;
224/// use rocket_ws as ws;
225///
226/// #[get("/")]
227/// fn echo(ws: ws::WebSocket) -> ws::Stream![] {
228/// ws::Stream! { ws =>
229/// for await message in ws {
230/// yield message?;
231/// yield "foo".into();
232/// yield vec![1, 2, 3, 4].into();
233/// }
234/// }
235/// }
236/// ```
237///
238/// It enjoins the following type requirements:
239///
240/// * The type of `ws` _must_ be [`WebSocket`]. `ws` can be any ident.
241/// * The type of yielded expressions (`expr` in `yield expr`) _must_ be [`Message`].
242/// * The `Err` type of expressions short-circuited with `?` _must_ be [`Error`].
243///
244/// [`Error`]: crate::result::Error
245///
246/// The macro takes any series of statements and expands them into an expression
247/// of type `impl Stream<Item = `[`Result`]`<T>>`, a stream that `yield`s elements of
248/// type [`Result`]`<T>`. It automatically converts yielded items of type `T` into
249/// `Ok(T)`. It supports any Rust statement syntax with the following
250/// extensions:
251///
252/// * `?` short-circuits stream termination on `Err`
253///
254/// The type of the error value must be [`Error`].
255/// <br /> <br />
256///
257/// * `yield expr`
258///
259/// Yields the result of evaluating `expr` to the caller (the stream
260/// consumer) wrapped in `Ok`.
261///
262/// `expr` must be of type `T`.
263/// <br /> <br />
264///
265/// * `for await x in stream { .. }`
266///
267/// `await`s the next element in `stream`, binds it to `x`, and executes the
268/// block with the binding.
269///
270/// `stream` must implement `Stream<Item = T>`; the type of `x` is `T`.
271///
272/// ### Examples
273///
274/// Borrow from the request. Send a single message and close:
275///
276/// ```rust
277/// # use rocket::get;
278/// use rocket_ws as ws;
279///
280/// #[get("/hello/<user>")]
281/// fn ws_hello(ws: ws::WebSocket, user: &str) -> ws::Stream!['_] {
282/// ws::Stream! { ws =>
283/// yield user.into();
284/// }
285/// }
286/// ```
287///
288/// Borrow from the request with explicit lifetime:
289///
290/// ```rust
291/// # use rocket::get;
292/// use rocket_ws as ws;
293///
294/// #[get("/hello/<user>")]
295/// fn ws_hello<'r>(ws: ws::WebSocket, user: &'r str) -> ws::Stream!['r] {
296/// ws::Stream! { ws =>
297/// yield user.into();
298/// }
299/// }
300/// ```
301///
302/// Emit several messages and short-circuit if the client sends a bad message:
303///
304/// ```rust
305/// # use rocket::get;
306/// use rocket_ws as ws;
307///
308/// #[get("/")]
309/// fn echo(ws: ws::WebSocket) -> ws::Stream![] {
310/// ws::Stream! { ws =>
311/// for await message in ws {
312/// for i in 0..5u8 {
313/// yield i.to_string().into();
314/// }
315///
316/// yield message?;
317/// }
318/// }
319/// }
320/// ```
321///
322#[macro_export]
323macro_rules! Stream {
324 () => ($crate::Stream!['static]);
325 ($l:lifetime) => (
326 $crate::stream::MessageStream<$l, impl rocket::futures::Stream<
327 Item = $crate::result::Result<$crate::Message>
328 > + $l>
329 );
330 ($channel:ident => $($token:tt)*) => (
331 let ws: $crate::WebSocket = $channel;
332 ws.stream(move |$channel| rocket::async_stream::try_stream! {
333 $($token)*
334 })
335 );
336}