use crate::commands::blocking::{self, ParkOutcome};
use crate::commands::ctx::Ctx;
use crate::commands::helpers::{lazy_expire_on_read, parse_utf8};
use crate::commands::stream_extra::{
self, Approx, IdmpArg, ReadCaps, TrimRefs, TrimTo, claim_effect, setid_effect, trim_stream,
trim_stream_approx,
};
use crate::keyspace_events::{KS_STREAM, notify};
use crate::replication::script_feed::{effect, effect_of_metadata, effects_begin};
use crate::resp::write::*;
use crate::store;
use crate::store::ValueRef;
use crate::types::{ConsumerGroup, KiviDBValue, PelEntry, StreamEntry, StreamId, StreamInner};
use crate::{read_lock, write_lock};
use ahash::AHashMap;
use parking_lot::RwLock;
use std::collections::BTreeMap;
use std::ops::Bound;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
#[inline]
fn reply_resp(ctx: &Ctx) -> u8 {
crate::commands::handler::effective_resp_for_reply(ctx)
}
#[inline]
fn stream_result_items(resp: u8, key: &[u8], entries: Vec<Vec<u8>>) -> Vec<Vec<u8>> {
if resp >= 3 {
vec![resp_bulk(key), resp_array(entries)]
} else {
vec![resp_array(vec![resp_bulk(key), resp_array(entries)])]
}
}
#[inline]
fn stream_results_reply(resp: u8, items: Vec<Vec<u8>>) -> Vec<u8> {
if resp >= 3 {
resp_map(items)
} else {
resp_array(items)
}
}
fn announce(ctx: &Ctx, name: &str, reply: &[u8]) {
if crate::keyspace_events::KS_FLAGS.load(std::sync::atomic::Ordering::Relaxed) == 0 {
return;
}
let ok = reply.starts_with(b"+OK");
let some = reply.first() == Some(&b':') && !reply.starts_with(b":0\r\n");
let sub = |word: &[u8]| {
ctx.cmd
.get(1)
.is_some_and(|sub| sub.eq_ignore_ascii_case(word))
};
let (event, key_at) = match name {
"XADD" if reply.first() == Some(&b'$') && !reply.starts_with(b"$-1") => ("xadd", 1),
"XDEL" | "XDELEX" | "XACKDEL" if some => ("xdel", 1),
"XTRIM" if some => ("xtrim", 1),
"XSETID" if ok => ("xsetid", 1),
"XGROUP" if sub(b"CREATE") && ok => ("xgroup-create", 2),
"XGROUP" if sub(b"SETID") && ok => ("xgroup-setid", 2),
"XGROUP" if sub(b"DESTROY") && some => ("xgroup-destroy", 2),
"XGROUP" if sub(b"CREATECONSUMER") && some => ("xgroup-createconsumer", 2),
_ => return,
};
if let Some(key) = ctx.cmd.get(key_at).copied() {
notify(ctx.pubsub, *ctx.selected_db, KS_STREAM, event, key);
}
}
pub fn handle(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
let reply = run(ctx, name)?;
announce(ctx, name, &reply);
Some(reply)
}
fn run(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
match name {
"XADD" => Some(xadd(ctx)),
"XLEN" => Some(xlen(ctx)),
"XRANGE" => Some(xrange(ctx)),
"XREVRANGE" => Some(xrevrange(ctx)),
"XREAD" => Some(xread(ctx)),
"XDEL" => Some(xdel(ctx)),
"XTRIM" => Some(xtrim(ctx)),
"XSETID" => Some(xsetid(ctx)),
"XIDMPRECORD" => Some(xidmprecord(ctx)),
"XGROUP" => Some(xgroup(ctx)),
"XREADGROUP" => Some(xreadgroup(ctx)),
"XACK" => Some(xack(ctx)),
"XNACK" => Some(xnack(ctx)),
"XPENDING" => Some(xpending(ctx)),
"XCLAIM" => Some(xclaim(ctx)),
"XAUTOCLAIM" => Some(xautoclaim(ctx)),
"XINFO" => Some(xinfo(ctx)),
"XACKDEL" => Some(xackdel(ctx)),
"XDELEX" => Some(xdelex(ctx)),
"XCFGSET" => Some(xcfgset(ctx)),
_ => None,
}
}
fn xidmprecord(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() != 5 {
return resp_error("ERR wrong number of arguments for 'xidmprecord' command");
}
let Some(id) = parse_utf8(cmd[4]).and_then(StreamId::parse) else {
return resp_error("ERR Invalid stream ID specified as stream command argument");
};
if cmd[2].is_empty() {
return resp_error("ERR producer ID must be non-empty");
}
if cmd[3].is_empty() {
return resp_error("ERR idempotent ID must be non-empty");
}
let key: &[u8] = cmd[1];
let (producer, iid) = (cmd[2], cmd[3]);
let defaults = stream_extra::idmp_defaults(ctx.config);
let shard = store::get_shard(&ctx.store[*ctx.selected_db], key);
let stream = match read_lock!(shard).get(key) {
Some(ValueRef::Stream(s)) => Arc::clone(s),
Some(_) => {
return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
}
None => return resp_error("ERR no such key"),
};
let mut inner = stream.write();
if !inner.entries.contains_key(&id) {
return resp_error("ERR No such message in stream");
}
let recorded = inner
.idmp
.producers
.get(producer)
.and_then(|p| p.by_iid.get(iid))
.cloned();
match recorded {
Some(same) if same == id => return resp_simple("OK"),
Some(_) => {
return resp_error(
"ERR IID already exists for this producer with a different stream ID",
);
}
None => {}
}
stream_extra::idmp_record(&mut inner, producer, Arc::from(iid), id, now_ms(), defaults);
resp_simple("OK")
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
fn get_or_create_stream(ctx: &mut Ctx, key: &[u8]) -> Result<Arc<RwLock<StreamInner>>, Vec<u8>> {
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let mut map = write_lock!(shard);
match map.get(key) {
Some(ValueRef::Stream(s)) => Ok(Arc::clone(s)),
Some(_) => Err(resp_error(
"WRONGTYPE Operation against a key holding the wrong kind of value",
)),
None => {
let s = Arc::new(RwLock::new(StreamInner::new()));
map.insert(key, KiviDBValue::Stream(Arc::clone(&s)));
Ok(s)
}
}
}
fn parse_range_id_lo(s: &str) -> Option<StreamId> {
match s {
"-" => Some(StreamId::min()),
"+" => Some(StreamId::max()),
s => StreamId::parse(s).or_else(|| {
s.parse::<u64>().ok().map(|ms| StreamId::new(ms, 0))
}),
}
}
fn parse_range_id_hi(s: &str) -> Option<StreamId> {
match s {
"+" => Some(StreamId::max()),
"-" => Some(StreamId::min()),
s => {
if s.contains('-') {
StreamId::parse(s)
} else {
s.parse::<u64>().ok().map(|ms| StreamId::new(ms, u64::MAX))
}
}
}
}
fn id_after(id: &StreamId) -> Option<StreamId> {
match (id.ms, id.seq) {
(u64::MAX, u64::MAX) => None,
(ms, u64::MAX) => Some(StreamId::new(ms + 1, 0)),
(ms, seq) => Some(StreamId::new(ms, seq + 1)),
}
}
fn id_preceding(id: &StreamId) -> Option<StreamId> {
match (id.ms, id.seq) {
(0, 0) => None,
(ms, 0) => Some(StreamId::new(ms - 1, u64::MAX)),
(ms, seq) => Some(StreamId::new(ms, seq - 1)),
}
}
fn id_interval(start: &str, end: &str) -> Result<Option<(StreamId, StreamId)>, Vec<u8>> {
let invalid = || resp_error("ERR Invalid stream ID specified as stream command argument");
let named = |s: &str| !matches!(s, "-" | "+");
let lo = match start.strip_prefix('(') {
Some(id) => parse_range_id_lo(id)
.filter(|_| named(id))
.ok_or_else(invalid)
.and_then(|id| {
id_after(&id).ok_or_else(|| resp_error("ERR invalid start ID for the interval"))
})?,
None => parse_range_id_lo(start).ok_or_else(invalid)?,
};
let hi = match end.strip_prefix('(') {
Some(id) => parse_range_id_hi(id)
.filter(|_| named(id))
.ok_or_else(invalid)
.and_then(|id| {
id_preceding(&id).ok_or_else(|| resp_error("ERR invalid end ID for the interval"))
})?,
None => parse_range_id_hi(end).ok_or_else(invalid)?,
};
Ok((lo <= hi).then_some((lo, hi)))
}
fn format_entry(id: &StreamId, entry: &StreamEntry) -> Vec<u8> {
let field_values: Vec<Vec<u8>> = entry
.fields
.iter()
.flat_map(|(f, v)| vec![resp_bulk(f.as_ref()), resp_bulk(v.as_ref())])
.collect();
resp_array(vec![
resp_bulk_str(&id.to_string()),
resp_array(field_values),
])
}
pub(crate) struct XaddOptions<'a> {
pub idmp_twice: bool,
pub id_index: usize,
pub nomkstream: bool,
pub maxlen: Option<u64>,
pub minid: Option<StreamId>,
pub trim_refs: TrimRefs,
pub idmp: Option<IdmpArg<'a>>,
pub approx: bool,
pub limit: Option<i64>,
}
pub(crate) fn parse_xadd_options<'a>(cmd: &[&'a [u8]]) -> XaddOptions<'a> {
let mut i = 2usize;
let mut nomkstream = false;
let mut maxlen: Option<u64> = None;
let mut minid: Option<StreamId> = None;
let mut trim_refs = TrimRefs::default();
let mut idmp: Option<IdmpArg<'a>> = None;
let mut idmp_twice = false;
let mut approx = false;
let mut limit: Option<i64> = None;
while i < cmd.len() {
let tok = std::str::from_utf8(cmd[i])
.unwrap_or("")
.to_ascii_uppercase();
match tok.as_str() {
"NOMKSTREAM" => {
nomkstream = true;
i += 1;
}
"KEEPREF" | "DELREF" | "ACKED" => {
trim_refs = TrimRefs::parse(cmd[i]).unwrap_or_default();
i += 1;
}
"IDMP" if i + 2 < cmd.len() => {
if idmp.is_some() {
idmp_twice = true;
}
idmp = Some(IdmpArg::Explicit {
producer: cmd[i + 1],
iid: cmd[i + 2],
});
i += 3;
}
"IDMPAUTO" if i + 1 < cmd.len() => {
if idmp.is_some() {
idmp_twice = true;
}
idmp = Some(IdmpArg::Auto {
producer: cmd[i + 1],
});
i += 2;
}
"MAXLEN" => {
i += 1;
if let Some(b) = cmd.get(i)
&& (*b == b"~" || *b == b"=")
{
approx = *b == b"~";
i += 1;
}
maxlen = cmd
.get(i)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok());
i += 1;
}
"MINID" => {
i += 1;
if let Some(b) = cmd.get(i)
&& (*b == b"~" || *b == b"=")
{
approx = *b == b"~";
i += 1;
}
minid = cmd
.get(i)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(StreamId::parse);
i += 1;
}
"LIMIT" => {
limit = Some(
cmd.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(-1),
);
i += 2;
}
_ => break,
}
}
XaddOptions {
id_index: i,
idmp_twice,
nomkstream,
maxlen,
minid,
trim_refs,
idmp,
approx,
limit,
}
}
fn approx_of(approx: bool, limit: Option<i64>) -> Result<Option<Approx>, Vec<u8>> {
match limit {
Some(_) if !approx => Err(resp_error(
"ERR syntax error, LIMIT cannot be used without the special ~ option",
)),
Some(n) if n < 0 => Err(resp_error("ERR The LIMIT argument must be >= 0.")),
Some(n) => Ok(Some(Approx::new(Some(n as u64)))),
None => Ok(approx.then(|| Approx::new(None))),
}
}
enum NewId {
Auto,
AutoSeq(u64),
Explicit(StreamId),
}
pub fn xadd(ctx: &mut Ctx) -> Vec<u8> {
let (key, id_str, id_index, fields, nomkstream, maxlen, minid, trim_refs, idmp, approx) = {
let cmd = &ctx.cmd;
if cmd.len() < 5 {
return resp_error("ERR wrong number of arguments for 'xadd' command");
}
let key: Vec<u8> = cmd[1].to_vec();
let XaddOptions {
id_index,
idmp_twice,
nomkstream,
maxlen,
minid,
trim_refs,
idmp,
approx,
limit,
} = parse_xadd_options(cmd);
let approx = match approx_of(approx, limit) {
Ok(approx) => approx,
Err(e) => return e,
};
let mut i = id_index;
if idmp_twice {
return resp_error("ERR syntax error, IDMP/IDMPAUTO specified multiple times");
}
match &idmp {
Some(IdmpArg::Explicit { producer, .. } | IdmpArg::Auto { producer })
if producer.is_empty() =>
{
let which = if matches!(idmp, Some(IdmpArg::Auto { .. })) {
"IDMPAUTO"
} else {
"IDMP"
};
return resp_error(&format!("ERR {which} requires a non-empty producer ID"));
}
Some(IdmpArg::Explicit { iid: [], .. }) => {
return resp_error("ERR IDMP requires a non-empty idempotent ID");
}
_ => {}
}
let id_str = match cmd.get(i).and_then(|b| std::str::from_utf8(b).ok()) {
Some(s) => s.to_string(),
None => return resp_error("ERR syntax error: missing ID"),
};
i += 1;
let id_ok = id_str == "*"
|| StreamId::parse(&id_str).is_some()
|| id_str
.strip_suffix("-*")
.is_some_and(|ms| ms.parse::<u64>().is_ok());
if !id_ok {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
if (cmd.len() - i) < 2 || !(cmd.len() - i).is_multiple_of(2) {
return resp_error("ERR wrong number of arguments: field-value pairs required");
}
type FieldsType = Vec<(Arc<[u8]>, Arc<[u8]>)>;
let fields: FieldsType = cmd[i..]
.as_chunks::<2>()
.0
.iter()
.map(|chunk| (Arc::from(chunk[0]), Arc::from(chunk[1])))
.collect();
let idmp: Option<(Vec<u8>, Arc<[u8]>)> =
idmp.map(|arg| (arg.producer().to_vec(), arg.iid(&fields)));
(
key, id_str, id_index, fields, nomkstream, maxlen, minid, trim_refs, idmp, approx,
)
};
if idmp.is_some() {
if id_str != "*" && !ctx.apply_replication && !ctx.bypass_cluster_check {
return resp_error("ERR IDMP/IDMPAUTO can be used only with auto-generated IDs");
}
}
let recorded = idmp.is_some() || approx.is_some();
if recorded {
effects_begin();
}
let new_id = if id_str == "*" {
NewId::Auto
} else if let Some(ms) = id_str.strip_suffix("-*") {
match ms.parse() {
Ok(ms) => NewId::AutoSeq(ms),
Err(_) => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
} else {
match StreamId::parse(&id_str) {
Some(id) if id == StreamId::min() => {
return resp_error("ERR The ID specified in XADD must be greater than 0-0");
}
Some(id) => NewId::Explicit(id),
None => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
};
if nomkstream {
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, &key);
let map = read_lock!(shard);
if !map.contains_key(key.as_slice()) {
return resp_null_bulk();
}
}
let stream = match get_or_create_stream(ctx, &key) {
Ok(s) => s,
Err(e) => return e,
};
let mut inner = stream.write();
let now = now_ms();
let idmp_defaults = stream_extra::idmp_defaults(ctx.config);
if let Some((producer, iid)) = &idmp
&& !ctx.apply_replication
&& !ctx.bypass_cluster_check
&& let Some(existing) =
stream_extra::idmp_lookup(&mut inner, producer, iid, now, idmp_defaults)
{
return resp_bulk_str(&existing.to_string());
}
let smaller = || {
resp_error(
"ERR The ID specified in XADD is equal or smaller than the target stream top item",
)
};
let last = inner.last_id.clone();
let entry_id = match new_id {
NewId::Auto if now > last.ms => StreamId::new(now, 0),
NewId::Auto => match id_after(&last) {
Some(id) => id,
None => {
return resp_error(
"ERR The stream has exhausted the last possible ID, unable to add more items",
);
}
},
NewId::AutoSeq(ms) if ms > last.ms => StreamId::new(ms, 0),
NewId::AutoSeq(ms) if ms == last.ms && last.seq < u64::MAX => {
StreamId::new(ms, last.seq + 1)
}
NewId::AutoSeq(_) => return smaller(),
NewId::Explicit(id) => id,
};
if entry_id <= inner.last_id && inner.last_id != StreamId::min() {
return resp_error(
"ERR The ID specified in XADD is equal or smaller than the target stream top item",
);
}
let id_str_out = entry_id.to_string();
stream_extra::record_append(&mut inner, &fields);
inner
.entries
.insert(entry_id.clone(), StreamEntry { fields });
inner.last_id = entry_id.clone();
inner.entries_added += 1;
if let Some((producer, iid)) = idmp {
stream_extra::idmp_record(&mut inner, &producer, iid, entry_id, now, idmp_defaults);
}
let mut trim = |to: TrimTo| match approx {
Some(approx) => trim_stream_approx(&mut inner, &to, trim_refs, approx),
None => trim_stream(&mut inner, &to, trim_refs),
};
if let Some(max) = maxlen {
trim(TrimTo::MaxLen(max));
}
if let Some(min) = minid {
trim(TrimTo::MinId(min));
}
if recorded {
let mut parts: Vec<Vec<u8>> = ctx.cmd.iter().map(|b| b.to_vec()).collect();
parts[id_index] = id_str_out.clone().into_bytes();
if approx.is_some() {
stream_extra::exact_trim_args(&mut parts, 2, id_index, &inner, trim_refs);
}
effect(parts);
}
if let Some(max) = inner.max_entries {
trim_stream(&mut inner, &TrimTo::MaxLen(max), TrimRefs::KeepRef);
}
drop(inner);
notify_xread_waiters(ctx, &key);
resp_bulk_str(&id_str_out)
}
pub fn xlen(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() != 2 {
return resp_error("ERR wrong number of arguments for 'xlen' command");
}
let key: &[u8] = cmd[1];
let gone = lazy_expire_on_read(ctx.store, *ctx.selected_db, key);
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key).filter(|_| !gone) {
None => resp_integer(0),
Some(ValueRef::Stream(s)) => resp_integer(s.read().entries.len() as i64),
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xrange(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'xrange' command");
}
let key: &[u8] = cmd[1];
let start_str = std::str::from_utf8(cmd[2]).unwrap_or("-");
let end_str = std::str::from_utf8(cmd[3]).unwrap_or("+");
let mut count = usize::MAX;
let mut i = 4;
while i < cmd.len() {
if std::str::from_utf8(cmd[i])
.unwrap_or("")
.eq_ignore_ascii_case("COUNT")
{
count = cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok())
.unwrap_or(usize::MAX);
i += 2;
} else {
i += 1;
}
}
let (lo, hi, count) = match id_interval(start_str, end_str) {
Ok(Some((lo, hi))) => (lo, hi, count),
Ok(None) => (StreamId::min(), StreamId::min(), 0),
Err(e) => return e,
};
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_array(vec![]),
Some(ValueRef::Stream(s)) => {
let inner = s.read();
let items: Vec<Vec<u8>> = inner
.entries
.range(lo..=hi)
.take(count)
.map(|(id, entry)| format_entry(id, entry))
.collect();
resp_array(items)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xrevrange(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'xrevrange' command");
}
let key: &[u8] = cmd[1];
let end_str = std::str::from_utf8(cmd[2]).unwrap_or("+");
let start_str = std::str::from_utf8(cmd[3]).unwrap_or("-");
let mut count = usize::MAX;
let mut i = 4;
while i < cmd.len() {
if std::str::from_utf8(cmd[i])
.unwrap_or("")
.eq_ignore_ascii_case("COUNT")
{
count = cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok())
.unwrap_or(usize::MAX);
i += 2;
} else {
i += 1;
}
}
let (lo, hi, count) = match id_interval(start_str, end_str) {
Ok(Some((lo, hi))) => (lo, hi, count),
Ok(None) => (StreamId::min(), StreamId::min(), 0),
Err(e) => return e,
};
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_array(vec![]),
Some(ValueRef::Stream(s)) => {
let inner = s.read();
let items: Vec<Vec<u8>> = inner
.entries
.range(lo..=hi)
.rev()
.take(count)
.map(|(id, entry)| format_entry(id, entry))
.collect();
resp_array(items)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
fn id_before(id: &StreamId) -> StreamId {
if id.seq > 0 {
StreamId::new(id.ms, id.seq - 1)
} else {
StreamId::new(id.ms.saturating_sub(1), u64::MAX)
}
}
fn read_streams(
ctx: &Ctx,
resp: u8,
keys: &[&[u8]],
after: &[StreamId],
count: usize,
caps: ReadCaps,
) -> Vec<Vec<u8>> {
let mut budget = caps.budget();
let mut results = Vec::new();
for (key, after_id) in keys.iter().zip(after) {
if budget.exhausted() {
break;
}
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
let Some(ValueRef::Stream(stream)) = map.get(key) else {
continue;
};
let inner = stream.read();
let mut entries: Vec<Vec<u8>> = Vec::new();
let newer = (Bound::Excluded(after_id.clone()), Bound::Unbounded);
for (id, entry) in inner.entries.range(newer).take(count) {
let item = format_entry(id, entry);
if !budget.admit(item.len()) {
break;
}
entries.push(item);
}
if !entries.is_empty() {
results.extend(stream_result_items(resp, key, entries));
}
}
results
}
pub fn xread(ctx: &mut Ctx) -> Vec<u8> {
let resp = reply_resp(ctx);
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'xread' command");
}
let mut count: Option<usize> = None;
let mut caps = ReadCaps::default();
let mut block_ms: Option<u64> = None;
let mut i = 1usize;
while i < cmd.len() {
let tok = std::str::from_utf8(cmd[i])
.unwrap_or("")
.to_ascii_uppercase();
match tok.as_str() {
"COUNT" => {
count = cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok());
i += 2;
}
"MAXCOUNT" => {
match ReadCaps::parse_positive("MAXCOUNT", cmd.get(i + 1)) {
Ok(n) => caps.max_count = Some(n),
Err(e) => return resp_error(&e),
}
i += 2;
}
"MAXSIZE" => {
match ReadCaps::parse_positive("MAXSIZE", cmd.get(i + 1)) {
Ok(n) => caps.max_size = Some(n),
Err(e) => return resp_error(&e),
}
i += 2;
}
"BLOCK" => {
block_ms = cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok());
i += 2;
}
"CLAIM" if i + 1 < cmd.len() => {
return resp_error(
"ERR The CLAIM option is only supported by XREADGROUP. You called XREAD instead.",
);
}
"STREAMS" => {
i += 1;
break;
}
_ => {
i += 1;
}
}
}
if let Err(e) = caps.check_against_count(count) {
return resp_error(&e);
}
let count = count.unwrap_or(usize::MAX);
let remaining = cmd.len().saturating_sub(i);
if remaining < 2 || !remaining.is_multiple_of(2) {
return resp_error(
"ERR Unbalanced 'xread' list of streams: for each stream key an ID, '+', or '$' must be specified.",
);
}
let half = remaining / 2;
let keys: Vec<&[u8]> = cmd[i..i + half].to_vec();
let ids: Vec<&str> = cmd[i + half..]
.iter()
.map(|b| std::str::from_utf8(b).unwrap_or(""))
.collect();
let resumed = blocking::take_resume(ctx);
let (carried_ids, carried_deadline) = match blocking::take_state(ctx) {
Some(blocking::BlockState::StreamIds { ids, deadline, .. }) => (Some(ids), Some(deadline)),
_ => (None, None),
};
let timed_out = matches!(resumed, Some(None));
let resolved_ids: Vec<StreamId> = match carried_ids {
Some(ids) => ids,
None => keys
.iter()
.zip(ids.iter())
.map(|(key, id_str)| {
if *id_str == "$" || *id_str == "+" {
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
let Some(ValueRef::Stream(s)) = map.get(key) else {
return StreamId::min();
};
let inner = s.read();
if *id_str == "$" {
inner.last_id.clone()
} else {
match inner.entries.keys().next_back() {
Some(last) => id_before(last),
None => inner.last_id.clone(),
}
}
} else {
StreamId::parse(id_str).unwrap_or(StreamId::min())
}
})
.collect(),
};
let results = read_streams(ctx, resp, &keys, &resolved_ids, count, caps);
if results.is_empty() {
if timed_out {
return resp_null_array();
}
if let Some(ms) = block_ms {
let deadline = carried_deadline.unwrap_or_else(|| {
blocking::timeout_from_ms(ms).map(|timeout| std::time::Instant::now() + timeout)
});
let Some(remaining) = blocking::remaining_time(deadline) else {
return resp_null_array();
};
let mut registered = ctx.wait_table.stream_wait();
let rxs: Vec<(
Vec<u8>,
tokio::sync::oneshot::Receiver<crate::wait_table::Value>,
)> = keys
.iter()
.map(|k| (k.to_vec(), registered.register(k)))
.collect();
let immediate = read_streams(ctx, resp, &keys, &resolved_ids, count, caps);
if !immediate.is_empty() {
return stream_results_reply(resp, immediate);
}
return match blocking::park_with_state(
ctx,
rxs,
remaining,
Some(blocking::BlockState::StreamIds {
ids: resolved_ids,
deadline,
registered,
}),
) {
ParkOutcome::Parked => Vec::new(),
ParkOutcome::CannotWait => resp_null_array(),
};
}
return resp_null_array();
}
stream_results_reply(resp, results)
}
pub fn xdel(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'xdel' command");
}
let key: &[u8] = cmd[1];
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_integer(0),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
let mut removed = 0i64;
for id_bytes in &cmd[2..] {
let id_str = std::str::from_utf8(id_bytes).unwrap_or("");
if let Some(id) = StreamId::parse(id_str)
&& inner.entries.remove(&id).is_some()
{
removed += 1;
if id > inner.max_deleted_id {
inner.max_deleted_id = id;
}
}
}
resp_integer(removed)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xtrim(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'xtrim' command");
}
let key: &[u8] = cmd[1];
let mut i = 3usize;
let mut approx = false;
if let Some(b) = cmd.get(i)
&& (*b == b"=" || *b == b"~")
{
approx = *b == b"~";
i += 1;
}
let threshold_str = match cmd.get(i).and_then(|b| std::str::from_utf8(b).ok()) {
Some(s) => s,
None => return resp_error("ERR syntax error"),
};
let to = if cmd[2].eq_ignore_ascii_case(b"MAXLEN") {
match threshold_str.parse::<u64>() {
Ok(max) => TrimTo::MaxLen(max),
Err(_) => return resp_error("ERR value is not an integer or out of range"),
}
} else if cmd[2].eq_ignore_ascii_case(b"MINID") {
match StreamId::parse(threshold_str) {
Some(min) => TrimTo::MinId(min),
None => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
} else {
return resp_error("ERR syntax error");
};
i += 1;
let mut refs = TrimRefs::default();
let mut limit: Option<i64> = None;
while i < cmd.len() {
if cmd[i].eq_ignore_ascii_case(b"LIMIT") && i + 1 < cmd.len() {
limit = Some(
parse_utf8(cmd[i + 1])
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(-1),
);
i += 2;
} else if let Some(mode) = TrimRefs::parse(cmd[i]) {
refs = mode;
i += 1;
} else {
return resp_error("ERR syntax error");
}
}
let approx = match approx_of(approx, limit) {
Ok(approx) => approx,
Err(e) => return e,
};
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_integer(0),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
let removed = match approx {
None => trim_stream(&mut inner, &to, refs),
Some(approx) => {
effects_begin();
let removed = trim_stream_approx(&mut inner, &to, refs, approx);
if removed > 0 {
let mut parts: Vec<Vec<u8>> = cmd.iter().map(|b| b.to_vec()).collect();
let end = parts.len();
stream_extra::exact_trim_args(&mut parts, 2, end, &inner, refs);
effect(parts);
}
removed
}
};
resp_integer(removed as i64)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xsetid(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'xsetid' command");
}
let key: Vec<u8> = cmd[1].to_vec();
let id_str = std::str::from_utf8(cmd[2]).unwrap_or("");
let new_last_id = match StreamId::parse(id_str) {
Some(id) => id,
None => return resp_error("ERR Invalid stream ID specified as stream command argument"),
};
let mut entries_added: Option<u64> = None;
let mut max_deleted_id: Option<StreamId> = None;
let mut i = 3usize;
while i < cmd.len() {
let Some(value) = cmd.get(i + 1) else {
return resp_error("ERR syntax error");
};
if cmd[i].eq_ignore_ascii_case(b"ENTRIESADDED") {
entries_added = match parse_utf8(value).and_then(|s| s.parse::<i64>().ok()) {
Some(n) if n >= 0 => Some(n as u64),
Some(_) => return resp_error("ERR entries_added must be positive"),
None => return resp_error("ERR value is not an integer or out of range"),
};
} else if cmd[i].eq_ignore_ascii_case(b"MAXDELETEDID") {
max_deleted_id = match parse_utf8(value).and_then(StreamId::parse) {
Some(id) if new_last_id < id => {
return resp_error(
"ERR The ID specified in XSETID is smaller than the provided max_deleted_entry_id",
);
}
Some(id) => Some(id),
None => {
return resp_error(
"ERR Invalid stream ID specified as stream command argument",
);
}
};
} else {
return resp_error("ERR syntax error");
}
i += 2;
}
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, &key);
let map = read_lock!(shard);
let stream = match map.get(key.as_slice()) {
Some(ValueRef::Stream(s)) => s,
Some(_) => {
return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
}
None => return resp_error("ERR no such key"),
};
let mut inner = stream.write();
if new_last_id < inner.max_deleted_id {
return resp_error(
"ERR The ID specified in XSETID is smaller than current max_deleted_entry_id",
);
}
if let Some(top) = inner.entries.keys().next_back() {
if new_last_id < *top {
return resp_error(
"ERR The ID specified in XSETID is smaller than the target stream top item",
);
}
if entries_added.is_some_and(|n| n < inner.entries.len() as u64) {
return resp_error(
"ERR The entries_added specified in XSETID is smaller than the target stream length",
);
}
}
inner.last_id = new_last_id;
if let Some(n) = entries_added {
inner.entries_added = n;
}
if let Some(id) = max_deleted_id.filter(|id| *id != StreamId::min()) {
inner.max_deleted_id = id;
}
resp_simple("OK")
}
fn capped_entries_read(n: u64, added: u64) -> u64 {
if n != ConsumerGroup::NO_COUNT && n > added {
added
} else {
n
}
}
fn entries_read_arg(raw: &[u8]) -> Result<u64, Vec<u8>> {
match parse_utf8(raw).and_then(|s| s.parse::<i64>().ok()) {
Some(-1) => Ok(ConsumerGroup::NO_COUNT),
Some(n) if n >= 0 => Ok(n as u64),
Some(_) => Err(resp_error(
"ERR value for ENTRIESREAD must be positive or -1",
)),
None => Err(resp_error("ERR value is not an integer or out of range")),
}
}
const XGROUP_NO_KEY: &str = "ERR The XGROUP subcommand requires the key to exist. \
Note that for CREATE you may want to use the MKSTREAM option to create an \
empty stream automatically.";
fn help_reply(command: &str, lines: &[&str]) -> Vec<u8> {
let mut out = vec![resp_simple(&format!(
"{command} <subcommand> [<arg> [value] [opt] ...]. Subcommands are:"
))];
out.extend(lines.iter().map(|line| resp_simple(line)));
out.push(resp_simple("HELP"));
out.push(resp_simple(" Print this help."));
resp_array(out)
}
fn unknown_subcommand(command: &str, sub: &[u8]) -> Vec<u8> {
resp_error(&format!(
"ERR unknown subcommand '{}'. Try {command} HELP.",
String::from_utf8_lossy(sub)
))
}
pub fn xgroup_create(ctx: &mut Ctx) -> Vec<u8> {
let (key, group, id_str, mkstream, entries_read) = {
let cmd = &ctx.cmd;
if cmd.len() < 5 {
return resp_error("ERR wrong number of arguments for 'xgroup|create' command");
}
let key: Vec<u8> = cmd[2].to_vec();
let group = crate::types::StreamName::from(cmd[3]);
let id_str = std::str::from_utf8(cmd[4]).unwrap_or_default().to_string();
let mut mkstream = false;
let mut entries_read = ConsumerGroup::NO_COUNT;
let mut at = 5;
while at < cmd.len() {
if cmd[at].eq_ignore_ascii_case(b"MKSTREAM") {
mkstream = true;
at += 1;
} else if cmd[at].eq_ignore_ascii_case(b"ENTRIESREAD") && at + 1 < cmd.len() {
match entries_read_arg(cmd[at + 1]) {
Ok(n) => entries_read = n,
Err(e) => return e,
}
at += 2;
} else {
return resp_error(&format!(
"ERR unknown subcommand or wrong number of arguments for '{}'. Try XGROUP HELP.",
String::from_utf8_lossy(cmd[1])
));
}
}
(key, group, id_str, mkstream, entries_read)
};
{
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, &key);
let map = read_lock!(shard);
if !map.contains_key(key.as_slice()) && !mkstream {
return resp_error(XGROUP_NO_KEY);
}
}
let given_id = if id_str == "$" {
None
} else {
match parse_range_id_lo(&id_str) {
Some(id) => Some(id),
None => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
};
let stream = match get_or_create_stream(ctx, &key) {
Ok(s) => s,
Err(e) => return e,
};
let mut inner = stream.write();
if inner.groups.contains_key(&group) {
return resp_error("BUSYGROUP Consumer Group name already exists");
}
let last_id = given_id.unwrap_or_else(|| inner.last_id.clone());
let entries_read = capped_entries_read(entries_read, inner.entries_added);
inner.groups.insert(
group.clone(),
ConsumerGroup {
name: group,
last_id,
entries_read,
pel: BTreeMap::new(),
consumers: AHashMap::new(),
active: AHashMap::new(),
},
);
resp_simple("OK")
}
pub fn xgroup_destroy(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() != 4 {
return resp_error("ERR wrong number of arguments for 'xgroup|destroy' command");
}
let key: &[u8] = cmd[2];
let group: &[u8] = cmd[3];
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error(XGROUP_NO_KEY),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
resp_integer(inner.groups.remove(group).is_some() as i64)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xgroup_setid(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() != 5 && cmd.len() != 7 {
return resp_error("ERR wrong number of arguments for 'xgroup|setid' command");
}
let key: &[u8] = cmd[2];
let group = crate::types::StreamName::from(cmd[3]);
let id_str = std::str::from_utf8(cmd[4]).unwrap_or("$");
let entries_read: Option<u64> = if cmd.len() == 7 {
if !cmd[5].eq_ignore_ascii_case(b"ENTRIESREAD") {
return resp_error("ERR syntax error");
}
match entries_read_arg(cmd[6]) {
Ok(n) => Some(n),
Err(e) => return e,
}
} else {
None
};
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error(XGROUP_NO_KEY),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
let added = inner.entries_added;
let new_id = if id_str == "$" {
inner.last_id.clone()
} else {
match parse_range_id_lo(id_str) {
Some(id) => id,
None => {
return resp_error(
"ERR Invalid stream ID specified as stream command argument",
);
}
}
};
match inner.groups.get_mut(&group) {
None => resp_error_bytes(
&[
&b"NOGROUP No such consumer group '"[..],
c_str(group.as_bytes()),
&b"' for key name '"[..],
c_str(key),
&b"'"[..],
]
.concat(),
),
Some(g) => {
g.last_id = new_id;
g.entries_read =
capped_entries_read(entries_read.unwrap_or(ConsumerGroup::NO_COUNT), added);
resp_simple("OK")
}
}
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xgroup_createconsumer(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() != 5 {
return resp_error("ERR wrong number of arguments for 'xgroup|createconsumer' command");
}
let key: &[u8] = cmd[2];
let group = crate::types::StreamName::from(cmd[3]);
let consumer = crate::types::StreamName::from(cmd[4]);
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error(XGROUP_NO_KEY),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
match inner.groups.get_mut(&group) {
None => resp_error_bytes(
&[
&b"NOGROUP No such consumer group '"[..],
c_str(group.as_bytes()),
&b"' for key name '"[..],
c_str(key),
&b"'"[..],
]
.concat(),
),
Some(g) => {
if g.consumers.contains_key(&consumer) {
resp_integer(0) } else {
g.seen(&consumer, now_ms(), false);
resp_integer(1)
}
}
}
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xgroup_delconsumer(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() != 5 {
return resp_error("ERR wrong number of arguments for 'xgroup|delconsumer' command");
}
let key: &[u8] = cmd[2];
let group = crate::types::StreamName::from(cmd[3]);
let consumer = crate::types::StreamName::from(cmd[4]);
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error(XGROUP_NO_KEY),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
match inner.groups.get_mut(&group) {
None => resp_error_bytes(
&[
&b"NOGROUP No such consumer group '"[..],
c_str(group.as_bytes()),
&b"' for key name '"[..],
c_str(key),
&b"'"[..],
]
.concat(),
),
Some(g) => {
if g.consumers.remove(&consumer).is_some() {
notify(
ctx.pubsub,
*ctx.selected_db,
KS_STREAM,
"xgroup-delconsumer",
key,
);
}
g.active.remove(&consumer);
let pending: i64 =
g.pel.values().filter(|p| p.consumer == consumer).count() as i64;
g.pel.retain(|_, p| p.consumer != consumer);
resp_integer(pending)
}
}
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
struct GroupRead<'a> {
group: &'a [u8],
consumer: &'a [u8],
count: usize,
noack: bool,
claim_min_idle: Option<u64>,
caps: ReadCaps,
}
fn format_claimed_entry(
id: &StreamId,
entry: &StreamEntry,
idle_ms: u64,
deliveries: u64,
) -> Vec<u8> {
let field_values: Vec<Vec<u8>> = entry
.fields
.iter()
.flat_map(|(f, v)| vec![resp_bulk(f.as_ref()), resp_bulk(v.as_ref())])
.collect();
resp_array(vec![
resp_bulk_str(&id.to_string()),
resp_array(field_values),
resp_integer(idle_ms.min(i64::MAX as u64) as i64),
resp_integer(deliveries.min(i64::MAX as u64) as i64),
])
}
fn c_str(bytes: &[u8]) -> &[u8] {
&bytes[..memchr::memchr(0, bytes).unwrap_or(bytes.len())]
}
fn nogroup_error(key: &[u8], group: &[u8]) -> Vec<u8> {
resp_error_bytes(
&[
&b"NOGROUP No such key '"[..],
c_str(key),
&b"' or consumer group '"[..],
c_str(group),
&b"' in XREADGROUP with GROUP option"[..],
]
.concat(),
)
}
pub fn xreadgroup(ctx: &mut Ctx) -> Vec<u8> {
let resp = reply_resp(ctx);
let cmd = ctx.cmd.clone();
if cmd.len() < 7 {
return resp_error("ERR wrong number of arguments for 'xreadgroup' command");
}
if !std::str::from_utf8(cmd[1])
.unwrap_or("")
.eq_ignore_ascii_case("GROUP")
{
return resp_error("ERR syntax error");
}
let group = crate::types::StreamName::from(cmd[2]);
let consumer = crate::types::StreamName::from(cmd[3]);
let mut count: Option<usize> = None;
let mut caps = ReadCaps::default();
let mut noack = false;
let mut claim_min_idle: Option<u64> = None;
let mut i = 4usize;
let mut block_ms: Option<u64> = None;
let mut saw_streams = false;
while i < cmd.len() {
let tok = std::str::from_utf8(cmd[i])
.unwrap_or("")
.to_ascii_uppercase();
let has_arg = i + 1 < cmd.len();
match tok.as_str() {
"COUNT" if has_arg => {
count = match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
Some(n) if n > 0 => Some(n as usize),
Some(_) => None,
None => return resp_error("ERR value is not an integer or out of range"),
};
i += 2;
}
"MAXCOUNT" => {
match ReadCaps::parse_positive("MAXCOUNT", cmd.get(i + 1)) {
Ok(n) => caps.max_count = Some(n),
Err(e) => return resp_error(&e),
}
i += 2;
}
"MAXSIZE" => {
match ReadCaps::parse_positive("MAXSIZE", cmd.get(i + 1)) {
Ok(n) => caps.max_size = Some(n),
Err(e) => return resp_error(&e),
}
i += 2;
}
"BLOCK" if has_arg => {
block_ms = match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
Some(ms) if ms < 0 => return resp_error("ERR timeout is negative"),
Some(ms) => Some(ms as u64),
None => return resp_error("ERR timeout is not an integer or out of range"),
};
i += 2;
}
"CLAIM" => {
claim_min_idle = match cmd.get(i + 1).and_then(|b| stream_extra::strict_integer(b))
{
Some(ms) if ms < 0 => {
return resp_error("ERR min-idle-time must be a positive integer");
}
Some(ms) => Some(ms as u64),
None => {
return resp_error("ERR min-idle-time is not an integer or out of range");
}
};
i += 2;
}
"NOACK" => {
noack = true;
i += 1;
}
"STREAMS" => {
i += 1;
saw_streams = true;
break;
}
_ => return resp_error("ERR syntax error"),
}
}
if !saw_streams {
return resp_error("ERR syntax error");
}
if let Err(e) = caps.check_against_count(count) {
return resp_error(&e);
}
let remaining = cmd.len().saturating_sub(i);
if remaining < 2 || !remaining.is_multiple_of(2) {
return resp_error(
"ERR Unbalanced 'xreadgroup' list of streams: for each stream key an ID or '>' must be specified.",
);
}
for id in &cmd[i + remaining / 2..] {
if *id == b">" {
continue;
}
if *id == b"$" {
return resp_error("ERR The $ ID is meaningless in the context of XREADGROUP");
}
if parse_utf8(id).and_then(StreamId::parse).is_none() {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
let half = remaining / 2;
let keys: Vec<Vec<u8>> = cmd[i..i + half].iter().map(|b| b.to_vec()).collect();
let ids: Vec<&str> = cmd[i + half..]
.iter()
.map(|b| std::str::from_utf8(b).unwrap_or(""))
.collect();
let spec = GroupRead {
group: &group,
consumer: &consumer,
count: count.unwrap_or(usize::MAX),
noack,
claim_min_idle,
caps,
};
let gone = blocking::client_gone(ctx);
let resumed = blocking::take_resume(ctx);
let timed_out = matches!(resumed, Some(None));
let (carried_deadline, ticket) = match blocking::take_state(ctx) {
Some(blocking::BlockState::GroupRead { deadline, ticket }) => (Some(deadline), ticket),
_ => (None, ctx.wait_table.new_ticket()),
};
let done = |ctx: &Ctx, reply: Vec<u8>| {
if resumed.is_some() {
for key in &keys {
ctx.wait_table.reader_done(key, &ticket);
}
}
reply
};
if gone {
return done(ctx, resp_null_array());
}
let results = match run_xreadgroup_delivery(ctx, &keys, &ids, &spec) {
Ok(results) => results,
Err(e) => return done(ctx, e),
};
if !results.is_empty() {
return done(ctx, stream_results_reply(resp, results));
}
let claim_min_idle = spec.claim_min_idle;
let waiting_on = match (resumed.is_some(), carried_deadline) {
(true, Some(deadline)) if claim_min_idle.is_some() || !timed_out => Some(deadline),
(true, _) => None,
(false, _) => block_ms.map(|ms| {
blocking::timeout_from_ms(ms).map(|timeout| std::time::Instant::now() + timeout)
}),
};
let Some((deadline, remaining)) = waiting_on
.and_then(|deadline| blocking::remaining_time(deadline).map(|left| (deadline, left)))
else {
return done(ctx, resp_null_array());
};
let rxs: Vec<(
Vec<u8>,
tokio::sync::oneshot::Receiver<crate::wait_table::Value>,
)> = keys
.iter()
.map(|k| (k.clone(), ctx.wait_table.enqueue_reader(k, &ticket)))
.collect();
let leave = |ctx: &Ctx| {
for key in &keys {
ctx.wait_table.reader_done(key, &ticket);
}
};
let second_check = match run_xreadgroup_delivery(ctx, &keys, &ids, &spec) {
Ok(results) => results,
Err(e) => {
drop(rxs);
leave(ctx);
return e;
}
};
if !second_check.is_empty() {
drop(rxs);
leave(ctx);
return stream_results_reply(resp, second_check);
}
if resumed.is_some() {
for key in &keys {
ctx.wait_table.reader_pass_on(key, &ticket);
}
}
let wait = match claim_min_idle {
Some(min_idle) => {
let claimable = next_claimable_in(ctx, &keys, spec.group, min_idle);
match (remaining, claimable) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
None => remaining,
};
let state = blocking::BlockState::GroupRead {
deadline,
ticket: Arc::clone(&ticket),
};
match blocking::park_with_state(ctx, rxs, wait, Some(state)) {
ParkOutcome::Parked => {
ticket.parks_in(&keys, true);
Vec::new()
}
ParkOutcome::CannotWait => {
leave(ctx);
resp_null_array()
}
}
}
fn next_claimable_in(
ctx: &Ctx,
keys: &[Vec<u8>],
group: &[u8],
min_idle: u64,
) -> Option<std::time::Duration> {
let now = now_ms();
let mut soonest: Option<u64> = None;
for key in keys {
let shard = store::get_shard(&ctx.store[*ctx.selected_db], key.as_slice());
let map = read_lock!(shard);
let Some(ValueRef::Stream(stream)) = map.get(key.as_slice()) else {
continue;
};
let inner = stream.read();
let Some(g) = inner.groups.get(group) else {
continue;
};
for pending in g.pel.values() {
let at = pending.delivered_at.saturating_add(min_idle);
soonest = Some(soonest.map_or(at, |s| s.min(at)));
}
}
soonest.map(|at| std::time::Duration::from_millis(at.saturating_sub(now).max(1)))
}
fn run_xreadgroup_delivery(
ctx: &mut Ctx,
keys: &[Vec<u8>],
ids: &[&str],
spec: &GroupRead,
) -> Result<Vec<Vec<u8>>, Vec<u8>> {
let resp = reply_resp(ctx);
let now = now_ms();
effects_begin();
let mut streams = Vec::with_capacity(keys.len());
for key in keys {
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key.as_slice());
let map = read_lock!(shard);
match map.get(key.as_slice()) {
Some(ValueRef::Stream(s)) => {
if !s.read().groups.contains_key(spec.group) {
return Err(nogroup_error(key, spec.group));
}
streams.push(Arc::clone(s));
}
Some(_) => {
return Err(resp_error(
"WRONGTYPE Operation against a key holding the wrong kind of value",
));
}
None => return Err(nogroup_error(key, spec.group)),
}
}
let mut budget = spec.caps.budget();
let mut results: Vec<Vec<u8>> = Vec::new();
for ((key, id_str), stream) in keys.iter().zip(ids.iter()).zip(streams) {
let mut guard = stream.write();
let shape = stream_extra::Shape::of(&guard);
let StreamInner {
entries, groups, ..
} = &mut *guard;
let Some(g) = groups.get_mut(spec.group) else {
continue;
};
let is_new = !g.consumers.contains_key(spec.consumer);
g.seen(spec.consumer, now, false);
if is_new {
notify(
ctx.pubsub,
*ctx.selected_db,
KS_STREAM,
"xgroup-createconsumer",
key,
);
effect(vec![
b"XGROUP".to_vec(),
b"CREATECONSUMER".to_vec(),
key.to_vec(),
spec.group.to_vec(),
spec.consumer.to_vec(),
]);
}
let mut items: Vec<Vec<u8>> = Vec::new();
let history = *id_str != ">";
if !history {
if let Some(min_idle) = spec.claim_min_idle {
let mut candidates: Vec<(u64, StreamId)> = g
.pel
.iter()
.filter(|(_, p)| now.saturating_sub(p.delivered_at) >= min_idle)
.map(|(id, p)| (p.delivered_at, id.clone()))
.collect();
candidates.sort();
for (_, id) in candidates {
if items.len() >= spec.count || budget.exhausted() {
break;
}
let Some(entry) = entries.get(&id) else {
continue;
};
let Some(pending) = g.pel.get_mut(&id) else {
continue;
};
let idle = if pending.delivered_at < stream_extra::NACKED_BELOW {
0
} else {
now.saturating_sub(pending.delivered_at)
};
let item = format_claimed_entry(&id, entry, idle, pending.delivery_count);
if !budget.admit(item.len()) {
break;
}
pending.consumer = crate::types::StreamName::from(spec.consumer);
pending.delivered_at = now;
pending.delivery_count = pending.delivery_count.saturating_add(1);
effect(claim_effect(
key,
spec.group,
spec.consumer,
&id,
now,
pending.delivery_count,
));
items.push(item);
}
}
let newer = (Bound::Excluded(g.last_id.clone()), Bound::Unbounded);
let mut delivered = 0u64;
for (id, entry) in entries.range(newer) {
if items.len() >= spec.count || budget.exhausted() {
break;
}
let item = if spec.claim_min_idle.is_some() {
format_claimed_entry(id, entry, 0, 0)
} else {
format_entry(id, entry)
};
if !budget.admit(item.len()) {
break;
}
if !spec.noack {
g.pel.insert(
id.clone(),
PelEntry {
consumer: crate::types::StreamName::from(spec.consumer),
delivered_at: now,
delivery_count: 1,
},
);
effect(claim_effect(key, spec.group, spec.consumer, id, now, 1));
}
shape.deliver(g, id);
delivered += 1;
items.push(item);
}
if delivered > 0 {
effect(setid_effect(key, spec.group, &g.last_id, g.entries_read));
}
} else {
let from = StreamId::parse(id_str).unwrap_or(StreamId::min());
let after = if from == StreamId::min() {
Bound::Unbounded
} else {
Bound::Excluded(from)
};
let pending_ids: Vec<StreamId> = g
.pel
.range((after, Bound::Unbounded))
.filter(|(_, p)| p.consumer == spec.consumer)
.take(spec.count)
.map(|(id, _)| id.clone())
.collect();
for id in pending_ids {
if budget.exhausted() {
break;
}
let item = match entries.get(&id) {
Some(entry) => format_entry(&id, entry),
None => resp_array(vec![resp_bulk_str(&id.to_string()), resp_null_for(resp)]),
};
if !budget.admit(item.len()) {
break;
}
if let Some(pending) = g.pel.get_mut(&id) {
pending.delivered_at = now;
pending.delivery_count = pending.delivery_count.saturating_add(1);
effect_of_metadata(claim_effect(
key,
spec.group,
spec.consumer,
&id,
now,
pending.delivery_count,
));
}
items.push(item);
}
}
if !items.is_empty() {
g.seen(spec.consumer, now, true);
}
if history || !items.is_empty() {
results.extend(stream_result_items(resp, key, items));
}
}
Ok(results)
}
pub fn xack(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'xack' command");
}
let key: &[u8] = cmd[1];
let group = crate::types::StreamName::from(cmd[2]);
let mut ids = Vec::with_capacity(cmd.len() - 3);
for raw in &cmd[3..] {
match parse_utf8(raw).and_then(StreamId::parse) {
Some(id) => ids.push(id),
None => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
}
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_integer(0),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
match inner.groups.get_mut(&group) {
None => resp_integer(0),
Some(g) => {
let acked = ids.iter().filter(|id| g.pel.remove(id).is_some()).count();
resp_integer(acked as i64)
}
}
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xpending(ctx: &mut Ctx) -> Vec<u8> {
let resp = reply_resp(ctx);
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'xpending' command");
}
let key: &[u8] = cmd[1];
let group = crate::types::StreamName::from(cmd[2]);
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error("ERR no such key"),
Some(ValueRef::Stream(s)) => {
let inner = s.read();
let g = match inner.groups.get(&group) {
None => return resp_error("NOGROUP No such consumer group"),
Some(g) => g,
};
if cmd.len() == 3 {
let count = g.pel.len() as i64;
let min_id = g
.pel
.keys()
.next()
.map(|id| id.to_string())
.unwrap_or_default();
let max_id = g
.pel
.keys()
.next_back()
.map(|id| id.to_string())
.unwrap_or_default();
let mut per_consumer: BTreeMap<&[u8], i64> = BTreeMap::new();
for pel in g.pel.values() {
*per_consumer.entry(pel.consumer.as_bytes()).or_insert(0) += 1;
}
let consumer_list: Vec<Vec<u8>> = per_consumer
.iter()
.map(|(name, cnt)| {
resp_array(vec![resp_bulk(name), resp_bulk_str(&cnt.to_string())])
})
.collect();
resp_array(vec![
resp_integer(count),
if min_id.is_empty() {
resp_null_for(resp)
} else {
resp_bulk_str(&min_id)
},
if max_id.is_empty() {
resp_null_for(resp)
} else {
resp_bulk_str(&max_id)
},
resp_array(consumer_list),
])
} else {
let mut i = 3usize;
let mut min_idle: Option<u64> = None;
if std::str::from_utf8(cmd[i])
.unwrap_or("")
.eq_ignore_ascii_case("IDLE")
{
min_idle = cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok());
i += 2;
}
let start_str =
std::str::from_utf8(cmd.get(i).copied().unwrap_or(b"-")).unwrap_or("-");
let end_str =
std::str::from_utf8(cmd.get(i + 1).copied().unwrap_or(b"+")).unwrap_or("+");
let count: usize = cmd
.get(i + 2)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok())
.unwrap_or(10);
let filter_consumer: Option<&str> =
cmd.get(i + 3).and_then(|b| std::str::from_utf8(b).ok());
let (lo, hi, count) = match id_interval(start_str, end_str) {
Ok(Some((lo, hi))) => (lo, hi, count),
Ok(None) => (StreamId::min(), StreamId::min(), 0),
Err(e) => return e,
};
let now = now_ms();
let items: Vec<Vec<u8>> = g
.pel
.range(lo..=hi)
.filter(|(_, p)| {
if let Some(fc) = filter_consumer {
p.consumer == fc
} else {
true
}
})
.filter(|(_, p)| {
if let Some(idle) = min_idle {
now.saturating_sub(p.delivered_at) >= idle
} else {
true
}
})
.take(count)
.map(|(id, p)| {
let idle = if p.delivered_at < stream_extra::NACKED_BELOW {
-1
} else {
now.saturating_sub(p.delivered_at) as i64
};
resp_array(vec![
resp_bulk_str(&id.to_string()),
resp_bulk(&p.consumer),
resp_integer(idle),
resp_integer(p.delivery_count as i64),
])
})
.collect();
resp_array(items)
}
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xclaim(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 6 {
return resp_error("ERR wrong number of arguments for 'xclaim' command");
}
let key: &[u8] = cmd[1];
let group = crate::types::StreamName::from(cmd[2]);
let new_consumer = crate::types::StreamName::from(cmd[3]);
let min_idle: u64 = match parse_utf8(cmd[4]).and_then(|s| s.parse().ok()) {
Some(ms) => ms,
None => return resp_error("ERR Invalid min-idle-time argument for XCLAIM"),
};
let is_option = |tok: &[u8]| {
[
&b"IDLE"[..],
b"TIME",
b"RETRYCOUNT",
b"FORCE",
b"JUSTID",
b"LASTID",
]
.iter()
.any(|opt| tok.eq_ignore_ascii_case(opt))
};
let mut ids: Vec<StreamId> = Vec::new();
let mut i = 5usize;
while i < cmd.len() && !is_option(cmd[i]) {
match parse_utf8(cmd[i]).and_then(StreamId::parse) {
Some(id) => ids.push(id),
None => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
i += 1;
}
let mut justid = false;
let mut force = false;
let mut idle: Option<u64> = None;
let mut time: Option<u64> = None;
let mut retry_count: Option<u64> = None;
let mut last_id: Option<StreamId> = None;
let number = |arg: Option<&&[u8]>| -> Option<u64> {
arg.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok())
};
while i < cmd.len() {
let tok = String::from_utf8_lossy(cmd[i]).to_ascii_uppercase();
match tok.as_str() {
"JUSTID" => {
justid = true;
i += 1;
}
"FORCE" => {
force = true;
i += 1;
}
"IDLE" | "TIME" | "RETRYCOUNT" => {
let Some(n) = number(cmd.get(i + 1)) else {
return resp_error("ERR value is not an integer or out of range");
};
match tok.as_str() {
"IDLE" => idle = Some(n),
"TIME" => time = Some(n),
_ => retry_count = Some(n),
}
i += 2;
}
"LASTID" => {
last_id = match cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(StreamId::parse)
{
Some(id) => Some(id),
None => {
return resp_error(
"ERR Invalid stream ID specified as stream command argument",
);
}
};
i += 2;
}
_ => return resp_error("ERR syntax error"),
}
}
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error_bytes(
&[
&b"NOGROUP No such key '"[..],
c_str(key),
&b"' or consumer group '"[..],
c_str(group.as_bytes()),
&b"'"[..],
]
.concat(),
),
Some(ValueRef::Stream(s)) => {
let mut guard = s.write();
let StreamInner {
entries, groups, ..
} = &mut *guard;
let now = now_ms();
let delivered_at = time.unwrap_or_else(|| now.saturating_sub(idle.unwrap_or(0)));
let Some(g) = groups.get_mut(&group) else {
return resp_error_bytes(
&[
&b"NOGROUP No such key '"[..],
c_str(key),
&b"' or consumer group '"[..],
c_str(group.as_bytes()),
&b"'"[..],
]
.concat(),
);
};
effects_begin();
if !g.consumers.contains_key(&new_consumer) {
notify(
ctx.pubsub,
*ctx.selected_db,
KS_STREAM,
"xgroup-createconsumer",
key,
);
}
g.seen(&new_consumer, now, false);
if let Some(last) = last_id
&& last > g.last_id
{
g.last_id = last;
}
let mut claimed: Vec<Vec<u8>> = Vec::new();
for id in &ids {
let exists = entries.contains_key(id);
match g.pel.get(id) {
Some(_) if !exists => {
g.pel.remove(id);
effect(vec![
b"XACK".to_vec(),
key.to_vec(),
group.as_bytes().to_vec(),
id.to_string().into_bytes(),
]);
continue;
}
Some(p) if now.saturating_sub(p.delivered_at) < min_idle => continue,
Some(_) => {}
None if force && exists => {}
None => continue,
}
let pending = g.pel.entry(id.clone()).or_insert(PelEntry {
consumer: new_consumer.clone(),
delivered_at,
delivery_count: 1,
});
pending.consumer = new_consumer.clone();
pending.delivered_at = delivered_at;
pending.delivery_count = match retry_count {
Some(n) => n,
None if justid => pending.delivery_count,
None => pending.delivery_count.saturating_add(1),
};
effect(claim_effect(
key,
&group,
&new_consumer,
id,
delivered_at,
pending.delivery_count,
));
if justid {
claimed.push(resp_bulk_str(&id.to_string()));
} else if let Some(entry) = entries.get(id) {
claimed.push(format_entry(id, entry));
}
}
if !claimed.is_empty() {
g.seen(&new_consumer, now, true);
}
resp_array(claimed)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xautoclaim(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 6 {
return resp_error("ERR wrong number of arguments for 'xautoclaim' command");
}
let key: &[u8] = cmd[1];
let group = crate::types::StreamName::from(cmd[2]);
let new_consumer = crate::types::StreamName::from(cmd[3]);
let min_idle: u64 = match parse_utf8(cmd[4]).and_then(|s| s.parse().ok()) {
Some(ms) => ms,
None => return resp_error("ERR Invalid min-idle-time argument for XAUTOCLAIM"),
};
let start = match parse_range_id_lo(std::str::from_utf8(cmd[5]).unwrap_or("")) {
Some(id) => id,
None => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
};
let mut count = 100usize;
let mut justid = false;
let mut i = 6usize;
while i < cmd.len() {
if cmd[i].eq_ignore_ascii_case(b"COUNT") {
count = match cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse::<usize>().ok())
{
Some(n) if n > 0 && n <= (i64::MAX / 16) as usize => n,
_ => return resp_error("ERR COUNT must be > 0"),
};
i += 2;
} else if cmd[i].eq_ignore_ascii_case(b"JUSTID") {
justid = true;
i += 1;
} else {
return resp_error("ERR syntax error");
}
}
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error_bytes(
&[
&b"NOGROUP No such key '"[..],
c_str(key),
&b"' or consumer group '"[..],
c_str(group.as_bytes()),
&b"'"[..],
]
.concat(),
),
Some(ValueRef::Stream(s)) => {
let mut guard = s.write();
let StreamInner {
entries, groups, ..
} = &mut *guard;
let now = now_ms();
let Some(g) = groups.get_mut(&group) else {
return resp_error_bytes(
&[
&b"NOGROUP No such key '"[..],
c_str(key),
&b"' or consumer group '"[..],
c_str(group.as_bytes()),
&b"'"[..],
]
.concat(),
);
};
effects_begin();
if !g.consumers.contains_key(&new_consumer) {
notify(
ctx.pubsub,
*ctx.selected_db,
KS_STREAM,
"xgroup-createconsumer",
key,
);
}
g.seen(&new_consumer, now, false);
let scan: Vec<(StreamId, u64)> = g
.pel
.range(start..)
.take(count.saturating_mul(10).saturating_add(1))
.map(|(id, p)| (id.clone(), p.delivered_at))
.collect();
let mut claimed: Vec<Vec<u8>> = Vec::new();
let mut deleted: Vec<StreamId> = Vec::new();
let mut cursor = StreamId::min();
let mut attempts = count.saturating_mul(10);
for (id, last_delivered) in scan {
if attempts == 0 || claimed.len() + deleted.len() >= count {
cursor = id;
break;
}
attempts -= 1;
let Some(entry) = entries.get(&id) else {
g.pel.remove(&id);
deleted.push(id);
continue;
};
if now.saturating_sub(last_delivered) < min_idle {
continue;
}
let Some(pending) = g.pel.get_mut(&id) else {
continue;
};
pending.consumer = new_consumer.clone();
pending.delivered_at = now;
if !justid {
pending.delivery_count = pending.delivery_count.saturating_add(1);
}
effect(claim_effect(
key,
&group,
&new_consumer,
&id,
now,
pending.delivery_count,
));
claimed.push(if justid {
resp_bulk_str(&id.to_string())
} else {
format_entry(&id, entry)
});
}
if !claimed.is_empty() {
g.seen(&new_consumer, now, true);
}
if !deleted.is_empty() {
let mut xack = vec![b"XACK".to_vec(), key.to_vec(), group.to_vec()];
xack.extend(deleted.iter().map(|id| id.to_string().into_bytes()));
effect(xack);
}
resp_array(vec![
resp_bulk_str(&cursor.to_string()),
resp_array(claimed),
resp_array(
deleted
.iter()
.map(|id| resp_bulk_str(&id.to_string()))
.collect(),
),
])
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xinfo(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() == 2 && cmd[1].eq_ignore_ascii_case(b"HELP") {
return help_reply(
"XINFO",
&[
"CONSUMERS <key> <groupname>",
" Show consumers of <groupname>.",
"GROUPS <key>",
" Show the stream consumer groups.",
"STREAM <key> [FULL [COUNT <count>]",
" Show information about the stream.",
],
);
}
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'xinfo' command");
}
let subcommand = std::str::from_utf8(cmd[1])
.unwrap_or("")
.to_ascii_uppercase();
match subcommand.as_str() {
"STREAM" => xinfo_stream(ctx),
"GROUPS" => xinfo_groups(ctx),
"CONSUMERS" => xinfo_consumers(ctx),
_ => unknown_subcommand("XINFO", cmd[1]),
}
}
fn xinfo_stream(ctx: &mut Ctx) -> Vec<u8> {
let resp = reply_resp(ctx);
let cmd = &ctx.cmd;
let key: &[u8] = cmd[2];
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error("ERR no such key"),
Some(ValueRef::Stream(s)) => {
let inner = s.read();
if let Some(full) = cmd.get(3) {
if !full.eq_ignore_ascii_case(b"FULL") {
return resp_error("ERR syntax error");
}
let count = match cmd.len() {
4 => 10,
6 if cmd[4].eq_ignore_ascii_case(b"COUNT") => {
match parse_utf8(cmd[5]).and_then(|s| s.parse::<i64>().ok()) {
Some(0) => usize::MAX,
Some(n) if n > 0 => n as usize,
_ => {
return resp_error("ERR value is not an integer or out of range");
}
}
}
_ => return resp_error("ERR syntax error"),
};
let idmp_defaults = stream_extra::idmp_defaults(ctx.config);
return xinfo_stream_full(resp, &inner, count, idmp_defaults);
}
let first_entry = inner
.entries
.iter()
.next()
.map(|(id, e)| format_entry(id, e))
.unwrap_or_else(|| resp_null_for(resp));
let last_entry = inner
.entries
.iter()
.next_back()
.map(|(id, e)| format_entry(id, e))
.unwrap_or_else(|| resp_null_for(resp));
let (idmp_duration, idmp_maxsize) =
stream_extra::idmp_settings(&inner, stream_extra::idmp_defaults(ctx.config));
let (pids_tracked, iids_tracked) = stream_extra::idmp_tracked(
&inner,
stream_extra::idmp_defaults(ctx.config),
now_ms(),
);
resp_map_for(
resp,
vec![
resp_bulk_str("length"),
resp_integer(inner.entries.len() as i64),
resp_bulk_str("radix-tree-keys"),
resp_integer(stream_extra::node_count(&inner) as i64),
resp_bulk_str("radix-tree-nodes"),
resp_integer(match stream_extra::node_count(&inner) {
0 => 1,
nodes => nodes as i64 + 1,
}),
resp_bulk_str("last-generated-id"),
resp_bulk_str(&inner.last_id.to_string()),
resp_bulk_str("max-deleted-entry-id"),
resp_bulk_str(&inner.max_deleted_id.to_string()),
resp_bulk_str("entries-added"),
resp_integer(inner.entries_added as i64),
resp_bulk_str("recorded-first-entry-id"),
resp_bulk_str(&first_entry_id(&inner).to_string()),
resp_bulk_str("groups"),
resp_integer(inner.groups.len() as i64),
resp_bulk_str("idmp-duration"),
resp_integer(idmp_duration as i64),
resp_bulk_str("idmp-maxsize"),
resp_integer(idmp_maxsize as i64),
resp_bulk_str("pids-tracked"),
resp_integer(pids_tracked as i64),
resp_bulk_str("iids-tracked"),
resp_integer(iids_tracked as i64),
resp_bulk_str("iids-added"),
resp_integer(inner.idmp.iids_added as i64),
resp_bulk_str("iids-duplicates"),
resp_integer(inner.idmp.iids_duplicates as i64),
resp_bulk_str("first-entry"),
first_entry,
resp_bulk_str("last-entry"),
last_entry,
],
)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
fn first_entry_id(stream: &StreamInner) -> StreamId {
stream
.entries
.keys()
.next()
.cloned()
.unwrap_or_else(StreamId::min)
}
fn read_and_lag(resp: u8, stream: &StreamInner, g: &ConsumerGroup) -> (Vec<u8>, Vec<u8>) {
let entries_read = if g.entries_read == ConsumerGroup::NO_COUNT {
resp_null_for(resp)
} else {
resp_integer(g.entries_read as i64)
};
let lag = match stream_extra::Shape::of(stream).lag(g) {
Some(lag) => resp_integer(lag as i64),
None => resp_null_for(resp),
};
(entries_read, lag)
}
fn groups_in_order(stream: &StreamInner) -> Vec<&ConsumerGroup> {
let mut groups: Vec<&ConsumerGroup> = stream.groups.values().collect();
groups.sort_by(|a, b| a.name.cmp(&b.name));
groups
}
fn consumers_in_order(g: &ConsumerGroup) -> Vec<(&crate::types::StreamName, u64)> {
let mut consumers: Vec<(&crate::types::StreamName, u64)> = g
.consumers
.iter()
.map(|(name, seen)| (name, *seen))
.collect();
consumers.sort();
consumers
}
fn xinfo_stream_full(
resp: u8,
inner: &StreamInner,
count: usize,
idmp_defaults: (u64, u64),
) -> Vec<u8> {
let entries: Vec<Vec<u8>> = inner
.entries
.iter()
.take(count)
.map(|(id, e)| format_entry(id, e))
.collect();
let groups: Vec<Vec<u8>> = groups_in_order(inner)
.into_iter()
.map(|g| {
let (entries_read, lag) = read_and_lag(resp, inner, g);
let pel: Vec<Vec<u8>> = g
.pel
.iter()
.take(count)
.map(|(id, p)| {
resp_array(vec![
resp_bulk_str(&id.to_string()),
resp_bulk(&p.consumer),
resp_integer(shown_delivery_time(p.delivered_at)),
resp_integer(p.delivery_count as i64),
])
})
.collect();
let consumers: Vec<Vec<u8>> = consumers_in_order(g)
.into_iter()
.map(|(name, seen)| {
let own = || g.pel.iter().filter(|(_, p)| p.consumer == *name);
let pel: Vec<Vec<u8>> = own()
.take(count)
.map(|(id, p)| {
resp_array(vec![
resp_bulk_str(&id.to_string()),
resp_integer(shown_delivery_time(p.delivered_at)),
resp_integer(p.delivery_count as i64),
])
})
.collect();
resp_map_for(
resp,
vec![
resp_bulk_str("name"),
resp_bulk(name),
resp_bulk_str("seen-time"),
resp_integer(seen as i64),
resp_bulk_str("active-time"),
resp_integer(g.active.get(name).map_or(-1, |at| *at as i64)),
resp_bulk_str("pel-count"),
resp_integer(own().count() as i64),
resp_bulk_str("pending"),
resp_array(pel),
],
)
})
.collect();
resp_map_for(
resp,
vec![
resp_bulk_str("name"),
resp_bulk(&g.name),
resp_bulk_str("last-delivered-id"),
resp_bulk_str(&g.last_id.to_string()),
resp_bulk_str("entries-read"),
entries_read,
resp_bulk_str("lag"),
lag,
resp_bulk_str("pel-count"),
resp_integer(g.pel.len() as i64),
resp_bulk_str("nacked-count"),
resp_integer(g.pel.values().filter(|p| p.consumer.is_empty()).count() as i64),
resp_bulk_str("pending"),
resp_array(pel),
resp_bulk_str("consumers"),
resp_array(consumers),
],
)
})
.collect();
let (idmp_duration, idmp_maxsize) = stream_extra::idmp_settings(inner, idmp_defaults);
let (pids_tracked, iids_tracked) = stream_extra::idmp_tracked(inner, idmp_defaults, now_ms());
let nodes = stream_extra::node_count(inner);
resp_map_for(
resp,
vec![
resp_bulk_str("length"),
resp_integer(inner.entries.len() as i64),
resp_bulk_str("radix-tree-keys"),
resp_integer(nodes as i64),
resp_bulk_str("radix-tree-nodes"),
resp_integer(if nodes == 0 { 1 } else { nodes as i64 + 1 }),
resp_bulk_str("last-generated-id"),
resp_bulk_str(&inner.last_id.to_string()),
resp_bulk_str("max-deleted-entry-id"),
resp_bulk_str(&inner.max_deleted_id.to_string()),
resp_bulk_str("entries-added"),
resp_integer(inner.entries_added as i64),
resp_bulk_str("recorded-first-entry-id"),
resp_bulk_str(&first_entry_id(inner).to_string()),
resp_bulk_str("idmp-duration"),
resp_integer(idmp_duration as i64),
resp_bulk_str("idmp-maxsize"),
resp_integer(idmp_maxsize as i64),
resp_bulk_str("pids-tracked"),
resp_integer(pids_tracked as i64),
resp_bulk_str("iids-tracked"),
resp_integer(iids_tracked as i64),
resp_bulk_str("iids-added"),
resp_integer(inner.idmp.iids_added as i64),
resp_bulk_str("iids-duplicates"),
resp_integer(inner.idmp.iids_duplicates as i64),
resp_bulk_str("entries"),
resp_array(entries),
resp_bulk_str("groups"),
resp_array(groups),
],
)
}
fn xinfo_groups(ctx: &mut Ctx) -> Vec<u8> {
let resp = reply_resp(ctx);
let cmd = &ctx.cmd;
let key: &[u8] = cmd[2];
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error("ERR no such key"),
Some(ValueRef::Stream(s)) => {
let inner = s.read();
let groups: Vec<Vec<u8>> = groups_in_order(&inner)
.into_iter()
.map(|g| {
let (entries_read, lag) = read_and_lag(resp, &inner, g);
resp_map_for(
resp,
vec![
resp_bulk_str("name"),
resp_bulk(&g.name),
resp_bulk_str("consumers"),
resp_integer(g.consumers.len() as i64),
resp_bulk_str("pending"),
resp_integer(g.pel.len() as i64),
resp_bulk_str("last-delivered-id"),
resp_bulk_str(&g.last_id.to_string()),
resp_bulk_str("entries-read"),
entries_read,
resp_bulk_str("lag"),
lag,
],
)
})
.collect();
resp_array(groups)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
fn xinfo_consumers(ctx: &mut Ctx) -> Vec<u8> {
let resp = reply_resp(ctx);
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'xinfo|consumers' command");
}
let key: &[u8] = cmd[2];
let group = crate::types::StreamName::from(cmd[3]);
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => resp_error("ERR no such key"),
Some(ValueRef::Stream(s)) => {
let inner = s.read();
let g = match inner.groups.get(&group) {
None => return resp_error("NOGROUP No such consumer group"),
Some(g) => g,
};
let now = now_ms();
let consumers: Vec<Vec<u8>> = consumers_in_order(g)
.into_iter()
.map(|(name, last_seen)| {
let pending = g.pel.values().filter(|p| p.consumer == *name).count() as i64;
let idle = now.saturating_sub(last_seen);
let inactive = g
.active
.get(name)
.map_or(-1, |at| now.saturating_sub(*at) as i64);
resp_map_for(
resp,
vec![
resp_bulk_str("name"),
resp_bulk(name),
resp_bulk_str("pending"),
resp_integer(pending),
resp_bulk_str("idle"),
resp_integer(idle as i64),
resp_bulk_str("inactive"),
resp_integer(inactive),
],
)
})
.collect();
resp_array(consumers)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}
pub fn xgroup(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 2 {
return resp_error("ERR wrong number of arguments for 'xgroup' command");
}
match std::str::from_utf8(cmd[1])
.unwrap_or("")
.to_ascii_uppercase()
.as_str()
{
"CREATE" => xgroup_create(ctx),
"DESTROY" => xgroup_destroy(ctx),
"SETID" => xgroup_setid(ctx),
"CREATECONSUMER" => xgroup_createconsumer(ctx),
"DELCONSUMER" => xgroup_delconsumer(ctx),
"HELP" if cmd.len() == 2 => help_reply(
"XGROUP",
&[
"CREATE <key> <groupname> <id|$> [option]",
" Create a new consumer group. Options are:",
" * MKSTREAM",
" Create the empty stream if it does not exist.",
" * ENTRIESREAD entries_read",
" Set the group's entries_read counter (internal use).",
"CREATECONSUMER <key> <groupname> <consumer>",
" Create a new consumer in the specified group.",
"DELCONSUMER <key> <groupname> <consumer>",
" Remove the specified consumer.",
"DESTROY <key> <groupname>",
" Remove the specified group.",
"SETID <key> <groupname> <id|$> [ENTRIESREAD entries_read]",
" Set the current group ID and entries_read counter.",
],
),
_ => unknown_subcommand("XGROUP", cmd[1]),
}
}
fn notify_xread_waiters(ctx: &Ctx, key: &[u8]) {
ctx.wait_table.notify_stream_waiters(key);
}
pub fn xdelex(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 5 {
return resp_error("ERR wrong number of arguments for 'xdelex' command");
}
let key: Vec<u8> = cmd[1].to_vec();
let (refs, ids) = match stream_extra::parse_policy_and_ids(&cmd[2..], false) {
Ok(parsed) => parsed,
Err(e) => return e,
};
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, &key);
let map = read_lock!(shard);
let stream = match map.get(key.as_slice()) {
None => return resp_array(ids.iter().map(|_| resp_integer(-1)).collect()),
Some(ValueRef::Stream(s)) => Arc::clone(s),
Some(_) => {
return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
}
};
drop(map);
let mut inner = stream.write();
let replies = ids
.iter()
.map(|id| {
if !inner.entries.contains_key(id) {
if refs == TrimRefs::DelRef {
stream_extra::delete_entry(&mut inner, id, refs);
}
return resp_integer(-1);
}
if stream_extra::delete_entry(&mut inner, id, refs) {
resp_integer(1)
} else {
resp_integer(2)
}
})
.collect();
resp_array(replies)
}
pub fn xackdel(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'xackdel' command");
}
let key: Vec<u8> = cmd[1].to_vec();
let group_name = crate::types::StreamName::from(cmd[2]);
let (refs, ids) = match stream_extra::parse_policy_and_ids(&cmd[3..], true) {
Ok(parsed) => parsed,
Err(e) => return e,
};
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, &key);
let stream = {
let map = read_lock!(shard);
match map.get(key.as_slice()) {
Some(ValueRef::Stream(s)) => Arc::clone(s),
Some(_) => {
return resp_error(
"WRONGTYPE Operation against a key holding the wrong kind of value",
);
}
None => return resp_array(ids.iter().map(|_| resp_integer(-1)).collect()),
}
};
let mut inner = stream.write();
if !inner.groups.contains_key(&group_name) {
return resp_array(ids.iter().map(|_| resp_integer(-1)).collect());
}
let replies = ids
.iter()
.map(|id| {
let was_pending = inner
.groups
.get_mut(&group_name)
.is_some_and(|group| group.pel.remove(id).is_some());
if !was_pending {
return resp_integer(-1);
}
if stream_extra::delete_entry(&mut inner, id, refs) {
resp_integer(1)
} else {
resp_integer(2)
}
})
.collect();
resp_array(replies)
}
pub fn xcfgset(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 2 {
return resp_error("ERR wrong number of arguments for 'xcfgset' command");
}
let key: Vec<u8> = cmd[1].to_vec();
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, &key);
let map = read_lock!(shard);
let stream_arc = match map.get(key.as_slice()) {
Some(ValueRef::Stream(s)) => Arc::clone(s),
Some(_) => {
return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
}
None => return resp_error("ERR no such key"),
};
drop(map);
struct Patch {
max_entries: Option<Option<u64>>, max_deleted_id: Option<StreamId>,
idmp_duration: Option<u64>,
idmp_maxsize: Option<u64>,
}
let mut patch = Patch {
max_entries: None,
max_deleted_id: None,
idmp_duration: None,
idmp_maxsize: None,
};
let mut i = 2usize;
while i < cmd.len() {
let field = match parse_utf8(cmd[i]) {
Some(f) => f.to_ascii_uppercase(),
None => return resp_error("ERR syntax error"),
};
let Some(raw) = cmd.get(i + 1) else {
return resp_error("ERR syntax error");
};
let value = match parse_utf8(raw) {
Some(v) => v.to_string(),
None => return resp_error("ERR value is not an integer or out of range"),
};
match field.as_str() {
"MAX-ENTRIES" => {
let n: u64 = match value.parse() {
Ok(n) => n,
Err(_) => return resp_error("ERR value is not an integer or out of range"),
};
patch.max_entries = Some(if n == 0 { None } else { Some(n) });
}
"IDMP-DURATION" | "IDMP-MAXSIZE" => {
let (slot, range, unit) = if field == "IDMP-DURATION" {
(
&mut patch.idmp_duration,
stream_extra::IDMP_DURATION_RANGE,
"seconds",
)
} else {
(
&mut patch.idmp_maxsize,
stream_extra::IDMP_MAXSIZE_RANGE,
"entries",
)
};
if slot.is_some() {
return resp_error(&format!("ERR {field} specified multiple times"));
}
let Some(n) = stream_extra::strict_integer(raw) else {
return resp_error("ERR value is not an integer or out of range");
};
if !(*range.start() as i64..=*range.end() as i64).contains(&n) {
return resp_error(&format!(
"ERR {field} must be between {} and {} {unit}",
range.start(),
range.end()
));
}
*slot = Some(n as u64);
}
"MAX-DELETED-ENTRY-ID" => match StreamId::parse(&value) {
Some(id) => patch.max_deleted_id = Some(id),
None => {
return resp_error(
"ERR Invalid stream ID specified as stream command argument",
);
}
},
_ => return resp_error("ERR syntax error"),
}
i += 2;
}
if patch.max_entries.is_none()
&& patch.max_deleted_id.is_none()
&& patch.idmp_duration.is_none()
&& patch.idmp_maxsize.is_none()
{
return resp_error("ERR At least one parameter must be specified");
}
let defaults = stream_extra::idmp_defaults(ctx.config);
let mut inner = stream_arc.write();
if let Some(policy) = patch.max_entries {
inner.max_entries = policy;
if let Some(max) = inner.max_entries {
while inner.entries.len() as u64 > max {
if let Some((id, _)) = inner.entries.pop_first()
&& id > inner.max_deleted_id
{
inner.max_deleted_id = id;
}
}
}
}
if let Some(id) = patch.max_deleted_id {
if id > inner.max_deleted_id {
inner.max_deleted_id = id;
}
}
let mut changed = false;
if let Some(duration) = patch.idmp_duration {
changed |= inner.idmp.duration_secs.unwrap_or(defaults.0) != duration;
inner.idmp.duration_secs = Some(duration);
}
if let Some(maxsize) = patch.idmp_maxsize {
changed |= inner.idmp.maxsize.unwrap_or(defaults.1) != maxsize;
inner.idmp.maxsize = Some(maxsize);
}
if changed {
inner.idmp.producers.clear();
}
resp_simple("OK")
}
fn shown_delivery_time(delivered_at: u64) -> i64 {
if delivered_at < stream_extra::NACKED_BELOW {
0
} else {
delivered_at as i64
}
}
pub fn xnack(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if cmd.len() < 7 {
return resp_error("ERR wrong number of arguments for 'xnack' command");
}
let key: &[u8] = cmd[1];
let group = crate::types::StreamName::from(cmd[2]);
#[derive(Clone, Copy, PartialEq)]
enum Mode {
Silent,
Fail,
Fatal,
}
let mode = if cmd[3].eq_ignore_ascii_case(b"SILENT") {
Mode::Silent
} else if cmd[3].eq_ignore_ascii_case(b"FAIL") {
Mode::Fail
} else if cmd[3].eq_ignore_ascii_case(b"FATAL") {
Mode::Fatal
} else {
return resp_error("ERR mode must be SILENT, FAIL, or FATAL");
};
let mut ids_at: Option<(usize, usize)> = None;
let mut retrycount: Option<u64> = None;
let mut force = false;
let mut i = 4;
while i < cmd.len() {
let more = i + 1 < cmd.len();
if cmd[i].eq_ignore_ascii_case(b"IDS") && more {
let numids = match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
Some(n) if (1..=i64::from(i32::MAX)).contains(&n) => n as usize,
_ => return resp_error("ERR numids must be a positive integer"),
};
if numids > cmd.len() - (i + 2) {
return resp_error("ERR number of IDs doesn't match numids");
}
ids_at = Some((i + 2, numids));
i += 2 + numids;
} else if cmd[i].eq_ignore_ascii_case(b"FORCE") {
force = true;
i += 1;
} else if cmd[i].eq_ignore_ascii_case(b"RETRYCOUNT") && more {
match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
Some(n) if n >= 0 => retrycount = Some(n as u64),
Some(_) => return resp_error("ERR Invalid RETRYCOUNT value, must be >= 0"),
None => return resp_error("ERR value is not an integer or out of range"),
}
i += 2;
} else {
return resp_error(&format!(
"ERR Unrecognized XNACK option '{}'",
String::from_utf8_lossy(cmd[i])
));
}
}
let Some((ids_from, numids)) = ids_at else {
return resp_error("ERR syntax error, expected IDS keyword");
};
let mut ids: Vec<StreamId> = Vec::with_capacity(numids);
for raw in &cmd[ids_from..ids_from + numids] {
match StreamId::parse(std::str::from_utf8(raw).unwrap_or("")) {
Some(id) => ids.push(id),
None => {
return resp_error("ERR Invalid stream ID specified as stream command argument");
}
}
}
let no_group = || {
resp_error_bytes(
&[
&b"NOGROUP No such key '"[..],
c_str(key),
&b"' or consumer group '"[..],
c_str(group.as_bytes()),
&b"'"[..],
]
.concat(),
)
};
let db_ref = &ctx.store[*ctx.selected_db];
let shard = store::get_shard(db_ref, key);
let map = read_lock!(shard);
match map.get(key) {
None => no_group(),
Some(ValueRef::Stream(s)) => {
let mut inner = s.write();
let existing_ids: Vec<bool> = if force {
ids.iter()
.map(|id| inner.entries.contains_key(id))
.collect()
} else {
Vec::new()
};
let Some(g) = inner.groups.get_mut(&group) else {
return no_group();
};
let mut released = 0i64;
for (pos, id) in ids.iter().enumerate() {
match g.pel.get_mut(id) {
Some(entry) => {
entry.delivery_count = match retrycount {
Some(n) => n,
None => match mode {
Mode::Silent => entry.delivery_count.saturating_sub(1),
Mode::Fail => entry.delivery_count,
Mode::Fatal => i64::MAX as u64,
},
};
entry.consumer = crate::types::StreamName::default();
entry.delivered_at = stream_extra::nack_time();
released += 1;
}
None if force => {
if !existing_ids.get(pos).copied().unwrap_or(false) {
continue;
}
let delivery_count = match (retrycount, mode) {
(Some(n), _) => n,
(None, Mode::Fatal) => i64::MAX as u64,
(None, _) => 0,
};
g.pel.insert(
id.clone(),
PelEntry {
consumer: crate::types::StreamName::default(),
delivered_at: stream_extra::nack_time(),
delivery_count,
},
);
released += 1;
}
None => {}
}
}
resp_integer(released)
}
Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
}
}