pub struct Job {Show 36 fields
pub id: JobId,
pub queue_name: String,
pub payload: Value,
pub status: JobStatus,
pub attempts: i32,
pub max_attempts: i32,
pub created_at: DateTime<Utc>,
pub scheduled_at: DateTime<Utc>,
pub started_at: Option<DateTime<Utc>>,
pub completed_at: Option<DateTime<Utc>>,
pub failed_at: Option<DateTime<Utc>>,
pub timed_out_at: Option<DateTime<Utc>>,
pub timeout: Option<Duration>,
pub error_message: Option<String>,
pub priority: JobPriority,
pub cron_schedule: Option<String>,
pub next_run_at: Option<DateTime<Utc>>,
pub recurring: bool,
pub timezone: Option<String>,
pub batch_id: Option<BatchId>,
pub result_config: ResultConfig,
pub result_data: Option<Value>,
pub result_stored_at: Option<DateTime<Utc>>,
pub result_expires_at: Option<DateTime<Utc>>,
pub retry_strategy: Option<RetryStrategy>,
pub depends_on: Vec<JobId>,
pub dependents: Vec<JobId>,
pub dependency_status: DependencyStatus,
pub workflow_id: Option<WorkflowId>,
pub workflow_name: Option<String>,
pub trace_id: Option<String>,
pub correlation_id: Option<String>,
pub parent_span_id: Option<String>,
pub span_context: Option<String>,
pub pii_fields: Vec<String>,
pub is_encrypted: bool,
}Expand description
A unit of work to be processed by the job queue.
Jobs are the fundamental building blocks of the Hammerwork system. Each job contains:
- A unique identifier for tracking
- Queue name for routing to appropriate workers
- JSON payload containing the work data
- Scheduling and retry configuration
- Priority level for queue ordering
- Optional cron schedule for recurring jobs
- Timeout configuration for automatic termination
§Examples
§Basic Job Creation
use hammerwork::Job;
use serde_json::json;
let job = Job::new("email_queue".to_string(), json!({
"to": "user@example.com",
"subject": "Welcome!",
"body": "Thanks for signing up"
}));
assert_eq!(job.queue_name, "email_queue");
assert_eq!(job.max_attempts, 3); // Default retry attempts§Job with Priority and Timeout
use hammerwork::{Job, JobPriority};
use serde_json::json;
use std::time::Duration;
let job = Job::new("processing".to_string(), json!({"data": "important"}))
.as_high_priority()
.with_timeout(Duration::from_secs(300))
.with_max_attempts(5);
assert_eq!(job.priority, JobPriority::High);
assert_eq!(job.timeout, Some(Duration::from_secs(300)));
assert_eq!(job.max_attempts, 5);§Delayed Job
use hammerwork::Job;
use serde_json::json;
use chrono::Duration;
let job = Job::with_delay(
"notifications".to_string(),
json!({"message": "Reminder"}),
Duration::hours(1)
);
// Job will be scheduled to run 1 hour from now
assert!(job.scheduled_at > job.created_at);Fields§
§id: JobIdUnique identifier for this job.
queue_name: StringName of the queue this job belongs to.
payload: ValueJSON payload containing the work data.
status: JobStatusCurrent status of the job.
attempts: i32Number of times this job has been attempted.
max_attempts: i32Maximum number of attempts before marking the job as dead.
created_at: DateTime<Utc>When the job was created.
scheduled_at: DateTime<Utc>When the job should be processed (may be in the future for delayed jobs).
started_at: Option<DateTime<Utc>>When the job started processing (if it has started).
completed_at: Option<DateTime<Utc>>When the job completed successfully (if it completed).
failed_at: Option<DateTime<Utc>>When the job failed permanently (if it failed).
timed_out_at: Option<DateTime<Utc>>When the job timed out (if it timed out).
timeout: Option<Duration>Maximum duration the job is allowed to run before timing out.
error_message: Option<String>Error message if the job failed.
priority: JobPriorityPriority level for queue ordering.
cron_schedule: Option<String>Cron expression for recurring jobs.
next_run_at: Option<DateTime<Utc>>Next scheduled execution time for recurring jobs.
recurring: boolWhether this is a recurring job.
timezone: Option<String>Timezone for cron calculations.
batch_id: Option<BatchId>Batch ID if this job is part of a batch operation.
result_config: ResultConfigConfiguration for how job results should be stored.
result_data: Option<Value>The actual result data from job execution (if stored).
result_stored_at: Option<DateTime<Utc>>When the result was stored (if applicable).
result_expires_at: Option<DateTime<Utc>>When the stored result will expire (if applicable).
retry_strategy: Option<RetryStrategy>Retry strategy for this job (overrides worker default if specified).
depends_on: Vec<JobId>Job IDs this job depends on (must complete before this job can run).
dependents: Vec<JobId>Job IDs that depend on this job (cached for performance).
dependency_status: DependencyStatusStatus of dependency resolution for this job.
workflow_id: Option<WorkflowId>ID of the workflow this job belongs to (if any).
workflow_name: Option<String>Name of the workflow this job belongs to (if any).
trace_id: Option<String>Distributed trace identifier for cross-service tracing.
correlation_id: Option<String>Business correlation identifier for grouping related operations.
parent_span_id: Option<String>Parent span identifier for hierarchical tracing.
span_context: Option<String>Serialized span context for trace propagation.
pii_fields: Vec<String>List of field names that contain PII and should be encrypted.
is_encrypted: boolWhether the payload is currently encrypted.
Implementations§
Source§impl Job
impl Job
Sourcepub fn new(queue_name: String, payload: Value) -> Self
pub fn new(queue_name: String, payload: Value) -> Self
Creates a new job with default settings.
The job will be created with:
- A unique UUID identifier
- Normal priority level
- 3 maximum retry attempts
- Scheduled to run immediately
- Pending status
§Arguments
queue_name- The name of the queue this job should be processed bypayload- JSON data containing the work to be performed
§Examples
use hammerwork::{Job, JobStatus, JobPriority};
use serde_json::json;
let job = Job::new("email_queue".to_string(), json!({
"to": "user@example.com",
"subject": "Welcome!",
"template": "welcome"
}));
assert_eq!(job.queue_name, "email_queue");
assert_eq!(job.status, JobStatus::Pending);
assert_eq!(job.priority, JobPriority::Normal);
assert_eq!(job.max_attempts, 3);
assert_eq!(job.attempts, 0);
assert!(!job.is_recurring());Sourcepub fn with_delay(queue_name: String, payload: Value, delay: Duration) -> Self
pub fn with_delay(queue_name: String, payload: Value, delay: Duration) -> Self
Creates a new job scheduled to run after a delay.
This is useful for implementing delayed notifications, retries with backoff, or any work that should be performed at a specific time in the future.
§Arguments
queue_name- The name of the queue this job should be processed bypayload- JSON data containing the work to be performeddelay- How long to wait before the job becomes eligible for processing
§Examples
use hammerwork::Job;
use serde_json::json;
use chrono::Duration;
// Send a reminder email in 24 hours
let job = Job::with_delay(
"email_queue".to_string(),
json!({
"to": "user@example.com",
"subject": "Don't forget to complete your profile",
"template": "reminder"
}),
Duration::hours(24)
);
// Job will be scheduled 24 hours from now
assert!(job.scheduled_at > job.created_at);
let delay_diff = job.scheduled_at - job.created_at;
assert_eq!(delay_diff, Duration::hours(24));Sourcepub fn with_max_attempts(self, max_attempts: i32) -> Self
pub fn with_max_attempts(self, max_attempts: i32) -> Self
Sets the maximum number of retry attempts for this job.
When a job fails, it will be retried up to this many times before being marked as dead. The default is 3 attempts.
§Arguments
max_attempts- Maximum number of attempts (including the initial attempt)
§Examples
use hammerwork::Job;
use serde_json::json;
// Critical job that should be retried many times
let job = Job::new("critical_task".to_string(), json!({"task": "important"}))
.with_max_attempts(10);
assert_eq!(job.max_attempts, 10);Sourcepub fn with_timeout(self, timeout: Duration) -> Self
pub fn with_timeout(self, timeout: Duration) -> Self
Sets a timeout duration for this job.
If the job takes longer than this duration to complete, it will be automatically terminated and marked as timed out. Job-level timeouts take precedence over worker-level default timeouts.
The PostgreSQL and MySQL backends store the timeout in whole seconds, rounding a
fractional timeout up (200ms is stored as one second). Duration::ZERO means no
job-level timeout, so the worker’s default applies.
§Arguments
timeout- Maximum duration the job is allowed to run
§Examples
use hammerwork::Job;
use serde_json::json;
use std::time::Duration;
// API call that should timeout after 30 seconds
let job = Job::new("api_call".to_string(), json!({"url": "https://api.example.com"}))
.with_timeout(Duration::from_secs(30));
assert_eq!(job.timeout, Some(Duration::from_secs(30)));Sourcepub fn with_priority(self, priority: JobPriority) -> Self
pub fn with_priority(self, priority: JobPriority) -> Self
Sets the priority level for this job.
Priority affects the order in which jobs are processed by workers. Higher priority jobs are generally processed before lower priority ones.
§Arguments
priority- The priority level to assign to this job
§Examples
use hammerwork::{Job, JobPriority};
use serde_json::json;
let job = Job::new("task".to_string(), json!({"data": "test"}))
.with_priority(JobPriority::High);
assert_eq!(job.priority, JobPriority::High);
assert!(job.is_high_priority());Sourcepub fn as_critical(self) -> Self
pub fn as_critical(self) -> Self
Sets the job as critical priority (highest priority).
Critical jobs are processed with the highest priority and should be used sparingly for truly urgent work like system alerts or emergency responses.
§Examples
use hammerwork::{Job, JobPriority};
use serde_json::json;
let job = Job::new("system_alert".to_string(), json!({"alert": "system_down"}))
.as_critical();
assert_eq!(job.priority, JobPriority::Critical);
assert!(job.is_critical());Sourcepub fn as_high_priority(self) -> Self
pub fn as_high_priority(self) -> Self
Sets the job as high priority.
High priority jobs are processed before normal priority jobs but after critical jobs. Suitable for user-facing operations or important business logic.
§Examples
use hammerwork::{Job, JobPriority};
use serde_json::json;
let job = Job::new("user_notification".to_string(), json!({"user_id": 123}))
.as_high_priority();
assert_eq!(job.priority, JobPriority::High);
assert!(job.is_high_priority());Sourcepub fn as_low_priority(self) -> Self
pub fn as_low_priority(self) -> Self
Sets the job as low priority.
Low priority jobs are processed after normal priority jobs but before background jobs. Suitable for analytics, reporting, or non-urgent tasks.
§Examples
use hammerwork::{Job, JobPriority};
use serde_json::json;
let job = Job::new("analytics".to_string(), json!({"event": "page_view"}))
.as_low_priority();
assert_eq!(job.priority, JobPriority::Low);
assert!(job.is_low_priority());Sourcepub fn as_background(self) -> Self
pub fn as_background(self) -> Self
Sets the job as background priority (lowest priority).
Background jobs are processed only when no higher priority jobs are available. Suitable for cleanup tasks, maintenance, or work that can wait indefinitely.
§Examples
use hammerwork::{Job, JobPriority};
use serde_json::json;
let job = Job::new("cleanup".to_string(), json!({"type": "temp_files"}))
.as_background();
assert_eq!(job.priority, JobPriority::Background);
assert!(job.is_background());Sourcepub fn with_retry_strategy(self, strategy: RetryStrategy) -> Self
pub fn with_retry_strategy(self, strategy: RetryStrategy) -> Self
Sets a custom retry strategy for this job.
The retry strategy determines how long to wait between retry attempts when the job fails. This overrides any default retry strategy configured on the worker.
§Arguments
strategy- The retry strategy to use for this job
§Examples
use hammerwork::{Job, retry::RetryStrategy};
use serde_json::json;
use std::time::Duration;
// Use exponential backoff for API calls
let job = Job::new("api_call".to_string(), json!({"url": "https://api.example.com"}))
.with_retry_strategy(RetryStrategy::exponential(
Duration::from_secs(1),
2.0,
Some(Duration::from_secs(10 * 60))
));Sourcepub fn with_exponential_backoff(
self,
base: Duration,
multiplier: f64,
max_delay: Duration,
) -> Self
pub fn with_exponential_backoff( self, base: Duration, multiplier: f64, max_delay: Duration, ) -> Self
Sets exponential backoff retry strategy for this job.
This is a convenience method for the most common retry pattern. Each retry attempt waits exponentially longer than the previous one.
§Arguments
base- Base delay for the first retry attemptmultiplier- Exponential growth multiplier (typically 2.0)max_delay- Maximum delay to cap exponential growth
§Examples
use hammerwork::Job;
use serde_json::json;
use std::time::Duration;
// Exponential backoff: 1s, 2s, 4s, 8s, 16s... (capped at 10 minutes)
let job = Job::new("network_request".to_string(), json!({"url": "https://example.com"}))
.with_exponential_backoff(
Duration::from_secs(1),
2.0,
Duration::from_secs(10 * 60)
);Sourcepub fn with_linear_backoff(
self,
base: Duration,
increment: Duration,
max_delay: Option<Duration>,
) -> Self
pub fn with_linear_backoff( self, base: Duration, increment: Duration, max_delay: Option<Duration>, ) -> Self
Sets linear backoff retry strategy for this job.
Each retry attempt waits longer than the previous by a fixed increment.
§Arguments
base- Base delay for the first retry attemptincrement- Amount to add for each subsequent attemptmax_delay- Optional maximum delay to cap growth
§Examples
use hammerwork::Job;
use serde_json::json;
use std::time::Duration;
// Linear backoff: 10s, 20s, 30s, 40s... (capped at 2 minutes)
let job = Job::new("database_operation".to_string(), json!({"query": "SELECT ..."}))
.with_linear_backoff(
Duration::from_secs(10),
Duration::from_secs(10),
Some(Duration::from_secs(2 * 60))
);Sourcepub fn with_fibonacci_backoff(
self,
base: Duration,
max_delay: Option<Duration>,
) -> Self
pub fn with_fibonacci_backoff( self, base: Duration, max_delay: Option<Duration>, ) -> Self
Sets Fibonacci sequence backoff retry strategy for this job.
Each retry waits according to the Fibonacci sequence multiplied by the base delay.
§Arguments
base- Base delay multiplied by Fibonacci numbersmax_delay- Optional maximum delay to cap growth
§Examples
use hammerwork::Job;
use serde_json::json;
use std::time::Duration;
// Fibonacci backoff: 2s, 2s, 4s, 6s, 10s, 16s, 26s...
let job = Job::new("file_processing".to_string(), json!({"file": "data.csv"}))
.with_fibonacci_backoff(
Duration::from_secs(2),
Some(Duration::from_secs(5 * 60))
);Sourcepub fn with_cron_schedule(
queue_name: String,
payload: Value,
cron_schedule: CronSchedule,
) -> Result<Self, CronError>
pub fn with_cron_schedule( queue_name: String, payload: Value, cron_schedule: CronSchedule, ) -> Result<Self, CronError>
Create a recurring job with a cron schedule
Sourcepub fn with_cron(self, cron_schedule: CronSchedule) -> Result<Self, CronError>
pub fn with_cron(self, cron_schedule: CronSchedule) -> Result<Self, CronError>
Add a cron schedule to an existing job
Sourcepub fn with_scheduled_at(self, scheduled_at: DateTime<Utc>) -> Self
pub fn with_scheduled_at(self, scheduled_at: DateTime<Utc>) -> Self
Schedule the job to run at scheduled_at instead of as soon as possible.
§Examples
use chrono::{Duration, Utc};
use hammerwork::Job;
use serde_json::json;
let run_at = Utc::now() + Duration::days(7);
let job = Job::new("reports".to_string(), json!({})).with_scheduled_at(run_at);
assert_eq!(job.scheduled_at, run_at);Sourcepub fn as_recurring(self) -> Self
pub fn as_recurring(self) -> Self
Set the job as recurring without a cron schedule (for manual rescheduling)
Sourcepub fn with_timezone(self, timezone: String) -> Self
pub fn with_timezone(self, timezone: String) -> Self
Set the timezone for the job
Sourcepub fn with_result_storage(self, storage: ResultStorage) -> Self
pub fn with_result_storage(self, storage: ResultStorage) -> Self
Configure how job results should be stored.
This allows jobs to store their results for later retrieval by other systems. Results can be stored in the database, memory, or not stored at all.
§Arguments
storage- The storage backend to use for results
§Examples
use hammerwork::{Job, job::ResultStorage};
use serde_json::json;
let job = Job::new("data_processing".to_string(), json!({"input": "data"}))
.with_result_storage(ResultStorage::Database);Sourcepub fn with_result_ttl(self, ttl: Duration) -> Self
pub fn with_result_ttl(self, ttl: Duration) -> Self
Set the time-to-live (TTL) for stored job results.
After this duration elapses, the result will be eligible for cleanup. This is useful for managing storage costs and compliance requirements.
§Arguments
ttl- How long to keep results before they expire
§Examples
use hammerwork::Job;
use serde_json::json;
use std::time::Duration;
let job = Job::new("report_generation".to_string(), json!({"type": "monthly"}))
.with_result_ttl(Duration::from_secs(7 * 24 * 60 * 60)); // 7 daysSourcepub fn with_result_config(self, config: ResultConfig) -> Self
pub fn with_result_config(self, config: ResultConfig) -> Self
Configure complete result storage settings.
This provides full control over how results are stored and managed.
§Arguments
config- Complete result configuration
§Examples
use hammerwork::{Job, job::{ResultConfig, ResultStorage}};
use serde_json::json;
use std::time::Duration;
let config = ResultConfig::new(ResultStorage::Database)
.with_ttl(Duration::from_secs(3600))
.with_max_size(1024 * 1024); // 1MB
let job = Job::new("large_processing".to_string(), json!({"data": "..."}))
.with_result_config(config);Sourcepub fn has_result_storage(&self) -> bool
pub fn has_result_storage(&self) -> bool
Check if the job has result storage configured.
Returns true if the job is configured to store results in any backend
other than ResultStorage::None.
§Examples
use hammerwork::{Job, job::ResultStorage};
use serde_json::json;
let job1 = Job::new("test".to_string(), json!({}));
assert!(!job1.has_result_storage());
let job2 = Job::new("test".to_string(), json!({}))
.with_result_storage(ResultStorage::Database);
assert!(job2.has_result_storage());Sourcepub fn has_result_data(&self) -> bool
pub fn has_result_data(&self) -> bool
Check if the job has stored result data.
Returns true if the job has result data available for retrieval.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({}));
assert!(!job.has_result_data());Sourcepub fn is_timed_out(&self) -> bool
pub fn is_timed_out(&self) -> bool
Check if the job has timed out
Sourcepub fn is_critical(&self) -> bool
pub fn is_critical(&self) -> bool
Check if the job is critical priority
Sourcepub fn is_high_priority(&self) -> bool
pub fn is_high_priority(&self) -> bool
Check if the job is high priority
Sourcepub fn is_normal_priority(&self) -> bool
pub fn is_normal_priority(&self) -> bool
Check if the job is normal priority
Sourcepub fn is_low_priority(&self) -> bool
pub fn is_low_priority(&self) -> bool
Check if the job is low priority
Sourcepub fn is_background(&self) -> bool
pub fn is_background(&self) -> bool
Check if the job is background priority
Sourcepub fn priority_value(&self) -> i32
pub fn priority_value(&self) -> i32
Get the priority level as a numeric value for comparison
Sourcepub fn has_exhausted_retries(&self) -> bool
pub fn has_exhausted_retries(&self) -> bool
Check if the job has exhausted all retry attempts
Sourcepub fn should_timeout(&self) -> bool
pub fn should_timeout(&self) -> bool
Checks if the job should timeout based on its start time and timeout setting.
Returns true if the job has been running longer than its configured timeout
duration. Returns false if the job hasn’t started yet, has no timeout set,
or is still within the timeout window.
§Examples
use hammerwork::Job;
use serde_json::json;
use std::time::Duration;
use chrono::Utc;
let mut job = Job::new("test".to_string(), json!({"data": "test"}))
.with_timeout(Duration::from_secs(30));
// Job hasn't started yet, so it shouldn't timeout
assert!(!job.should_timeout());
// Simulate job starting 45 seconds ago
job.started_at = Some(Utc::now() - chrono::Duration::seconds(45));
// Job should timeout since 45s > 30s timeout
assert!(job.should_timeout());Sourcepub fn age(&self) -> Duration
pub fn age(&self) -> Duration
Gets the duration since the job was created.
This is useful for monitoring how long jobs have been in the system and identifying jobs that may be stuck or delayed.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({"data": "test"}));
let age = job.age();
// Job was just created, so age should be very small
assert!(age.num_milliseconds() >= 0);
assert!(age.num_seconds() < 1);Sourcepub fn processing_duration(&self) -> Option<Duration>
pub fn processing_duration(&self) -> Option<Duration>
Gets the processing duration if the job has started.
Returns the time between when the job started and when it finished
(completed, failed, or timed out). If the job is still running,
returns the time since it started. Returns None if the job hasn’t
started yet.
§Examples
use hammerwork::Job;
use serde_json::json;
use chrono::Utc;
let mut job = Job::new("test".to_string(), json!({"data": "test"}));
// Job hasn't started, so no processing duration
assert!(job.processing_duration().is_none());
// Simulate job that started and completed
let start_time = Utc::now() - chrono::Duration::seconds(10);
let end_time = start_time + chrono::Duration::seconds(5);
job.started_at = Some(start_time);
job.completed_at = Some(end_time);
let duration = job.processing_duration().unwrap();
assert_eq!(duration.num_seconds(), 5);Sourcepub fn is_recurring(&self) -> bool
pub fn is_recurring(&self) -> bool
Check if this is a recurring job
Sourcepub fn has_cron_schedule(&self) -> bool
pub fn has_cron_schedule(&self) -> bool
Check if this job has a cron schedule
Sourcepub fn get_cron_schedule(&self) -> Option<Result<CronSchedule, CronError>>
pub fn get_cron_schedule(&self) -> Option<Result<CronSchedule, CronError>>
Get the cron schedule if it exists
Sourcepub fn calculate_next_run(&self) -> Option<DateTime<Utc>>
pub fn calculate_next_run(&self) -> Option<DateTime<Utc>>
Calculate the next run time for a recurring job
Sourcepub fn prepare_for_next_run(&mut self) -> Option<DateTime<Utc>>
pub fn prepare_for_next_run(&mut self) -> Option<DateTime<Utc>>
Update the job for the next run (for recurring jobs)
Sourcepub fn depends_on(self, job_id: &JobId) -> Self
pub fn depends_on(self, job_id: &JobId) -> Self
Adds a dependency on another job.
This job will not be executed until the specified job completes successfully. If the dependency job fails, this job’s dependency status will be set to Failed.
§Arguments
job_id- The ID of the job this job should depend on
§Examples
use hammerwork::Job;
use serde_json::json;
let job1 = Job::new("step1".to_string(), json!({"data": "step1"}));
let job2 = Job::new("step2".to_string(), json!({"data": "step2"}))
.depends_on(&job1.id);
assert!(job2.has_dependencies());Sourcepub fn depends_on_jobs(self, job_ids: &[JobId]) -> Self
pub fn depends_on_jobs(self, job_ids: &[JobId]) -> Self
Adds multiple dependencies on other jobs.
This job will not be executed until all specified jobs complete successfully.
§Arguments
job_ids- The IDs of the jobs this job should depend on
§Examples
use hammerwork::Job;
use serde_json::json;
let job1 = Job::new("step1".to_string(), json!({}));
let job2 = Job::new("step2".to_string(), json!({}));
let final_job = Job::new("final".to_string(), json!({}))
.depends_on_jobs(&[job1.id, job2.id]);
assert_eq!(final_job.depends_on.len(), 2);Sourcepub fn with_workflow(
self,
workflow_id: WorkflowId,
workflow_name: impl Into<String>,
) -> Self
pub fn with_workflow( self, workflow_id: WorkflowId, workflow_name: impl Into<String>, ) -> Self
Sets the workflow this job belongs to.
§Arguments
workflow_id- The ID of the workflowworkflow_name- The name of the workflow
§Examples
use hammerwork::Job;
use serde_json::json;
use uuid::Uuid;
let workflow_id = Uuid::new_v4();
let job = Job::new("test".to_string(), json!({}))
.with_workflow(workflow_id, "data_pipeline");
assert_eq!(job.workflow_id, Some(workflow_id));
assert_eq!(job.workflow_name, Some("data_pipeline".to_string()));Sourcepub fn has_dependencies(&self) -> bool
pub fn has_dependencies(&self) -> bool
Checks if this job has any dependencies.
§Examples
use hammerwork::Job;
use serde_json::json;
let job1 = Job::new("independent".to_string(), json!({}));
assert!(!job1.has_dependencies());
let job2 = Job::new("dependent".to_string(), json!({}))
.depends_on(&job1.id);
assert!(job2.has_dependencies());Sourcepub fn is_part_of_workflow(&self) -> bool
pub fn is_part_of_workflow(&self) -> bool
Checks if this job is part of a workflow.
§Examples
use hammerwork::Job;
use serde_json::json;
use uuid::Uuid;
let job1 = Job::new("standalone".to_string(), json!({}));
assert!(!job1.is_part_of_workflow());
let job2 = Job::new("workflow_job".to_string(), json!({}))
.with_workflow(Uuid::new_v4(), "test_workflow");
assert!(job2.is_part_of_workflow());Sourcepub fn dependencies_satisfied(&self) -> bool
pub fn dependencies_satisfied(&self) -> bool
Checks if all dependencies for this job are satisfied.
§Examples
use hammerwork::Job;
use serde_json::json;
let job1 = Job::new("independent".to_string(), json!({}));
assert!(job1.dependencies_satisfied());
let job2 = Job::new("dependent".to_string(), json!({}))
.depends_on(&job1.id);
assert!(!job2.dependencies_satisfied()); // Dependencies not satisfied yetSourcepub fn dependencies_failed(&self) -> bool
pub fn dependencies_failed(&self) -> bool
Checks if any dependencies for this job have failed.
§Examples
use hammerwork::Job;
use serde_json::json;
let mut job = Job::new("test".to_string(), json!({}));
job.dependency_status = hammerwork::workflow::DependencyStatus::Failed;
assert!(job.dependencies_failed());Sourcepub fn dependency_count(&self) -> usize
pub fn dependency_count(&self) -> usize
Gets the number of dependencies for this job.
§Examples
use hammerwork::Job;
use serde_json::json;
use uuid::Uuid;
let job = Job::new("test".to_string(), json!({}))
.depends_on_jobs(&[Uuid::new_v4(), Uuid::new_v4()]);
assert_eq!(job.dependency_count(), 2);Sourcepub fn dependent_count(&self) -> usize
pub fn dependent_count(&self) -> usize
Gets the number of jobs that depend on this job.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({}));
assert_eq!(job.dependent_count(), 0);Sourcepub fn with_trace_id(self, trace_id: impl Into<String>) -> Self
pub fn with_trace_id(self, trace_id: impl Into<String>) -> Self
Sets the distributed trace identifier for this job.
The trace ID is used to track jobs across service boundaries in distributed systems. All related operations should share the same trace ID.
§Arguments
trace_id- The distributed trace identifier
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("service_call".to_string(), json!({"data": "test"}))
.with_trace_id("trace-123-456");
assert_eq!(job.trace_id, Some("trace-123-456".to_string()));Sourcepub fn with_correlation_id(self, correlation_id: impl Into<String>) -> Self
pub fn with_correlation_id(self, correlation_id: impl Into<String>) -> Self
Sets the business correlation identifier for this job.
The correlation ID groups related business operations together, even if they span multiple traces or services. Use this to correlate jobs that process the same business entity or workflow.
§Arguments
correlation_id- The business correlation identifier
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("order_processing".to_string(), json!({"order_id": 12345}))
.with_correlation_id("order-12345");
assert_eq!(job.correlation_id, Some("order-12345".to_string()));Sourcepub fn with_parent_span_id(self, parent_span_id: impl Into<String>) -> Self
pub fn with_parent_span_id(self, parent_span_id: impl Into<String>) -> Self
Sets the parent span identifier for hierarchical tracing.
Use this to create a parent-child relationship between spans, enabling hierarchical trace visualization in tracing systems.
§Arguments
parent_span_id- The parent span identifier
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("child_task".to_string(), json!({"data": "test"}))
.with_parent_span_id("span-parent-123");
assert_eq!(job.parent_span_id, Some("span-parent-123".to_string()));Sourcepub fn with_span_context(self, span_context: impl Into<String>) -> Self
pub fn with_span_context(self, span_context: impl Into<String>) -> Self
Sets the serialized span context for trace propagation.
The span context contains all the information needed to propagate tracing across service boundaries. This is typically a serialized representation of the current span context.
§Arguments
span_context- The serialized span context
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("distributed_task".to_string(), json!({"data": "test"}))
.with_span_context("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
assert_eq!(job.span_context, Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01".to_string()));Sourcepub fn with_tracing_id(self, id: impl Into<String>) -> Self
pub fn with_tracing_id(self, id: impl Into<String>) -> Self
Convenience method to set both trace ID and correlation ID.
This is useful when the trace ID and correlation ID are the same, which is common in simple tracing scenarios.
§Arguments
id- The identifier to use for both trace and correlation
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("task".to_string(), json!({"data": "test"}))
.with_tracing_id("unified-id-123");
assert_eq!(job.trace_id, Some("unified-id-123".to_string()));
assert_eq!(job.correlation_id, Some("unified-id-123".to_string()));Sourcepub fn has_tracing_info(&self) -> bool
pub fn has_tracing_info(&self) -> bool
Checks if this job has any tracing information.
Returns true if any of the tracing fields (trace_id, correlation_id,
parent_span_id, or span_context) are set.
§Examples
use hammerwork::Job;
use serde_json::json;
let job1 = Job::new("untraced".to_string(), json!({}));
assert!(!job1.has_tracing_info());
let job2 = Job::new("traced".to_string(), json!({}))
.with_trace_id("trace-123");
assert!(job2.has_tracing_info());Sourcepub fn get_trace_id(&self) -> Option<&str>
pub fn get_trace_id(&self) -> Option<&str>
Gets the trace ID if available.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({}))
.with_trace_id("trace-123");
assert_eq!(job.get_trace_id(), Some("trace-123"));Sourcepub fn get_correlation_id(&self) -> Option<&str>
pub fn get_correlation_id(&self) -> Option<&str>
Gets the correlation ID if available.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({}))
.with_correlation_id("corr-456");
assert_eq!(job.get_correlation_id(), Some("corr-456"));Sourcepub fn with_pii_fields(self, pii_fields: Vec<impl Into<String>>) -> Self
pub fn with_pii_fields(self, pii_fields: Vec<impl Into<String>>) -> Self
Sets the PII fields for this job.
PII (Personally Identifiable Information) fields are tracked separately for compliance and auditing purposes. When encryption is enabled, these fields receive special handling.
§Arguments
pii_fields- List of field names that contain PII
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("user_processing".to_string(), json!({
"user_id": "123",
"email": "user@example.com",
"ssn": "123-45-6789"
}))
.with_pii_fields(vec!["email", "ssn"]);
assert_eq!(job.pii_fields.len(), 2);
assert!(job.has_pii_fields());Sourcepub fn has_encryption(&self) -> bool
pub fn has_encryption(&self) -> bool
Checks if this job has encryption configured.
§Examples
use hammerwork::Job;
use serde_json::json;
let job1 = Job::new("plain".to_string(), json!({}));
assert!(!job1.has_encryption());
#[cfg(feature = "encryption")]
{
use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
let job2 = Job::new("encrypted".to_string(), json!({}))
.with_encryption(EncryptionConfig::new(EncryptionAlgorithm::AES256GCM));
assert!(job2.has_encryption());
}Sourcepub fn has_pii_fields(&self) -> bool
pub fn has_pii_fields(&self) -> bool
Checks if this job has PII fields configured.
§Examples
use hammerwork::Job;
use serde_json::json;
let job1 = Job::new("normal".to_string(), json!({}));
assert!(!job1.has_pii_fields());
let job2 = Job::new("with_pii".to_string(), json!({}))
.with_pii_fields(vec!["email"]);
assert!(job2.has_pii_fields());Sourcepub fn is_payload_encrypted(&self) -> bool
pub fn is_payload_encrypted(&self) -> bool
Checks if this job’s payload is currently encrypted.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({}));
assert!(!job.is_payload_encrypted());Sourcepub fn get_pii_fields(&self) -> &[String]
pub fn get_pii_fields(&self) -> &[String]
Gets the list of PII fields for this job.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({}))
.with_pii_fields(vec!["email", "ssn"]);
let pii_fields = job.get_pii_fields();
assert_eq!(pii_fields.len(), 2);
assert!(pii_fields.contains(&"email".to_string()));Sourcepub fn should_cleanup_encrypted_data(&self) -> bool
pub fn should_cleanup_encrypted_data(&self) -> bool
Checks if this job should have its encrypted data cleaned up now.
This method checks the retention policy and encrypted payload metadata to determine if the data has exceeded its retention period.
§Examples
use hammerwork::Job;
use serde_json::json;
let job = Job::new("test".to_string(), json!({}));
assert!(!job.should_cleanup_encrypted_data());Trait Implementations§
Source§impl<'de> Deserialize<'de> for Job
impl<'de> Deserialize<'de> for Job
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl JobSpawnExt for Job
impl JobSpawnExt for Job
Source§fn with_spawn_config(self, config: SpawnConfig) -> Result<Self>
fn with_spawn_config(self, config: SpawnConfig) -> Result<Self>
Source§fn with_spawning(self) -> Result<Self>
fn with_spawning(self) -> Result<Self>
Auto Trait Implementations§
impl !RefUnwindSafe for Job
impl !UnwindSafe for Job
impl Freeze for Job
impl Send for Job
impl Sync for Job
impl Unpin for Job
impl UnsafeUnpin for Job
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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