Skip to main content

Queue

Struct Queue 

Source
pub struct Queue<E: TitoEngine> {
    pub engine: E,
    pub config: QueueConfig,
}

Fields§

§engine: E§config: QueueConfig

Implementations§

Source§

impl<E: TitoEngine> Queue<E>

Source

pub fn new(engine: E, config: QueueConfig) -> Self

Examples found in repository?
examples/queue_fifo.rs (lines 36-39)
31async fn main() -> Result<(), TitoError> {
32    println!("Testing FIFO Queue\n");
33
34    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
35
36    let queue = Arc::new(TitoQueue::new(
37        tito_db.clone(),
38        QueueConfig::with_partitions(1),
39    ));
40
41    println!("Publishing 5 events...\n");
42
43    for i in 1..=5 {
44        let user_id = DBUuid::new_v4().to_string();
45        let event = QueueEvent::new(
46            format!("user:{}", user_id),
47            UserEvent {
48                user_id,
49                name: format!("User {}", i),
50                email: format!("user{}@example.com", i),
51                action: "created".to_string(),
52            },
53        );
54
55        queue.publish(event).await?;
56        println!("Published event for User {}", i);
57    }
58
59    println!("\nStarting worker...\n");
60
61    let events_processed = Arc::new(std::sync::atomic::AtomicU32::new(0));
62    let events_processed_clone = events_processed.clone();
63
64    let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
65
66    let handler = move |event: QueueEvent<UserEvent>| {
67        let counter = events_processed_clone.clone();
68        Box::pin(async move {
69            let count = counter.fetch_add(1, Ordering::SeqCst) + 1;
70            println!(
71                "[{}] {} - {} ({})",
72                count,
73                event.payload.action,
74                event.payload.name,
75                event.payload.email,
76            );
77            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
78            Ok::<_, TitoError>(())
79        }) as BoxFuture<'static, Result<(), TitoError>>
80    };
81
82    let worker_handle = run_worker(
83        queue.clone(),
84        WorkerConfig {
85            event_type: String::from("user"),
86            consumer: String::from("example-consumer"),
87            partition_range: 0..1,
88        },
89        handler,
90        shutdown_rx,
91    )
92    .await;
93
94    tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
95
96    println!("\nShutting down...");
97    let _ = shutdown_tx.send(());
98    let _ = worker_handle.await;
99
100    let total = events_processed.load(Ordering::SeqCst);
101    println!("\nProcessed {} events", total);
102
103    Ok(())
104}
Source

pub async fn publish_in_tx<T: EventType + Serialize>( &self, event: QueueEvent<T>, tx: &E::Transaction, ) -> Result<(), TitoError>

Source

pub async fn publish<T: EventType + Serialize>( &self, event: QueueEvent<T>, ) -> Result<(), TitoError>

Examples found in repository?
examples/queue_fifo.rs (line 55)
31async fn main() -> Result<(), TitoError> {
32    println!("Testing FIFO Queue\n");
33
34    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
35
36    let queue = Arc::new(TitoQueue::new(
37        tito_db.clone(),
38        QueueConfig::with_partitions(1),
39    ));
40
41    println!("Publishing 5 events...\n");
42
43    for i in 1..=5 {
44        let user_id = DBUuid::new_v4().to_string();
45        let event = QueueEvent::new(
46            format!("user:{}", user_id),
47            UserEvent {
48                user_id,
49                name: format!("User {}", i),
50                email: format!("user{}@example.com", i),
51                action: "created".to_string(),
52            },
53        );
54
55        queue.publish(event).await?;
56        println!("Published event for User {}", i);
57    }
58
59    println!("\nStarting worker...\n");
60
61    let events_processed = Arc::new(std::sync::atomic::AtomicU32::new(0));
62    let events_processed_clone = events_processed.clone();
63
64    let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
65
66    let handler = move |event: QueueEvent<UserEvent>| {
67        let counter = events_processed_clone.clone();
68        Box::pin(async move {
69            let count = counter.fetch_add(1, Ordering::SeqCst) + 1;
70            println!(
71                "[{}] {} - {} ({})",
72                count,
73                event.payload.action,
74                event.payload.name,
75                event.payload.email,
76            );
77            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
78            Ok::<_, TitoError>(())
79        }) as BoxFuture<'static, Result<(), TitoError>>
80    };
81
82    let worker_handle = run_worker(
83        queue.clone(),
84        WorkerConfig {
85            event_type: String::from("user"),
86            consumer: String::from("example-consumer"),
87            partition_range: 0..1,
88        },
89        handler,
90        shutdown_rx,
91    )
92    .await;
93
94    tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
95
96    println!("\nShutting down...");
97    let _ = shutdown_tx.send(());
98    let _ = worker_handle.await;
99
100    let total = events_processed.load(Ordering::SeqCst);
101    println!("\nProcessed {} events", total);
102
103    Ok(())
104}
Source

pub async fn pull<T: EventType + DeserializeOwned>( &self, event_type: &str, partition: u32, limit: u32, ) -> Result<Vec<(String, QueueEvent<T>)>, TitoError>

Source

pub async fn ack(&self, key: &str) -> Result<(), TitoError>

Source

pub async fn reschedule<T: EventType + Serialize>( &self, event: QueueEvent<T>, storage_key: &str, new_scheduled_at: i64, ) -> Result<(), TitoError>

Source

pub async fn clear(&self) -> Result<(), TitoError>

Source

pub async fn move_to_dlq<T: EventType + Serialize>( &self, event: QueueEvent<T>, storage_key: &str, ) -> Result<(), TitoError>

Trait Implementations§

Source§

impl<E: Clone + TitoEngine> Clone for Queue<E>

Source§

fn clone(&self) -> Queue<E>

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<E> Freeze for Queue<E>
where E: Freeze,

§

impl<E> RefUnwindSafe for Queue<E>
where E: RefUnwindSafe,

§

impl<E> Send for Queue<E>

§

impl<E> Sync for Queue<E>

§

impl<E> Unpin for Queue<E>
where E: Unpin,

§

impl<E> UnsafeUnpin for Queue<E>
where E: UnsafeUnpin,

§

impl<E> UnwindSafe for Queue<E>
where E: 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<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> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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
Source§

impl<T> ErasedDestructor for T
where T: 'static,