Skip to main content

callback

Attribute Macro callback 

Source
#[callback]
Expand description

Make a Queueable struct a batch or chain Callback.

Place the attribute on the impl block that holds the struct’s async then, catch, or finally methods. The callback is stored under the type’s path, and #[callback(name = "..")] stores it under another name.

A worker calls each method directly, without queueing it, as soon as the batch or chain reaches that method’s point. It calls then once every job of a batch has succeeded, catch when a job fails for good, and finally once every job of a batch has run. then and finally may take the &Batch, and catch may take the &Batch and the job’s &laravel::Error. Each method may also take Inject<T> services and Section<T> config sections, in any order. A chain calls only catch methods that don’t take a &Batch.

The worker never retries a callback. It reports the callback’s error or panic, and the job keeps the outcome it ended with. If the worker stops before it calls a callback, the callback never runs, so dispatch a job from the callback for work that must happen.

When the row of one of the callback’s models is gone, the worker skips the callback. #[callback(fail_when_missing_models)] reports a MissingModels error instead.

use laravel::container::Inject;
use laravel::queue::{Batch, callback};

#[derive(laravel::queue::Queueable)]
pub struct ImportFinished {
    pub import_id: i64,
}

#[callback]
impl ImportFinished {
    async fn then(self, batch: &Batch, imports: Inject<Imports>) -> laravel::Result<()> {
        imports.finish(self.import_id, batch.total_jobs()).await
    }

    async fn catch(self, error: &laravel::Error, imports: Inject<Imports>) -> laravel::Result<()> {
        imports.fail(self.import_id, error.to_string()).await
    }
}

A chain can’t call a catch that takes a &Batch:

ⓘ
#[derive(laravel::queue::Queueable)]
pub struct BatchOnly;

#[laravel::queue::callback]
impl BatchOnly {
    async fn catch(self, batch: &laravel::queue::Batch) {}
}

let chain = laravel::queue::chain(Ship).catch(BatchOnly);

For a callback with a single action, place the attribute on an async function instead. The function’s owned parameters become arguments that you pass when you construct the callback, and the worker supplies services, config sections, &Batch, and &Error when it calls the function. A function that takes &Error works as a catch callback, and any other function works as a then or finally callback.

use laravel::container::Inject;
use laravel::queue::{self, Batch, callback};

#[callback]
async fn finish_import(import_id: i64, batch: &Batch, imports: Inject<Imports>) -> laravel::Result<()> {
    imports.finish(import_id, batch.total_jobs()).await
}

queue::batch([ImportRow]).then(finish_import(import_id)).await?;