Job

Struct Job 

Source
pub struct Job {
    pub id: i32,
    pub payload: String,
    pub status: String,
    pub attempts: i32,
    pub available_at: NaiveDateTime,
    pub created_at: NaiveDateTime,
    pub updated_at: NaiveDateTime,
}
Expand description

Represents a unit of work in the system. Each Job can be in different states (pending, processing, etc.) and may have multiple attempts if it fails.

Corresponds to the jobs table in the database.

§Fields

  • id: Primary key of the job record. Auto-generated by the database.
  • payload: The data associated with this job (e.g., request parameters, message content).
  • status: Current status of the job (e.g., “pending”, “processing”).
  • attempts: Number of times an attempt has been made to run this job.
  • available_at: A timestamp indicating when this job is eligible to be processed.
  • created_at: Timestamp when the job was first created.
  • updated_at: Timestamp of the most recent update to the job record.

Fields§

§id: i32§payload: String§status: String§attempts: i32§available_at: NaiveDateTime§created_at: NaiveDateTime§updated_at: NaiveDateTime

Implementations§

Source§

impl Job

Source

pub fn new(payload: String) -> Self

Creates a new Job instance without inserting it into the database.

This sets default fields (e.g., status = "pending", attempts = 0, created_at = now, and updated_at = now).

§Parameters
  • payload: The data associated with the job.
§Returns

A new Job struct ready to be inserted into the DB or used in-memory.

Source

pub fn with_time(payload: String, _available_at: NaiveDateTime) -> Self

Creates a new Job with a custom available_at time, without inserting into the database.

§Parameters
  • payload: The data associated with the job.
  • _available_at: The desired time when the job becomes processable.
§Returns

A Job struct with default values for other fields.

Source

pub fn create(new_job: NewJob) -> QueryResult<Self>

Inserts a new Job record into the jobs table.

This method will:

  • Acquire a database connection from DB::get_conn.
  • Run a transaction inserting the provided new_job into the jobs table.
  • Fetch and return the newly inserted Job (based on its descending created_at).
§Parameters
  • new_job: The NewJob struct containing the data to be inserted.
§Returns
  • Ok(Job) if the insertion succeeded.
  • Err(diesel::result::Error) if there was a connection or insertion problem.
§Errors
Source

pub fn update(self) -> QueryResult<()>

Updates an existing Job record in the jobs table.

The following fields may be updated:

  • status (copied from self.status)
  • attempts
  • available_at
  • updated_at (set to now)
§Returns
  • Ok(()) if the update succeeded.
  • Err(diesel::result::Error) if there was a connection or update issue.
Source

pub fn complete(&self, _return_value: String) -> QueryResult<()>

Marks a job as completed by inserting a corresponding ProcessedJob record and then removing the Job from the jobs table.

§Parameters
  • _return_value: A string containing any relevant result data or message about the job’s completion.
§Returns
  • Ok(()) if the operation (inserting ProcessedJob and deleting the original Job) succeeded.
  • Err(diesel::result::Error) if any database operation failed.
Source

pub fn fail(&mut self, _reason: &str) -> QueryResult<()>

Marks a job as failed. If the job has remaining retry attempts, it increments the job’s attempts and defers its available_at time by the configured retry interval. Otherwise, it inserts a FailedJob record and removes the job from jobs.

§Parameters
  • _reason: A description of why the job failed.
§Returns
  • Ok(()) if the job was updated or moved to failed jobs.
  • Err(diesel::result::Error) if a database operation fails.
§Behavior
  • If max_retry_attempts (from Config::get_config) is greater than the current number of attempts, the job is set to retry later.
  • Otherwise, a record is inserted into failed_jobs, and the job is deleted from the jobs table.
Source

pub fn fetch_pending_jobs_count() -> QueryResult<i64>

Returns the count of jobs that are currently in pending status and have an available_at time less than or equal to now.

Useful for checking how many pending jobs are ready to be processed.

§Returns
  • Ok(i64) with the count of matching jobs.
  • Err(diesel::result::Error) if there was an issue retrieving data.
Source

pub fn fetch_pending_job() -> QueryResult<Option<Self>>

Fetches the next pending job (the earliest by ID) that is ready to be processed, and marks its status as processing.

§Returns
  • Ok(Some(Job)) if a pending job was found and updated.
  • Ok(None) if no pending job is available.
  • Err(diesel::result::Error) if a database operation fails.
§Transaction

This operation is performed within a transaction to ensure atomicity: retrieving the job and updating its status happen together.

Trait Implementations§

Source§

impl Clone for Job

Source§

fn clone(&self) -> Job

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Job

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Job

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<'insert> Insertable<table> for &'insert Job

Source§

type Values = <(Option<Grouped<Eq<id, <&'insert i32 as AsExpression<<id as Expression>::SqlType>>::Expression>>>, Option<Grouped<Eq<payload, <&'insert String as AsExpression<<payload as Expression>::SqlType>>::Expression>>>, Option<Grouped<Eq<status, <&'insert String as AsExpression<<status as Expression>::SqlType>>::Expression>>>, Option<Grouped<Eq<attempts, <&'insert i32 as AsExpression<<attempts as Expression>::SqlType>>::Expression>>>, Option<Grouped<Eq<available_at, <&'insert NaiveDateTime as AsExpression<<available_at as Expression>::SqlType>>::Expression>>>, Option<Grouped<Eq<created_at, <&'insert NaiveDateTime as AsExpression<<created_at as Expression>::SqlType>>::Expression>>>, Option<Grouped<Eq<updated_at, <&'insert NaiveDateTime as AsExpression<<updated_at as Expression>::SqlType>>::Expression>>>) as Insertable<table>>::Values

The VALUES clause to insert these records Read more
Source§

fn values( self, ) -> <(Option<Eq<id, &'insert i32>>, Option<Eq<payload, &'insert String>>, Option<Eq<status, &'insert String>>, Option<Eq<attempts, &'insert i32>>, Option<Eq<available_at, &'insert NaiveDateTime>>, Option<Eq<created_at, &'insert NaiveDateTime>>, Option<Eq<updated_at, &'insert NaiveDateTime>>) as Insertable<table>>::Values

Construct Self::Values Read more
Source§

fn insert_into(self, table: T) -> InsertStatement<T, Self::Values>
where T: Table, Self: Sized,

Insert self into a given table. Read more
Source§

impl Insertable<table> for Job

Source§

impl<__DB: Backend, __ST0, __ST1, __ST2, __ST3, __ST4, __ST5, __ST6> Queryable<(__ST0, __ST1, __ST2, __ST3, __ST4, __ST5, __ST6), __DB> for Job

Source§

type Row = (i32, String, String, i32, NaiveDateTime, NaiveDateTime, NaiveDateTime)

The Rust type you’d like to map from. Read more
Source§

fn build( row: (i32, String, String, i32, NaiveDateTime, NaiveDateTime, NaiveDateTime), ) -> Result<Self>

Construct an instance of this type
Source§

impl Serialize for Job

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl UndecoratedInsertRecord<table> for Job

Auto Trait Implementations§

§

impl Freeze for Job

§

impl RefUnwindSafe for Job

§

impl Send for Job

§

impl Sync for Job

§

impl Unpin for Job

§

impl UnwindSafe for Job

Blanket Implementations§

Source§

impl<T> AggregateExpressionMethods for T

Source§

fn aggregate_distinct(self) -> Self::Output
where Self: DistinctDsl,

DISTINCT modifier for aggregate functions Read more
Source§

fn aggregate_all(self) -> Self::Output
where Self: AllDsl,

ALL modifier for aggregate functions Read more
Source§

fn aggregate_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add an aggregate function filter Read more
Source§

fn aggregate_order<O>(self, o: O) -> Self::Output
where Self: OrderAggregateDsl<O>,

Add an aggregate function order Read more
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoSql for T

Source§

fn into_sql<T>(self) -> Self::Expression

Convert self to an expression for Diesel’s query builder. Read more
Source§

fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
where &'a Self: AsExpression<T>, T: SqlType + TypedExpressionType,

Convert &self to an expression for Diesel’s query builder. Read more
Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<T, ST, DB> StaticallySizedRow<ST, DB> for T
where ST: SqlTypeOrSelectable + TupleSize, T: Queryable<ST, DB>, DB: Backend,

Source§

const FIELD_COUNT: usize = <ST as crate::util::TupleSize>::SIZE

The number of fields that this type will consume.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WindowExpressionMethods for T

Source§

fn over(self) -> Self::Output
where Self: OverDsl,

Turn a function call into a window function call Read more
Source§

fn window_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add a filter to the current window function Read more
Source§

fn partition_by<E>(self, expr: E) -> Self::Output
where Self: PartitionByDsl<E>,

Add a partition clause to the current window function Read more
Source§

fn window_order<E>(self, expr: E) -> Self::Output
where Self: OrderWindowDsl<E>,

Add a order clause to the current window function Read more
Source§

fn frame_by<E>(self, expr: E) -> Self::Output
where Self: FrameDsl<E>,

Add a frame clause to the current window function Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,