use tokio::sync::broadcast;
use tokio::sync::broadcast::error::RecvError;
use crate::common::errors::ConnectorError;
use crate::common::ids::AccountId;
use crate::open_api::connection::{Connection, Event};
#[derive(Debug)]
pub(crate) struct Feed {
connection: Connection,
events: broadcast::Receiver<Event>,
account: AccountId,
}
pub(crate) const fn starts_replay(event: &Event) -> bool {
matches!(
event,
Event::Disconnected(_) | Event::ReconnectFailed { .. }
)
}
impl Feed {
pub(crate) fn new(connection: &Connection, account: AccountId) -> Self {
Self {
connection: connection.clone(),
events: connection.events(),
account,
}
}
pub(crate) async fn next(&mut self) -> Result<Event, ConnectorError> {
tokio::select! {
biased;
event = self.events.recv() => match event {
Ok(Event::SessionEnded(ended))
if ended.account.is_none_or(|account| account == self.account) =>
{
Err(ConnectorError::SessionEnded(ended))
}
Ok(event) => Ok(event),
Err(RecvError::Lagged(skipped)) => Err(ConnectorError::Lagged { skipped }),
Err(RecvError::Closed) => Err(ConnectorError::Closed),
},
() = self.connection.closed() => Err(ConnectorError::Closed),
}
}
}