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
//! Worker types and configuration
//!
//! This module contains the types used for job execution context and results.
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio_util::sync::CancellationToken;
/// Configuration for worker instances
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerConfig {
/// Unique identifier for the worker
pub worker_id: String,
/// Name of the server where the worker is running
pub server_name: String,
/// Queues that this worker will process
pub queues: Vec<String>,
/// Timeout for job execution
pub job_timeout: Duration,
/// Polling interval for checking new jobs
pub polling_interval: Duration,
}
impl Default for WorkerConfig {
fn default() -> Self {
Self {
worker_id: uuid::Uuid::new_v4().to_string(),
server_name: "default".to_string(),
queues: vec!["default".to_string()],
job_timeout: Duration::minutes(5),
polling_interval: Duration::seconds(1),
}
}
}
impl WorkerConfig {
/// Create a new worker configuration with the specified worker ID
pub fn new(worker_id: impl Into<String>) -> Self {
Self {
worker_id: worker_id.into(),
..Default::default()
}
}
/// Set the server name
pub fn server_name(mut self, server_name: impl Into<String>) -> Self {
self.server_name = server_name.into();
self
}
/// Set the queues this worker will process
pub fn queues(mut self, queues: Vec<String>) -> Self {
self.queues = queues;
self
}
/// Set the job timeout
pub fn job_timeout(mut self, timeout: Duration) -> Self {
self.job_timeout = timeout;
self
}
/// Set the polling interval
pub fn polling_interval(mut self, interval: Duration) -> Self {
self.polling_interval = interval;
self
}
}
/// Context information provided to workers during job execution
#[derive(Debug, Clone)]
pub struct WorkerContext {
/// Worker configuration
pub config: WorkerConfig,
/// When the job execution started
pub started_at: DateTime<Utc>,
/// Metadata for the current execution
pub execution_metadata: HashMap<String, String>,
/// Attempt number (for retries)
pub attempt: u32,
/// Previous exception if this is a retry
pub previous_exception: Option<String>,
/// Cancellation token for cooperative shutdown. A long-running worker
/// impl can race its work against this token to drop out cleanly when
/// the server is asked to stop:
///
/// ```ignore
/// tokio::select! {
/// _ = ctx.cancel.cancelled() => Ok(WorkerResult::retry(
/// "shutting down".into(),
/// None,
/// )),
/// res = do_expensive_work() => res,
/// }
/// ```
///
/// The token is a child of the `BackgroundJobServer` shutdown token, so
/// calling `server.stop()` flips every context in flight.
pub cancel: CancellationToken,
}
impl WorkerContext {
/// Create a new worker context with a detached cancellation token. The
/// server installs a real, shutdown-linked token via
/// `WorkerContext::with_cancel`.
pub fn new(config: WorkerConfig) -> Self {
Self {
config,
started_at: Utc::now(),
execution_metadata: HashMap::new(),
attempt: 1,
previous_exception: None,
cancel: CancellationToken::new(),
}
}
/// Create a retry context from a previous attempt
pub fn retry_from(
config: WorkerConfig,
attempt: u32,
previous_exception: Option<String>,
) -> Self {
Self {
config,
started_at: Utc::now(),
execution_metadata: HashMap::new(),
attempt,
previous_exception,
cancel: CancellationToken::new(),
}
}
/// Override the cancellation token. Builder-style so the server can
/// install the shutdown-linked child token.
pub fn with_cancel(mut self, cancel: CancellationToken) -> Self {
self.cancel = cancel;
self
}
/// Add execution metadata
pub fn add_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.execution_metadata.insert(key.into(), value.into());
}
/// Get execution duration so far
pub fn duration(&self) -> Duration {
Utc::now() - self.started_at
}
/// Check if the job has timed out
pub fn is_timed_out(&self) -> bool {
self.duration() > self.config.job_timeout
}
/// Check if this is a retry attempt
pub fn is_retry(&self) -> bool {
self.attempt > 1
}
}
/// Result of job execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WorkerResult {
/// Job completed successfully
Success {
/// Optional result data
result: Option<String>,
/// Execution duration in milliseconds
duration_ms: u64,
/// Metadata about the execution
metadata: HashMap<String, String>,
},
/// Job failed and should be retried
Retry {
/// Error message
error: String,
/// Stack trace if available
stack_trace: Option<String>,
/// When to retry (None for immediate retry)
retry_at: Option<DateTime<Utc>>,
/// Additional context about the failure
context: HashMap<String, String>,
},
/// Job failed permanently (no retry)
Failure {
/// Error message
error: String,
/// Stack trace if available
stack_trace: Option<String>,
/// Additional context about the failure
context: HashMap<String, String>,
},
}
impl WorkerResult {
/// Create a successful result
pub fn success(result: Option<String>, duration_ms: u64) -> Self {
Self::Success {
result,
duration_ms,
metadata: HashMap::new(),
}
}
/// Create a successful result with metadata
pub fn success_with_metadata(
result: Option<String>,
duration_ms: u64,
metadata: HashMap<String, String>,
) -> Self {
Self::Success {
result,
duration_ms,
metadata,
}
}
/// Create a retry result
pub fn retry(error: String, retry_at: Option<DateTime<Utc>>) -> Self {
Self::Retry {
error,
stack_trace: None,
retry_at,
context: HashMap::new(),
}
}
/// Create a retry result with context
pub fn retry_with_context(
error: String,
retry_at: Option<DateTime<Utc>>,
context: HashMap<String, String>,
) -> Self {
Self::Retry {
error,
stack_trace: None,
retry_at,
context,
}
}
/// Create a permanent failure result
pub fn failure(error: String) -> Self {
Self::Failure {
error,
stack_trace: None,
context: HashMap::new(),
}
}
/// Create a permanent failure result with context
pub fn failure_with_context(error: String, context: HashMap<String, String>) -> Self {
Self::Failure {
error,
stack_trace: None,
context,
}
}
/// Check if the result indicates success
pub fn is_success(&self) -> bool {
matches!(self, WorkerResult::Success { .. })
}
/// Check if the result indicates a retry should be attempted
pub fn should_retry(&self) -> bool {
matches!(self, WorkerResult::Retry { .. })
}
/// Check if the result indicates permanent failure
pub fn is_failure(&self) -> bool {
matches!(self, WorkerResult::Failure { .. })
}
/// Get the error message if this is an error result
pub fn error_message(&self) -> Option<&str> {
match self {
WorkerResult::Retry { error, .. } | WorkerResult::Failure { error, .. } => Some(error),
WorkerResult::Success { .. } => None,
}
}
}