use liminal_sdk::{
DeliveredMessage, RemoteConfig, SdkError, SubscriptionStream, WebSocketSubscriptionStream,
};
pub type Close = Box<dyn Fn() -> Result<(), SdkError> + Send + Sync>;
#[must_use]
pub fn is_websocket(address: &str) -> bool {
address.starts_with("ws://") || address.starts_with("wss://")
}
pub fn connect(
address: &str,
config: RemoteConfig,
credential: &[u8],
) -> Result<RemoteConfig, SdkError> {
if is_websocket(address) {
config.connect_websocket_with_auth(credential)
} else {
config.connect_tcp_with_auth(credential)
}
}
#[derive(Debug)]
pub enum Subscription {
Tcp(SubscriptionStream),
Ws(WebSocketSubscriptionStream),
}
impl Subscription {
pub fn open(address: &str, channel: &str, credential: &[u8]) -> Result<Self, SdkError> {
if is_websocket(address) {
WebSocketSubscriptionStream::open_with_auth(address, channel, Vec::new(), credential)
.map(Self::Ws)
} else {
SubscriptionStream::open_with_auth(address, channel, Vec::new(), credential)
.map(Self::Tcp)
}
}
pub fn recv(&self) -> Result<DeliveredMessage, SdkError> {
match self {
Self::Tcp(stream) => stream.recv(),
Self::Ws(stream) => stream.recv().map(DeliveredMessage::from),
}
}
pub fn recv_timeout(&self, timeout: std::time::Duration) -> Result<DeliveredMessage, SdkError> {
match self {
Self::Tcp(stream) => stream.recv_timeout(timeout),
Self::Ws(stream) => stream.recv_timeout(timeout).map(DeliveredMessage::from),
}
}
pub fn close_handle(&self) -> Result<Close, SdkError> {
Ok(match self {
Self::Tcp(stream) => Box::new(stream.close_handle()?),
Self::Ws(stream) => Box::new(stream.close_handle()?),
})
}
}
#[cfg(test)]
#[path = "rail_link_tests.rs"]
mod tests;