use std::{
fmt,
future::Future,
pin::Pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::{self, Poll},
thread,
time::{Duration, Instant},
};
use jsonx_lib::Kind;
use crate::{
error::{CallError, Error},
error_object::ErrorObject,
id::Id,
link::{Link, Scope},
raw::{Json, Raw},
slot::{Outcome, Slot},
stats::Stats,
};
#[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(crate) fn link(&self) -> &Arc<dyn Link> {
&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),
detached: false,
})
}
#[must_use]
pub fn is_closed(&self) -> bool {
self.link.is_closed()
}
#[must_use]
pub fn stats(&self) -> Stats {
self.link.stats()
}
}
impl fmt::Debug for Peer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Peer")
.field("closed", &self.is_closed())
.finish()
}
}
#[must_use = "dropping a Call cancels the request; call .detach() to let it run"]
pub struct Call {
id: u64,
outcome: Arc<Slot>,
deadline: Option<Instant>,
link: Arc<dyn Link>,
detached: bool,
}
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> {
if let Some(outcome) = self.outcome.try_take() {
return outcome;
}
if self.link.on_endpoint_thread() {
return Err(CallError::WouldDeadlock);
}
if let Some(deadline) = self.deadline {
if let Some(outcome) = self.outcome.wait_until(Some(deadline)) {
return outcome;
}
self.link.expire();
}
self.outcome
.wait_until(None)
.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_take() {
Some(outcome) => Ok(outcome),
None => Err(self),
}
}
pub fn detach(mut self) {
self.detached = true;
}
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 Drop for Call {
fn drop(&mut self) {
if !self.detached && !self.outcome.is_filled() {
let _cancelled = self.link.cancel(self.id);
}
}
}
impl Future for Call {
type Output = Outcome;
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Outcome> {
if self.deadline.is_some_and(|d| d <= Instant::now()) {
self.link.expire();
}
self.outcome.poll(cx)
}
}
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>,
serial: u64,
token: CancelToken,
link: Arc<dyn Link>,
answered: bool,
}
impl Responder {
pub(crate) fn new(
id: Id<'static>,
serial: u64,
token: CancelToken,
link: Arc<dyn Link>,
) -> Self {
Self {
id,
serial,
token,
link,
answered: false,
}
}
pub(crate) fn scope(&self) -> Scope {
Scope::Deferred {
id: self.id.clone(),
serial: self.serial,
}
}
#[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, self.serial, Ok(&value.into())),
Err(error) => self.link.respond(&self.id, self.serial, 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,
self.serial,
Err(&ErrorObject::internal_error(message)),
);
}
}
impl Responder {
#[must_use]
pub fn notifier(&self) -> Notifier {
Notifier {
peer: self.peer(),
scope: self.scope(),
}
}
}
#[derive(Clone)]
pub struct Notifier {
peer: Peer,
scope: Scope,
}
impl Notifier {
pub(crate) fn new(peer: Peer, scope: Scope) -> Self {
Self { peer, scope }
}
pub fn notify<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<(), Error> {
let params = outgoing_params(params)?;
self.peer
.link()
.notify_in(&self.scope, None, method, params.as_ref())
}
}
impl fmt::Debug for Notifier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Notifier").finish_non_exhaustive()
}
}
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()
}
}