use std::{
fmt,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{self, RecvTimeoutError, TryRecvError},
},
thread,
time::{Duration, Instant},
};
use jsonx_lib::Kind;
use crate::{
error::{CallError, Error},
error_object::ErrorObject,
id::Id,
link::{Link, Outcome},
raw::{Json, Raw},
};
#[derive(Clone, Debug, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Release);
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Acquire)
}
}
fn outgoing_params<'a>(params: impl Into<Json<'a>>) -> Result<Option<Json<'a>>, Error> {
let params = params.into();
match params.kind() {
Kind::Null => Ok(None),
Kind::Array | Kind::Object => Ok(Some(params)),
kind => Err(Error::InvalidParams(kind)),
}
}
#[derive(Clone)]
pub struct Peer {
link: Arc<dyn Link>,
}
impl Peer {
pub(crate) fn new(link: Arc<dyn Link>) -> Self {
Self { link }
}
pub fn notify<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<(), Error> {
let params = outgoing_params(params)?;
self.link.notify(method, params.as_ref())
}
pub fn request<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<Call, Error> {
self.send_request(method, params, None)
}
pub fn request_with_timeout<'a>(
&self,
method: &str,
params: impl Into<Json<'a>>,
timeout: Duration,
) -> Result<Call, Error> {
self.send_request(method, params, Some(timeout))
}
fn send_request<'a>(
&self,
method: &str,
params: impl Into<Json<'a>>,
timeout: Option<Duration>,
) -> Result<Call, Error> {
let params = outgoing_params(params)?;
let issued = self.link.request(method, params.as_ref(), timeout)?;
Ok(Call {
id: issued.id,
outcome: issued.outcome,
deadline: issued.deadline,
link: Arc::clone(&self.link),
})
}
#[must_use]
pub fn is_closed(&self) -> bool {
self.link.is_closed()
}
}
impl fmt::Debug for Peer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Peer")
.field("closed", &self.is_closed())
.finish()
}
}
pub struct Call {
id: u64,
outcome: mpsc::Receiver<Outcome>,
deadline: Option<Instant>,
link: Arc<dyn Link>,
}
impl Call {
#[inline]
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
#[inline]
#[must_use]
pub const fn deadline(&self) -> Option<Instant> {
self.deadline
}
pub fn wait(self) -> Result<Raw<'static>, CallError> {
match self.outcome.try_recv() {
Ok(outcome) => return outcome,
Err(TryRecvError::Disconnected) => return Err(CallError::Closed),
Err(TryRecvError::Empty) => {}
}
if self.link.on_endpoint_thread() {
return Err(CallError::WouldDeadlock);
}
if let Some(deadline) = self.deadline {
let left = deadline.saturating_duration_since(Instant::now());
match self.outcome.recv_timeout(left) {
Ok(outcome) => return outcome,
Err(RecvTimeoutError::Disconnected) => return Err(CallError::Closed),
Err(RecvTimeoutError::Timeout) => self.link.expire(),
}
}
self.outcome.recv().unwrap_or(Err(CallError::Closed))
}
pub fn try_wait(self) -> Result<Result<Raw<'static>, CallError>, Call> {
if self.deadline.is_some_and(|d| d <= Instant::now()) {
self.link.expire();
}
match self.outcome.try_recv() {
Ok(outcome) => Ok(outcome),
Err(TryRecvError::Disconnected) => Ok(Err(CallError::Closed)),
Err(TryRecvError::Empty) => Err(self),
}
}
pub fn cancel(self) -> bool {
self.link.cancel(self.id)
}
#[must_use]
pub fn canceller(&self) -> Canceller {
Canceller {
id: self.id,
link: Arc::clone(&self.link),
}
}
}
impl fmt::Debug for Call {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Call")
.field("id", &self.id)
.field("deadline", &self.deadline)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct Canceller {
id: u64,
link: Arc<dyn Link>,
}
impl Canceller {
pub fn cancel(&self) -> bool {
self.link.cancel(self.id)
}
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
}
impl fmt::Debug for Canceller {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Canceller").field("id", &self.id).finish()
}
}
pub struct Responder {
id: Id<'static>,
token: CancelToken,
link: Arc<dyn Link>,
answered: bool,
}
impl Responder {
pub(crate) fn new(id: Id<'static>, token: CancelToken, link: Arc<dyn Link>) -> Self {
Self {
id,
token,
link,
answered: false,
}
}
#[inline]
#[must_use]
pub fn id(&self) -> &Id<'static> {
&self.id
}
#[must_use]
pub fn token(&self) -> CancelToken {
self.token.clone()
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.token.is_cancelled()
}
#[must_use]
pub fn peer(&self) -> Peer {
Peer::new(Arc::clone(&self.link))
}
pub fn respond<'a, J: Into<Json<'a>>>(
mut self,
result: Result<J, ErrorObject>,
) -> Result<(), Error> {
self.answered = true;
match result {
Ok(value) => self.link.respond(&self.id, Ok(&value.into())),
Err(error) => self.link.respond(&self.id, Err(&error)),
}
}
pub fn ok<'a>(self, value: impl Into<Json<'a>>) -> Result<(), Error> {
self.respond(Ok(value.into()))
}
pub fn err(self, error: ErrorObject) -> Result<(), Error> {
self.respond(Err::<(), _>(error))
}
}
impl Drop for Responder {
fn drop(&mut self) {
if self.answered {
return;
}
let message = if thread::panicking() {
"the handler panicked before answering"
} else {
"the handler dropped the request without answering"
};
let _settled = self
.link
.respond(&self.id, Err(&ErrorObject::internal_error(message)));
}
}
impl fmt::Debug for Responder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Responder")
.field("id", &self.id)
.field("cancelled", &self.is_cancelled())
.finish_non_exhaustive()
}
}