-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreceiver.rs
More file actions
76 lines (67 loc) · 2.46 KB
/
receiver.rs
File metadata and controls
76 lines (67 loc) · 2.46 KB
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
use std::sync::Arc;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyDict;
use tokio::sync::{Mutex, mpsc};
use crate::asgi::{
http::HttpReceiveMessage, lifespan::LifespanReceiveMessage, websocket::WebSocketReceiveMessage,
};
enum ReceiverType {
Http(Arc<Mutex<mpsc::UnboundedReceiver<HttpReceiveMessage>>>),
WebSocket(Arc<Mutex<mpsc::UnboundedReceiver<WebSocketReceiveMessage>>>),
Lifespan(Arc<Mutex<mpsc::UnboundedReceiver<LifespanReceiveMessage>>>),
}
/// Allows Python to receive messages from Rust.
#[pyclass]
pub struct Receiver(ReceiverType);
impl Receiver {
/// Create a new Receiver instance for http ASGI message types.
pub fn http() -> (Receiver, mpsc::UnboundedSender<HttpReceiveMessage>) {
let (tx, rx) = mpsc::unbounded_channel::<HttpReceiveMessage>();
let rx = Arc::new(Mutex::new(rx));
(Receiver(ReceiverType::Http(rx)), tx)
}
/// Create a new Receiver instance for websocket ASGI message types.
pub fn websocket() -> (Receiver, mpsc::UnboundedSender<WebSocketReceiveMessage>) {
let (tx, rx) = mpsc::unbounded_channel::<WebSocketReceiveMessage>();
let rx = Arc::new(Mutex::new(rx));
(Receiver(ReceiverType::WebSocket(rx)), tx)
}
/// Create a new Receiver instance for lifespan ASGI message types.
pub fn lifespan() -> (Receiver, mpsc::UnboundedSender<LifespanReceiveMessage>) {
let (tx, rx) = mpsc::unbounded_channel::<LifespanReceiveMessage>();
let rx = Arc::new(Mutex::new(rx));
(Receiver(ReceiverType::Lifespan(rx)), tx)
}
}
#[pymethods]
impl Receiver {
async fn __call__(&mut self) -> PyResult<Py<PyDict>> {
match &self.0 {
ReceiverType::Http(rx) => {
let message = rx.lock().await.recv().await;
if let Some(msg) = message {
Python::attach(|py| Ok(msg.into_pyobject(py)?.unbind()))
} else {
Err(PyValueError::new_err("No message received"))
}
}
ReceiverType::WebSocket(rx) => {
let message = rx.lock().await.recv().await;
if let Some(msg) = message {
Python::attach(|py| Ok(msg.into_pyobject(py)?.unbind()))
} else {
Err(PyValueError::new_err("No message received"))
}
}
ReceiverType::Lifespan(rx) => {
let message = rx.lock().await.recv().await;
if let Some(msg) = message {
Python::attach(|py| Ok(msg.into_pyobject(py)?.unbind()))
} else {
Err(PyValueError::new_err("No message received"))
}
}
}
}
}