moirai-pal 0.7.0

Platform Abstraction Layer for Moirai async I/O operations
Documentation
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Browser WebSocket receive state shared by the WebAssembly PAL and tests.

use std::collections::VecDeque;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard};
use std::task::{Context, Poll, Waker};

/// Default maximum size of one browser WebSocket message.
pub const DEFAULT_MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024;

/// Default maximum number of messages retained per browser WebSocket.
pub const DEFAULT_MAX_QUEUED_MESSAGES: usize = 64;

/// Limits applied before browser data is copied into Rust-owned memory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WebSocketLimits {
    max_message_bytes: usize,
    max_queued_messages: usize,
}

impl WebSocketLimits {
    /// Construct limits with non-zero message and queue bounds.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] when either bound is zero.
    pub fn new(max_message_bytes: usize, max_queued_messages: usize) -> io::Result<Self> {
        if max_message_bytes == 0 || max_queued_messages == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "WebSocket limits must be non-zero",
            ));
        }

        Ok(Self {
            max_message_bytes,
            max_queued_messages,
        })
    }

    /// Return the maximum number of bytes accepted in one message.
    #[must_use]
    pub const fn max_message_bytes(self) -> usize {
        self.max_message_bytes
    }

    /// Return the maximum number of messages retained for one connection.
    #[must_use]
    pub const fn max_queued_messages(self) -> usize {
        self.max_queued_messages
    }
}

impl Default for WebSocketLimits {
    fn default() -> Self {
        Self {
            max_message_bytes: DEFAULT_MAX_MESSAGE_BYTES,
            max_queued_messages: DEFAULT_MAX_QUEUED_MESSAGES,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum WebSocketStatus {
    Connecting,
    Open,
    Closed {
        code: u16,
    },
    Failed {
        kind: io::ErrorKind,
        message: &'static str,
    },
}

#[derive(Debug)]
pub(crate) struct WebSocketState {
    status: WebSocketStatus,
    incoming: VecDeque<Vec<u8>>,
    waiter: Option<WaiterRegistration>,
    #[cfg(any(target_arch = "wasm32", test))]
    open_waiter: Option<WaiterRegistration>,
    next_waiter_id: u64,
    limits: WebSocketLimits,
}

#[derive(Debug)]
struct WaiterRegistration {
    id: u64,
    waker: Waker,
}

impl WebSocketState {
    pub(crate) fn new(limits: WebSocketLimits) -> Self {
        Self {
            status: WebSocketStatus::Connecting,
            // Defer allocation until a message arrives. The caller controls
            // the queue bound, so eagerly reserving that entire bound would
            // turn a valid policy value into an unbounded allocation request.
            incoming: VecDeque::new(),
            waiter: None,
            #[cfg(any(target_arch = "wasm32", test))]
            open_waiter: None,
            next_waiter_id: 1,
            limits,
        }
    }

    pub(crate) fn open(&mut self) -> bool {
        if matches!(self.status, WebSocketStatus::Connecting) {
            self.status = WebSocketStatus::Open;
            true
        } else {
            false
        }
    }

    #[cfg(any(target_arch = "wasm32", test))]
    pub(crate) fn take_open_waiter(&mut self) -> Option<Waker> {
        self.open_waiter
            .take()
            .map(|registration| registration.waker)
    }

    #[cfg(any(target_arch = "wasm32", test))]
    fn poll_open(&mut self, cx: &Context<'_>, waiter_id: &mut Option<u64>) -> Poll<io::Result<()>> {
        match self.status {
            WebSocketStatus::Connecting => {
                if let Some(waiter) = &mut self.open_waiter {
                    if Some(waiter.id) != *waiter_id {
                        return Poll::Ready(Err(io::Error::new(
                            io::ErrorKind::AlreadyExists,
                            "only one WebSocket OPEN waiter may be pending",
                        )));
                    }
                    waiter.waker = cx.waker().clone();
                } else {
                    let id = self.new_waiter_id();
                    *waiter_id = Some(id);
                    self.open_waiter = Some(WaiterRegistration {
                        id,
                        waker: cx.waker().clone(),
                    });
                }
                Poll::Pending
            }
            WebSocketStatus::Open => {
                *waiter_id = None;
                Poll::Ready(Ok(()))
            }
            WebSocketStatus::Closed { code } => {
                *waiter_id = None;
                Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    format!("WebSocket closed with code {code} before OPEN"),
                )))
            }
            WebSocketStatus::Failed { kind, message } => {
                *waiter_id = None;
                Poll::Ready(Err(io::Error::new(kind, message)))
            }
        }
    }

    fn new_waiter_id(&mut self) -> u64 {
        let id = self.next_waiter_id;
        self.next_waiter_id = self.next_waiter_id.checked_add(1).unwrap_or(1);
        id
    }

    pub(crate) fn enqueue_message(&mut self, message: Vec<u8>) -> MessageEnqueue {
        if message.len() > self.limits.max_message_bytes() {
            let waker = self.fail(
                io::ErrorKind::InvalidData,
                "WebSocket message exceeds configured byte bound",
            );
            return MessageEnqueue::Rejected {
                error: io::Error::new(
                    io::ErrorKind::InvalidData,
                    "WebSocket message exceeds configured byte bound",
                ),
                waker,
            };
        }

        if self.incoming.len() >= self.limits.max_queued_messages() {
            let waker = self.fail(
                io::ErrorKind::OutOfMemory,
                "WebSocket receive queue exceeds configured message bound",
            );
            return MessageEnqueue::Rejected {
                error: io::Error::new(
                    io::ErrorKind::OutOfMemory,
                    "WebSocket receive queue exceeds configured message bound",
                ),
                waker,
            };
        }

        if matches!(self.status, WebSocketStatus::Connecting) {
            self.status = WebSocketStatus::Open;
        }
        if !matches!(self.status, WebSocketStatus::Open) {
            return MessageEnqueue::Rejected {
                error: io::Error::new(
                    io::ErrorKind::BrokenPipe,
                    "WebSocket is no longer accepting messages",
                ),
                waker: None,
            };
        }

        if self.incoming.try_reserve(1).is_err() {
            let waker = self.fail(
                io::ErrorKind::OutOfMemory,
                "WebSocket receive queue could not reserve capacity",
            );
            return MessageEnqueue::Rejected {
                error: io::Error::new(
                    io::ErrorKind::OutOfMemory,
                    "WebSocket receive queue could not reserve capacity",
                ),
                waker,
            };
        }

        self.incoming.push_back(message);
        MessageEnqueue::Accepted(self.waiter.take().map(|registration| registration.waker))
    }

    pub(crate) fn close(&mut self, code: u16) -> Option<Waker> {
        if matches!(
            self.status,
            WebSocketStatus::Connecting | WebSocketStatus::Open
        ) {
            self.status = WebSocketStatus::Closed { code };
            self.waiter.take().map(|registration| registration.waker)
        } else {
            None
        }
    }

    pub(crate) fn fail(&mut self, kind: io::ErrorKind, message: &'static str) -> Option<Waker> {
        if matches!(
            self.status,
            WebSocketStatus::Connecting | WebSocketStatus::Open
        ) {
            self.incoming.clear();
            self.status = WebSocketStatus::Failed { kind, message };
            self.waiter.take().map(|registration| registration.waker)
        } else {
            None
        }
    }

    pub(crate) fn take_message(&mut self) -> io::Result<Vec<u8>> {
        if let Some(message) = self.incoming.pop_front() {
            return Ok(message);
        }

        match self.status {
            WebSocketStatus::Connecting | WebSocketStatus::Open => Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "WebSocket has no message available",
            )),
            WebSocketStatus::Closed { code } => Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                format!("WebSocket closed with code {code}"),
            )),
            WebSocketStatus::Failed { kind, message } => Err(io::Error::new(kind, message)),
        }
    }

    fn poll_receive(
        &mut self,
        cx: &Context<'_>,
        waiter_id: &mut Option<u64>,
    ) -> Poll<io::Result<Vec<u8>>> {
        if let Some(message) = self.incoming.pop_front() {
            self.waiter = None;
            *waiter_id = None;
            return Poll::Ready(Ok(message));
        }

        match self.status {
            WebSocketStatus::Connecting | WebSocketStatus::Open => {
                if let Some(waiter) = &mut self.waiter {
                    if Some(waiter.id) != *waiter_id {
                        return Poll::Ready(Err(io::Error::new(
                            io::ErrorKind::AlreadyExists,
                            "only one WebSocket receive may be pending",
                        )));
                    }
                    waiter.waker = cx.waker().clone();
                } else {
                    let id = self.new_waiter_id();
                    *waiter_id = Some(id);
                    self.waiter = Some(WaiterRegistration {
                        id,
                        waker: cx.waker().clone(),
                    });
                }
                Poll::Pending
            }
            WebSocketStatus::Closed { code } => {
                *waiter_id = None;
                Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    format!("WebSocket closed with code {code}"),
                )))
            }
            WebSocketStatus::Failed { kind, message } => {
                *waiter_id = None;
                Poll::Ready(Err(io::Error::new(kind, message)))
            }
        }
    }

    fn clear_waiter(&mut self, candidate: Option<u64>) {
        Self::clear_waiter_registration(&mut self.waiter, candidate);
    }

    #[cfg(any(target_arch = "wasm32", test))]
    fn clear_open_waiter(&mut self, candidate: Option<u64>) {
        Self::clear_waiter_registration(&mut self.open_waiter, candidate);
    }

    fn clear_waiter_registration(waiter: &mut Option<WaiterRegistration>, candidate: Option<u64>) {
        if let Some(candidate) = candidate
            && waiter
                .as_ref()
                .is_some_and(|registration| registration.id == candidate)
        {
            *waiter = None;
        }
    }
}

pub(crate) enum MessageEnqueue {
    Accepted(Option<Waker>),
    Rejected {
        error: io::Error,
        waker: Option<Waker>,
    },
}

fn lock_state<'a>(
    state: &'a Arc<Mutex<WebSocketState>>,
) -> io::Result<MutexGuard<'a, WebSocketState>> {
    state
        .lock()
        .map_err(|_| io::Error::other("WebSocket receive state lock is poisoned"))
}

fn poll_state_future<T>(
    state: &Arc<Mutex<WebSocketState>>,
    registered_id: &mut Option<u64>,
    cx: &mut Context<'_>,
    poll: impl FnOnce(&mut WebSocketState, &Context<'_>, &mut Option<u64>) -> Poll<io::Result<T>>,
) -> Poll<io::Result<T>> {
    let mut state = match lock_state(state) {
        Ok(state) => state,
        Err(error) => return Poll::Ready(Err(error)),
    };
    poll(&mut state, cx, registered_id)
}

fn clear_registered_waiter(
    state: &Arc<Mutex<WebSocketState>>,
    registered_id: Option<u64>,
    clear: impl FnOnce(&mut WebSocketState, Option<u64>),
) {
    if let Ok(mut state) = state.lock() {
        clear(&mut state, registered_id);
    }
}

/// A cancellation-safe future for the next browser WebSocket message.
#[must_use = "poll the future to observe the next WebSocket message"]
pub struct WebSocketReceive {
    state: Arc<Mutex<WebSocketState>>,
    registered_id: Option<u64>,
}

impl WebSocketReceive {
    pub(crate) fn new(state: Arc<Mutex<WebSocketState>>) -> Self {
        Self {
            state,
            registered_id: None,
        }
    }
}

impl Future for WebSocketReceive {
    type Output = io::Result<Vec<u8>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        poll_state_future(
            &this.state,
            &mut this.registered_id,
            cx,
            WebSocketState::poll_receive,
        )
    }
}

impl Drop for WebSocketReceive {
    fn drop(&mut self) {
        clear_registered_waiter(
            &self.state,
            self.registered_id,
            WebSocketState::clear_waiter,
        );
    }
}

/// A cancellation-safe future that resolves when a browser WebSocket is OPEN.
#[cfg(any(target_arch = "wasm32", test))]
#[must_use = "poll the future to observe WebSocket OPEN"]
pub struct WebSocketOpen {
    state: Arc<Mutex<WebSocketState>>,
    registered_id: Option<u64>,
}

impl WebSocketOpen {
    pub(crate) fn new(state: Arc<Mutex<WebSocketState>>) -> Self {
        Self {
            state,
            registered_id: None,
        }
    }
}

#[cfg(any(target_arch = "wasm32", test))]
impl Future for WebSocketOpen {
    type Output = io::Result<()>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        poll_state_future(
            &this.state,
            &mut this.registered_id,
            cx,
            WebSocketState::poll_open,
        )
    }
}

#[cfg(any(target_arch = "wasm32", test))]
impl Drop for WebSocketOpen {
    fn drop(&mut self) {
        clear_registered_waiter(
            &self.state,
            self.registered_id,
            WebSocketState::clear_open_waiter,
        );
    }
}

#[cfg(test)]
#[path = "websocket_state_tests.rs"]
mod tests;