etcdrs 0.1.2

An async etcd v3 client built on tonic and tokio, with composable operation builders and type-safe responses
Documentation
use std::{
    future::{Future, IntoFuture},
    pin::Pin,
    task::{Context, Poll},
};

use bytes::Bytes;

use crate::{
    Client, ResponseHeader, Revision,
    client::ClientInner,
    pb::etcdserverpb,
    record::{AsKey, Record},
};

/// # Reading Keys
impl Client {
    /// Get the contents of `key` from the database.
    ///
    /// ```no_run
    /// # async {
    /// let client: etcdrs::Client = todo!();
    /// let response = client.get("path/to/foo").await.unwrap();
    /// if let Some(entry) = response.record() {
    ///     println!("found: {entry:?}");
    /// } else {
    ///     println!("not found");
    /// }
    /// # };
    /// ```
    pub fn get(&self, key: impl AsKey) -> Get<Self> {
        Get::new(key).with_client(self.clone())
    }
}

/// A [`Client::get`] operation.
#[derive(Clone, Debug)]
pub struct Get<C> {
    pub(crate) client: C,
    pub(crate) request: etcdserverpb::RangeRequest,
}

impl Get<()> {
    pub fn new(key: impl AsKey) -> Self {
        Self {
            client: (),
            request: etcdserverpb::RangeRequest {
                key: Bytes::copy_from_slice(key.as_key()),
                ..Default::default()
            },
        }
    }
}

impl<C> Get<C> {
    /// Attach a `client` to this operation.
    ///
    /// You typically do not have to call this function, as it is called automatically by [`get`][`Client::get`].
    pub fn with_client<C2>(self, client: C2) -> Get<C2> {
        Get {
            client,
            request: self.request,
        }
    }

    /// Read the key as of a historical store `revision` instead of the current one.
    ///
    /// The revision is the global store revision from a [`ResponseHeader`] (or a record's
    /// [`modified_revision`][crate::Metadata::modified_revision]), not the key's version. Reading
    /// a revision that has been [compacted][Client::compact] fails with
    /// [`CompactedRevision`][GetErrorKind::CompactedRevision]; reading a revision the server has
    /// not reached yet fails with [`FutureRevision`][GetErrorKind::FutureRevision].
    ///
    /// ```no_run
    /// # async {
    /// let client: etcdrs::Client = todo!();
    /// let revision = client.put("foo").value("old").await.unwrap().header().revision();
    /// client.put("foo").value("new").await.unwrap();
    ///
    /// let old = client.get("foo").at_revision(revision).await.unwrap();
    /// assert_eq!(old.record().unwrap().value(), &b"old"[..]);
    /// # };
    /// ```
    pub fn at_revision(mut self, revision: Revision) -> Self {
        self.request.revision = revision.get();
        self
    }

    /// The key this operation addresses.
    pub fn target_key(&self) -> &[u8] {
        &self.request.key
    }

    /// The revision this operation reads from, or `None` for the server's current revision.
    pub fn revision(&self) -> Option<Revision> {
        Revision::new(self.request.revision)
    }

    /// Decompose this operation into its client and a detached `Get<()>`.
    pub(crate) fn into_parts(self) -> (C, Get<()>) {
        (
            self.client,
            Get {
                client: (),
                request: self.request,
            },
        )
    }
}

/// The response from a [`get`][Client::get] operation.
#[derive(Clone, Debug)]
pub struct GetResponse {
    header: ResponseHeader,
    record: Option<Record>,
}

impl GetResponse {
    /// Construct a new `GetResponse`.
    pub fn new(header: ResponseHeader, record: Option<Record>) -> Self {
        Self { header, record }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }

    /// The record associated with the key, or `None` if the key does not exist.
    pub fn record(&self) -> Option<&Record> {
        self.record.as_ref()
    }

    /// Consume the response and return the record, or `None` if the key does not exist.
    pub fn into_record(self) -> Option<Record> {
        self.record
    }
}

/// The [`Future`] type returned by awaiting a [`get`][`Client::get`].
pub struct GetFuture(Pin<Box<dyn Future<Output = Result<GetResponse, GetError>> + Send>>);

impl GetFuture {
    pub(crate) fn new(future: impl Future<Output = Result<GetResponse, GetError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for GetFuture {
    type Output = Result<GetResponse, GetError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::KvDriver> IntoFuture for Get<C> {
    type Output = Result<GetResponse, GetError>;
    type IntoFuture = C::GetFuture;

    fn into_future(self) -> C::GetFuture {
        let (client, detached) = self.into_parts();
        client.execute_get(detached)
    }
}

/// A enumeration of the [`kind`][GetError::kind]s of errors that can occur from a [`get`][Client::get] or
/// [`list`][Client::list] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GetErrorKind {
    /// The requested revision is older than the server has.
    ///
    /// This comes from the gRPC API as `OUT_OF_RANGE`.
    CompactedRevision,
    /// The requested revision is newer than the server has.
    ///
    /// This comes from the gRPC API as `OUT_OF_RANGE`.
    FutureRevision,
    /// There is an authentication or authorization error.
    ///
    /// This comes from the gRPC API as `UNAUTHENTICATED` or `PERMISSION_DENIED`, or as `INVALID_ARGUMENT` with
    /// "etcdserver: user name is empty" or "etcdserver: revision of auth store is old". Other `INVALID_ARGUMENT`
    /// responses describe the request rather than the caller, and are reported as [`Unknown`][Self::Unknown].
    Authentication,
    /// The server or transport is resource-exhausted.
    ///
    /// This comes from the gRPC API as `RESOURCE_EXHAUSTED`.
    Exhausted,
    /// The server is not ready to serve that request.
    ///
    /// This comes from the gRPC API as `UNAVAILABLE`.
    Unavailable,
    /// The request timed out.
    ///
    /// This comes from the gRPC API as `CANCELLED` or `DEADLINE_EXCEEDED`. We do not distinguish between the two, as
    /// the source of the timeout is usually not important.
    Timeout,
    /// The server has lost data.
    ///
    /// This comes from the gRPC API as `DATA_LOSS`.
    DataLoss,
    /// An error that is not covered by any other error kind.
    ///
    /// All uncovered gRPC errors are mapped to this kind of error. Among them are `INVALID_ARGUMENT` responses that
    /// describe the request, such as "etcdserver: key is not provided" for the empty key. Their message is available
    /// from [`grpc_status`][GetError::grpc_status]. Other uncovered errors should not happen unless the etcd server has
    /// changed its error codes. These can also be emitted from the client if the server does something unexpected
    /// (for example, returning more than one record for a single-key get).
    Unknown,
}

define_op_error! {
    /// An error from a [`get`][Client::get] or [`list`][Client::list] operation.
    pub struct GetError(GetErrorKind);
}

impl GetError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::Unauthenticated => GetErrorKind::Authentication,
            tonic::Code::PermissionDenied => GetErrorKind::Authentication,
            tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => GetErrorKind::Authentication,
            tonic::Code::ResourceExhausted => GetErrorKind::Exhausted,
            tonic::Code::OutOfRange => {
                if status.message().contains("compacted") {
                    GetErrorKind::CompactedRevision
                } else if status.message().contains("future") {
                    GetErrorKind::FutureRevision
                } else {
                    GetErrorKind::Unknown
                }
            }
            tonic::Code::Unavailable => GetErrorKind::Unavailable,
            // Don't care who timed us out
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => GetErrorKind::Timeout,
            _ => GetErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

const _: () = {
    fn _assert_send<T: Send>() {}
    fn _check() {
        _assert_send::<GetFuture>();
    }
};

#[cfg(test)]
mod test {
    use super::*;

    /// `get("")` gets "key is not provided", which is about the request.
    #[test]
    fn invalid_argument_is_authentication_only_for_token_messages() {
        use GetErrorKind::*;

        for (message, expected) in [
            ("etcdserver: user name is empty", Authentication),
            ("etcdserver: revision of auth store is old", Authentication),
            ("etcdserver: key is not provided", Unknown),
            ("etcdserver: invalid sort option", Unknown),
        ] {
            let kind = GetError::from_status(tonic::Status::invalid_argument(message)).kind();
            assert_eq!(kind, expected, "{message:?}");
        }
    }
}