Skip to main content

MemoryStreams

Struct MemoryStreams 

Source
pub struct MemoryStreams { /* private fields */ }
Expand description

The stream commands of Streams run in memory, with the semantics Redis 7 gives them, on a Clock the test controls: entry ids, idle times and blocking reads follow its time, so lease expiry, idle claims and delivery counts can be tested to the millisecond.

It implements exactly the commands the trait names, and keeps no trimming or persistence. A key given an expiry with EXPIRE goes once the clock passes it, as Redis expires keys: every command and inspection sees it gone. XAUTOCLAIM reports deleted entries the Redis 7 way. A blocking read on a manual clock waits until an entry arrives or the test advances the clock past its timeout.

The double is a cheap handle; clones share one set of streams.

use std::time::Duration;
use legit_streams::{Clock, EntryId, MemoryStreams, Streams};

let clock = Clock::manual(1_000);
let streams = MemoryStreams::with_clock(clock.clone());
streams.xgroup_create("hash_tasks", "hash_workers")?;
let id = streams.xadd("hash_tasks", &[(b"task_id".as_slice(), b"app_1".as_slice())])?;
streams.xreadgroup("hash_tasks", "hash_workers", "a", 1, None)?;

clock.advance(Duration::from_secs(300));
let claim = streams.xautoclaim("hash_tasks", "hash_workers", "b", Duration::from_secs(300), EntryId::ZERO, 1)?;
assert_eq!(claim.claimed[0].id, id);
assert_eq!(streams.xpending_entry("hash_tasks", "hash_workers", id)?.map(|p| p.deliveries), Some(2));

Implementations§

Source§

impl MemoryStreams

Source

pub fn new() -> Self

An empty double on the system clock.

use legit_streams::{MemoryStreams, Streams};

assert_eq!(MemoryStreams::new().xlen("hash_tasks")?, 0);
Source

pub fn with_clock(clock: Clock) -> Self

An empty double on clock.

use legit_streams::{Clock, MemoryStreams};

let streams = MemoryStreams::with_clock(Clock::manual(0));
assert!(streams.clock().is_manual());
Source

pub fn clock(&self) -> &Clock

The clock the double runs on.

use legit_streams::MemoryStreams;

assert!(!MemoryStreams::new().clock().is_manual());
Source

pub fn entries(&self, stream: &str) -> Vec<Entry>

Every entry of a stream, oldest first, as XRANGE stream - + gives them.

use legit_streams::{MemoryStreams, Streams};

let streams = MemoryStreams::new();
streams.xadd("hash_tasks", &[(b"k".as_slice(), b"v".as_slice())])?;
assert_eq!(streams.entries("hash_tasks")[0].field("k"), Some(&b"v"[..]));
Source

pub fn pending(&self, stream: &str, group: &str) -> Vec<Pending>

A group’s whole pending list, oldest first, as XPENDING stream group - + <all> gives it; empty when the group doesn’t exist.

use legit_streams::{MemoryStreams, Streams};

let streams = MemoryStreams::new();
streams.xgroup_create("hash_tasks", "hash_workers")?;
streams.xadd("hash_tasks", &[(b"k".as_slice(), b"v".as_slice())])?;
streams.xreadgroup("hash_tasks", "hash_workers", "c", 1, None)?;
assert_eq!(streams.pending("hash_tasks", "hash_workers")[0].consumer, "c");
Source

pub fn consumers(&self, stream: &str, group: &str) -> Vec<String>

A group’s consumers, in name order; empty when the group doesn’t exist.

use legit_streams::{MemoryStreams, Streams};

let streams = MemoryStreams::new();
streams.xgroup_create("hash_tasks", "hash_workers")?;
streams.xreadgroup("hash_tasks", "hash_workers", "c", 1, None)?;
assert_eq!(streams.consumers("hash_tasks", "hash_workers"), ["c"]);
Source

pub fn ttl(&self, key: &str) -> Option<Duration>

How long until a key’s expiry, or None when the key doesn’t exist or has none, as PTTL tells it.

use std::time::Duration;
use legit_streams::{Clock, MemoryStreams, Streams};

let clock = Clock::manual(0);
let streams = MemoryStreams::with_clock(clock.clone());
streams.xadd("results:app:hash:rpc:app_1", &[(b"k".as_slice(), b"v".as_slice())])?;
assert_eq!(streams.ttl("results:app:hash:rpc:app_1"), None);
streams.expire("results:app:hash:rpc:app_1", Duration::from_secs(60))?;
clock.advance(Duration::from_secs(15));
assert_eq!(streams.ttl("results:app:hash:rpc:app_1"), Some(Duration::from_secs(45)));

Trait Implementations§

Source§

impl Clone for MemoryStreams

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MemoryStreams

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for MemoryStreams

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Streams for MemoryStreams

Source§

fn group_backlog( &self, stream: &str, group: &str, ) -> Result<Option<GroupBacklog>>

Exact, where a server may not be: the lag is always known, as the number of entries after the group’s last-delivered id. Redis 7 and newer give the same count until entries the group hasn’t read are deleted, and then answer nil.

Source§

fn xadd(&self, stream: &str, fields: &[(&[u8], &[u8])]) -> Result<EntryId>

XADD stream * field value ...: append an entry and return its id. Read more
Source§

fn xlen(&self, stream: &str) -> Result<u64>

XLEN stream: how many entries the stream holds, 0 when it doesn’t exist. Read more
Source§

fn xgroup_create(&self, stream: &str, group: &str) -> Result<bool>

XGROUP CREATE stream group 0 MKSTREAM: create the group, reading from the start of the stream, and the stream when it doesn’t exist. Returns false when the group already existed (BUSYGROUP), which isn’t an error. Read more
Source§

fn xreadgroup( &self, stream: &str, group: &str, consumer: &str, count: usize, block: Option<Duration>, ) -> Result<Vec<Entry>>

XREADGROUP GROUP group consumer COUNT count [BLOCK ms] STREAMS stream >: deliver up to count entries no consumer of the group has seen, adding each to the group’s pending list under consumer. With block, wait up to that long for one when there are none; None returns at once. A block under a millisecond waits a millisecond: Redis reads BLOCK 0 as forever. Read more
Source§

fn xautoclaim( &self, stream: &str, group: &str, consumer: &str, min_idle: Duration, start: EntryId, count: usize, ) -> Result<AutoClaim>

XAUTOCLAIM stream group consumer min-idle start COUNT count: scan the pending list from start and claim for consumer up to count entries idle at least min_idle, adding one to each one’s delivery count. Read more
Source§

fn xclaim_justid( &self, stream: &str, group: &str, consumer: &str, ids: &[EntryId], idle: Option<Duration>, ) -> Result<Vec<EntryId>>

XCLAIM stream group consumer 0 id ... [IDLE ms] JUSTID: give pending entries to consumer without counting a delivery, and return the ids claimed. Without idle their idle time restarts at 0, which renews a lease; with it, it’s set to idle, which can make an entry claimable by another worker at once. Ids no longer pending are skipped. Read more
Source§

fn xpending_entry( &self, stream: &str, group: &str, id: EntryId, ) -> Result<Option<Pending>>

XPENDING stream group id id 1: the pending list’s record of one entry, or None when it isn’t pending. Read more
Source§

fn xpending_consumer( &self, stream: &str, group: &str, consumer: &str, count: usize, ) -> Result<Vec<Pending>>

XPENDING stream group - + count consumer: up to count of the entries consumer owns, oldest first. Read more
Source§

fn xack(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<u64>

XACK stream group id ...: drop entries from the group’s pending list, returning how many were pending. Read more
Source§

fn xdel(&self, stream: &str, ids: &[EntryId]) -> Result<u64>

XDEL stream id ...: delete entries from the stream, returning how many existed. Read more
Source§

fn xgroup_delconsumer( &self, stream: &str, group: &str, consumer: &str, ) -> Result<u64>

XGROUP DELCONSUMER stream group consumer: remove a consumer, and with it any entries it still owns; returns how many it owned. Read more
Source§

fn renew_lease( &self, stream: &str, group: &str, consumer: &str, id: EntryId, ) -> Result<Renewal>

Renew consumer’s lease on a pending entry, as one atomic step on the server: if, at the instant it runs, the entry is pending in the group for consumer, its idle time becomes 0 and nothing else changes, neither its owner nor its delivery count; otherwise nothing changes and the answer is Renewal::Lost. An entry still pending but deleted from the stream is dropped from the pending list and answers LostLease::NotPending. Read more
Source§

fn release_lease( &self, stream: &str, group: &str, consumer: &str, id: EntryId, idle: Duration, ) -> Result<bool>

Release consumer’s lease on a pending entry, as one atomic step on the server: if the entry is pending in the group for consumer, its idle time is set to idle, so a worker that claims entries idle that long takes it at once; otherwise nothing changes. The owner and the delivery count don’t change. Returns whether the entry was released. As with Streams::renew_lease, a separate check and XCLAIM could take back an entry another worker has just claimed. Read more
Source§

fn xread( &self, stream: &str, after: EntryId, count: usize, block: Option<Duration>, ) -> Result<Vec<Entry>>

XREAD COUNT count [BLOCK ms] STREAMS stream after: up to count entries added after after, without a consumer group, so nothing is delivered or pending. With block, wait up to that long for one when there are none; None returns at once. A block under a millisecond waits a millisecond, as for Streams::xreadgroup. A stream that doesn’t exist reads as empty. count 0 means no limit. Read more
Source§

fn expire(&self, key: &str, ttl: Duration) -> Result<bool>

EXPIRE key seconds: delete the key once ttl has passed, replacing any expiry it had. The time is rounded up to whole seconds, so the key never goes sooner than asked; a ttl of zero deletes it now, as Redis does. Returns whether the key existed. Read more
Source§

fn del(&self, keys: &[&str]) -> Result<u64>

DEL key ...: delete keys, returning how many existed. Read more
Source§

fn xack_xdel(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<()>

XACK then XDEL: how the contract finishes with an entry, so streams don’t grow. RedisStreams sends both in one round trip. Read more
Source§

fn xadd_expire( &self, stream: &str, fields: &[(&[u8], &[u8])], ttl: Duration, ) -> Result<EntryId>

XADD then EXPIRE: how a fast-lane worker writes a reply, so a reply nobody reads goes away on its own. The expiry is set again on every add. RedisStreams sends both in one round trip. Read more

Auto Trait Implementations§

§

impl Forget for MemoryStreams

§

impl Freeze for MemoryStreams
where *const ArcInner<Inner> is !null: Freeze, PhantomData<ArcInner<Inner>>: Freeze,

§

impl Move for MemoryStreams

§

impl RefUnwindSafe for MemoryStreams

§

impl Send for MemoryStreams
where Arc<Inner>: Send,

§

impl Sync for MemoryStreams
where Arc<Inner>: Sync,

§

impl Unpin for MemoryStreams
where Arc<Inner>: Unpin,

§

impl UnsafeUnpin for MemoryStreams
where *const ArcInner<Inner> is !null: UnsafeUnpin, PhantomData<ArcInner<Inner>>: UnsafeUnpin,

§

impl UnwindSafe for MemoryStreams
where Arc<Inner>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more