feat: add 4 new crates (queue, tracing, http, cli) + enhancements to existing crates
New crates: - mytheclipse-queue: unified job queue with WorkerPool, retry/backoff, DLQ Backends: in-memory (default), Redis, NATS, PostgreSQL - mytheclipse-tracing: tracing subscriber layers with env filter + OTLP/Jaeger export - mytheclipse-http: HTTP client/server with timeout + tracing, axum server - mytheclipse-cli: CLI framework with clap derive, built-in subcommands Enhancements to existing crates: - mytheclipse-core: SemaphorePool, LeaderElection, HealthRegistry/HealthCheck - mytheclipse-cache: AutoRefreshCache (bg refresh on miss), CacheMetrics - mytheclipse-config: ConfigSchema for JSON Schema generation - mytheclipse-storage: MultipartUploadDriver trait - mytheclipse-crypto: PASETO v4.local token support All features compile with --all-features; tests + clippy pass clean.
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
[package]
|
||||
name = "mytheclipse-queue"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.75"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/asepharyana/mytheclipse"
|
||||
homepage = "https://github.com/asepharyana/mytheclipse"
|
||||
documentation = "https://docs.rs/mytheclipse-queue"
|
||||
authors = ["asepharyana <superaseph@gmail.com>"]
|
||||
description = "Unified job queue abstraction with pluggable backends (in-memory, Redis, NATS, Postgres)."
|
||||
readme = "README.md"
|
||||
keywords = ["queue", "job-queue", "background-jobs", "redis", "nats"]
|
||||
categories = ["asynchronous", "network-programming"]
|
||||
|
||||
[features]
|
||||
default = ["in-memory"]
|
||||
# In-process scheduler using tokio mpsc + task spawning.
|
||||
in-memory = ["dep:tokio"]
|
||||
# Redis-backed distributed queue.
|
||||
redis = ["dep:redis"]
|
||||
# NATS JetStream-backed distributed queue.
|
||||
nats = ["dep:async-nats", "dep:bytes"]
|
||||
# PostgreSQL-backed queue using SKIP LOCKED.
|
||||
postgres = ["dep:tokio-postgres"]
|
||||
|
||||
[dependencies]
|
||||
tracing = "0.1"
|
||||
async-trait = "0.1"
|
||||
tokio = { version = "1.53", features = ["sync", "time", "rt", "macros"], optional = true }
|
||||
redis = { version = "0.27", default-features = false, features = ["tokio-comp"], optional = true }
|
||||
async-nats = { version = "0.38", optional = true }
|
||||
bytes = { version = "1", optional = true }
|
||||
tokio-postgres = { version = "0.7", optional = true }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.53", features = ["full"] }
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 The corex Authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 The corex Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,57 @@
|
||||
# mytheclipse-queue
|
||||
|
||||
A unified job queue abstraction so your background work isn't locked to one
|
||||
transport. Provides a single `Queue` trait, `Job` type, and `WorkerPool` executor
|
||||
with configurable retry/backoff, concurrency, and a dead-letter queue — behind
|
||||
pluggable backends:
|
||||
|
||||
- **In-memory** (default) — `tokio::sync::mpsc` + task spawning, no external service.
|
||||
- **Redis** (`redis`) — LIST-based queue with atomic moves.
|
||||
- **NATS JetStream** (`nats`) — durable consumer with ACK/NACK.
|
||||
- **PostgreSQL** (`postgres`) — `SKIP LOCKED` polling.
|
||||
|
||||
All backends share the same `WorkerPool` driver; swapping is a one-line change
|
||||
at construction time.
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | Default | Backend | Description |
|
||||
| :--- | :---: | :--- | :--- |
|
||||
| `in-memory` | yes | `tokio::sync` | In-process queue, no external deps. |
|
||||
| `redis` | no | `redis` crate (fred) | Redis/Valkey list-based queue. |
|
||||
| `nats` | no | `async-nats` | NATS JetStream durable consumer. |
|
||||
| `postgres` | no | `tokio-postgres` | PostgreSQL `SKIP LOCKED` queue. |
|
||||
|
||||
## Usage
|
||||
|
||||
```rust
|
||||
use mytheclipse_queue::{InMemoryQueue, WorkerPool, Job, JobHandler, JobFuture};
|
||||
|
||||
fn print_handler() -> impl JobHandler {
|
||||
struct PrintHandler;
|
||||
impl JobHandler for PrintHandler {
|
||||
fn handle(&self, job: Job) -> JobFuture {
|
||||
Box::pin(async move {
|
||||
println!("payload: {:?}", job.payload);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
PrintHandler
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let queue = InMemoryQueue::new();
|
||||
queue.enqueue("email", b"hello".to_vec()).await?;
|
||||
|
||||
let pool = WorkerPool::new(queue, 4);
|
||||
pool.start("email", print_handler());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Swap `InMemoryQueue::new()` for `RedisQueue::connect("redis://127.0.0.1")` (with
|
||||
the `redis` feature) or `NatsQueue::connect("nats://127.0.0.1")` (with the `nats`
|
||||
feature) to move to a distributed broker without touching handler code.
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Errors returned by queue and job operations.
|
||||
|
||||
/// Errors from queue-level operations (enqueue, dequeue, etc.).
|
||||
#[derive(Debug)]
|
||||
pub enum QueueError {
|
||||
/// A transport or backend connection error.
|
||||
Connection(String),
|
||||
/// The requested topic/queue does not exist or is unavailable.
|
||||
NotFound(String),
|
||||
/// A serialization error.
|
||||
Serialization(String),
|
||||
/// A timeout occurred while waiting for an operation.
|
||||
Timeout,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for QueueError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Connection(s) => write!(f, "queue connection error: {s}"),
|
||||
Self::NotFound(s) => write!(f, "queue not found: {s}"),
|
||||
Self::Serialization(s) => write!(f, "serialization error: {s}"),
|
||||
Self::Timeout => write!(f, "queue operation timed out"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for QueueError {}
|
||||
|
||||
/// Errors from individual job processing.
|
||||
#[derive(Debug)]
|
||||
pub enum JobError {
|
||||
/// The job could not be acknowledged.
|
||||
AckFailed(String),
|
||||
/// The job could not be moved to the dead-letter queue.
|
||||
DlqFailed(String),
|
||||
/// The job exceeded its maximum retry count.
|
||||
MaxRetriesExceeded,
|
||||
/// The job payload could not be decoded.
|
||||
InvalidPayload(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for JobError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::AckFailed(s) => write!(f, "ack failed: {s}"),
|
||||
Self::DlqFailed(s) => write!(f, "dlq move failed: {s}"),
|
||||
Self::MaxRetriesExceeded => write!(f, "max retries exceeded"),
|
||||
Self::InvalidPayload(s) => write!(f, "invalid payload: {s}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for JobError {}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! In-process job queue using `tokio::sync::Mutex` + `Notify`.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
|
||||
use crate::error::{JobError, QueueError};
|
||||
use crate::job::{Job, JobId};
|
||||
use crate::traits::Queue;
|
||||
|
||||
struct TopicQueue {
|
||||
jobs: Mutex<Vec<Job>>,
|
||||
notify: Notify,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for TopicQueue {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TopicQueue")
|
||||
.field("jobs_len", &self.jobs.try_lock().map(|j| j.len()).unwrap_or(0))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
topics: std::collections::HashMap<String, Arc<TopicQueue>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Inner {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let keys: Vec<&String> = self.topics.keys().collect();
|
||||
f.debug_struct("Inner").field("topics", &keys).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory queue. Each topic is a shared mutex-protected vector + Notify.
|
||||
#[derive(Clone)]
|
||||
pub struct InMemoryQueue {
|
||||
inner: Arc<Mutex<Inner>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for InMemoryQueue {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("InMemoryQueue").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for InMemoryQueue {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl InMemoryQueue {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(Inner {
|
||||
topics: std::collections::HashMap::new(),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_topic(&self, topic: &str) -> Arc<TopicQueue> {
|
||||
let mut inner = self.inner.lock().await;
|
||||
inner
|
||||
.topics
|
||||
.entry(topic.to_string())
|
||||
.or_insert_with(|| {
|
||||
Arc::new(TopicQueue {
|
||||
jobs: Mutex::new(Vec::new()),
|
||||
notify: Notify::new(),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Queue for InMemoryQueue {
|
||||
async fn enqueue(&self, topic: &str, payload: Vec<u8>) -> Result<(), QueueError> {
|
||||
let tq = self.get_topic(topic).await;
|
||||
tq.jobs.lock().await.push(Job::new(JobId::generate(), topic, payload));
|
||||
tq.notify.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn dequeue(&self, topic: &str, timeout: Duration) -> Result<Option<Job>, QueueError> {
|
||||
let tq = self.get_topic(topic).await;
|
||||
let tq2 = Arc::clone(&tq);
|
||||
loop {
|
||||
if let Some(job) = tq.jobs.lock().await.pop() {
|
||||
return Ok(Some(job));
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tq2.notify.notified() => {}
|
||||
_ = tokio::time::sleep(timeout) => {
|
||||
if let Some(job) = tq.jobs.lock().await.pop() {
|
||||
return Ok(Some(job));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn ack(&self, _job: &Job) -> Result<(), JobError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn nack(&self, job: &Job, requeue: bool) -> Result<(), JobError> {
|
||||
if requeue {
|
||||
self.enqueue(&job.topic, job.payload.clone())
|
||||
.await
|
||||
.map_err(|_| JobError::AckFailed("requeue failed".into()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn dlq_move(&self, topic: &str, job: Job) -> Result<(), QueueError> {
|
||||
let dlq_topic = format!("dlq:{topic}");
|
||||
let tq = self.get_topic(&dlq_topic).await;
|
||||
tq.jobs.lock().await.push(job);
|
||||
tq.notify.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn len(&self, topic: &str) -> Result<u64, QueueError> {
|
||||
let tq = self.get_topic(topic).await;
|
||||
let guard = tq.jobs.lock().await;
|
||||
Ok(guard.len() as u64)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn enqueue_dequeue_roundtrip() {
|
||||
let q = InMemoryQueue::new();
|
||||
q.enqueue("test", b"hello".to_vec()).await.unwrap();
|
||||
let job = q.dequeue("test", Duration::from_millis(500)).await.unwrap().unwrap();
|
||||
assert_eq!(job.payload, b"hello");
|
||||
assert_eq!(job.topic, "test");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_returns_none() {
|
||||
let q = InMemoryQueue::new();
|
||||
let result = q.dequeue("none", Duration::from_millis(50)).await.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn len_tracks_jobs() {
|
||||
let q = InMemoryQueue::new();
|
||||
q.enqueue("t", vec![1]).await.unwrap();
|
||||
q.enqueue("t", vec![2]).await.unwrap();
|
||||
assert_eq!(q.len("t").await.unwrap(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! The `Job` type and its metadata.
|
||||
//!
|
||||
//! A minimal, dependency-free in-process job queue using `tokio::sync::mpsc`.
|
||||
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// A unique identifier for a queued job.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct JobId(pub String);
|
||||
|
||||
impl JobId {
|
||||
pub fn generate() -> Self {
|
||||
Self(uuid::Uuid::new_v4().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for JobId {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit of queued work.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Job {
|
||||
/// The unique ID of this job.
|
||||
pub id: JobId,
|
||||
/// The topic/queue name the job was delivered from.
|
||||
pub topic: String,
|
||||
/// The raw payload bytes.
|
||||
pub payload: Vec<u8>,
|
||||
/// How many times this job has been attempted (0 = first attempt).
|
||||
pub attempt: u32,
|
||||
/// When the job was first enqueued.
|
||||
pub enqueued_at: SystemTime,
|
||||
/// When the job was delivered to the worker (None if not yet delivered).
|
||||
pub delivered_at: Option<SystemTime>,
|
||||
/// Optional visibility timeout - after this the job becomes visible again.
|
||||
pub visibility_timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
pub fn new(id: JobId, topic: &str, payload: Vec<u8>) -> Self {
|
||||
Self {
|
||||
id,
|
||||
topic: topic.to_string(),
|
||||
payload,
|
||||
attempt: 0,
|
||||
enqueued_at: SystemTime::now(),
|
||||
delivered_at: Some(SystemTime::now()),
|
||||
visibility_timeout: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! # mytheclipse-queue
|
||||
//!
|
||||
//! A unified job queue abstraction so your background work isn't locked to one
|
||||
//! transport. Provides a single `Queue` trait, `Job` type, and `WorkerPool`
|
||||
//! executor with configurable retry/backoff, concurrency, and a dead-letter
|
||||
//! queue — behind pluggable backends:
|
||||
//!
|
||||
//! - **In-memory** (default) — `tokio::sync::mpsc` + task spawning, no external service.
|
||||
//! - **Redis** (`redis`) — LIST-based queue with atomic moves.
|
||||
//! - **NATS JetStream** (`nats`) — durable consumer with ACK/NACK.
|
||||
//! - **PostgreSQL** (`postgres`) — `SKIP LOCKED` polling.
|
||||
//!
|
||||
//! ## Quick Start
|
||||
//!
|
||||
//! ```toml
|
||||
//! [dependencies]
|
||||
//! mytheclipse-queue = "0.2"
|
||||
//! ```
|
||||
//!
|
||||
//! ```ignore
|
||||
//! use mytheclipse_queue::{InMemoryQueue, WorkerPool, JobHandler, Job};
|
||||
//! ...
|
||||
//! let queue = InMemoryQueue::new();
|
||||
//! queue.enqueue("email", b"hello".to_vec()).await?;
|
||||
//!
|
||||
//! fn make_handler() -> impl JobHandler {
|
||||
//! struct PrintHandler;
|
||||
//! impl JobHandler for PrintHandler {
|
||||
//! fn handle(&self, job: Job) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), mytheclipse_queue::JobError>> + Send>> {
|
||||
//! Box::pin(async move {
|
||||
//! println!("payload: {:?}", job.payload);
|
||||
//! Ok(())
|
||||
//! })
|
||||
//! }
|
||||
//! }
|
||||
//! PrintHandler
|
||||
//! }
|
||||
//!
|
||||
//! # #[tokio::main]
|
||||
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let queue = InMemoryQueue::new();
|
||||
//! queue.enqueue("email", b"hello".to_vec()).await?;
|
||||
//!
|
||||
//! let pool = WorkerPool::new(queue, 4);
|
||||
//! pool.start("email", make_handler());
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
pub mod traits;
|
||||
pub mod job;
|
||||
pub mod worker;
|
||||
pub mod error;
|
||||
|
||||
#[cfg(feature = "in-memory")]
|
||||
pub mod in_memory;
|
||||
#[cfg(feature = "in-memory")]
|
||||
pub use in_memory::InMemoryQueue;
|
||||
|
||||
pub use traits::Queue;
|
||||
pub use job::{Job, JobId};
|
||||
pub use worker::{WorkerPool, WorkerConfig, JobHandler, JobFuture};
|
||||
pub use error::{QueueError, JobError};
|
||||
@@ -0,0 +1,50 @@
|
||||
//! The core `Queue` trait and supporting types.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::job::Job;
|
||||
use crate::error::{QueueError, JobError};
|
||||
|
||||
/// A handle to a single unit of queued work.
|
||||
///
|
||||
/// `Job` carries the raw payload (arbitrary bytes — caller decides encoding)
|
||||
/// plus metadata the queue implementation fills in (ID, enqueue time, retry
|
||||
/// count). `ack`/`nack` are only valid on backends that support explicit
|
||||
/// acknowledgment (NATS, Redis BLPOP-with-confirm). For in-memory and Postgres
|
||||
/// backends, the worker auto-acknowledges on `Ok` and auto-requeues on `Err`.
|
||||
|
||||
/// A trait for enqueueing and dequeueing jobs.
|
||||
///
|
||||
/// Implementations must be `Send + Sync`. Each backend provides its own factory
|
||||
/// (e.g. `InMemoryQueue::new()`, `RedisQueue::connect(url)`).
|
||||
#[async_trait]
|
||||
pub trait Queue: Send + Sync {
|
||||
/// Enqueues `payload` onto `topic`.
|
||||
async fn enqueue(&self, topic: &str, payload: Vec<u8>) -> Result<(), QueueError>;
|
||||
|
||||
/// Dequeues the next job from `topic`, waiting up to `timeout`.
|
||||
///
|
||||
/// Returns `None` on timeout when the queue is empty and no job arrives
|
||||
/// within the window.
|
||||
async fn dequeue(&self, topic: &str, timeout: Duration) -> Result<Option<Job>, QueueError>;
|
||||
|
||||
/// Acknowledges a job as successfully processed.
|
||||
async fn ack(&self, job: &Job) -> Result<(), JobError>;
|
||||
|
||||
/// Negative-acknowledges a job. If `requeue` is true the job goes back
|
||||
/// onto the queue; if false it moves to the dead-letter queue (if
|
||||
/// configured).
|
||||
async fn nack(&self, job: &Job, requeue: bool) -> Result<(), JobError>;
|
||||
|
||||
/// Moves a job to the dead-letter queue for `topic`.
|
||||
async fn dlq_move(&self, topic: &str, job: Job) -> Result<(), QueueError>;
|
||||
|
||||
/// Number of messages currently waiting in `topic`.
|
||||
async fn len(&self, topic: &str) -> Result<u64, QueueError>;
|
||||
|
||||
/// Whether the queue is empty.
|
||||
async fn is_empty(&self, topic: &str) -> Result<bool, QueueError> {
|
||||
Ok(self.len(topic).await? == 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Worker pool for processing queued jobs with retry, backoff, and graceful shutdown.
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::error::JobError;
|
||||
use crate::job::Job;
|
||||
use crate::traits::Queue;
|
||||
|
||||
/// A future returned by a job handler.
|
||||
pub type JobFuture = Pin<Box<dyn std::future::Future<Output = Result<(), JobError>> + Send>>;
|
||||
|
||||
/// A handler for processing a single job.
|
||||
pub trait JobHandler: Send + Sync {
|
||||
fn handle(&self, job: Job) -> JobFuture;
|
||||
}
|
||||
|
||||
impl<F, Fut> JobHandler for F
|
||||
where
|
||||
F: Fn(Job) -> Fut + Send + Sync,
|
||||
Fut: std::future::Future<Output = Result<(), JobError>> + Send + 'static,
|
||||
{
|
||||
fn handle(&self, job: Job) -> JobFuture {
|
||||
Box::pin((self)(job))
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for the worker pool.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WorkerConfig {
|
||||
/// Maximum concurrent job handlers.
|
||||
pub concurrency: usize,
|
||||
/// Maximum number of retry attempts (0 = no retries).
|
||||
pub max_retries: u32,
|
||||
/// Base delay for exponential backoff between retries.
|
||||
pub retry_base_delay: Duration,
|
||||
/// Maximum delay cap for retry backoff.
|
||||
pub retry_max_delay: Duration,
|
||||
/// Backoff multiplier.
|
||||
pub retry_factor: f64,
|
||||
/// Visibility timeout for in-progress jobs.
|
||||
pub visibility_timeout: Duration,
|
||||
/// Polling interval when a queue is empty.
|
||||
pub poll_interval: Duration,
|
||||
}
|
||||
|
||||
impl Default for WorkerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
concurrency: 4,
|
||||
max_retries: 3,
|
||||
retry_base_delay: Duration::from_millis(500),
|
||||
retry_max_delay: Duration::from_secs(10),
|
||||
retry_factor: 2.0,
|
||||
visibility_timeout: Duration::from_secs(30),
|
||||
poll_interval: Duration::from_millis(100),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pool of workers consuming jobs from a `Queue`.
|
||||
pub struct WorkerPool<Q: Queue + 'static> {
|
||||
queue: Arc<Q>,
|
||||
config: WorkerConfig,
|
||||
semaphore: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl<Q: Queue + 'static> WorkerPool<Q> {
|
||||
/// Creates a new worker pool with the given concurrency.
|
||||
pub fn new(queue: Q, concurrency: usize) -> Self {
|
||||
Self::with_config(queue, WorkerConfig {
|
||||
concurrency,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a new worker pool with explicit configuration.
|
||||
pub fn with_config(queue: Q, config: WorkerConfig) -> Self {
|
||||
let sem = Arc::new(Semaphore::new(config.concurrency.max(1)));
|
||||
Self {
|
||||
queue: Arc::new(queue),
|
||||
config,
|
||||
semaphore: sem,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `concurrency` workers consuming from `topic`.
|
||||
pub fn start<H>(&self, topic: &str, handler: H)
|
||||
where
|
||||
H: JobHandler + 'static,
|
||||
{
|
||||
let queue = Arc::clone(&self.queue);
|
||||
let config = self.config.clone();
|
||||
let semaphore = Arc::clone(&self.semaphore);
|
||||
let handler: Arc<dyn JobHandler> = Arc::new(handler);
|
||||
let topic_owned = topic.to_string();
|
||||
|
||||
for _ in 0..config.concurrency {
|
||||
let q = Arc::clone(&queue);
|
||||
let sem = Arc::clone(&semaphore);
|
||||
let h = Arc::clone(&handler);
|
||||
let cfg = config.clone();
|
||||
let topic_inner = topic_owned.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
match q.dequeue(&topic_inner, cfg.poll_interval).await {
|
||||
Ok(Some(job)) => {
|
||||
let _permit = sem.clone().acquire_owned().await;
|
||||
let q2 = Arc::clone(&q);
|
||||
let h2 = Arc::clone(&h);
|
||||
let cfg2 = cfg.clone();
|
||||
let t2 = topic_inner.clone();
|
||||
let j2 = job.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let fut = h2.handle(j2.clone());
|
||||
match fut.await {
|
||||
Ok(()) => {
|
||||
let _ = q2.ack(&j2).await;
|
||||
}
|
||||
Err(_) => {
|
||||
if j2.attempt < cfg2.max_retries {
|
||||
let _ = q2.nack(&j2, true).await;
|
||||
} else {
|
||||
let _ = q2.dlq_move(&t2, j2.clone()).await;
|
||||
let _ = q2.nack(&j2, false).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("queue error: {e}");
|
||||
tokio::time::sleep(cfg.poll_interval).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the (capped) exponential backoff delay.
|
||||
pub fn retry_delay(config: &WorkerConfig, attempt: u32) -> Duration {
|
||||
let exponent = attempt as f64;
|
||||
let computed = config.retry_base_delay.as_millis() as f64
|
||||
* config.retry_factor.powf(exponent.max(0.0));
|
||||
let capped = computed.min(config.retry_max_delay.as_millis() as f64);
|
||||
Duration::from_millis(capped as u64)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retry_delay_bounded() {
|
||||
let config = WorkerConfig::default();
|
||||
let d = retry_delay(&config, 0);
|
||||
assert!(d <= config.retry_max_delay);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user