Skip to main content

socketio_next/
event.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use serde::de::DeserializeOwned;
5use tokio::sync::mpsc;
6
7use crate::actor::Command;
8use crate::protocol::socketio::Packet;
9use crate::{Error, Payload, Result};
10
11/// An event from the server: its name, its arguments and, when the server asked for one, the
12/// means to acknowledge it.
13#[derive(Debug, Clone)]
14pub struct Event {
15    name: String,
16    payload: Payload,
17    ack: Option<AckSender>,
18}
19
20impl Event {
21    pub(crate) fn new(name: String, payload: Payload, ack: Option<AckSender>) -> Self {
22        Event { name, payload, ack }
23    }
24
25    /// The event name.
26    pub fn name(&self) -> &str {
27        &self.name
28    }
29
30    /// The arguments.
31    pub fn payload(&self) -> &Payload {
32        &self.payload
33    }
34
35    /// The arguments, owned.
36    pub fn into_payload(self) -> Payload {
37        self.payload
38    }
39
40    /// Argument `index` as `T` (see [`Payload::arg`]).
41    pub fn arg<T: DeserializeOwned>(&self, index: usize) -> Result<T> {
42        Ok(self.payload.arg(index)?)
43    }
44
45    /// The server emitted this event with a callback (`socket.emit("ev", data, (reply) => ..)`).
46    pub fn wants_ack(&self) -> bool {
47        self.ack.is_some()
48    }
49
50    /// Answers the server's callback with `data`. Sent at most once: later calls (and calls on
51    /// clones) are ignored, as in socket.io-client. A no-op when no ack was requested.
52    pub fn ack(&self, data: impl Into<Payload>) -> Result<()> {
53        match &self.ack {
54            Some(ack) => ack.send(data),
55            None => Ok(()),
56        }
57    }
58
59    /// The ack handle, to answer later or from another task.
60    pub fn ack_sender(&self) -> Option<AckSender> {
61        self.ack.clone()
62    }
63}
64
65/// Answers one server callback. Clones share the "already sent" flag.
66#[derive(Debug, Clone)]
67pub struct AckSender {
68    id: u64,
69    nsp: Arc<str>,
70    cmd: mpsc::UnboundedSender<Command>,
71    sent: Arc<AtomicBool>,
72}
73
74impl AckSender {
75    pub(crate) fn new(id: u64, nsp: Arc<str>, cmd: mpsc::UnboundedSender<Command>) -> Self {
76        AckSender {
77            id,
78            nsp,
79            cmd,
80            sent: Arc::default(),
81        }
82    }
83
84    /// The ack id the server chose.
85    pub fn id(&self) -> u64 {
86        self.id
87    }
88
89    /// Sends the ack (ACK, or BINARY_ACK when `data` has binary parts). Only the first call
90    /// sends.
91    pub fn send(&self, data: impl Into<Payload>) -> Result<()> {
92        if self.sent.swap(true, Ordering::AcqRel) {
93            return Ok(());
94        }
95        let packet = Packet::new_ack(data.into(), &self.nsp, self.id)?;
96        self.cmd
97            .send(Command::Send { packet })
98            .map_err(|_| Error::Closed)
99    }
100}