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
//! # Hammerwork
//!
//! A high-performance, database-driven job queue for Rust with comprehensive features for production workloads.
//!
//! ## Features
//!
//! - **Multi-database support**: PostgreSQL and MySQL backends with feature flags
//! - **Job prioritization**: Five priority levels with weighted and strict scheduling algorithms
//! - **Job result storage**: Store and retrieve job execution results with TTL support
//! - **Cron scheduling**: Full cron expression support with timezone awareness
//! - **Rate limiting**: Token bucket rate limiting with configurable burst limits
//! - **Monitoring**: Prometheus metrics and advanced alerting (enabled by default)
//! - **Job timeouts**: Per-job and worker-level timeout configuration
//! - **Statistics**: Comprehensive job statistics and dead job management
//! - **Async/await**: Built on Tokio for high concurrency
//! - **Type-safe**: Leverages Rust's type system for reliability
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use hammerwork::{Job, Worker, WorkerPool, JobQueue, Result, worker::JobHandler, queue::DatabaseQueue};
//! use serde_json::json;
//! use std::sync::Arc;
//!
//! #[tokio::main]
//! async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
//! // Setup database connection (requires PostgreSQL or MySQL)
//! # #[cfg(feature = "postgres")]
//! let pool = sqlx::PgPool::connect("postgresql://localhost/hammerwork").await?;
//! # #[cfg(feature = "mysql")]
//! # let pool = sqlx::MySqlPool::connect("mysql://localhost/hammerwork").await?;
//!
//! let queue = Arc::new(JobQueue::new(pool));
//!
//! // Note: Run database migrations first using `cargo hammerwork migrate`
//! // or use the migration manager programmatically
//!
//! // Create job handler
//! let handler: JobHandler = Arc::new(|job: Job| {
//! Box::pin(async move {
//! println!("Processing job: {:?}", job.payload);
//! // Your job processing logic here
//! Ok(())
//! })
//! });
//!
//! // Create and start worker
//! let worker = Worker::new(queue.clone(), "default".to_string(), handler);
//! let mut pool = WorkerPool::new();
//! pool.add_worker(worker);
//!
//! // Enqueue a job
//! # #[cfg(any(feature = "postgres", feature = "mysql"))]
//! {
//! use hammerwork::queue::DatabaseQueue;
//! let job = Job::new("default".to_string(), json!({"task": "send_email"}));
//! queue.enqueue(job).await?;
//! }
//!
//! // Start processing jobs
//! Ok(pool.start().await?)
//! }
//! ```
//!
//! ## Core Concepts
//!
//! ### Jobs
//!
//! Jobs are the fundamental unit of work in Hammerwork. Each job has:
//! - A unique UUID identifier
//! - A queue name for routing
//! - A JSON payload containing work data
//! - Priority level (Background, Low, Normal, High, Critical)
//! - Optional scheduling and timeout configuration
//!
//! ### Workers
//!
//! Workers poll queues for pending jobs and execute them using provided handlers.
//! Workers support:
//! - Configurable polling intervals and retry logic
//! - Priority-aware job selection with weighted or strict algorithms
//! - Rate limiting and throttling
//! - Automatic timeout detection and handling
//! - Statistics collection and metrics reporting
//!
//! ### Queues
//!
//! The job queue provides a database-backed persistent store for jobs with:
//! - ACID transactions for reliable job state management
//! - Optimized indexes for high-performance job polling
//! - Support for delayed jobs and cron-based recurring jobs
//! - Dead job management and bulk operations
//!
//! ### Event System
//!
//! The event system provides real-time job lifecycle tracking with:
//! - Publish/subscribe pattern for job lifecycle events
//! - Webhook delivery with authentication and retry policies
//! - Streaming integration with Kafka, Kinesis, and Pub/Sub
//! - Flexible event filtering and routing
//! - Multiple serialization formats and partitioning strategies
//!
//! ### Configuration & Operations
//!
//! Comprehensive configuration and operational tooling:
//! - TOML-based configuration with environment variable overrides
//! - CLI tooling for database migrations, job management, and monitoring
//! - Development and production configuration presets
//! - Health checks and graceful shutdown support
//!
//! ## Event System Integration
//!
//! Hammerwork provides a comprehensive event system for integrating with external systems:
//!
//! ```rust,ignore
//! use hammerwork::{
//! events::{EventManager, EventFilter, JobLifecycleEventType},
//! webhooks::{WebhookManager, WebhookConfig, WebhookAuth, HttpMethod},
//! streaming::{StreamManager, StreamConfig, StreamBackend, PartitioningStrategy},
//! config::HammerworkConfig,
//! };
//! use std::sync::Arc;
//! use std::collections::HashMap;
//!
//! #[tokio::main]
//! async fn main() -> hammerwork::Result<()> {
//! // Create event manager
//! let event_manager = Arc::new(EventManager::new_default());
//!
//! // Set up webhooks for job completion notifications
//! let webhook_manager = WebhookManager::new(
//! event_manager.clone(),
//! Default::default()
//! );
//!
//! let webhook = WebhookConfig::new(
//! "completion_hook".to_string(),
//! "https://api.example.com/job-completed".to_string(),
//! )
//! .with_auth(WebhookAuth::Bearer {
//! token: "your-api-token".to_string()
//! })
//! .with_filter(
//! EventFilter::new()
//! .with_event_types(vec![JobLifecycleEventType::Completed])
//! );
//!
//! webhook_manager.add_webhook(webhook).await?;
//!
//! // Set up Kafka streaming for analytics
//! let stream_manager = StreamManager::new_default(event_manager.clone());
//!
//! let kafka_stream = StreamConfig {
//! id: uuid::Uuid::new_v4(),
//! name: "analytics_stream".to_string(),
//! backend: StreamBackend::Kafka {
//! brokers: vec!["localhost:9092".to_string()],
//! topic: "job-events".to_string(),
//! config: HashMap::new(),
//! },
//! filter: EventFilter::new().include_payload(),
//! partitioning: PartitioningStrategy::QueueName,
//! enabled: true,
//! ..Default::default()
//! };
//!
//! stream_manager.add_stream(kafka_stream).await?;
//!
//! Ok(())
//! }
//! ```
//!
//! ## Configuration Management
//!
//! Hammerwork supports comprehensive configuration through TOML files and environment variables:
//!
//! ```rust,ignore
//! use hammerwork::config::HammerworkConfig;
//!
//! // Load from TOML file
//! let config = HammerworkConfig::from_file("hammerwork.toml")?;
//!
//! // Load from environment variables
//! let config = HammerworkConfig::from_env()?;
//!
//! // Create with builder pattern
//! let config = HammerworkConfig::new()
//! .with_database_url("postgresql://localhost/hammerwork")
//! .with_worker_pool_size(8)
//! .with_events_enabled(true);
//!
//! # Ok::<(), hammerwork::HammerworkError>(())
//! ```
//!
//! ## CLI Integration
//!
//! Hammerwork includes a comprehensive CLI for operations:
//!
//! ```bash
//! # Database operations
//! cargo hammerwork migrate --database-url postgresql://localhost/hammerwork
//!
//! # Job management
//! cargo hammerwork job list --queue=email
//! cargo hammerwork job retry --job-id=abc123
//! cargo hammerwork job enqueue --queue=email --payload='{"to":"user@example.com"}'
//!
//! # Queue operations
//! cargo hammerwork queue stats --queue=email
//! cargo hammerwork queue clear --queue=test
//!
//! # Webhook management
//! cargo hammerwork webhook list
//! cargo hammerwork webhook test --webhook-id=abc123
//!
//! # Monitoring
//! cargo hammerwork monitor --tail --queue=email
//! ```
//!
//! ## Feature Flags
//!
//! - `postgres` - Enable PostgreSQL database support
//! - `mysql` - Enable MySQL database support
//! - `metrics` - Enable Prometheus metrics collection (default)
//! - `alerting` - Enable webhook/Slack/email alerting (default)
//! - `webhooks` - Enable webhook and event system features (default)
//! - `encryption` - Enable job payload encryption and PII protection
//! - `tracing` - Enable OpenTelemetry distributed tracing
pub use ;
pub use ;
pub use ;
pub use ;
pub use StreamConfig;
pub use ;
pub use ;
pub use ;
pub use HammerworkError;
pub use ;
pub use ;
pub use JobQueue;
pub use ;
pub use ;
pub use ;
pub use ;
pub use WebhookConfig;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
/// Convenient type alias for Results with [`HammerworkError`] as the error type.
///
/// This is used throughout the crate for consistent error handling.
pub type Result<T> = Result;