use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use popsub_protocol::{CloseCode, Encoding};
use tokio::sync::mpsc;
use crate::driver::Command;
use crate::error::Error;
#[derive(Debug)]
pub struct Message {
pub topic: String,
pub seq: u64,
pub message_id: String,
pub payload: String,
pub encoding: Option<Encoding>,
pub qos: u8,
pub published_at_ms: i64,
pub(crate) acker: Option<mpsc::UnboundedSender<Command>>,
}
impl Message {
pub fn bytes(&self) -> Result<Vec<u8>, Error> {
match self.encoding {
None => Ok(self.payload.as_bytes().to_vec()),
Some(Encoding::Base64) => STANDARD
.decode(&self.payload)
.map_err(|e| Error::Protocol(format!("the payload isn't valid base64: {e}"))),
}
}
pub fn ack(&self) {
if let Some(acker) = &self.acker {
let _ = acker.send(Command::Ack {
topic: self.topic.clone(),
seq: self.seq,
});
}
}
}
#[derive(Debug)]
pub struct Subscription {
pub(crate) topic: String,
pub(crate) messages: mpsc::Receiver<Message>,
pub(crate) commands: mpsc::UnboundedSender<Command>,
pub(crate) generation: u64,
}
impl Subscription {
pub fn topic(&self) -> &str {
&self.topic
}
pub async fn next(&mut self) -> Option<Message> {
self.messages.recv().await
}
}
impl Drop for Subscription {
fn drop(&mut self) {
let _ = self.commands.send(Command::Forget {
topic: self.topic.clone(),
generation: self.generation,
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
Connected {
resumed: Vec<String>,
},
Disconnected {
code: Option<CloseCode>,
reconnecting: bool,
},
Truncated {
topic: String,
first_available: u64,
},
Stalled {
topic: String,
seq: u64,
},
AuthExpiring {
expires_at_ms: i64,
},
AuthRefreshed,
Unsubscribed {
topic: String,
},
ServerError {
code: popsub_protocol::ErrorCode,
message: String,
},
}