1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
//! The server implementation for [axum].
//!
//! Use [`server()`] to set up the server and feed it incoming requests.
//!
//! [axum]: <https://docs.rs/axum>
use Pin;
use Poll;
use ;
use Bytes;
use Error;
use ;
use Stream;
use Sink;
use crate;
/// Construct a new axum connection with the specified handler.
///
/// The returned [`Connect`] cannot send anything. Call [`Connect::connect`] to
/// perform the [negotiation protocol], which hands back the [`Server`] that
/// can. This is what makes it impossible to write a message before the client
/// has agreed on the [`Format`] it will be encoded with.
///
/// [`Format`]: crate::api::Format
/// [`Server`]: crate::ws::Server
/// [negotiation protocol]: crate::api#negotiating-the-format
///
/// # Examples
///
/// ```
/// # extern crate axum08 as axum;
/// use std::error::Error;
/// use std::pin::pin;
///
/// use axum::Router;
/// use axum::extract::State;
/// use axum::extract::ws::{WebSocket, WebSocketUpgrade};
/// use axum::response::Response;
/// use axum::routing::any;
/// use tokio::sync::broadcast::Sender;
/// use tokio::time::{self, Duration};
///
/// use musli_web::api::MessageId;
/// use musli_web::axum08;
/// use musli_web::ws;
///
/// mod api {
/// use musli::{Decode, Encode};
/// use musli_web::api;
///
/// #[derive(Encode, Decode)]
/// pub struct HelloRequest<'de> {
/// pub message: &'de str,
/// }
///
/// #[derive(Encode, Decode)]
/// pub struct HelloResponse<'de> {
/// pub message: &'de str,
/// }
///
/// #[derive(Encode, Decode)]
/// pub struct TickEvent<'de> {
/// pub message: &'de str,
/// pub tick: u32,
/// }
///
/// api::define! {
/// pub type Hello;
///
/// impl Endpoint for Hello {
/// impl<'de> Request for HelloRequest<'de>;
/// type Response<'de> = HelloResponse<'de>;
/// }
///
/// pub type Tick;
///
/// impl Broadcast for Tick {
/// impl<'de> Event for TickEvent<'de>;
/// }
/// }
/// }
///
/// #[derive(Debug, Clone)]
/// enum Broadcast {
/// Tick { tick: u32 },
/// }
///
/// #[derive(Clone)]
/// struct MyHandler;
///
/// impl ws::Handler for MyHandler {
/// type Id = api::Request;
/// type Response = Option<()>;
///
/// async fn handle(
/// &self,
/// id: Self::Id,
/// incoming: &mut ws::Incoming<'_>,
/// outgoing: &mut ws::Outgoing<'_>,
/// ) -> Self::Response {
/// tracing::info!("Handling: {id:?}");
///
/// match id {
/// api::Request::Hello => {
/// let request = incoming.read::<api::HelloRequest<'_>>()?;
///
/// outgoing.write(api::HelloResponse {
/// message: request.message,
/// });
///
/// Some(())
/// }
/// api::Request::Unknown(id) => {
/// None
/// }
/// }
/// }
/// }
///
/// async fn handler(ws: WebSocketUpgrade, State(sender): State<Sender<Broadcast>>) -> Response {
/// ws.on_upgrade(move |socket: WebSocket| async move {
/// let mut subscribe = sender.subscribe();
///
/// // NB: Nothing can be sent until the client has negotiated a format,
/// // which is what this step waits for.
/// let mut server = match axum08::server(socket, MyHandler).connect().await {
/// Ok(server) => server,
/// Err(error) => {
/// tracing::error!("Failed to negotiate: {error}");
/// return;
/// }
/// };
///
/// loop {
/// tokio::select! {
/// m = subscribe.recv() => {
/// let Ok(message) = m else {
/// continue;
/// };
///
/// let result = match message {
/// Broadcast::Tick { tick } => {
/// server.broadcast(api::TickEvent { message: "tick", tick })
/// },
/// };
///
/// if let Err(error) = result {
/// tracing::error!("Broadcast failed: {error}");
///
/// let mut error = error.source();
///
/// while let Some(e) = error.take() {
/// tracing::error!("Caused by: {e}");
/// error = e.source();
/// }
/// }
/// }
/// result = server.run() => {
/// if let Err(error) = result {
/// tracing::error!("Websocket error: {error}");
///
/// let mut error = error.source();
///
/// while let Some(e) = error.take() {
/// tracing::error!("Caused by: {e}");
/// error = e.source();
/// }
/// }
///
/// break;
/// }
/// }
/// }
/// })
/// }
/// ```
/// Marker type used in combination with [`Server`] to indicate that the
/// implementation uses axum.
///
/// See [`server()`] for how this is constructed and used.