use std::collections::HashMap;
use futures_util::{SinkExt, StreamExt};
use tokio::sync::{broadcast, mpsc, oneshot};
use shep_core::protocol::{
BusEvent, Envelope, Reply, Request, Response, ServerFrame, decode_frame, encode_frame,
};
use crate::client::RequestError;
use crate::connection::Frames;
pub(crate) const EVENT_CHANNEL_CAPACITY: usize = 64;
const COMMAND_CHANNEL_CAPACITY: usize = 64;
pub(crate) enum Command {
Request {
body: Request,
deadline_ms: Option<u64>,
reply_to: oneshot::Sender<Result<Response, RequestError>>,
},
Subscribe {
reply_to: oneshot::Sender<broadcast::Receiver<BusEvent>>,
},
}
pub(crate) fn spawn(frames: Frames) -> mpsc::Sender<Command> {
let (commands_tx, commands_rx) = mpsc::channel(COMMAND_CHANNEL_CAPACITY);
let (events_tx, _events_rx) = broadcast::channel(EVENT_CHANNEL_CAPACITY);
tokio::spawn(run(frames, commands_rx, events_tx));
commands_tx
}
async fn run(
mut frames: Frames,
mut commands: mpsc::Receiver<Command>,
events: broadcast::Sender<BusEvent>,
) {
let mut next_id: u64 = 1;
let mut pending: HashMap<u64, oneshot::Sender<Result<Response, RequestError>>> = HashMap::new();
loop {
tokio::select! {
command = commands.recv() => {
match command {
Some(Command::Request { body, deadline_ms, reply_to }) => {
let alive = send_request(&mut frames, &mut next_id, &mut pending, body, deadline_ms, reply_to).await;
pending.retain(|_, tx| !tx.is_closed());
if !alive {
break; }
}
Some(Command::Subscribe { reply_to }) => {
let _ = reply_to.send(events.subscribe());
}
None => break, }
}
frame = frames.next() => {
match frame {
Some(Ok(bytes)) => route_frame(&bytes, &mut pending, &events),
Some(Err(_)) | None => break, }
}
}
}
for (_id, reply_to) in pending.drain() {
let _ = reply_to.send(Err(RequestError::Closed)); }
}
async fn send_request(
frames: &mut Frames,
next_id: &mut u64,
pending: &mut HashMap<u64, oneshot::Sender<Result<Response, RequestError>>>,
body: Request,
deadline_ms: Option<u64>,
reply_to: oneshot::Sender<Result<Response, RequestError>>,
) -> bool {
let id = *next_id;
*next_id += 1;
let envelope = Envelope {
id,
deadline_ms,
body,
};
let payload = match encode_frame(&envelope) {
Ok(payload) => payload,
Err(err) => {
let _ = reply_to.send(Err(RequestError::Wire(err)));
return true; }
};
if frames.send(payload).await.is_err() {
let _ = reply_to.send(Err(RequestError::Closed));
return false;
}
pending.insert(id, reply_to);
true
}
fn route_frame(
bytes: &[u8],
pending: &mut HashMap<u64, oneshot::Sender<Result<Response, RequestError>>>,
events: &broadcast::Sender<BusEvent>,
) {
let Ok(frame) = decode_frame::<ServerFrame>(bytes) else {
return;
};
match frame {
ServerFrame::Reply(Reply { id, result }) => {
if let Some(reply_to) = pending.remove(&id) {
let _ = reply_to.send(result.map_err(RequestError::Rpc));
}
}
ServerFrame::Event(event) => {
let _ = events.send(event); }
_ => {}
}
}