Move replies to core
This commit is contained in:
parent
10efaeb8d2
commit
619e04c42a
4 changed files with 3 additions and 6 deletions
|
|
@ -7,12 +7,11 @@ use cove_core::packets::{
|
|||
Cmd, IdentifyCmd, IdentifyRpl, JoinNtf, NickNtf, NickRpl, Ntf, Packet, PartNtf, RoomCmd,
|
||||
RoomRpl, Rpl, SendNtf, SendRpl, WhoRpl,
|
||||
};
|
||||
use cove_core::{Session, SessionId};
|
||||
use cove_core::replies::Replies;
|
||||
use cove_core::{replies, Session, SessionId};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::replies::{self, Replies};
|
||||
|
||||
// TODO Split into "interacting" and "maintenance" parts?
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@
|
|||
mod config;
|
||||
mod cove;
|
||||
mod never;
|
||||
mod replies;
|
||||
mod ui;
|
||||
|
||||
use std::io;
|
||||
|
|
|
|||
|
|
@ -1,72 +0,0 @@
|
|||
// TODO Move this into core
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
use std::result;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::oneshot::{self, Receiver, Sender};
|
||||
use tokio::time;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("timed out")]
|
||||
TimedOut,
|
||||
#[error("canceled")]
|
||||
Canceled,
|
||||
}
|
||||
|
||||
pub type Result<T> = result::Result<T, Error>;
|
||||
|
||||
pub struct PendingReply<R> {
|
||||
timeout: Duration,
|
||||
result: Receiver<R>,
|
||||
}
|
||||
|
||||
impl<R> PendingReply<R> {
|
||||
pub async fn get(self) -> Result<R> {
|
||||
let result = time::timeout(self.timeout, self.result).await;
|
||||
match result {
|
||||
Err(_) => Err(Error::TimedOut),
|
||||
Ok(Err(_)) => Err(Error::Canceled),
|
||||
Ok(Ok(value)) => Ok(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Replies<I, R> {
|
||||
timeout: Duration,
|
||||
pending: HashMap<I, Sender<R>>,
|
||||
}
|
||||
|
||||
impl<I: Eq + Hash, R> Replies<I, R> {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Self {
|
||||
timeout,
|
||||
pending: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wait_for(&mut self, id: I) -> PendingReply<R> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.pending.insert(id, tx);
|
||||
PendingReply {
|
||||
timeout: self.timeout,
|
||||
result: rx,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn complete(&mut self, id: &I, result: R) {
|
||||
if let Some(tx) = self.pending.remove(id) {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cancel(&mut self, id: &I) {
|
||||
self.pending.remove(id);
|
||||
}
|
||||
|
||||
pub fn purge(&mut self) {
|
||||
self.pending.retain(|_, tx| !tx.is_closed());
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue