kiomq 0.2.0

An all-in-one task-queue and orchestration library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use crate::{
    stores::Store, timers::DelayQueueTimer, utils::processor_types::SharedStore,
    worker::processor_types::SyncFn, Job, JobState, JobToken, KioError, KioResult, Queue,
};

use crate::utils::main_loop;
use derive_more::Debug;
use futures::future::{Future, FutureExt};
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
use uuid::Uuid;
mod metrics;
mod worker_opts;
pub use metrics::*;

use crate::error::WorkerError;
use crate::events::EventParameters;
use crate::Counter;
use arc_swap::ArcSwapOption;
use hdrhistogram::Histogram;
use tokio::{sync::Notify, task::JoinHandle};
use tokio_metrics::TaskMonitor;
use tokio_util::{sync::CancellationToken, task::TaskTracker};

type JobMeta<D, R, P> = (
    Job<D, R, P>,
    JobToken,
    TaskHandle,
    TaskMonitor,
    Histogram<u64>,
);
use crossbeam::atomic::AtomicCell;
use dashmap::DashMap;
pub type JobMap<D, R, P> = Arc<DashMap<u64, JobMeta<D, R, P>>>;
pub type Task = JoinHandle<KioResult<()>>;
pub type TaskHandle = ArcSwapOption<Task>;
pub type SharedTaskHandle = Arc<TaskHandle>;
/// Alias for the `processing_queue`. changed from (`Futures::FuturesUnordered` -> `TaskTracker`)
pub type ProcessingQueue = TaskTracker;
use derive_more::IsVariant;
pub use worker_opts::WorkerOpts;
/// The current lifecycle state of a [`Worker`].
#[derive(IsVariant, Default, Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum WorkerState {
    /// The worker is actively polling and processing jobs.
    Active,
    /// The worker is running but has no jobs to process (idle / sleeping).
    #[default]
    Idle,
    /// The worker has been shut down via [`Worker::close`].
    Closed,
}
#[cfg(feature = "tracing")]
use tracing::{debug, instrument, warn, Instrument, Span};

pub use worker_opts::MIN_DELAY_MS_LIMIT;
/// A job processor that consumes jobs from a [`Queue`].
///
/// Each `Worker` runs an internal async loop that fetches jobs from the queue
/// and invokes your processor function.  Multiple workers can be attached to
/// the same queue to increase throughput.
///
/// # Type parameters
///
/// | Parameter | Description |
/// |-----------|-------------|
/// | `D` | Job input data type |
/// | `R` | Job return / result type |
/// | `P` | Job progress type |
/// | `S` | Backing [`Store`] implementation |
///
/// # Lifecycle
///
/// 1. Create with [`Worker::new_async`] or [`Worker::new_sync`].
/// 2. Call [`run`](Worker::run) to start the processing loop.
/// 3. Call [`close`](Worker::close) to stop the worker (idempotent—calling
///    `close` on an already-closed worker is a no-op).
///
/// # Examples
///
/// ```rust
/// # #[tokio::main]
/// # async fn main() -> kiomq::KioResult<()> {
/// use std::sync::Arc;
/// use kiomq::{InMemoryStore, Job, KioError, Queue, Worker, WorkerOpts};
///
/// let store: InMemoryStore<u64, u64, ()> = InMemoryStore::new(None, "worker-demo");
/// let queue = Queue::new(store, None).await?;
///
/// let worker = Worker::new_async(
///     &queue,
///     |_store: Arc<_>, job: Job<u64, u64, ()>| async move {
///         Ok::<u64, KioError>(job.data.unwrap_or_default() * 2)
///     },
///     Some(WorkerOpts::default()),
/// )?;
///
/// worker.run()?;
/// worker.close();
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct Worker<D, R, P, S> {
    /// Unique identifier for this worker instance.
    pub id: Uuid,
    #[cfg(feature = "tracing")]
    resource_span: Span,
    queue: Arc<Queue<D, R, P, S>>,
    jobs_in_progress: JobMap<D, R, P>,
    #[debug(skip)]
    processor: WorkerCallback<D, R, P, S>,
    /// Configuration options for this worker.
    pub opts: WorkerOpts,
    cancellation_token: Arc<CancellationToken>,
    /// Current lifecycle state of the worker.
    pub state: Arc<AtomicCell<WorkerState>>,
    processing: ProcessingQueue,
    timer_pauser: Arc<AtomicCell<bool>>,
    timers: DelayQueueTimer<D, R, P, S>,
    block_until: Counter,
    active_job_count: Arc<AtomicCell<usize>>,
    continue_notifier: Arc<Notify>,
    main_task: SharedTaskHandle,
}
use crate::utils::processor_types;
use processor_types::Callback;
/// A callback definition alias for the worker
pub type WorkerCallback<D, R, P, S> = Callback<D, R, P, S>;

impl<
        D: Clone + DeserializeOwned + 'static + Send + Sync + Serialize,
        R: Clone + DeserializeOwned + 'static + Serialize + Send + Sync,
        P: Clone + DeserializeOwned + 'static + Send + Sync + Serialize,
        S: Clone + Store<D, R, P> + Send + 'static + Sync,
    > Worker<D, R, P, S>
{
    /// Creates a worker with a **sync** (blocking) processor function.
    ///
    /// The processor runs on a dedicated OS thread via
    /// [`tokio::task::spawn_blocking`](https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html),
    /// so heavy CPU-bound or blocking work will not starve Tokio's async executor threads.
    ///
    /// # Errors
    ///
    /// Returns [`KioError`] if the worker cannot be initialised (e.g. if
    /// `WorkerOpts::autorun` is `true` and the initial [`run`](Worker::run) call
    /// fails).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[tokio::main]
    /// # async fn main() -> kiomq::KioResult<()> {
    /// use std::sync::Arc;
    /// use kiomq::{InMemoryStore, Job, KioError, Queue, Worker, WorkerOpts};
    ///
    /// let store: InMemoryStore<u64, u64, ()> = InMemoryStore::new(None, "sync-worker");
    /// let queue = Queue::new(store, None).await?;
    ///
    /// let worker = Worker::new_sync(
    ///     &queue,
    ///     |_store: Arc<_>, job: Job<u64, u64, ()>| {
    ///         Ok::<u64, KioError>(job.data.unwrap_or_default() * 2)
    ///     },
    ///     Some(WorkerOpts::default()),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    #[track_caller]
    pub fn new_sync<C, E>(
        queue: &Queue<D, R, P, S>,
        processor: C,
        worker_opts: Option<WorkerOpts>,
    ) -> KioResult<Self>
    where
        KioError: From<E>,
        C: Fn(SharedStore<S>, Job<D, R, P>) -> Result<R, E> + Send + Sync + 'static,
        P: Send + Sync + 'static,
        R: Send + Sync + 'static,
        D: Send + Sync + 'static,
        S: Sync + Store<D, R, P> + Send + 'static,
        E: std::error::Error + Send + 'static,
    {
        Self::new::<C, SyncFn<C, D, R, P, S, E>, E>(queue, processor, worker_opts)
    }
    /// Creates a worker with an **async** processor function.
    ///
    /// The processor runs directly on the Tokio runtime; it is best suited for
    /// I/O-bound work.  For CPU-intensive or blocking workloads prefer
    /// [`new_sync`](Worker::new_sync).
    ///
    /// # Errors
    ///
    /// Returns [`KioError`] if initialisation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[tokio::main]
    /// # async fn main() -> kiomq::KioResult<()> {
    /// use std::sync::Arc;
    /// use kiomq::{InMemoryStore, Job, KioError, Queue, Worker, WorkerOpts};
    ///
    /// let store: InMemoryStore<u64, u64, ()> = InMemoryStore::new(None, "async-worker");
    /// let queue = Queue::new(store, None).await?;
    ///
    /// let worker = Worker::new_async(
    ///     &queue,
    ///     |_store: Arc<_>, job: Job<u64, u64, ()>| async move {
    ///         Ok::<u64, KioError>(job.data.unwrap_or_default() * 2)
    ///     },
    ///     None,
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    #[track_caller]
    pub fn new_async<C, Fut, E>(
        queue: &Queue<D, R, P, S>,
        processor: C,
        worker_opts: Option<WorkerOpts>,
    ) -> KioResult<Self>
    where
        KioError: From<E>,
        C: Fn(SharedStore<S>, Job<D, R, P>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<R, E>> + Send + 'static,
        P: Send + Sync + 'static,
        R: Send + Sync + 'static,
        S: Sync + Store<D, R, P> + Send + 'static,
        D: Send + Sync + 'static,
        E: std::error::Error + Send + 'static,
    {
        use processor_types::AsyncFn;
        Self::new::<C, AsyncFn<C, D, R, P, S, E>, E>(queue, processor, worker_opts)
    }
    #[track_caller]
    fn new<C, F, E>(
        queue: &Queue<D, R, P, S>,
        processor: C,
        worker_opts: Option<WorkerOpts>,
    ) -> KioResult<Self>
    where
        KioError: From<E>,
        C: Into<F>,
        Callback<D, R, P, S>: From<F>,
        P: Send + Sync + 'static,
        R: Send + Sync + 'static,
        D: Send + Sync + 'static,
        S: Store<D, R, P> + Send + Sync + 'static,
        E: std::error::Error + Send + 'static,
    {
        let queue = Arc::new(queue.clone());
        let jobs_in_progress: JobMap<_, _, _> = Arc::new(DashMap::new());
        let f: F = processor.into();
        let callback = Callback::from(f);

        let id = Uuid::new_v4();
        let opts = worker_opts.unwrap_or_default();
        let jobs = jobs_in_progress.clone();
        let cancellation_token: Arc<CancellationToken> = Arc::default();
        let continue_notifier = queue.worker_notifier.clone();
        let notifier = continue_notifier.clone();
        let state: Arc<AtomicCell<WorkerState>> = Arc::default();
        let worker_state = state.clone();
        let timer_pauser: Arc<AtomicCell<bool>> = Arc::default();
        let processing = TaskTracker::new();
        let timers = DelayQueueTimer::new(
            jobs,
            id,
            opts,
            queue.clone(),
            cancellation_token.clone(),
            worker_state,
            notifier,
            timer_pauser.clone(),
            processing.clone(),
        );

        #[cfg(feature = "tracing")]
        let resource_span = {
            let callback_type = match &callback {
                Callback::Async(_) => "Async",
                Callback::Sync(_) => "Sync",
            };
            {
                let location = std::panic::Location::caller().to_string();
                let queue_name = queue.name();
                let worker_type = format!(
                    "{}-Worker({},{queue_name})",
                    callback_type,
                    id.as_u64_pair().0,
                );
                tracing::info_span!(parent:None, "",worker_type, ?location)
            }
        };
        let main_task = Arc::default();
        let worker = Self {
            state,
            timer_pauser,
            main_task,
            #[cfg(feature = "tracing")]
            resource_span,
            timers,
            continue_notifier,
            block_until: Arc::default(),
            opts,
            id,
            queue,
            jobs_in_progress,
            processing,
            processor: callback,
            cancellation_token,
            active_job_count: Arc::default(),
        };
        if worker.opts.autorun {
            worker.run()?;
        }

        Ok(worker)
    }

    /// Returns `true` if the worker is actively processing jobs.
    #[must_use]
    pub fn is_running(&self) -> bool {
        self.state.load().is_active() && !self.cancellation_token.is_cancelled()
    }
    /// Returns `true` if the worker is idle (started but waiting for work).
    #[must_use]
    pub fn is_idle(&self) -> bool {
        self.state.load().is_idle()
    }
    /// Starts the worker's job-processing loop.
    ///
    /// # Errors
    ///
    /// | Condition | Error |
    /// |-----------|-------|
    /// | Worker is already running | `WorkerAlreadyRunning` |
    /// | Worker has been closed | `WorkerAlreadyClosed` |
    ///
    /// Calling `run` on a closed worker (after [`close`](Worker::close)) is an
    /// error; create a new worker instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[tokio::main]
    /// # async fn main() -> kiomq::KioResult<()> {
    /// use std::sync::Arc;
    /// use kiomq::{InMemoryStore, Job, KioError, Queue, Worker};
    ///
    /// let store: InMemoryStore<u64, u64, ()> = InMemoryStore::new(None, "run-demo");
    /// let queue = Queue::new(store, None).await?;
    /// let worker = Worker::new_async(
    ///     &queue,
    ///     |_: Arc<_>, job: Job<u64, u64, ()>| async move { Ok::<u64, KioError>(0) },
    ///     None,
    /// )?;
    ///
    /// worker.run()?;
    /// assert!(worker.is_running());
    /// worker.close();
    /// # Ok(())
    /// # }
    /// ```
    pub fn run(&self) -> KioResult<()> {
        let prev = self
            .state
            .compare_exchange(WorkerState::Idle, WorkerState::Active);
        if let Err(current) = prev {
            if current.is_active() && !self.cancellation_token.is_cancelled() {
                return Err(WorkerError::WorkerAlreadyRunningWithId(self.id).into());
            }
            // if closed or canceled, return another error
            if current.is_closed() || self.cancellation_token.is_cancelled() {
                return Err(WorkerError::WorkerAlreadyClosed(self.id).into());
            }
        }
        #[cfg(not(feature = "tracing"))]
        let params = (
            self.id,
            self.cancellation_token.clone(),
            self.processing.clone(),
            self.opts,
            self.block_until.clone(),
            self.jobs_in_progress.clone(),
            self.active_job_count.clone(),
            self.processor.clone(),
            self.queue.clone(),
            self.state.clone(),
            self.continue_notifier.clone(),
            self.timers.clone(),
            self.timer_pauser.clone(),
        );
        #[cfg(feature = "tracing")]
        let params = (
            self.resource_span.clone(),
            self.id,
            self.cancellation_token.clone(),
            self.processing.clone(),
            self.opts,
            self.block_until.clone(),
            self.jobs_in_progress.clone(),
            self.active_job_count.clone(),
            self.processor.clone(),
            self.queue.clone(),
            self.state.clone(),
            self.continue_notifier.clone(),
            self.timers.clone(),
            self.timer_pauser.clone(),
        );
        #[cfg(feature = "tracing")]
        let main = main_loop(params).instrument(self.resource_span.clone());
        #[cfg(not(feature = "tracing"))]
        let main = main_loop(params);
        let main_task = tokio::spawn(main.boxed());
        self.main_task.swap(Some(main_task.into()));
        Ok(())
    }
    /// Returns `true` if the worker has been closed (cancelled).
    #[must_use]
    pub fn closed(&self) -> bool {
        self.cancellation_token.is_cancelled() || self.state.load().is_closed()
    }

    #[cfg_attr(feature="tracing", instrument(parent = &self.resource_span, skip(self)))]
    /// Stops the worker's processing loop.
    ///
    /// Signals the internal cancellation token and waits for the main loop
    /// task to finish.  Already-running jobs are allowed to complete.
    ///
    /// Calling `close` on a worker that is not running is a no-op (idempotent).
    ///
    /// # Note
    ///
    /// After calling `close` the worker **cannot** be restarted.  Create a new
    /// worker if you need to resume processing.
    pub fn close(&self) {
        if !self.is_running() {
            return;
        }
        #[cfg(feature = "tracing")]
        debug!(
            "cancel the worker's engine_loop, current_state: {:#?}",
            self.state.load()
        );
        self.processing.close();

        self.queue.resume_workers();
        self.queue.worker_notifier.notify_waiters();
        self.queue.pause_workers.store(false);
        self.cancellation_token.cancel();
        let mut main_task = self.main_task.load_full();
        if let Some(handle) = main_task.take() {
            // wait for handle to finishd
            #[cfg(feature = "tracing")]
            {
                let running_tasks = self.processing.len();
                warn!("waiting for all {running_tasks} tasks to complete or abort");
            }
            // wait for the main loop to close
            while !handle.is_finished() {}
        }
    }

    /// Registers a listener for a specific job-state event on the underlying queue.
    ///
    /// This is a convenience wrapper around [`Queue::on`].  Returns a listener
    /// ID that can be passed to [`remove_event_listener`](Worker::remove_event_listener).
    pub fn on<F, C>(&self, event: JobState, callback: C) -> Uuid
    where
        C: Fn(EventParameters<R, P>) -> F + Send + Sync + 'static,
        F: Future<Output = ()> + Send + Sync + 'static,
    {
        self.queue.on(event, callback)
    }
    /// Registers a listener for **all** job-state events on the underlying queue.
    ///
    /// This is a convenience wrapper around [`Queue::on_all_events`].
    pub fn on_all_events<F, C>(&self, callback: C) -> Uuid
    where
        C: Fn(EventParameters<R, P>) -> F + Send + Sync + 'static,
        F: Future<Output = ()> + Send + Sync + 'static,
    {
        self.queue.on_all_events(callback)
    }
    /// Removes a previously registered event listener from the underlying queue.
    ///
    /// Returns the listener ID if found and removed, or `None` otherwise.
    #[must_use]
    pub fn remove_event_listener(&self, id: Uuid) -> Option<Uuid> {
        self.queue.remove_event_listener(id)
    }
}