use crate::{builders, error::RpcResult, parser, RpcSocket};
use identity::Identity;
use std::sync::Arc;
pub struct Service {
pub name: String,
pub version: u16,
pub description: String,
hash_id: Option<Identity>,
socket: Option<Arc<RpcSocket>>,
}
impl Service {
pub fn new<S: Into<String>>(name: S, version: u16, description: S) -> Self {
Self {
name: name.into(),
version,
description: description.into(),
hash_id: None,
socket: None,
}
}
pub async fn register(&mut self, socket: Arc<RpcSocket>) -> RpcResult<Identity> {
self.socket = Some(socket);
let msg = builders::register(&self)?;
Ok(self
.socket
.as_ref()
.unwrap()
.send(msg, |msg| parser::resp_id(msg))
.await?)
}
pub fn hash_id(&self) -> Option<Identity> {
self.hash_id
}
pub fn get_socket(&self) -> Arc<RpcSocket> {
Arc::clone(
self.socket
.as_ref()
.expect("Can not get socket; service not registered!"),
)
}
}
#[async_trait::async_trait]
pub trait ServiceConnector: Default {
async fn establish_connection(self: Arc<Self>) -> RpcResult<()>;
async fn terminate_connection(self: Arc<Self>) -> RpcResult<()>;
}