use super::GroupRuntime;
use crate::error::{NasaRedisError, Result};
pub(super) fn bytes(value: redis::Value) -> Result<Vec<u8>> {
match value {
redis::Value::BulkString(v) => Ok(v),
redis::Value::SimpleString(v) => Ok(v.into_bytes()),
_ => Err(NasaRedisError::Parsing(
"partition RESP text expected".into(),
)),
}
}
pub(super) fn array(value: redis::Value) -> Result<Vec<redis::Value>> {
match value {
redis::Value::Array(values) => Ok(values),
_ => Err(NasaRedisError::Parsing(
"partition RESP array expected".into(),
)),
}
}
pub(super) fn id(value: redis::Value) -> Result<String> {
let id = String::from_utf8(bytes(value)?)
.map_err(|_| NasaRedisError::Parsing("non UTF-8 stream id".into()))?;
if !id.split_once('-').is_some_and(|(a, b)| {
!a.is_empty()
&& !b.is_empty()
&& a.bytes().all(|byte| byte.is_ascii_digit())
&& b.bytes().all(|byte| byte.is_ascii_digit())
&& a.parse::<u64>().is_ok()
&& b.parse::<u64>().is_ok()
}) {
return Err(NasaRedisError::Parsing("invalid stream id".into()));
}
Ok(id)
}
pub(super) fn entries(value: redis::Value) -> Result<Vec<(String, Option<Vec<u8>>)>> {
let mut result = Vec::new();
for entry in array(value)? {
let mut pair = array(entry)?;
if pair.len() != 2 {
return Err(NasaRedisError::Parsing("invalid stream entry".into()));
}
let fields = pair.pop().expect("fields");
let id = id(pair.pop().expect("id"))?;
if matches!(fields, redis::Value::Nil) {
result.push((id, None));
continue;
}
let pairs = match fields {
redis::Value::Map(pairs) => pairs,
other => {
let fields = array(other)?;
if fields.len() % 2 != 0 {
return Err(NasaRedisError::Parsing("odd stream fields".into()));
}
let mut it = fields.into_iter();
let mut pairs = Vec::new();
while let (Some(a), Some(b)) = (it.next(), it.next()) {
pairs.push((a, b));
}
pairs
}
};
let mut data = None;
for (key, value) in pairs {
if bytes(key)? == crate::partition::DATA_FIELD.as_bytes() {
data = Some(bytes(value)?);
}
}
result.push((id, Some(data.unwrap_or_default())));
}
Ok(result)
}
pub(super) fn read(value: redis::Value, stream: &str) -> Result<Vec<(String, Option<Vec<u8>>)>> {
if matches!(value, redis::Value::Nil) {
return Ok(Vec::new());
}
let pairs = match value {
redis::Value::Map(pairs) => pairs,
other => {
let mut pairs = Vec::new();
for item in array(other)? {
let mut pair = array(item)?;
if pair.len() != 2 {
return Err(NasaRedisError::Parsing("invalid stream response".into()));
}
let values = pair.pop().expect("values");
pairs.push((pair.pop().expect("key"), values));
}
pairs
}
};
if pairs.len() > 1 {
return Err(NasaRedisError::Parsing("unexpected stream count".into()));
}
let mut result = Vec::new();
for (key, value) in pairs {
if bytes(key)? != stream.as_bytes() {
return Err(NasaRedisError::Parsing(
"unexpected stream coordinate".into(),
));
}
result.extend(entries(value)?);
}
Ok(result)
}
pub(super) struct Pending {
pub id: String,
pub consumer: String,
pub deliveries: u64,
}
pub(super) fn pending(value: redis::Value) -> Result<Vec<Pending>> {
let mut result = Vec::new();
for item in array(value)? {
let fields = array(item)?;
if fields.len() != 4 {
return Err(NasaRedisError::Parsing("invalid XPENDING row".into()));
}
let mut it = fields.into_iter();
let id = id(it.next().expect("id"))?;
let consumer = String::from_utf8(bytes(it.next().expect("consumer"))?)
.map_err(|_| NasaRedisError::Parsing("invalid consumer".into()))?;
if !matches!(it.next(), Some(redis::Value::Int(idle)) if idle >= 0) {
return Err(NasaRedisError::Parsing("invalid pending idle time".into()));
}
let deliveries = match it.next() {
Some(redis::Value::Int(n)) if n >= 0 => n as u64,
_ => return Err(NasaRedisError::Parsing("invalid delivery count".into())),
};
result.push(Pending {
id,
consumer,
deliveries,
});
}
Ok(result)
}
pub(super) async fn exact_pending(
rt: &GroupRuntime,
partition: u32,
entry: &str,
) -> Result<Option<Pending>> {
let value = redis::cmd("XPENDING")
.arg(rt.layout.stream(partition))
.arg(rt.layout.group())
.arg(entry)
.arg(entry)
.arg(1)
.query_async(&mut rt.client.conn())
.await?;
let mut rows = pending(value)?;
if rows.len() > 1 || rows.first().is_some_and(|row| row.id != entry) {
return Err(NasaRedisError::Parsing(
"XPENDING coordinate mismatch".into(),
));
}
Ok(rows.pop())
}
pub(super) async fn exact_body(
rt: &GroupRuntime,
partition: u32,
entry: &str,
) -> Result<Option<Vec<u8>>> {
let value = redis::cmd("XRANGE")
.arg(rt.layout.stream(partition))
.arg(entry)
.arg(entry)
.arg("COUNT")
.arg(1)
.query_async(&mut rt.client.conn())
.await?;
let mut rows = entries(value)?;
if rows.len() > 1 || rows.first().is_some_and(|(id, _)| id != entry) {
return Err(NasaRedisError::Parsing("XRANGE coordinate mismatch".into()));
}
match rows.pop() {
None => Ok(None),
Some((_, Some(body))) => Ok(Some(body)),
Some((_, None)) => Err(NasaRedisError::Parsing(
"XRANGE entry has no field collection".into(),
)),
}
}