use std::sync::Arc;
use crate::client::RedisClient;
use crate::error::{NasaRedisError, Result};
use crate::idempotent::metrics::IdempotentCounterMetrics;
use crate::idempotent::runtime::{interpret_result, Operation};
use crate::pipeline::{PipelineSession, Ticket};
pub struct IdempotentTicket<T> {
inner: Ticket<Vec<redis::Value>>,
metrics: Arc<IdempotentCounterMetrics>,
_value: std::marker::PhantomData<T>,
}
impl IdempotentTicket<i64> {
pub fn await_result(self) -> Result<i64> {
let raw = self.inner.await_result()?;
interpret_result(&self.metrics, &raw)?
.parse::<i64>()
.map_err(|_| protocol("idempotent pipeline integer result is not int64"))
}
}
impl IdempotentTicket<f64> {
pub fn await_result(self) -> Result<f64> {
let raw = self.inner.await_result()?;
let value = interpret_result(&self.metrics, &raw)?;
match value.to_ascii_lowercase().as_str() {
"inf" | "+inf" => Ok(f64::INFINITY),
"-inf" => Ok(f64::NEG_INFINITY),
_ => value
.parse::<f64>()
.map_err(|_| protocol("idempotent pipeline ZSet result is not numeric")),
}
}
}
pub struct IdempotentPipelineSession {
client: Arc<RedisClient>,
inner: PipelineSession,
}
impl RedisClient {
pub async fn idempotent_pipeline(self: &Arc<Self>) -> Result<IdempotentPipelineSession> {
self.prepare_idempotent_counter().await?;
Ok(IdempotentPipelineSession {
client: Arc::clone(self),
inner: self.deferred_pipeline(),
})
}
}
impl IdempotentPipelineSession {
pub fn incr_idempotent(&mut self, key: &str, nonce: &str) -> Result<IdempotentTicket<i64>> {
self.incr_by_idempotent(key, 1, nonce)
}
pub fn incr_by_idempotent(
&mut self,
key: &str,
delta: i64,
nonce: &str,
) -> Result<IdempotentTicket<i64>> {
self.enqueue_integer(Operation::StringIncrement, key, b"", delta, nonce)
}
pub fn decr_idempotent(&mut self, key: &str, nonce: &str) -> Result<IdempotentTicket<i64>> {
self.decr_by_idempotent(key, 1, nonce)
}
pub fn decr_by_idempotent(
&mut self,
key: &str,
delta: i64,
nonce: &str,
) -> Result<IdempotentTicket<i64>> {
self.enqueue_integer(Operation::StringDecrement, key, b"", delta, nonce)
}
pub fn h_incr_idempotent(
&mut self,
key: &str,
field: &str,
nonce: &str,
) -> Result<IdempotentTicket<i64>> {
self.h_incr_by_idempotent(key, field, 1, nonce)
}
pub fn h_incr_by_idempotent(
&mut self,
key: &str,
field: &str,
delta: i64,
nonce: &str,
) -> Result<IdempotentTicket<i64>> {
self.enqueue_integer(
Operation::HashIncrement,
key,
field.as_bytes(),
delta,
nonce,
)
}
pub fn h_decr_idempotent(
&mut self,
key: &str,
field: &str,
nonce: &str,
) -> Result<IdempotentTicket<i64>> {
self.h_decr_by_idempotent(key, field, 1, nonce)
}
pub fn h_decr_by_idempotent(
&mut self,
key: &str,
field: &str,
delta: i64,
nonce: &str,
) -> Result<IdempotentTicket<i64>> {
self.enqueue_integer(
Operation::HashDecrement,
key,
field.as_bytes(),
delta,
nonce,
)
}
pub fn z_incr_by_idempotent<V>(
&mut self,
key: &str,
member: V,
delta: f64,
nonce: &str,
) -> Result<IdempotentTicket<f64>>
where
V: redis::ToSingleRedisArg,
{
let member = single_arg(member)?;
let command = self.client.idempotent_runtime()?.pipeline_command(
Operation::ZSetIncrement,
key,
&member,
delta.to_string().into_bytes(),
nonce,
)?;
let inner = self.inner.enqueue(command)?;
Ok(IdempotentTicket {
inner,
metrics: self.client.idempotent_runtime()?.metrics().clone(),
_value: std::marker::PhantomData,
})
}
pub async fn execute(self) -> Result<()> {
self.inner.execute().await
}
fn enqueue_integer(
&mut self,
op: Operation,
key: &str,
member: &[u8],
delta: i64,
nonce: &str,
) -> Result<IdempotentTicket<i64>> {
let runtime = self.client.idempotent_runtime()?;
let command =
runtime.pipeline_command(op, key, member, delta.to_string().into_bytes(), nonce)?;
let inner = self.inner.enqueue(command)?;
Ok(IdempotentTicket {
inner,
metrics: runtime.metrics().clone(),
_value: std::marker::PhantomData,
})
}
}
fn single_arg<V: redis::ToSingleRedisArg>(value: V) -> Result<Vec<u8>> {
let mut args = redis::ToRedisArgs::to_redis_args(&value);
let arg = args
.pop()
.ok_or_else(|| protocol("ZSet member did not produce a Redis argument"))?;
if !args.is_empty() {
return Err(protocol("ZSet member produced multiple Redis arguments"));
}
Ok(arg)
}
fn protocol(message: &str) -> NasaRedisError {
NasaRedisError::IdempotentProtocol(message.to_owned())
}