use std::{
collections::VecDeque,
future::{Future, IntoFuture},
marker::PhantomData,
ops::{Deref, DerefMut},
pin::Pin,
sync::Arc,
task::{Context, Poll, ready},
time::Duration,
};
use bytes::Bytes;
use futures_core::Stream;
use crate::{Client, LeaseId, ResponseHeader, client::ClientInner, pb::etcdserverpb};
impl Client {
pub fn grant_lease(&self) -> GrantLease<Self> {
GrantLease::new().with_client(self.clone())
}
pub fn revoke_lease(&self, lease_id: LeaseId) -> RevokeLease<Self> {
RevokeLease::new(lease_id).with_client(self.clone())
}
pub fn lease_time_to_live(&self, lease_id: LeaseId) -> LeaseTimeToLive<Self> {
LeaseTimeToLive::new(lease_id).with_client(self.clone())
}
pub fn leases(&self) -> Leases<Self> {
Leases::new().with_client(self.clone())
}
pub fn lease_keeper(&self) -> LeaseKeeper {
crate::driver::LeaseDriver::start_lease_keeper(self.clone())
}
}
#[derive(Clone, Copy, Debug)]
pub struct LeaseInfo {
pub lease_id: LeaseId,
pub ttl: Option<Duration>,
}
#[derive(Clone)]
#[must_use = "GrantLease does nothing unless you `await` it"]
pub struct GrantLease<C> {
pub(crate) client: C,
pub(crate) request: etcdserverpb::LeaseGrantRequest,
}
impl GrantLease<()> {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
client: (),
request: etcdserverpb::LeaseGrantRequest::default(),
}
}
}
impl<C> GrantLease<C> {
pub fn with_client<C2>(self, client: C2) -> GrantLease<C2> {
GrantLease {
client,
request: self.request,
}
}
pub fn lease_id(mut self, lease_id: LeaseId) -> Self {
self.request.id = lease_id.get();
self
}
pub fn ttl(mut self, duration: Duration) -> Self {
self.request.ttl = i64::try_from(duration.as_secs()).unwrap_or(i64::MAX);
self
}
pub fn requested_lease_id(&self) -> Option<LeaseId> {
LeaseId::new(self.request.id)
}
pub fn requested_ttl(&self) -> Option<Duration> {
(self.request.ttl > 0).then(|| Duration::from_secs(self.request.ttl as _))
}
pub(crate) fn into_parts(self) -> (C, GrantLease<()>) {
(
self.client,
GrantLease {
client: (),
request: self.request,
},
)
}
}
#[derive(Clone, Copy, Debug)]
pub struct GrantLeaseResponse {
header: ResponseHeader,
info: LeaseInfo,
}
impl GrantLeaseResponse {
pub(crate) fn new(header: ResponseHeader, info: LeaseInfo) -> Self {
Self { header, info }
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
pub fn info(&self) -> &LeaseInfo {
&self.info
}
pub fn into_info(self) -> LeaseInfo {
self.info
}
}
impl Deref for GrantLeaseResponse {
type Target = LeaseInfo;
fn deref(&self) -> &LeaseInfo {
&self.info
}
}
#[derive(Clone, Copy, Debug)]
pub struct RevokeLeaseResponse {
header: ResponseHeader,
}
impl RevokeLeaseResponse {
pub(crate) fn new(header: ResponseHeader) -> Self {
Self { header }
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
}
pub struct GrantLeaseFuture(Pin<Box<dyn Future<Output = Result<GrantLeaseResponse, GrantLeaseError>> + Send>>);
impl GrantLeaseFuture {
pub(crate) fn new(
future: impl Future<Output = Result<GrantLeaseResponse, GrantLeaseError>> + Send + 'static,
) -> Self {
Self(Box::pin(future))
}
}
impl Future for GrantLeaseFuture {
type Output = Result<GrantLeaseResponse, GrantLeaseError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.get_mut().0.as_mut().poll(cx)
}
}
impl<C: crate::driver::LeaseDriver> IntoFuture for GrantLease<C> {
type Output = Result<GrantLeaseResponse, GrantLeaseError>;
type IntoFuture = C::GrantFuture;
fn into_future(self) -> Self::IntoFuture {
let (client, detached) = self.into_parts();
client.execute_grant_lease(detached)
}
}
#[derive(Clone)]
#[must_use = "RevokeLease does nothing unless you `await` it"]
pub struct RevokeLease<C> {
client: C,
pub(crate) lease_id: LeaseId,
}
impl RevokeLease<()> {
pub fn new(lease_id: LeaseId) -> Self {
Self { client: (), lease_id }
}
}
impl<C> RevokeLease<C> {
pub fn with_client<C2>(self, client: C2) -> RevokeLease<C2> {
RevokeLease {
client,
lease_id: self.lease_id,
}
}
pub fn lease_id(&self) -> LeaseId {
self.lease_id
}
pub(crate) fn into_parts(self) -> (C, RevokeLease<()>) {
(
self.client,
RevokeLease {
client: (),
lease_id: self.lease_id,
},
)
}
}
pub struct RevokeLeaseFuture(Pin<Box<dyn Future<Output = Result<RevokeLeaseResponse, RevokeLeaseError>> + Send>>);
impl RevokeLeaseFuture {
pub(crate) fn new(
future: impl Future<Output = Result<RevokeLeaseResponse, RevokeLeaseError>> + Send + 'static,
) -> Self {
Self(Box::pin(future))
}
}
impl Future for RevokeLeaseFuture {
type Output = Result<RevokeLeaseResponse, RevokeLeaseError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.get_mut().0.as_mut().poll(cx)
}
}
impl<C: crate::driver::LeaseDriver> IntoFuture for RevokeLease<C> {
type Output = Result<RevokeLeaseResponse, RevokeLeaseError>;
type IntoFuture = C::RevokeFuture;
fn into_future(self) -> Self::IntoFuture {
let (client, detached) = self.into_parts();
client.execute_revoke_lease(detached)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrantLeaseErrorKind {
LeaseExists,
TtlTooLarge,
Authentication,
Exhausted,
DataLoss,
Unavailable,
Timeout,
Unknown,
}
define_op_error! {
pub struct GrantLeaseError(GrantLeaseErrorKind);
}
impl GrantLeaseError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::Unauthenticated => GrantLeaseErrorKind::Authentication,
tonic::Code::PermissionDenied => GrantLeaseErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
GrantLeaseErrorKind::Authentication
}
tonic::Code::ResourceExhausted => GrantLeaseErrorKind::Exhausted,
tonic::Code::OutOfRange => GrantLeaseErrorKind::TtlTooLarge,
tonic::Code::FailedPrecondition => {
if status.message().contains("already exists") {
GrantLeaseErrorKind::LeaseExists
} else {
GrantLeaseErrorKind::Unknown
}
}
tonic::Code::DataLoss => GrantLeaseErrorKind::DataLoss,
tonic::Code::Unavailable => GrantLeaseErrorKind::Unavailable,
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => GrantLeaseErrorKind::Timeout,
_ => GrantLeaseErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RevokeLeaseErrorKind {
NotFound,
Authentication,
Exhausted,
DataLoss,
Unavailable,
Timeout,
Unknown,
}
define_op_error! {
pub struct RevokeLeaseError(RevokeLeaseErrorKind);
}
impl RevokeLeaseError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::NotFound => RevokeLeaseErrorKind::NotFound,
tonic::Code::Unauthenticated => RevokeLeaseErrorKind::Authentication,
tonic::Code::PermissionDenied => RevokeLeaseErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
RevokeLeaseErrorKind::Authentication
}
tonic::Code::ResourceExhausted => RevokeLeaseErrorKind::Exhausted,
tonic::Code::DataLoss => RevokeLeaseErrorKind::DataLoss,
tonic::Code::Unavailable => RevokeLeaseErrorKind::Unavailable,
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => RevokeLeaseErrorKind::Timeout,
_ => RevokeLeaseErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
#[derive(Clone, Debug)]
#[must_use = "LeaseTimeToLive does nothing unless you `await` it"]
pub struct LeaseTimeToLive<C, K = ()> {
client: C,
pub(crate) request: etcdserverpb::LeaseTimeToLiveRequest,
_keys: PhantomData<fn() -> K>,
}
impl LeaseTimeToLive<()> {
pub fn new(lease_id: LeaseId) -> Self {
Self {
client: (),
request: etcdserverpb::LeaseTimeToLiveRequest {
id: lease_id.get(),
..Default::default()
},
_keys: PhantomData,
}
}
}
impl<C, K> LeaseTimeToLive<C, K> {
pub fn with_client<C2>(self, client: C2) -> LeaseTimeToLive<C2, K> {
LeaseTimeToLive {
client,
request: self.request,
_keys: PhantomData,
}
}
pub fn with_keys(self) -> LeaseTimeToLive<C, WithKeys> {
let mut request = self.request;
request.keys = true;
LeaseTimeToLive {
client: self.client,
request,
_keys: PhantomData,
}
}
pub fn lease_id(&self) -> LeaseId {
LeaseId::new(self.request.id).expect("LeaseTimeToLive lease ID should be non-zero")
}
pub fn returns_keys(&self) -> bool {
self.request.keys
}
pub(crate) fn into_parts(self) -> (C, LeaseTimeToLive<(), K>) {
(
self.client,
LeaseTimeToLive {
client: (),
request: self.request,
_keys: PhantomData,
},
)
}
}
#[derive(Clone, Debug)]
pub struct LeaseTimeToLiveResponse<K = ()> {
header: ResponseHeader,
info: LeaseInfo,
granted_ttl: Option<Duration>,
keys: Vec<Bytes>,
_marker: PhantomData<fn() -> K>,
}
impl<K> LeaseTimeToLiveResponse<K> {
pub fn new(header: ResponseHeader, info: LeaseInfo, granted_ttl: Option<Duration>, keys: Vec<Bytes>) -> Self {
Self {
header,
info,
granted_ttl,
keys,
_marker: PhantomData,
}
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
pub fn info(&self) -> &LeaseInfo {
&self.info
}
pub fn granted_ttl(&self) -> Option<Duration> {
self.granted_ttl
}
}
impl LeaseTimeToLiveResponse<WithKeys> {
pub fn keys(&self) -> &[Bytes] {
&self.keys
}
pub fn into_keys(self) -> Vec<Bytes> {
self.keys
}
}
impl<K> Deref for LeaseTimeToLiveResponse<K> {
type Target = LeaseInfo;
fn deref(&self) -> &LeaseInfo {
&self.info
}
}
pub struct LeaseTimeToLiveFuture<T>(Pin<Box<dyn Future<Output = T> + Send>>);
impl<T> LeaseTimeToLiveFuture<T> {
pub(crate) fn new(future: impl Future<Output = T> + Send + 'static) -> Self {
Self(Box::pin(future))
}
}
impl<T> Future for LeaseTimeToLiveFuture<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.get_mut().0.as_mut().poll(cx)
}
}
impl<C, K> IntoFuture for LeaseTimeToLive<C, K>
where
C: crate::driver::LeaseDriver,
{
type Output = Result<LeaseTimeToLiveResponse<K>, LeaseTimeToLiveError>;
type IntoFuture = C::TimeToLiveFuture<K>;
fn into_future(self) -> Self::IntoFuture {
let (client, detached) = self.into_parts();
client.execute_lease_time_to_live(detached)
}
}
pub struct WithKeys;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeaseTimeToLiveErrorKind {
NotFound,
Authentication,
Exhausted,
DataLoss,
Unavailable,
Timeout,
Unknown,
}
define_op_error! {
pub struct LeaseTimeToLiveError(LeaseTimeToLiveErrorKind);
}
impl LeaseTimeToLiveError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::NotFound => LeaseTimeToLiveErrorKind::NotFound,
tonic::Code::Unauthenticated => LeaseTimeToLiveErrorKind::Authentication,
tonic::Code::PermissionDenied => LeaseTimeToLiveErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
LeaseTimeToLiveErrorKind::Authentication
}
tonic::Code::ResourceExhausted => LeaseTimeToLiveErrorKind::Exhausted,
tonic::Code::DataLoss => LeaseTimeToLiveErrorKind::DataLoss,
tonic::Code::Unavailable => LeaseTimeToLiveErrorKind::Unavailable,
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => LeaseTimeToLiveErrorKind::Timeout,
_ => LeaseTimeToLiveErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
#[derive(Clone)]
#[must_use = "Leases does nothing unless you `await` it"]
pub struct Leases<C> {
client: C,
}
impl Leases<()> {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self { client: () }
}
}
impl<C> Leases<C> {
pub fn with_client<C2>(self, client: C2) -> Leases<C2> {
Leases { client }
}
pub(crate) fn into_parts(self) -> (C, Leases<()>) {
(self.client, Leases { client: () })
}
}
#[derive(Clone, Debug)]
pub struct LeasesResponse {
header: ResponseHeader,
leases: Vec<LeaseId>,
}
impl LeasesResponse {
pub(crate) fn new(header: ResponseHeader, leases: Vec<LeaseId>) -> Self {
Self { header, leases }
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
pub fn leases(&self) -> &[LeaseId] {
&self.leases
}
pub fn into_leases(self) -> Vec<LeaseId> {
self.leases
}
}
pub struct LeasesFuture(Pin<Box<dyn Future<Output = Result<LeasesResponse, LeasesError>> + Send>>);
impl LeasesFuture {
pub(crate) fn new(future: impl Future<Output = Result<LeasesResponse, LeasesError>> + Send + 'static) -> Self {
Self(Box::pin(future))
}
}
impl Future for LeasesFuture {
type Output = Result<LeasesResponse, LeasesError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.get_mut().0.as_mut().poll(cx)
}
}
impl<C: crate::driver::LeaseDriver> IntoFuture for Leases<C> {
type Output = Result<LeasesResponse, LeasesError>;
type IntoFuture = C::LeasesFuture;
fn into_future(self) -> Self::IntoFuture {
let (client, detached) = self.into_parts();
client.execute_leases(detached)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeasesErrorKind {
Authentication,
Exhausted,
DataLoss,
Unavailable,
Timeout,
Unknown,
}
define_op_error! {
pub struct LeasesError(LeasesErrorKind);
}
impl LeasesError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::Unauthenticated => LeasesErrorKind::Authentication,
tonic::Code::PermissionDenied => LeasesErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
LeasesErrorKind::Authentication
}
tonic::Code::ResourceExhausted => LeasesErrorKind::Exhausted,
tonic::Code::DataLoss => LeasesErrorKind::DataLoss,
tonic::Code::Unavailable => LeasesErrorKind::Unavailable,
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => LeasesErrorKind::Timeout,
_ => LeasesErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
#[derive(Clone, Copy, Debug)]
pub struct KeepAliveResponse {
header: ResponseHeader,
info: LeaseInfo,
}
impl KeepAliveResponse {
pub(crate) fn new(header: ResponseHeader, info: LeaseInfo) -> Self {
Self { header, info }
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
pub fn info(&self) -> &LeaseInfo {
&self.info
}
}
impl Deref for KeepAliveResponse {
type Target = LeaseInfo;
fn deref(&self) -> &LeaseInfo {
&self.info
}
}
pub struct LeaseKeeper {
sender: KeepAliveSender,
stream: KeepAliveStream,
}
impl LeaseKeeper {
pub(crate) fn new(sender: KeepAliveSender, stream: KeepAliveStream) -> Self {
Self { sender, stream }
}
pub fn into_parts(self) -> (KeepAliveSender, KeepAliveStream) {
(self.sender, self.stream)
}
pub fn keep_alive(&self, lease_id: LeaseId) {
self.sender.keep_alive(lease_id);
}
}
impl Deref for LeaseKeeper {
type Target = KeepAliveStream;
fn deref(&self) -> &Self::Target {
&self.stream
}
}
impl DerefMut for LeaseKeeper {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.stream
}
}
impl Stream for LeaseKeeper {
type Item = Result<KeepAliveResponse, KeepAliveError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.stream).poll_next(cx)
}
}
#[cfg(feature = "nightly-async-iterator")]
impl std::async_iter::AsyncIterator for LeaseKeeper {
type Item = Result<KeepAliveResponse, KeepAliveError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Stream::poll_next(Pin::new(&mut self.stream), cx)
}
}
pub struct KeepAliveSender {
sender: tokio::sync::mpsc::UnboundedSender<etcdserverpb::LeaseKeepAliveRequest>,
}
impl KeepAliveSender {
pub(crate) fn new(sender: tokio::sync::mpsc::UnboundedSender<etcdserverpb::LeaseKeepAliveRequest>) -> Self {
Self { sender }
}
pub fn keep_alive(&self, lease_id: LeaseId) {
let _ = self
.sender
.send(etcdserverpb::LeaseKeepAliveRequest { id: lease_id.get() });
}
}
pub struct KeepAliveStream {
inner: Box<dyn Stream<Item = Result<KeepAliveResponse, KeepAliveError>> + Send>,
}
impl KeepAliveStream {
pub(crate) fn new(inner: impl Stream<Item = Result<KeepAliveResponse, KeepAliveError>> + Send + 'static) -> Self {
Self { inner: Box::new(inner) }
}
fn poll_next_impl(
self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Result<Option<KeepAliveResponse>, KeepAliveError>> {
let inner = unsafe { self.map_unchecked_mut(|s| s.inner.as_mut()) };
inner.poll_next(cx).map(|item| match item {
None => Ok(None),
Some(Ok(resp)) => Ok(Some(resp)),
Some(Err(err)) => Err(err),
})
}
}
impl Stream for KeepAliveStream {
type Item = Result<KeepAliveResponse, KeepAliveError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.poll_next_impl(cx).map(Result::transpose)
}
}
#[cfg(feature = "nightly-async-iterator")]
impl std::async_iter::AsyncIterator for KeepAliveStream {
type Item = Result<KeepAliveResponse, KeepAliveError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.poll_next_impl(cx).map(Result::transpose)
}
}
pub(crate) struct KeepAliveRequests {
receiver: tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::LeaseKeepAliveRequest>,
unanswered: VecDeque<etcdserverpb::LeaseKeepAliveRequest>,
sent: usize,
stream: u64,
}
impl KeepAliveRequests {
pub(crate) fn new(receiver: tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::LeaseKeepAliveRequest>) -> Self {
Self {
receiver,
unanswered: VecDeque::new(),
sent: 0,
stream: 0,
}
}
pub(crate) fn answered(&mut self) {
self.unanswered.pop_front();
self.sent = self
.sent
.checked_sub(1)
.expect("etcd should answer only the keep-alives it was sent");
}
}
pub(crate) struct KeepAliveReceiverStream {
requests: Arc<std::sync::Mutex<KeepAliveRequests>>,
stream: u64,
}
impl KeepAliveReceiverStream {
pub(crate) fn new(requests: &Arc<std::sync::Mutex<KeepAliveRequests>>) -> Self {
let mut state = requests.lock().unwrap();
state.stream += 1;
state.sent = 0;
Self {
requests: requests.clone(),
stream: state.stream,
}
}
}
impl Stream for KeepAliveReceiverStream {
type Item = etcdserverpb::LeaseKeepAliveRequest;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut requests = self.requests.lock().unwrap();
if requests.stream != self.stream {
return Poll::Ready(None);
}
if requests.sent == requests.unanswered.len() {
let Some(request) = ready!(requests.receiver.poll_recv(cx)) else {
return Poll::Ready(None);
};
requests.unanswered.push_back(request);
}
let request = requests.unanswered[requests.sent];
requests.sent += 1;
Poll::Ready(Some(request))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeepAliveErrorKind {
NotFound,
Authentication,
Exhausted,
DataLoss,
Unavailable,
Timeout,
Unknown,
}
define_op_error! {
pub struct KeepAliveError(KeepAliveErrorKind);
}
impl KeepAliveError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::NotFound => KeepAliveErrorKind::NotFound,
tonic::Code::Unauthenticated => KeepAliveErrorKind::Authentication,
tonic::Code::PermissionDenied => KeepAliveErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
KeepAliveErrorKind::Authentication
}
tonic::Code::ResourceExhausted => KeepAliveErrorKind::Exhausted,
tonic::Code::DataLoss => KeepAliveErrorKind::DataLoss,
tonic::Code::Unavailable => KeepAliveErrorKind::Unavailable,
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => KeepAliveErrorKind::Timeout,
_ => KeepAliveErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
const _: () = {
fn _assert_send<T: Send>() {}
fn _check() {
_assert_send::<GrantLeaseFuture>();
_assert_send::<KeepAliveSender>();
_assert_send::<KeepAliveStream>();
_assert_send::<LeaseKeeper>();
_assert_send::<LeaseTimeToLiveFuture<Result<LeaseTimeToLiveResponse, LeaseTimeToLiveError>>>();
_assert_send::<LeaseTimeToLiveFuture<Result<LeaseTimeToLiveResponse<WithKeys>, LeaseTimeToLiveError>>>();
_assert_send::<LeasesFuture>();
}
};
#[cfg(test)]
mod test {
use super::*;
fn requests() -> (KeepAliveSender, Arc<std::sync::Mutex<KeepAliveRequests>>) {
let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
let requests = Arc::new(std::sync::Mutex::new(KeepAliveRequests::new(receiver)));
(KeepAliveSender::new(sender), requests)
}
fn take(stream: &mut KeepAliveReceiverStream) -> Poll<Option<i64>> {
let mut cx = Context::from_waker(std::task::Waker::noop());
Pin::new(stream)
.poll_next(&mut cx)
.map(|request| request.map(|request| request.id))
}
fn keep_alive(sender: &KeepAliveSender, id: i64) {
sender.keep_alive(LeaseId::new(id).unwrap());
}
#[test]
fn a_new_stream_sends_what_etcd_never_answered_first() {
let (sender, requests) = requests();
let mut failed = KeepAliveReceiverStream::new(&requests);
for id in 1..=3 {
keep_alive(&sender, id);
}
assert_eq!(take(&mut failed), Poll::Ready(Some(1)));
assert_eq!(take(&mut failed), Poll::Ready(Some(2)));
requests.lock().unwrap().answered();
let mut next = KeepAliveReceiverStream::new(&requests);
assert_eq!(take(&mut failed), Poll::Ready(None));
keep_alive(&sender, 4);
assert_eq!(take(&mut next), Poll::Ready(Some(2)));
assert_eq!(take(&mut next), Poll::Ready(Some(3)));
assert_eq!(take(&mut next), Poll::Ready(Some(4)));
assert_eq!(take(&mut next), Poll::Pending);
}
#[test]
fn a_stream_that_fails_while_sending_again_keeps_the_order() {
let (sender, requests) = requests();
let mut first = KeepAliveReceiverStream::new(&requests);
for id in 1..=3 {
keep_alive(&sender, id);
assert_eq!(take(&mut first), Poll::Ready(Some(id)));
}
let mut second = KeepAliveReceiverStream::new(&requests);
assert_eq!(take(&mut second), Poll::Ready(Some(1)));
requests.lock().unwrap().answered();
assert_eq!(take(&mut second), Poll::Ready(Some(2)));
let mut third = KeepAliveReceiverStream::new(&requests);
assert_eq!(take(&mut third), Poll::Ready(Some(2)));
assert_eq!(take(&mut third), Poll::Ready(Some(3)));
assert_eq!(take(&mut third), Poll::Pending);
}
#[test]
fn dropping_the_sender_ends_the_stream() {
let (sender, requests) = requests();
let mut first = KeepAliveReceiverStream::new(&requests);
keep_alive(&sender, 1);
assert_eq!(take(&mut first), Poll::Ready(Some(1)));
drop(sender);
let mut second = KeepAliveReceiverStream::new(&requests);
assert_eq!(take(&mut second), Poll::Ready(Some(1)));
assert_eq!(take(&mut second), Poll::Ready(None));
}
#[test]
fn a_ttl_past_i64_max_seconds_saturates() {
for ttl in [Duration::from_secs(1 << 63), Duration::MAX] {
let grant = GrantLease::new().ttl(ttl);
assert_eq!(
grant.requested_ttl(),
Some(Duration::from_secs(i64::MAX as u64)),
"{ttl:?}"
);
}
}
#[test]
fn invalid_argument_is_authentication_only_for_token_messages() {
for (message, expected) in [
("etcdserver: user name is empty", "Authentication"),
("etcdserver: revision of auth store is old", "Authentication"),
("etcdserver: request is too large", "Unknown"),
("etcdserver: invalid client api version", "Unknown"),
] {
let status = || tonic::Status::invalid_argument(message);
let kinds = [
format!("{:?}", GrantLeaseError::from_status(status()).kind()),
format!("{:?}", RevokeLeaseError::from_status(status()).kind()),
format!("{:?}", LeaseTimeToLiveError::from_status(status()).kind()),
format!("{:?}", LeasesError::from_status(status()).kind()),
format!("{:?}", KeepAliveError::from_status(status()).kind()),
];
assert_eq!(kinds, [expected; 5], "{message:?}");
}
}
}