use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use redis::{Cmd, Connection, ConnectionAddr, Pipeline, RedisError, Value};
use crate::entry::{AutoClaim, Entry, EntryId, GroupBacklog, LostLease, Pending, RawFields, Renewal};
use crate::error::{Error, Result};
use crate::streams::{Streams, expire_seconds};
const MAX_IDLE_CONNECTIONS: usize = 16;
const RENEW_SCRIPT: &str = "\
local p = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[3], ARGV[3], 1)
if #p == 0 then return 0 end
if p[1][2] ~= ARGV[2] then return -1 end
local c = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[2], 0, ARGV[3], 'JUSTID')
if #c == 0 then return 0 end
return 1
";
const RELEASE_SCRIPT: &str = "\
local p = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[3], ARGV[3], 1)
if #p == 0 then return 0 end
if p[1][2] ~= ARGV[2] then return -1 end
local c = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[2], 0, ARGV[3], 'IDLE', ARGV[4], 'JUSTID')
if #c == 0 then return 0 end
return 1
";
#[derive(Clone)]
pub struct RedisStreams {
inner: Arc<Inner>,
}
struct Inner {
client: redis::Client,
idle: Mutex<Vec<Connection>>,
timeout: Duration,
prefix: String,
}
impl RedisStreams {
pub fn open(url: &str) -> Result<Self> {
let client =
redis::Client::open(url).map_err(|_| Error::Redis("the URL isn't a valid Redis URL".to_owned()))?;
Ok(Self {
inner: Arc::new(Inner {
client,
idle: Mutex::new(Vec::new()),
timeout: Duration::from_secs(30),
prefix: String::new(),
}),
})
}
#[must_use]
pub fn timeout(self, timeout: Duration) -> Self {
Self {
inner: Arc::new(Inner {
client: self.inner.client.clone(),
idle: Mutex::new(Vec::new()),
timeout,
prefix: self.inner.prefix.clone(),
}),
}
}
#[must_use]
pub fn with_key_prefix(self, prefix: impl Into<String>) -> Self {
Self {
inner: Arc::new(Inner {
client: self.inner.client.clone(),
idle: Mutex::new(Vec::new()),
timeout: self.inner.timeout,
prefix: prefix.into(),
}),
}
}
#[must_use]
pub fn key_prefix(&self) -> &str {
&self.inner.prefix
}
fn commands(&self) -> Commands<'_> {
Commands {
prefix: &self.inner.prefix,
}
}
fn query(&self, cmd: &Cmd, block: Option<Duration>) -> Result<Value> {
self.with_connection(block, |connection| cmd.query(connection))
.map_err(|error| redis_error(&error))
}
fn with_connection<T>(
&self,
block: Option<Duration>,
run: impl FnOnce(&mut Connection) -> redis::RedisResult<T>,
) -> redis::RedisResult<T> {
let timeout = self.inner.timeout;
let pooled = self.inner.idle.lock().unwrap_or_else(PoisonError::into_inner).pop();
let mut connection = match pooled {
Some(connection) => connection,
None => self.inner.client.get_connection_with_timeout(timeout)?,
};
connection.set_read_timeout(Some(timeout.saturating_add(block.unwrap_or_default())))?;
connection.set_write_timeout(Some(timeout))?;
let result = run(&mut connection);
let reusable = match &result {
Ok(_) => true,
Err(error) => error.code().is_some() && !error.is_io_error() && !error.is_timeout(),
};
if reusable {
let mut idle = self.inner.idle.lock().unwrap_or_else(PoisonError::into_inner);
if idle.len() < MAX_IDLE_CONNECTIONS {
idle.push(connection);
}
}
result
}
fn query_group(&self, cmd: &Cmd, block: Option<Duration>, stream: &str, group: &str) -> Result<Value> {
self.with_connection(block, |connection| cmd.query(connection))
.map_err(|error| {
if is_nogroup(&error) {
Error::NoGroup {
stream: stream.to_owned(),
group: group.to_owned(),
}
} else {
redis_error(&error)
}
})
}
}
impl fmt::Debug for RedisStreams {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let endpoint = match self.inner.client.get_connection_info().addr() {
ConnectionAddr::Tcp(host, port) => format!("redis://{host}:{port}"),
ConnectionAddr::TcpTls { host, port, .. } => format!("rediss://{host}:{port}"),
ConnectionAddr::Unix(path) => format!("unix://{}", path.display()),
_ => "redis".to_owned(),
};
f.debug_struct("RedisStreams")
.field("endpoint", &endpoint)
.field("timeout", &self.inner.timeout)
.field("key_prefix", &self.inner.prefix)
.finish_non_exhaustive()
}
}
impl Streams for RedisStreams {
fn xadd(&self, stream: &str, fields: &[(&[u8], &[u8])]) -> Result<EntryId> {
entry_id(&self.query(&self.commands().xadd(stream, fields), None)?)
}
fn xlen(&self, stream: &str) -> Result<u64> {
count(&self.query(&self.commands().xlen(stream), None)?)
}
fn xgroup_create(&self, stream: &str, group: &str) -> Result<bool> {
let cmd = self.commands().xgroup_create(stream, group);
match self.with_connection(None, |connection| cmd.query::<Value>(connection)) {
Ok(_) => Ok(true),
Err(error) if error.code() == Some("BUSYGROUP") => Ok(false),
Err(error) => Err(redis_error(&error)),
}
}
fn xreadgroup(
&self,
stream: &str,
group: &str,
consumer: &str,
count: usize,
block: Option<Duration>,
) -> Result<Vec<Entry>> {
let cmd = self.commands().xreadgroup(stream, group, consumer, count, block);
let reply = self.query_group(&cmd, block, stream, group)?;
parse_read(&reply)
}
fn xautoclaim(
&self,
stream: &str,
group: &str,
consumer: &str,
min_idle: Duration,
start: EntryId,
count: usize,
) -> Result<AutoClaim> {
let cmd = self
.commands()
.xautoclaim(stream, group, consumer, min_idle, start, count);
let reply = self.query_group(&cmd, None, stream, group)?;
let parts = array("XAUTOCLAIM", &reply)?;
let (Some(next), Some(claimed)) = (parts.first(), parts.get(1)) else {
return Err(unexpected("XAUTOCLAIM", &reply));
};
let mut claim = AutoClaim {
next: entry_id(next)?,
..AutoClaim::default()
};
for value in array("XAUTOCLAIM", claimed)? {
match parse_entry(value)? {
Some(entry) => claim.claimed.push(entry),
None => {
if let Value::Array(pair) = value
&& let Some(id) = pair.first()
{
claim.deleted.push(entry_id(id)?);
}
}
}
}
if let Some(deleted) = parts.get(2) {
for id in array("XAUTOCLAIM", deleted)? {
claim.deleted.push(entry_id(id)?);
}
}
Ok(claim)
}
fn xclaim_justid(
&self,
stream: &str,
group: &str,
consumer: &str,
ids: &[EntryId],
idle: Option<Duration>,
) -> Result<Vec<EntryId>> {
if ids.is_empty() {
return Ok(Vec::new());
}
let cmd = self.commands().xclaim_justid(stream, group, consumer, ids, idle);
let reply = self.query_group(&cmd, None, stream, group)?;
array("XCLAIM", &reply)?.iter().map(entry_id).collect()
}
fn xpending_entry(&self, stream: &str, group: &str, id: EntryId) -> Result<Option<Pending>> {
let cmd = self.commands().xpending_entry(stream, group, id);
let reply = self.query_group(&cmd, None, stream, group)?;
array("XPENDING", &reply)?.first().map(parse_pending).transpose()
}
fn xpending_consumer(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Result<Vec<Pending>> {
let cmd = self.commands().xpending_consumer(stream, group, consumer, count);
let reply = self.query_group(&cmd, None, stream, group)?;
array("XPENDING", &reply)?.iter().map(parse_pending).collect()
}
fn xack(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<u64> {
if ids.is_empty() {
return Ok(0);
}
count(&self.query(&self.commands().xack(stream, group, ids), None)?)
}
fn xdel(&self, stream: &str, ids: &[EntryId]) -> Result<u64> {
if ids.is_empty() {
return Ok(0);
}
count(&self.query(&self.commands().xdel(stream, ids), None)?)
}
fn xack_xdel(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<()> {
if ids.is_empty() {
return Ok(());
}
let pipe = self.commands().xack_xdel(stream, group, ids);
self.with_connection(None, |connection| pipe.exec(connection))
.map_err(|error| redis_error(&error))
}
fn xgroup_delconsumer(&self, stream: &str, group: &str, consumer: &str) -> Result<u64> {
let cmd = self.commands().xgroup_delconsumer(stream, group, consumer);
count(&self.query_group(&cmd, None, stream, group)?)
}
fn renew_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId) -> Result<Renewal> {
let cmd = self.commands().renew_lease(stream, group, consumer, id);
let reply = self.query_group(&cmd, None, stream, group)?;
match reply {
Value::Int(1) => Ok(Renewal::Renewed),
Value::Int(0) => Ok(Renewal::Lost(LostLease::NotPending)),
Value::Int(-1) => Ok(Renewal::Lost(LostLease::OtherConsumer)),
other => Err(unexpected("the lease renewal script", &other)),
}
}
fn release_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId, idle: Duration) -> Result<bool> {
let cmd = self.commands().release_lease(stream, group, consumer, id, idle);
let reply = self.query_group(&cmd, None, stream, group)?;
match reply {
Value::Int(1) => Ok(true),
Value::Int(0 | -1) => Ok(false),
other => Err(unexpected("the lease release script", &other)),
}
}
fn xread(&self, stream: &str, after: EntryId, count: usize, block: Option<Duration>) -> Result<Vec<Entry>> {
parse_read(&self.query(&self.commands().xread(stream, after, count, block), block)?)
}
fn expire(&self, key: &str, ttl: Duration) -> Result<bool> {
let reply = self.query(&self.commands().expire(key, ttl), None)?;
Ok(count(&reply)? > 0)
}
fn del(&self, keys: &[&str]) -> Result<u64> {
if keys.is_empty() {
return Ok(0);
}
count(&self.query(&self.commands().del(keys), None)?)
}
fn xadd_expire(&self, stream: &str, fields: &[(&[u8], &[u8])], ttl: Duration) -> Result<EntryId> {
let pipe = self.commands().xadd_expire(stream, fields, ttl);
let replies: Vec<Value> = self
.with_connection(None, |connection| pipe.query(connection))
.map_err(|error| redis_error(&error))?;
match replies.first() {
Some(id) => entry_id(id),
None => Err(Error::UnexpectedReply(
"XADD and EXPIRE answered with no replies".to_owned(),
)),
}
}
fn group_backlog(&self, stream: &str, group: &str) -> Result<Option<GroupBacklog>> {
let no_group = || Error::NoGroup {
stream: stream.to_owned(),
group: group.to_owned(),
};
let cmd = self.commands().xinfo_groups(stream);
let reply = self
.with_connection(None, |connection| cmd.query::<Value>(connection))
.map_err(|error| {
if is_no_such_key(&error) {
no_group()
} else {
redis_error(&error)
}
})?;
let backlog = parse_backlog(&reply, group)?.ok_or_else(no_group)?;
Ok(Some(with_estimate(backlog, || self.xlen(stream))))
}
}
fn with_estimate(backlog: GroupBacklog, xlen: impl FnOnce() -> Result<u64>) -> GroupBacklog {
if backlog.lag.is_some() {
return backlog;
}
match xlen() {
Ok(length) => backlog.with_length(length),
Err(_) => backlog,
}
}
struct Commands<'a> {
prefix: &'a str,
}
impl Commands<'_> {
fn key(&self, name: &str) -> String {
format!("{}{name}", self.prefix)
}
fn xadd(&self, stream: &str, fields: &[(&[u8], &[u8])]) -> Cmd {
let mut cmd = redis::cmd("XADD");
cmd.arg(self.key(stream)).arg("*");
for (name, value) in fields {
cmd.arg(*name).arg(*value);
}
cmd
}
fn xlen(&self, stream: &str) -> Cmd {
let mut cmd = redis::cmd("XLEN");
cmd.arg(self.key(stream));
cmd
}
fn xgroup_create(&self, stream: &str, group: &str) -> Cmd {
let mut cmd = redis::cmd("XGROUP");
cmd.arg("CREATE")
.arg(self.key(stream))
.arg(group)
.arg("0")
.arg("MKSTREAM");
cmd
}
fn xreadgroup(&self, stream: &str, group: &str, consumer: &str, count: usize, block: Option<Duration>) -> Cmd {
let mut cmd = redis::cmd("XREADGROUP");
cmd.arg("GROUP").arg(group).arg(consumer).arg("COUNT").arg(count);
if let Some(block) = block {
cmd.arg("BLOCK").arg(millis(block).max(1));
}
cmd.arg("STREAMS").arg(self.key(stream)).arg(">");
cmd
}
fn xautoclaim(
&self,
stream: &str,
group: &str,
consumer: &str,
min_idle: Duration,
start: EntryId,
count: usize,
) -> Cmd {
let mut cmd = redis::cmd("XAUTOCLAIM");
cmd.arg(self.key(stream))
.arg(group)
.arg(consumer)
.arg(millis(min_idle))
.arg(start.to_string());
cmd.arg("COUNT").arg(count.max(1));
cmd
}
fn xclaim_justid(&self, stream: &str, group: &str, consumer: &str, ids: &[EntryId], idle: Option<Duration>) -> Cmd {
let mut cmd = redis::cmd("XCLAIM");
cmd.arg(self.key(stream)).arg(group).arg(consumer).arg(0);
for id in ids {
cmd.arg(id.to_string());
}
if let Some(idle) = idle {
cmd.arg("IDLE").arg(millis(idle));
}
cmd.arg("JUSTID");
cmd
}
fn xpending_entry(&self, stream: &str, group: &str, id: EntryId) -> Cmd {
let id = id.to_string();
let mut cmd = redis::cmd("XPENDING");
cmd.arg(self.key(stream)).arg(group).arg(&id).arg(&id).arg(1);
cmd
}
fn xpending_consumer(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Cmd {
let mut cmd = redis::cmd("XPENDING");
cmd.arg(self.key(stream))
.arg(group)
.arg("-")
.arg("+")
.arg(count)
.arg(consumer);
cmd
}
fn xack(&self, stream: &str, group: &str, ids: &[EntryId]) -> Cmd {
let mut cmd = redis::cmd("XACK");
cmd.arg(self.key(stream)).arg(group);
for id in ids {
cmd.arg(id.to_string());
}
cmd
}
fn xdel(&self, stream: &str, ids: &[EntryId]) -> Cmd {
let mut cmd = redis::cmd("XDEL");
cmd.arg(self.key(stream));
for id in ids {
cmd.arg(id.to_string());
}
cmd
}
fn xack_xdel(&self, stream: &str, group: &str, ids: &[EntryId]) -> Pipeline {
let mut pipe = redis::pipe();
pipe.add_command(self.xack(stream, group, ids));
pipe.add_command(self.xdel(stream, ids));
pipe
}
fn xgroup_delconsumer(&self, stream: &str, group: &str, consumer: &str) -> Cmd {
let mut cmd = redis::cmd("XGROUP");
cmd.arg("DELCONSUMER").arg(self.key(stream)).arg(group).arg(consumer);
cmd
}
fn renew_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId) -> Cmd {
let mut cmd = redis::cmd("EVAL");
cmd.arg(RENEW_SCRIPT)
.arg(1)
.arg(self.key(stream))
.arg(group)
.arg(consumer)
.arg(id.to_string());
cmd
}
fn release_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId, idle: Duration) -> Cmd {
let mut cmd = redis::cmd("EVAL");
cmd.arg(RELEASE_SCRIPT)
.arg(1)
.arg(self.key(stream))
.arg(group)
.arg(consumer)
.arg(id.to_string())
.arg(millis(idle));
cmd
}
fn xread(&self, stream: &str, after: EntryId, count: usize, block: Option<Duration>) -> Cmd {
let mut cmd = redis::cmd("XREAD");
cmd.arg("COUNT").arg(count);
if let Some(block) = block {
cmd.arg("BLOCK").arg(millis(block).max(1));
}
cmd.arg("STREAMS").arg(self.key(stream)).arg(after.to_string());
cmd
}
fn expire(&self, key: &str, ttl: Duration) -> Cmd {
let mut cmd = redis::cmd("EXPIRE");
cmd.arg(self.key(key)).arg(expire_seconds(ttl));
cmd
}
fn del(&self, keys: &[&str]) -> Cmd {
let mut cmd = redis::cmd("DEL");
for key in keys {
cmd.arg(self.key(key));
}
cmd
}
fn xinfo_groups(&self, stream: &str) -> Cmd {
let mut cmd = redis::cmd("XINFO");
cmd.arg("GROUPS").arg(self.key(stream));
cmd
}
fn xadd_expire(&self, stream: &str, fields: &[(&[u8], &[u8])], ttl: Duration) -> Pipeline {
let mut pipe = redis::pipe();
pipe.add_command(self.xadd(stream, fields));
pipe.add_command(self.expire(stream, ttl));
pipe
}
}
fn is_nogroup(error: &RedisError) -> bool {
error.code() == Some("NOGROUP") || error.detail().is_some_and(|detail| detail.contains("NOGROUP"))
}
fn is_no_such_key(error: &RedisError) -> bool {
error.code() == Some("ERR") && error.detail().is_some_and(|detail| detail.contains("no such key"))
}
fn redis_error(error: &RedisError) -> Error {
Error::Redis(error.to_string())
}
fn millis(duration: Duration) -> u64 {
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}
fn unexpected(command: &str, value: &Value) -> Error {
let shape = match value {
Value::Nil => "nil",
Value::Int(_) => "an integer",
Value::BulkString(_) | Value::SimpleString(_) | Value::VerbatimString { .. } => "a string",
Value::Array(_) | Value::Set(_) => "an array",
Value::Map(_) => "a map",
_ => "another type",
};
Error::UnexpectedReply(format!(
"{command} answered with {shape} where the crate expects another shape"
))
}
fn array<'a>(command: &str, value: &'a Value) -> Result<&'a [Value]> {
match value {
Value::Array(items) | Value::Set(items) => Ok(items),
Value::Nil => Ok(&[]),
other => Err(unexpected(command, other)),
}
}
fn bytes(value: &Value) -> Option<&[u8]> {
match value {
Value::BulkString(bytes) => Some(bytes),
Value::SimpleString(text) => Some(text.as_bytes()),
Value::VerbatimString { text, .. } => Some(text.as_bytes()),
_ => None,
}
}
fn entry_id(value: &Value) -> Result<EntryId> {
let raw = bytes(value).ok_or_else(|| unexpected("an entry id", value))?;
std::str::from_utf8(raw)
.map_err(|_| Error::InvalidEntryId(String::from_utf8_lossy(raw).into_owned()))?
.parse()
}
fn count(value: &Value) -> Result<u64> {
match value {
Value::Int(n) => u64::try_from(*n).map_err(|_| unexpected("a count", value)),
other => bytes(other)
.and_then(|raw| std::str::from_utf8(raw).ok())
.and_then(|text| text.parse().ok())
.ok_or_else(|| unexpected("a count", other)),
}
}
fn parse_entry(value: &Value) -> Result<Option<Entry>> {
let pair = match value {
Value::Nil => return Ok(None),
Value::Array(pair) if pair.len() == 2 => pair,
other => return Err(unexpected("an entry", other)),
};
let id = entry_id(&pair[0])?;
let raw: Vec<&Value> = match &pair[1] {
Value::Nil => return Ok(None),
Value::Array(items) => items.iter().collect(),
Value::Map(pairs) => pairs.iter().flat_map(|(name, value)| [name, value]).collect(),
other => return Err(unexpected("an entry's fields", other)),
};
if !raw.len().is_multiple_of(2) {
return Err(Error::UnexpectedReply(format!(
"entry {id} has an odd number of field names and values"
)));
}
let mut fields: RawFields = Vec::with_capacity(raw.len() / 2);
for [name, value] in raw.as_chunks::<2>().0 {
let name = bytes(name).ok_or_else(|| unexpected("a field name", name))?;
let value = bytes(value).ok_or_else(|| unexpected("a field value", value))?;
fields.push((name.to_vec(), value.to_vec()));
}
Ok(Some(Entry::new(id, fields)))
}
fn parse_read(reply: &Value) -> Result<Vec<Entry>> {
let lists: Vec<&Value> = match reply {
Value::Nil => return Ok(Vec::new()),
Value::Array(pairs) => pairs
.iter()
.map(|pair| match pair {
Value::Array(pair) if pair.len() == 2 => Ok(&pair[1]),
other => Err(unexpected("XREADGROUP", other)),
})
.collect::<Result<_>>()?,
Value::Map(pairs) => pairs.iter().map(|(_, entries)| entries).collect(),
other => return Err(unexpected("XREADGROUP", other)),
};
let mut entries = Vec::new();
for list in lists {
for value in array("XREADGROUP", list)? {
if let Some(entry) = parse_entry(value)? {
entries.push(entry);
}
}
}
Ok(entries)
}
fn parse_pending(value: &Value) -> Result<Pending> {
let row = array("XPENDING", value)?;
let [id, consumer, idle, deliveries] = row else {
return Err(unexpected("XPENDING", value));
};
let consumer = bytes(consumer).ok_or_else(|| unexpected("XPENDING", consumer))?;
Ok(Pending {
id: entry_id(id)?,
consumer: String::from_utf8_lossy(consumer).into_owned(),
idle: Duration::from_millis(count(idle)?),
deliveries: count(deliveries)?,
})
}
fn info_row(value: &Value) -> Result<Vec<(&Value, &Value)>> {
match value {
Value::Map(pairs) => Ok(pairs.iter().map(|(name, value)| (name, value)).collect()),
Value::Array(items) if items.len().is_multiple_of(2) => Ok(items
.as_chunks::<2>()
.0
.iter()
.map(|[name, value]| (name, value))
.collect()),
other => Err(unexpected("XINFO GROUPS", other)),
}
}
fn info_field<'a>(row: &[(&'a Value, &'a Value)], name: &str) -> Option<&'a Value> {
row.iter()
.find(|(field, _)| bytes(field) == Some(name.as_bytes()))
.map(|(_, value)| *value)
}
fn parse_backlog(reply: &Value, group: &str) -> Result<Option<GroupBacklog>> {
for value in array("XINFO GROUPS", reply)? {
let row = info_row(value)?;
if info_field(&row, "name").and_then(bytes) != Some(group.as_bytes()) {
continue;
}
let pending = info_field(&row, "pending").ok_or_else(|| unexpected("XINFO GROUPS", value))?;
let lag = match info_field(&row, "lag") {
None | Some(Value::Nil) => None,
Some(lag) => Some(count(lag)?),
};
return Ok(Some(GroupBacklog::new(count(pending)?, lag)));
}
Ok(None)
}
#[cfg(test)]
mod tests {
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use redis::{Arg, Cmd, Value};
use super::{Commands, RedisStreams, is_no_such_key, is_nogroup, parse_backlog, parse_read, with_estimate};
use crate::entry::{EntryId, GroupBacklog, Waiting};
use crate::error::Error;
use crate::streams::Streams;
fn args(cmd: &Cmd) -> Vec<String> {
cmd.args_iter()
.map(|arg| match arg {
Arg::Simple(bytes) => String::from_utf8_lossy(bytes).into_owned(),
_ => "<not a plain argument>".to_owned(),
})
.collect()
}
#[test]
fn the_prefix_goes_on_every_key_and_nothing_else() {
let on = Commands { prefix: "app_" };
let id = EntryId::new(5, 1);
let ms = Some(Duration::from_millis(100));
let fields: [(&[u8], &[u8]); 1] = [(b"reply_to", b"results:app:hash")];
let cases: Vec<(Cmd, &[usize])> = vec![
(on.xadd("s", &fields), &[1]),
(on.xlen("s"), &[1]),
(on.xgroup_create("s", "g"), &[2]),
(on.xreadgroup("s", "g", "c", 2, ms), &[9]),
(on.xautoclaim("s", "g", "c", Duration::from_secs(1), id, 3), &[1]),
(on.xclaim_justid("s", "g", "c", &[id], ms), &[1]),
(on.xpending_entry("s", "g", id), &[1]),
(on.xpending_consumer("s", "g", "c", 1), &[1]),
(on.xack("s", "g", &[id]), &[1]),
(on.xdel("s", &[id]), &[1]),
(on.xgroup_delconsumer("s", "g", "c"), &[2]),
(on.renew_lease("s", "g", "c", id), &[3]),
(on.release_lease("s", "g", "c", id, Duration::from_secs(2)), &[3]),
(on.xread("s", id, 1, ms), &[6]),
(on.expire("s", Duration::from_secs(60)), &[1]),
(on.del(&["s", "t"]), &[1, 2]),
(on.xinfo_groups("s"), &[2]),
];
let off = Commands { prefix: "" };
let unprefixed: Vec<Cmd> = vec![
off.xadd("s", &fields),
off.xlen("s"),
off.xgroup_create("s", "g"),
off.xreadgroup("s", "g", "c", 2, ms),
off.xautoclaim("s", "g", "c", Duration::from_secs(1), id, 3),
off.xclaim_justid("s", "g", "c", &[id], ms),
off.xpending_entry("s", "g", id),
off.xpending_consumer("s", "g", "c", 1),
off.xack("s", "g", &[id]),
off.xdel("s", &[id]),
off.xgroup_delconsumer("s", "g", "c"),
off.renew_lease("s", "g", "c", id),
off.release_lease("s", "g", "c", id, Duration::from_secs(2)),
off.xread("s", id, 1, ms),
off.expire("s", Duration::from_secs(60)),
off.del(&["s", "t"]),
off.xinfo_groups("s"),
];
assert_eq!(cases.len(), unprefixed.len());
for ((cmd, keys), plain) in cases.iter().zip(&unprefixed) {
let (prefixed, plain) = (args(cmd), args(plain));
assert_eq!(prefixed.len(), plain.len(), "{plain:?}");
for (n, (with, without)) in prefixed.iter().zip(&plain).enumerate() {
if keys.contains(&n) {
assert_eq!(with, &format!("app_{without}"), "{plain:?}, argument {n}");
assert!(matches!(without.as_str(), "s" | "t"), "{plain:?}, argument {n}");
} else {
assert_eq!(with, without, "{plain:?}, argument {n}: not a key");
}
}
}
assert_eq!(args(&cases[0].0)[4], "results:app:hash");
for pipe in [
on.xack_xdel("s", "g", &[id]),
on.xadd_expire("s", &fields, Duration::from_secs(60)),
] {
for cmd in pipe.cmd_iter() {
assert_eq!(args(cmd)[1], "app_s", "{:?}", args(cmd));
}
}
}
#[test]
fn nogroup_is_read_from_the_code_or_from_inside_a_scripts_message() {
let error = |reply: &[u8]| {
redis::parse_redis_value(reply)
.expect("a reply")
.extract_error()
.expect_err("an error reply")
};
let plain = error(b"-NOGROUP No such key 's' or consumer group 'g' in XPENDING command\r\n");
assert_eq!(plain.code(), Some("NOGROUP"));
assert!(is_nogroup(&plain));
let wrapped = error(
b"-ERR Error running script (call to f_0123): @user_script:1: NOGROUP No such key 's' or consumer \
group 'g' in XPENDING command\r\n",
);
assert_eq!(wrapped.code(), Some("ERR"));
assert!(is_nogroup(&wrapped));
let other = error(b"-ERR Error running script (call to f_0123): @user_script:1: WRONGTYPE wrong kind\r\n");
assert!(!is_nogroup(&other));
assert!(!is_nogroup(&error(
b"-BUSYGROUP Consumer Group name already exists\r\n"
)));
}
fn text(text: &str) -> Value {
Value::BulkString(text.as_bytes().to_vec())
}
fn entries(count: u64) -> Value {
Value::Array(
(1..=count)
.map(|n| {
Value::Array(vec![
text(&format!("{n}-0")),
Value::Array(vec![text("k"), text(&n.to_string())]),
])
})
.collect(),
)
}
fn ids(reply: &Value) -> Vec<EntryId> {
parse_read(reply)
.expect("a readable reply")
.iter()
.map(|entry| entry.id)
.collect()
}
#[test]
fn a_resp2_reply_of_any_batch_size_is_read() {
for count in [1, 2, 3] {
let reply = Value::Array(vec![Value::Array(vec![text("tasks"), entries(count)])]);
assert_eq!(
ids(&reply),
(1..=count).map(|n| EntryId::new(n, 0)).collect::<Vec<_>>(),
"{count}"
);
}
}
#[test]
fn a_resp3_reply_of_any_batch_size_is_read() {
for count in [1, 2, 3] {
let reply = Value::Map(vec![(text("tasks"), entries(count))]);
assert_eq!(
ids(&reply),
(1..=count).map(|n| EntryId::new(n, 0)).collect::<Vec<_>>(),
"{count}"
);
}
}
#[test]
fn an_empty_reply_is_no_entries_and_a_malformed_one_an_error() {
assert!(ids(&Value::Nil).is_empty());
assert!(
parse_read(&Value::Array(vec![entries(3)])).is_err(),
"a RESP2 reply needs its stream name"
);
assert!(parse_read(&Value::Int(1)).is_err());
}
fn flat_row(pairs: &[(&str, Value)]) -> Value {
Value::Array(
pairs
.iter()
.flat_map(|(name, value)| [text(name), value.clone()])
.collect(),
)
}
fn map_row(pairs: &[(&str, Value)]) -> Value {
Value::Map(pairs.iter().map(|(name, value)| (text(name), value.clone())).collect())
}
#[test]
fn a_group_backlog_is_read_by_field_name_from_either_shape() {
let other = [
("name", text("other")),
("consumers", Value::Int(0)),
("pending", Value::Int(9)),
];
let ours = [
("lag", Value::Int(1_203)),
("entries-read", Value::Int(7)),
("last-delivered-id", text("5-0")),
("pending", Value::Int(64)),
("consumers", Value::Int(2)),
("name", text("g")),
];
for row in [flat_row, map_row] {
let reply = Value::Array(vec![row(&other), row(&ours)]);
assert_eq!(
parse_backlog(&reply, "g").expect("a readable reply"),
Some(GroupBacklog::new(64, Some(1_203)))
);
assert_eq!(parse_backlog(&reply, "missing").expect("a readable reply"), None);
}
let nil_lag = [("name", text("g")), ("pending", Value::Int(2)), ("lag", Value::Nil)];
let no_lag = [("name", text("g")), ("pending", text("2"))];
for row in [
flat_row(&nil_lag),
map_row(&nil_lag),
flat_row(&no_lag),
map_row(&no_lag),
] {
assert_eq!(
parse_backlog(&Value::Array(vec![row]), "g").expect("a readable reply"),
Some(GroupBacklog::new(2, None))
);
}
assert_eq!(parse_backlog(&Value::Array(Vec::new()), "g").expect("no groups"), None);
}
#[test]
fn a_malformed_group_backlog_is_an_error() {
let odd = Value::Array(vec![Value::Array(vec![text("name"), text("g"), text("pending")])]);
assert!(parse_backlog(&odd, "g").is_err());
let no_pending = Value::Array(vec![flat_row(&[("name", text("g"))])]);
assert!(parse_backlog(&no_pending, "g").is_err());
let negative = Value::Array(vec![flat_row(&[("name", text("g")), ("pending", Value::Int(-1))])]);
assert!(parse_backlog(&negative, "g").is_err());
assert!(parse_backlog(&Value::Int(1), "g").is_err());
}
#[test]
fn waiting_is_the_lag_when_given_and_an_estimate_from_the_length_otherwise() {
let mut asked = false;
let exact = with_estimate(GroupBacklog::new(64, Some(1_203)), || {
asked = true;
Ok(10_000)
});
assert!(!asked, "no XLEN when the server gives a lag");
assert_eq!(exact, GroupBacklog::new(64, Some(1_203)));
assert_eq!(exact.waiting(), Some(Waiting::Exact(1_203)));
let drained = with_estimate(GroupBacklog::new(0, Some(0)), || Ok(1));
assert_eq!(drained.waiting(), Some(Waiting::Exact(0)));
let estimate = with_estimate(GroupBacklog::new(64, None), || Ok(10_950));
assert_eq!(estimate, GroupBacklog::new(64, None).with_length(10_950));
assert_eq!(estimate.waiting(), Some(Waiting::Estimate(10_886)));
let clamped = with_estimate(GroupBacklog::new(64, None), || Ok(9));
assert_eq!(clamped.waiting(), Some(Waiting::Estimate(0)));
let refused = with_estimate(GroupBacklog::new(64, None), || {
Err(Error::Redis(
"NOPERM no permissions to run the 'xlen' command".to_owned(),
))
});
assert_eq!(refused, GroupBacklog::new(64, None));
assert_eq!(refused.waiting(), None);
}
struct FakeServer {
url: String,
seen: Arc<Mutex<Vec<Vec<String>>>>,
}
impl FakeServer {
fn start(xinfo: &'static [u8], xlen: &'static [u8]) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").expect("a local port");
let url = format!("redis://{}", listener.local_addr().expect("an address"));
let seen = Arc::new(Mutex::new(Vec::new()));
let record = Arc::clone(&seen);
thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { return };
let record = Arc::clone(&record);
thread::spawn(move || serve(stream, &record, xinfo, xlen));
}
});
Self { url, seen }
}
fn seen(&self) -> Vec<Vec<String>> {
let seen = self.seen.lock().expect("not poisoned");
seen.iter().filter(|cmd| cmd[0] != "CLIENT").cloned().collect()
}
}
fn serve(stream: TcpStream, seen: &Mutex<Vec<Vec<String>>>, xinfo: &[u8], xlen: &[u8]) {
let mut writer = stream.try_clone().expect("a second handle");
let mut reader = BufReader::new(stream);
let mut line = String::new();
let mut read_line = |reader: &mut BufReader<TcpStream>| {
line.clear();
match reader.read_line(&mut line) {
Ok(0) | Err(_) => None,
Ok(_) => Some(line.trim_end().to_owned()),
}
};
while let Some(header) = read_line(&mut reader) {
let count: usize = header.trim_start_matches('*').parse().expect("an array of arguments");
let mut args = Vec::new();
for _ in 0..count {
let length = read_line(&mut reader).expect("a length");
let length: usize = length.trim_start_matches('$').parse().expect("a bulk length");
let mut arg = vec![0; length + 2];
reader.read_exact(&mut arg).expect("the argument");
args.push(String::from_utf8_lossy(&arg[..length]).into_owned());
}
let reply: &[u8] = match args[0].to_ascii_uppercase().as_str() {
"XINFO" => xinfo,
"XLEN" => xlen,
_ => b"+OK\r\n",
};
seen.lock().expect("not poisoned").push(args);
if writer.write_all(reply).is_err() {
return;
}
}
}
const XINFO_LAG: &[u8] = b"*1\r\n*6\r\n$4\r\nname\r\n$1\r\ng\r\n$7\r\npending\r\n:64\r\n$3\r\nlag\r\n:1203\r\n";
const XINFO_NIL_LAG: &[u8] = b"*1\r\n*6\r\n$4\r\nname\r\n$1\r\ng\r\n$7\r\npending\r\n:64\r\n$3\r\nlag\r\n$-1\r\n";
const XINFO_NO_LAG: &[u8] = b"*1\r\n*4\r\n$4\r\nname\r\n$1\r\ng\r\n$7\r\npending\r\n:64\r\n";
fn backlog(server: &FakeServer) -> crate::Result<Option<GroupBacklog>> {
let streams = RedisStreams::open(&server.url)?
.timeout(Duration::from_secs(5))
.with_key_prefix("app_");
streams.group_backlog("tasks", "g")
}
#[test]
fn a_backlog_with_a_lag_sends_no_xlen() {
let server = FakeServer::start(XINFO_LAG, b":10950\r\n");
let backlog = backlog(&server).expect("a backlog").expect("the group");
assert_eq!(backlog, GroupBacklog::new(64, Some(1_203)));
assert_eq!(backlog.waiting(), Some(Waiting::Exact(1_203)));
assert_eq!(server.seen(), vec![vec!["XINFO", "GROUPS", "app_tasks"]]);
}
#[test]
fn a_backlog_with_a_nil_or_missing_lag_reads_the_length_of_the_prefixed_stream() {
for xinfo in [XINFO_NIL_LAG, XINFO_NO_LAG] {
let server = FakeServer::start(xinfo, b":10950\r\n");
let backlog = backlog(&server).expect("a backlog").expect("the group");
assert_eq!(backlog, GroupBacklog::new(64, None).with_length(10_950));
assert_eq!(backlog.waiting(), Some(Waiting::Estimate(10_886)));
assert_eq!(
server.seen(),
vec![vec!["XINFO", "GROUPS", "app_tasks"], vec!["XLEN", "app_tasks"]]
);
}
let server = FakeServer::start(XINFO_NIL_LAG, b":9\r\n");
let backlog = backlog(&server).expect("a backlog").expect("the group");
assert_eq!(backlog.waiting(), Some(Waiting::Estimate(0)));
}
#[test]
fn a_refused_xlen_leaves_a_readable_backlog_without_a_length() {
let refusals: [&[u8]; 2] = [
b"-NOPERM User app has no permissions to run the 'xlen' command\r\n",
b"+not a count\r\n",
];
for refusal in refusals {
let server = FakeServer::start(XINFO_NIL_LAG, refusal);
let backlog = backlog(&server).expect("a backlog").expect("the group");
assert_eq!(backlog, GroupBacklog::new(64, None));
assert_eq!(backlog.waiting(), None);
assert_eq!(server.seen().len(), 2, "XLEN was sent and failed");
}
}
#[test]
fn xinfo_on_a_missing_key_is_told_apart_from_other_errors() {
let error = |reply: &[u8]| {
redis::parse_redis_value(reply)
.expect("a reply")
.extract_error()
.expect_err("an error reply")
};
assert!(is_no_such_key(&error(b"-ERR no such key\r\n")));
assert!(!is_no_such_key(&error(
b"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
)));
assert!(!is_no_such_key(&error(b"-ERR unknown command 'XINFO'\r\n")));
}
}