use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use crate::entry::{Entry, EntryId};
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::result::TaskResult;
use crate::streams::Streams;
use crate::task::Task;
use crate::worker::check_task_stream;
pub const DEFAULT_TARGET_DEPTH: u64 = 300;
#[derive(Clone)]
pub struct Producer {
streams: Arc<dyn Streams>,
stream: String,
target_depth: Option<u64>,
}
impl Producer {
#[must_use]
pub fn new(streams: impl Streams + 'static, stream: impl Into<String>) -> Self {
Self {
streams: Arc::new(streams),
stream: stream.into(),
target_depth: Some(DEFAULT_TARGET_DEPTH),
}
}
#[must_use]
pub const fn target_depth(mut self, target_depth: u64) -> Self {
self.target_depth = Some(target_depth);
self
}
#[must_use]
pub const fn unbounded(mut self) -> Self {
self.target_depth = None;
self
}
pub fn depth(&self) -> Result<u64> {
self.streams.xlen(&self.stream)
}
pub fn send(&self, task: &Task) -> Result<EntryId> {
check_task_stream(&self.stream)?;
let fields = task.wire_fields();
fields::check_strings(&fields, &Limits::default())?;
if let Some(target_depth) = self.target_depth {
let depth = self.depth()?;
if depth >= target_depth {
return Err(Error::StreamFull {
stream: self.stream.clone(),
depth,
target_depth,
});
}
}
self.streams.xadd(&self.stream, &fields::as_bytes(&fields))
}
}
impl fmt::Debug for Producer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Producer")
.field("stream", &self.stream)
.field("target_depth", &self.target_depth)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Received {
pub id: EntryId,
pub result: Result<TaskResult>,
pub deliveries: Option<u64>,
}
#[derive(Clone)]
pub struct ResultReader {
streams: Arc<dyn Streams>,
stream: String,
group: String,
consumer: String,
limits: Limits,
}
impl ResultReader {
#[must_use]
pub fn new(
streams: impl Streams + 'static,
stream: impl Into<String>,
group: impl Into<String>,
consumer: impl Into<String>,
) -> Self {
Self {
streams: Arc::new(streams),
stream: stream.into(),
group: group.into(),
consumer: consumer.into(),
limits: Limits::default(),
}
}
#[must_use]
pub const fn limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn create_group(&self) -> Result<bool> {
self.streams.xgroup_create(&self.stream, &self.group)
}
pub fn read(&self, count: usize, block: Option<Duration>) -> Result<Vec<Received>> {
let read = || {
self.streams
.xreadgroup(&self.stream, &self.group, &self.consumer, count, block)
};
let entries = match read() {
Err(Error::NoGroup { .. }) => {
self.create_group()?;
read()?
}
other => other?,
};
Ok(self.receive(entries.into_iter().map(|entry| (entry, Some(1))).collect()))
}
pub fn reclaim(&self, min_idle: Duration, count: usize) -> Result<Vec<Received>> {
let mut received = Vec::new();
let mut cursor = EntryId::ZERO;
loop {
let claim = self
.streams
.xautoclaim(&self.stream, &self.group, &self.consumer, min_idle, cursor, count)?;
if !claim.deleted.is_empty() {
self.streams.xack(&self.stream, &self.group, &claim.deleted)?;
}
let empty = claim.claimed.is_empty();
let counted = claim
.claimed
.into_iter()
.map(|entry| {
let deliveries = match self.streams.xpending_entry(&self.stream, &self.group, entry.id) {
Ok(pending) => pending.map(|pending| pending.deliveries),
Err(error) => {
tracing::warn!(entry = %entry.id, %error, "Couldn't read a result's delivery count");
None
}
};
(entry, deliveries)
})
.collect();
received.extend(self.receive(counted));
cursor = claim.next;
if cursor == EntryId::ZERO || empty {
return Ok(received);
}
}
}
pub fn ack(&self, ids: &[EntryId]) -> Result<()> {
self.streams.xack_xdel(&self.stream, &self.group, ids)
}
fn receive(&self, entries: Vec<(Entry, Option<u64>)>) -> Vec<Received> {
let received: Vec<Received> = entries
.into_iter()
.map(|(entry, deliveries)| Received {
id: entry.id,
result: TaskResult::from_raw(&entry.fields, &self.limits),
deliveries,
})
.collect();
let malformed: Vec<EntryId> = received
.iter()
.filter(|received| received.result.is_err())
.map(|received| received.id)
.collect();
if !malformed.is_empty()
&& let Err(error) = self.ack(&malformed)
{
tracing::warn!(%error, "Couldn't remove entries that aren't results; they stay pending");
}
received
}
}
impl fmt::Debug for ResultReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResultReader")
.field("stream", &self.stream)
.field("group", &self.group)
.field("consumer", &self.consumer)
.finish_non_exhaustive()
}
}