# Queues

- [Introduction](#introduction)
    - [Connections and queues](#connections-and-queues)
- [Configuration](#configuration)
    - [Drivers](#drivers)
    - [The jobs table](#the-jobs-table)
    - [Redis](#redis)
    - [Amazon SQS](#amazon-sqs)
    - [Laravel Cloud](#laravel-cloud)
    - [Defining your own connections](#defining-your-own-connections)
- [Creating jobs](#creating-jobs)
    - [Models in jobs](#models-in-jobs)
    - [Job names](#job-names)
- [Dispatching jobs](#dispatching-jobs)
    - [Connections, queues, and delays](#connections-queues-and-delays)
    - [Database transactions](#database-transactions)
    - [Synchronous dispatching](#synchronous-dispatching)
    - [Dispatching jobs in bulk](#dispatching-jobs-in-bulk)
    - [Debounced jobs](#debounced-jobs)
- [Retries and timeouts](#job-options)
    - [Limiting errors](#limiting-errors)
- [Inside a job](#inside-a-job)
    - [Releasing, deleting, and failing](#releasing-deleting-and-failing)
    - [Handling failures](#handling-failures)
- [Job middleware](#job-middleware)
    - [Defining middleware](#defining-middleware)
    - [Assigning middleware to jobs](#assigning-middleware-to-jobs)
- [Job chains](#job-chains)
    - [Adding jobs to the chain](#adding-jobs-to-the-chain)
    - [Chain failures](#chain-failures)
- [Job batches](#job-batches)
    - [The batches tables](#the-batches-tables)
    - [Batch callbacks](#batch-callbacks)
    - [Chains and batches](#chains-and-batches)
    - [Adding jobs and cancelling batches](#adding-jobs-and-cancelling-batches)
    - [Inspecting batches](#inspecting-batches)
    - [Batch failures](#batch-failures)
    - [Pruning batches](#pruning-batches)
- [Running the worker](#running-the-worker)
    - [Worker options](#worker-options)
    - [Worker concurrency](#worker-concurrency)
    - [Running workers in production](#running-workers-in-production)
    - [Running workers on Laravel Cloud](#laravel-cloud-workers)
    - [Restarting workers](#restarting-workers)
    - [Pausing queues](#pausing-queues)
    - [Counting jobs](#counting-jobs)
- [Failed jobs](#failed-jobs)
- [Events](#events)
- [Writing a driver](#writing-a-driver)
- [Testing](#testing)
    - [Faking the queue](#faking-the-queue)
    - [Testing a job](#testing-a-job)
    - [Testing chains](#testing-chains)
    - [Testing batches](#testing-batches)

<a name="introduction"></a>

## Introduction


웹 애플리케이션을 만들다 보면 업로드한 팟캐스트를 트랜스코딩하거나 이메일을 일괄 전송하는 것처럼 사용자가 기다리는 동안 처리하기에는 오래 걸리는 작업이 있습니다. 큐를 사용하면 이를 잡으로 미뤄 별도의 큐 워커 프로세스가 백그라운드에서 처리하는 동안 애플리케이션은 즉시 응답할 수 있습니다.


Laravel은 데이터베이스, Redis, Amazon SQS, Laravel Cloud 관리형 큐에 통일된 큐 API를 제공합니다. 각 잡은 비동기 `handle` 메서드가 있는 구조체이며 `laravel queue:work`로 워커가 가져오면 실행됩니다.


재시작 후 유지할 필요가 없는 가벼운 작업은 [`task::background`](/rust/docs/tasks#managed-background-work)로 큐 없이 현재 프로세스에서 실행합니다. 이벤트 리스너를 큐에 넣으려면 [queued listeners](/rust/docs/events#queued-listeners)를 사용하세요.

<a name="connections-and-queues"></a>

### Connections and queues


잡을 디스패치하기 전에 연결과 큐의 차이를 알아야 합니다. 연결은 데이터베이스나 Redis 서버처럼 잡을 보관하는 백엔드입니다. 큐는 연결에 있는 이름 있는 잡 목록이며 연결마다 원하는 수의 큐를 둘 수 있습니다.


큐를 지정하지 않고 잡을 디스패치하면 연결의 `default` 큐에 넣습니다. 큐를 나누면 작업의 우선순위를 정할 수 있습니다. 예를 들어 긴급한 잡을 `high` 큐에 넣고 워커에 먼저 처리하도록 지시할 수 있습니다.

```shell
laravel queue:work --queue=high,default
```

<a name="configuration"></a>

## Configuration


Laravel은 기본적으로 `database` 큐 연결을 사용하고 기본 데이터베이스 연결의 `jobs` 테이블에 큐에 넣은 잡을 저장합니다. 환경 변수로 다른 연결을 선택하거나 기본값을 바꿀 수 있습니다.

| 변수 | 설정 대상 | 기본값 |
| --- | --- | --- |
| `QUEUE_CONNECTION` | 기본 연결 | `database` |
| `DB_QUEUE_CONNECTION`, `DB_QUEUE_TABLE`, `DB_QUEUE` | `database` 연결의 데이터베이스 연결, 테이블, 기본 큐 | 기본 데이터베이스 연결, `jobs`, `default` |
| `REDIS_QUEUE_CONNECTION`, `REDIS_QUEUE` | `redis` 연결의 Redis 연결과 기본 큐 | `default`, `default` |
| `DB_QUEUE_FAILED_CONNECTION`, `DB_QUEUE_FAILED_TABLE` | [failed jobs](#failed-jobs)를 저장하는 위치 | 기본 데이터베이스 연결과 `failed_jobs` |


[Amazon SQS](#amazon-sqs) 및 [Laravel Cloud](#laravel-cloud) 연결에는 별도의 환경 변수가 있습니다.

<a name="drivers"></a>

### Drivers


Laravel은 여러 내장 큐 드라이버를 제공합니다.

| 드라이버 | 동작 |
| --- | --- |
| `database` | [database connections](/rust/docs/database) 중 하나의 [table](#the-jobs-table)에 잡을 저장합니다 |
| `redis` | [Redis](#redis)에 잡을 저장합니다. `redis` 기능이 필요합니다 |
| `sqs` | [Amazon SQS](#amazon-sqs) 큐에 잡을 넣습니다. `sqs` 기능이 필요합니다 |
| `cloud` | [Laravel Cloud's managed queues](#laravel-cloud)에 잡을 넣습니다. `sqs` 기능이 필요합니다 |
| `sync` | 현재 프로세스에서 각 잡을 즉시 실행하고 디스패치에서 오류를 반환합니다 |
| `discard` | 디스패치한 잡을 실행하지 않고 버립니다 |


`sync` 드라이버는 별도 워커를 실행하고 싶지 않은 로컬 개발에 유용하며 Laravel은 테스트에서 기본적으로 사용합니다. 큐 작업을 완전히 비활성화하려면 `QUEUE_CONNECTION=discard`를 설정하세요.

<a name="the-jobs-table"></a>

### The jobs table


`database` 드라이버는 큐에 넣은 잡을 `jobs` 테이블에 저장하고 영구적으로 실패한 [failed jobs](#failed-jobs)를 `failed_jobs` 테이블로 옮겨 나중에 확인하고 재시도할 수 있게 합니다. 새 애플리케이션은 `queue::tables!` 매크로만 있는 `create_jobs_table` 마이그레이션에서 두 테이블과 [job batch](#job-batches) 테이블을 생성합니다.

```rust
// database/migrations/0001_01_01_000002_create_jobs_table.rs
laravel::queue::tables!();
```


잡을 디스패치하기 전에 마이그레이션을 실행하세요.

```shell
laravel migrate
```


`DB_QUEUE_TABLE` 또는 `DB_QUEUE_FAILED_TABLE`을 변경한다면 매크로를 해당 마이그레이션 코드로 바꾸고 테이블 이름을 맞추세요.

```rust
// database/migrations/0001_01_01_000002_create_jobs_table.rs
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("jobs", |table| {
            table.id();
            table.string("queue").index();
            table.long_text("payload");
            table.integer("attempts").default(0);
            table.timestamp("reserved_at").nullable();
            table.timestamp("available_at");
            table.timestamp("created_at");
        })
        .await?;

    tx.schema()
        .create("failed_jobs", |table| {
            table.id();
            table.string("job_id").length(36).unique();
            table.string("connection");
            table.string("queue");
            table.long_text("payload");
            table.long_text("error");
            table.timestamp("failed_at");

            table.index(["connection", "queue", "failed_at"]);
        })
        .await?;

    tx.schema()
        .create("job_batches", |table| {
            table.string("id").length(36).primary();
            table.string("name").nullable();
            table.integer("total_jobs");
            table.integer("pending_jobs");
            table.integer("failed_jobs");
            table.long_text("options");
            table.timestamp("created_at");
            table.timestamp("cancelled_at").nullable();
            table.timestamp("finished_at").nullable();
        })
        .await?;

    tx.schema()
        .create("job_batch_jobs", |table| {
            table.string("batch_id").length(36);
            table.string("job_id").length(36);
            table.string("status").length(16);

            table.primary(["batch_id", "job_id"]);
        })
        .await
}
```


사용하는 큐 드라이버와 관계없이 영구적으로 실패한 잡은 `failed_jobs`에 기록합니다. 예외는 [Laravel Cloud](#laravel-cloud)로, 관리형 큐가 실패한 잡을 Laravel Cloud 대시보드에 저장해 그곳에서 확인, 재시도, 삭제할 수 있습니다. 실패한 잡을 저장하지 않고 버리려면 [your queue configuration](#defining-your-own-connections)에서 `queue.failed`를 `FailedJobs::Discard`로 설정하세요.

```rust
use laravel::config::queue::FailedJobs;

queue.failed = FailedJobs::Discard;
```

<a name="redis"></a>

### Redis


Redis에 큐 잡을 저장하려면 `Cargo.toml`에서 Laravel의 `redis` 기능을 활성화하고 [Redis connection](/rust/docs/redis)을 구성한 뒤 `QUEUE_CONNECTION=redis`를 설정하세요.

```toml
laravel-rust = { version = "0.1", features = ["database-postgres", "redis"] }
```


캐시를 비우면 해당 데이터베이스의 모든 키가 삭제되므로 큐 잡은 [cache](/rust/docs/cache)와 별도 Redis 데이터베이스에 저장하세요. 기본적으로 `default` Redis 연결은 데이터베이스 0을, `cache` 연결은 데이터베이스 1을 사용합니다. `REDIS_URL`에 데이터베이스 번호를 지정하면 두 연결이 공유하므로 큐 전용 Redis 연결을 구성해야 합니다. Laravel은 큐 키에 접두사를 붙이지 않으므로 애플리케이션마다 별도 Redis 서버를 사용해야 합니다.

<a name="blocking"></a>

#### Blocking


기본적으로 유휴 워커는 새 잡을 폴링하기 전에 `--sleep`초 동안 대기합니다. `block_for`를 사용하면 해당 기간 동안 Redis에서 블로킹하며 새 잡이 들어오는 즉시 가져옵니다. [your queue configuration](#defining-your-own-connections)에서 `block_for`를 설정하세요.

```rust
use laravel::config::queue::RedisQueue;

queue.add_connection("redis", RedisQueue::from_env(env).block_for(5.seconds()));
```


Redis Cluster에서는 `block_for`를 지원하지 않습니다.

<a name="amazon-sqs"></a>

### Amazon SQS


큐에 [Amazon SQS](https://aws.amazon.com/sqs/)를 사용하려면 `Cargo.toml`에서 Laravel의 `sqs` 기능을 활성화하고 `QUEUE_CONNECTION=sqs`를 설정하세요.

```toml
laravel-rust = { version = "0.1", features = ["database-postgres", "sqs"] }
```


다음 환경 변수로 `sqs` 연결을 구성할 수 있습니다.

| 변수 | 설명 | 기본값 |
| --- | --- | --- |
| `AWS_DEFAULT_REGION` | AWS 리전 | `AWS_REGION` 등 AWS SDK가 결정한 리전 |
| `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` | AWS 인증 정보 | 컨테이너의 IAM 역할 등 AWS SDK가 결정한 인증 정보 |
| `SQS_PREFIX` | `https://sqs.us-east-1.amazonaws.com/123456789012` 같은 큐 기본 URL | 이름으로 각 큐 URL 조회 |
| `SQS_SUFFIX` | `-production`처럼 모든 큐 이름에 추가할 접미사 | 없음 |
| `SQS_QUEUE` | 연결의 기본 큐 | `default` |
| `AWS_ENDPOINT_URL_SQS` | 로컬 에뮬레이터 같은 사용자 지정 SQS 엔드포인트 | 해당 리전의 AWS 엔드포인트 |
| `SQS_OVERFLOW_ENABLED`, `SQS_OVERFLOW_STORE` | SQS 한도를 넘는 페이로드를 캐시 저장소에 저장 | 비활성화, 기본 캐시 저장소 사용 |


각 큐 이름은 SQS 큐에 직접 대응합니다. 위 접두사와 접미사로 `emails` 큐는 `https://sqs.us-east-1.amazonaws.com/123456789012/emails-production`이 됩니다. Laravel은 SQS 큐를 자동 생성하지 않으므로 AWS에서 먼저 만드세요. 유휴 워커가 새 잡을 효율적으로 기다리도록 롱 폴링을 활성화하려면 AWS에서 각 큐의 메시지 수신 대기 시간을 최대 20초로 설정하세요.


SQS의 15분 제한보다 긴 지연을 지정해 잡을 디스패치할 수 있습니다. Laravel은 실행 시점까지 보관합니다. SQS의 실패한 잡은 [`failed_jobs` table](#the-jobs-table)에 기록하므로 실패한 잡을 버리지 않는 한 `sqs` 드라이버에는 데이터베이스 기능이 필요합니다.

<a name="fifo-queues"></a>

#### FIFO queues


`.fifo`로 끝나는 큐 이름은 SQS FIFO 큐로 취급하며 각 메시지 그룹 안에서 디스패치 순서대로 한 번에 잡 하나를 처리합니다. `SQS_SUFFIX`를 설정하면 Laravel은 `.fifo` 앞에 삽입하므로 `orders.fifo`는 `orders-production.fifo`가 됩니다. `on_group`으로 메시지 그룹을 지정하세요. 그룹 없이 디스패치한 잡은 단일 그룹을 공유합니다.

```rust
use laravel::prelude::*;

pub async fn ship(Params(order_id): Params<i64>) -> laravel::Result<Redirect> {
    let order = Order::find_or_fail(order_id).await?;

    ShipOrder { order_id }
        .dispatch()
        .on_queue("orders.fifo")
        .on_group(format!("customer-{}", order.customer_id))
        .await?;

    Ok(Redirect::back())
}
```


SQS FIFO 큐는 중복 제거 ID가 최근 5분 이내 디스패치한 다른 잡과 일치하는 잡을 버립니다. 기본적으로 Laravel은 디스패치마다 고유 ID를 생성하므로 중복 디스패치도 각각 실행됩니다. 중복을 제거하려면 직접 `deduplication_id`를 전달하세요.

```rust
ShipOrder { order_id }
    .dispatch()
    .on_queue("orders.fifo")
    .deduplication_id(format!("ship-order-{order_id}"))
    .await?;
```


SQS FIFO 큐는 메시지별 지연을 지원하지 않으므로 지연 잡은 표준 큐로 디스패치하세요.

<a name="large-payloads"></a>

#### Large payloads


SQS 메시지는 1 MiB로 제한되며 더 큰 잡을 디스패치하면 오류가 반환됩니다. 더 큰 페이로드를 지원하려면 `SQS_OVERFLOW_ENABLED=true`를 설정하세요. 초과한 페이로드는 [cache](/rust/docs/cache) 저장소에 저장하고 SQS 메시지에는 캐시 키만 넣습니다. `SQS_OVERFLOW_STORE`로 특정 저장소를 선택하거나 생략하여 기본 저장소를 사용하세요. 모든 워커가 페이로드를 읽도록 `database`, `redis` 같은 공유 캐시 저장소를 사용해야 합니다.

<a name="laravel-cloud"></a>

### Laravel Cloud


[Laravel Cloud](https://cloud.laravel.com)의 관리형 큐는 AWS 설정 없이 완전 관리형 자동 확장 큐 인프라를 제공합니다. 잡이 갑자기 늘어도 자동 확장하므로 SQS 큐 프로비저닝, IAM 인증 정보 관리, 큐 서버 용량 산정을 직접 할 필요가 없습니다. 관리형 큐를 사용하는 애플리케이션은 미리 구성된 `cloud` 연결을 자동으로 받습니다. 기본 연결로 사용하려면 `sqs` 기능을 활성화하고 `QUEUE_CONNECTION=cloud`를 설정하세요.


관리형 큐는 SQS를 기반으로 하므로 [FIFO queues](#fifo-queues), [large payloads](#large-payloads)를 포함한 모든 [`sqs` driver](#amazon-sqs) 기능을 지원합니다. Laravel Cloud 큐 설정이나 `CLOUD_QUEUE_OVERFLOW_ENABLED`, `CLOUD_QUEUE_OVERFLOW_STORE`로 페이로드 초과 처리를 활성화할 수 있습니다. Laravel Cloud 대시보드는 각 잡의 진행 상황을 추적하고 영구적으로 실패한 잡을 `failed_jobs` 테이블 대신 저장하므로 대시보드에서 바로 확인, 재시도, 삭제할 수 있습니다.

<a name="defining-your-own-connections"></a>

### Defining your own connections


`reporting` 데이터베이스 연결의 `report_jobs` 테이블에 잡을 저장하는 `reports` 연결처럼 추가 연결이 필요하다면 `src/config/queue.rs` [configuration file](/rust/docs/configuration#config-files)을 만드세요. `Queue::from_env`로 기본 연결을 상속하고 직접 연결을 추가합니다. 여러 연결이 같은 드라이버를 다른 설정으로 공유할 수 있습니다.

```rust
// src/config/queue.rs
use laravel::config::queue::{DatabaseQueue, Queue};
use laravel::config::{self, Env};

#[config::section]
fn queue(env: &Env) -> Queue {
    let mut queue = Queue::from_env(env);

    queue.add_connection(
        "reports",
        DatabaseQueue::new()
            .connection("reporting")
            .table("report_jobs")
            .queue("reports"),
    );

    queue
}
```


그런 다음 파일을 `src/config/mod.rs`에 추가하세요.

```rust
mod queue;
```


이후 [Connections, queues, and delays](#connections-queues-and-delays)에 나온 것처럼 이름으로 연결에 잡을 디스패치할 수 있습니다.

<a name="creating-jobs"></a>

## Creating jobs


잡은 `Queueable`을 파생한 구조체와 `handle` 메서드가 있는 `#[job]` impl의 조합입니다. `src/jobs/` 등 어떤 모듈에나 둘 수 있으며 Laravel이 자동으로 발견하므로 등록할 것은 없습니다.


예를 들어 업로드한 각 에피소드를 공개 전에 처리하는 팟캐스트 게시 애플리케이션을 생각해 보겠습니다. 다음 잡은 팟캐스트 ID를 받고 실행 시 `Podcast` 모델을 불러옵니다.

```rust
// src/jobs/process_podcast.rs
use laravel::queue::{Queueable, job};

use crate::models::Podcast;

#[derive(Queueable)]
pub struct ProcessPodcast {
    pub podcast_id: i64,
}

#[job]
impl ProcessPodcast {
    async fn handle(self) -> laravel::Result<()> {
        let podcast = Podcast::find_or_fail(self.podcast_id).await?;

        // Process the uploaded podcast...

        Ok(())
    }
}
```


큐에 넣은 잡은 워커가 실행할 때까지 직렬화되므로 데이터베이스 연결이나 열린 파일 핸들 대신 일반 데이터나 [models](#models-in-jobs)를 담아야 합니다.


`handle`은 `self`를 소비하고 `()` 또는 `laravel::Result<()>`를 반환합니다. `self` 외에도 `Inject<T>`를 통한 [services](/rust/docs/container), `Section<T>`를 통한 [config sections](/rust/docs/configuration#your-own-config-sections), 현재 [`&Attempt`](#inside-a-job)를 순서에 관계없이 받을 수 있습니다.

```rust
use laravel::container::Inject;
use laravel::queue::job;

use crate::models::Podcast;
use crate::services::AudioProcessor;

#[job]
impl ProcessPodcast {
    async fn handle(self, processor: Inject<AudioProcessor>) -> laravel::Result<()> {
        let podcast = Podcast::find_or_fail(self.podcast_id).await?;

        processor.process(&podcast).await?;

        Ok(())
    }
}
```


각 잡은 새로운 [application context](/rust/docs/context)에서 실행되므로 HTTP 요청과 세션은 없지만 `config`, `resolve`, URL 생성, `once` 같은 헬퍼가 모두 작동합니다. Laravel은 디스패치 시 존재한 활성 테넌트 등의 [context values](/rust/docs/context#adding-to-the-context)를 잡 실행 컨텍스트로 전파합니다.

<a name="models-in-jobs"></a>

### Models in jobs


ID를 저장하고 직접 레코드를 불러오는 대신 잡 필드에 모델을 직접 저장할 수 있습니다. 디스패치할 때 Laravel은 각 모델의 기본 키만 직렬화합니다. 워커는 `handle` 실행 전에 모델을 데이터베이스에서 다시 불러오므로 항상 최신 데이터로 작업합니다.

```rust
// src/jobs/process_podcast.rs
use laravel::queue::{Queueable, job};

use crate::models::Podcast;

#[derive(Queueable)]
pub struct ProcessPodcast {
    pub podcast: Podcast,
}

#[job]
impl ProcessPodcast {
    async fn handle(self) -> laravel::Result<()> {
        // Process self.podcast...

        Ok(())
    }
}
```


`ProcessPodcast { podcast }.dispatch().await?`처럼 디스패치할 때 모델을 직접 전달하세요. `Option<Podcast>`와 `Vec<Podcast>` 필드도 키를 저장하고 잡 실행 시 모델을 다시 불러옵니다. 연관관계는 직렬화하지 않으므로 `self.podcast.load(Podcast::episodes).await?`처럼 `handle`에 필요한 연관관계를 불러오세요.


잡 실행 시 모델의 행이 이미 없어졌다면 워커는 실행하지 않고 잡을 삭제합니다. 예를 들어 작성자가 삭제한 팟캐스트를 처리할 이유가 없고 재시도해도 레코드를 복구할 수 없습니다. 워커는 이렇게 삭제한 잡을 누락된 모델 이름과 키를 포함해 `info` 수준으로 기록하며 해당 잡의 [`JobProcessed`](#events) 이벤트는 `MissingModels` 결과를 보고합니다. `Vec<Podcast>` 필드에서는 삭제된 레코드를 제외하고 남은 모델로 잡을 실행합니다.


삭제된 잡이 [chain](#job-chains)의 일부라면 나머지 체인은 실행되지 않습니다. 실패한 잡이 없으므로 [chain's `catch` callback](#chain-failures)도 호출하지 않습니다. [batch](#job-batches)에서는 해당 잡과 나머지 체인을 건너뛴 것으로 계산하므로 배치는 완료되어 `then` 콜백을 실행할 수 있습니다.


청구서가 절대로 없어져서는 안 되는 결제 잡이나 `catch`에서 이전 단계를 되돌려야 하는 체인처럼 삭제된 레코드가 문제를 의미한다면 `fail_when_missing_models`를 추가하여 `MissingModels` 오류로 잡을 영구 실패시키세요.

```rust
#[job(fail_when_missing_models)]
impl ChargeInvoice {
    // ...
}
```


`fail_when_missing_models`를 사용해도 워커가 전달할 잡 모델을 불러올 수 없으므로 실패한 잡의 `failed` 훅은 실행되지 않습니다.

<a name="job-names"></a>

### Job names


Laravel은 큐 페이로드에 잡 이름을 기록하고 워커 실행 시 그 이름으로 잡 타입을 찾습니다. 기본 이름은 `app::jobs::ProcessPodcast` 같은 타입의 모듈 경로입니다. 구조체 이름이나 위치를 바꾸면 이미 큐에 있는 잡의 타입을 찾지 못합니다. 리팩터링에도 식별자를 유지하려면 이름을 명시하세요.

```rust
#[job(name = "podcasts.process")]
impl ProcessPodcast {
    // ...
}
```


이미 큐에 있는 잡은 직렬화 당시의 필드를 유지합니다. 새 필드를 추가할 때는 이전 잡도 역직렬화되도록 `#[serde(default)]`를 붙이세요. 필드 이름을 바꿀 때는 `#[serde(alias = "...")]`로 이전 이름을 보존하세요.

```rust
#[derive(Queueable)]
pub struct TranscribeEpisode {
    #[serde(alias = "podcast_id")]
    pub episode_id: i64,
    #[serde(default)]
    pub include_timestamps: bool,
}
```


잡 구조체에 새 모델 필드를 추가하면서 `#[serde(default)]`를 사용한다면 모델 자체에는 기본값이 없으므로 `Option`이나 `Vec`으로 감싸세요.

<a name="dispatching-jobs"></a>

## Dispatching jobs


잡을 정의했다면 `#[job]`이 생성한 `dispatch` 메서드를 호출하고 await하여 디스패치합니다. 기본적으로 await하면 기본 큐 연결에 잡을 넣습니다. 다음 핸들러는 팟캐스트를 생성하고 백그라운드 처리를 위해 큐에 넣습니다.

```rust
use laravel::model::create;
use laravel::prelude::*;

use crate::jobs::ProcessPodcast;

#[laravel::input]
#[validate(anyone)]
pub struct NewPodcast {
    #[validate(required, max_length(255))]
    title: String,
}

pub async fn store(Valid(form): Valid<NewPodcast>) -> laravel::Result<Redirect> {
    let podcast = create!(Podcast { title: &form.title }).await?;

    ProcessPodcast { podcast }.dispatch().await?;

    Ok(Redirect::to("/podcasts"))
}
```


`dispatch`를 await하면 `attempt.id()` 및 [failed jobs](#failed-jobs) 명령어에 표시되는 ID와 같은 `JobId`를 반환합니다. 라우트 핸들러, 콘솔 명령어, 예약 태스크, 이벤트 리스너, 다른 잡에서 디스패치할 수 있습니다.

<a name="connections-queues-and-delays"></a>

### Connections, queues, and delays


디스패치를 await하기 전에 연결과 큐를 선택하거나 잡이 실행 가능해지는 시점을 지연할 수 있습니다.

```rust
ProcessPodcast { podcast }
    .dispatch()
    .on_connection("redis")
    .on_queue("podcasts")
    .delay(10.minutes())
    .await?;
```


`delay`는 기간, `Timestamp`, `ZonedDateTime`을 받습니다. `sync` 연결은 지연을 무시하고 즉시 실행합니다.


잡의 모든 디스패치가 기본적으로 특정 큐로 가게 하려면 `#[job(queue = "podcasts")]`처럼 잡 자체에 [`queue` option](#job-options)을 설정하세요. 디스패치 시 `on_queue`를 호출하면 기본값을 덮어씁니다.

<a name="database-transactions"></a>

### Database transactions


[database transaction](/rust/docs/database#transactions) 안에서 잡을 디스패치하면 Laravel은 트랜잭션 커밋까지 기다린 뒤 큐에 넣고 롤백되면 버립니다. 따라서 데이터베이스 레코드가 보이기 전에 워커가 잡을 처리하는 일이 없습니다.

```rust
use laravel::db;
use laravel::model::create;

db::transaction(async |_tx| {
    let podcast = create!(Podcast { title: &form.title }).await?;

    ProcessPodcast { podcast }.dispatch().await?;

    Ok(())
})
.await?;
```


트랜잭션 안에서 `dispatch`는 즉시 `JobId`를 반환하고 커밋 후 잡을 넣습니다. 커밋 후 큐 추가가 실패하면 [after-commit work](/rust/docs/database#after-commit-work-from-business-logic)에 설명된 대로 데이터베이스 변경은 커밋된 채로 `db::transaction`이 오류를 반환합니다. 이 경우 트랜잭션을 재실행하지 말고 잡 디스패치를 재시도하세요.


트랜잭션 안에서 디스패치한 [Events](/rust/docs/events#database-transactions)도 커밋될 때까지 실행을 기다립니다.

<a name="synchronous-dispatching"></a>

### Synchronous dispatching


큐에 넣지 않고 현재 프로세스에서 잡을 즉시 실행하려면 `dispatch_sync`를 호출하세요.

```rust
ProcessPodcast { podcast }.dispatch_sync().await?;
```


잡은 정상 수명 주기로 실행되며 `dispatch_sync`는 `handle`의 오류를 반환합니다. `dispatch`와 달리 열린 데이터베이스 트랜잭션 안에서도 즉시 실행하므로 해당 트랜잭션의 미커밋 쓰기를 볼 수 있습니다.

<a name="dispatching-jobs-in-bulk"></a>

### Dispatching jobs in bulk


여러 잡을 한꺼번에 큐에 넣으려면 `queue::bulk`에 전달하세요. Laravel은 개별적으로 넣지 않고 가능한 적은 백엔드 요청으로 전송합니다.

```rust
use laravel::queue;

let subscriber_ids = Subscriber::query()
    .filter(Subscriber::podcast_id.eq(podcast.id))
    .pluck(Subscriber::id)
    .await?;

let jobs = subscriber_ids.into_iter().map(|subscriber_id| NotifySubscriber {
    podcast_id: podcast.id,
    subscriber_id,
});

queue::bulk(jobs).on_queue("notifications").await?;
```


`queue::bulk`는 단일 잡, 같은 타입 잡의 이터레이터, 다른 타입 잡의 튜플을 받고 `JobId`를 순서대로 반환합니다. 도중에 추가가 실패하면 앞선 잡은 이미 큐에 있을 수 있습니다. 잡 그룹을 함께 추적하거나 모두 완료했을 때 콜백을 실행하려면 [job batch](#job-batches)를 사용하세요.

<a name="debounced-jobs"></a>

### Debounced jobs


짧은 시간에 잡을 반복 디스패치한다면 마지막 디스패치만 실행하려 할 수 있습니다. 예를 들어 몇 초 사이에 게시물을 세 번 수정해도 검색 인덱스는 한 번만 갱신하면 됩니다. `#[job]`에 `debounce_for`를 설정하고 `debounce_id`를 구현해 서로 대체할 디스패치를 묶으세요.

```rust
use laravel::prelude::*;
use laravel::queue::{Queueable, job};

#[derive(Queueable)]
pub struct UpdateSearchIndex {
    pub post_id: i64,
}

#[job(debounce_for = 30.seconds())]
impl UpdateSearchIndex {
    fn debounce_id(&self) -> i64 {
        self.post_id
    }

    async fn handle(self) -> laravel::Result<()> {
        // Update the post's search index...

        Ok(())
    }
}
```


각 디스패치는 실행 가능해지기 전 30초 기다립니다. 차례가 되면 같은 게시물의 더 최근 디스패치가 대기 중일 경우 워커가 버립니다. `debounce_id`는 `Display` 구현 타입을 반환할 수 있으며 생략하면 해당 잡 타입의 모든 디스패치가 이전 것을 대체합니다.


수정이 계속 들어오면 매 디스패치가 대기 시간을 끝없이 초기화합니다. 총 지연의 상한을 정하려면 `max_wait`를 설정하세요. 가장 오래된 대기 디스패치가 해당 시간에 도달하면 다음 디스패치를 즉시 실행합니다.

```rust
#[job(debounce_for = 30.seconds(), max_wait = 2.minutes())]
```


Laravel은 기본 [cache](/rust/docs/cache) 저장소에서 디바운스 상태를 추적하므로 `database`, `redis` 같은 공유 저장소를 사용하세요. `sync` 연결은 잡을 즉시 실행하므로 디바운스를 적용하지 않습니다.

<a name="job-options"></a>

## Retries and timeouts


기본적으로 오류를 반환하거나 패닉이 발생한 잡은 한 번만 시도하고 재시도하지 않습니다. `#[job]`에서 재시도, 백오프 지연, 실행 타임아웃을 설정할 수 있습니다.

```rust
use laravel::prelude::*;
use laravel::queue::job;

#[job(
    queue = "podcasts",
    tries = 3,
    backoff = [10.seconds(), 1.minutes()],
    timeout = 2.minutes(),
)]
impl ProcessPodcast {
    // ...
}
```


이 옵션이면 실패한 잡은 두 번째 시도 전 10초, 세 번째 시도 전 1분 기다린 뒤 영구 실패합니다. `backoff`가 목록이면 각 항목이 해당 재시도 전 대기 시간을 정하며 그 이후에는 마지막 기간을 반복합니다.

| 옵션 | 설명 | 기본값 |
| --- | --- | --- |
| `queue = "podcasts"` | 디스패치 시 `on_queue`가 없을 때 기본 큐 | 연결의 기본 큐 |
| `tries = 3` | 큐로 반환한 경우를 포함한 최대 시도 횟수 | `1` |
| `backoff = 30.seconds()` | 재시도 전 대기 시간 또는 `[10.seconds(), 1.minutes()]` 같은 목록 | 지연 없음 |
| `timeout = 2.minutes()` | 한 번의 시도 최대 시간 | 60초 |
| `retry_for = 1.hours()` | `tries`를 대체하며 디스패치 후 재시도할 수 있는 시간 범위 | 제한 없음 |
| `max_errors = 3` | [stopping retries](#limiting-errors)로 재시도를 중단하기 전 최대 실패 횟수 | `tries`를 따름 |
| `debounce_for`, `max_wait` | [debounced jobs](#debounced-jobs)의 중복 제거 기간 | 디바운스 없음 |
| `name = "podcasts.process"` | 큐 페이로드에 저장할 고정 [job name](#job-names) | 타입 경로 |
| `fail_when_missing_models` | [a model row is missing](#models-in-jobs)일 때 잡을 실패시킴 | 잡 삭제 |


잡 옵션은 잡 타입에 연결되므로 새 코드를 배포하면 변경 사항이 이미 큐에 있는 잡에도 적용됩니다.


잡이 `timeout`을 초과하면 워커는 다음 `.await` 지점에서 취소하고 `JobTimedOut` 오류로 시도를 실패시킵니다. Rust future는 `.await` 지점에서만 취소할 수 있으므로 CPU 중심 또는 블로킹 작업은 [`task::spawn_blocking`](/rust/docs/tasks#blocking-work)으로 옮기세요.


시도가 실패했지만 재시도할 예정이면 워커는 오류를 경고로 기록합니다. 잡이 영구 실패하면 [failed jobs table](#failed-jobs)에 기록하고 [`failed` hook](#handling-failures)을 호출하며 [error handler](/rust/docs/errors#reporting-errors)로 오류를 보고합니다. `retry_for`가 있는 잡은 다음 시도 전에 기간이 끝나게 되면 즉시 영구 실패하고 해당 시도의 오류를 보관합니다.

<a name="limiting-errors"></a>

### Limiting errors


외부 요청 제한을 기다리는 경우처럼 반복적으로 [releases itself](#releasing-deleting-and-failing)하여 큐로 돌아가는 잡은 많은 시도가 필요할 수 있지만 예상치 못한 오류에는 빨리 실패해야 합니다. `retry_for`와 `max_errors`를 함께 사용하면 기간 안에서 계속 큐로 돌아갈 수 있으면서 일정 횟수의 오류 후 영구 실패합니다.

```rust
#[job(retry_for = 1.hours(), max_errors = 3)]
impl SyncContacts {
    // ...
}
```


워커는 기본 [cache](/rust/docs/cache) 저장소에서 오류 횟수를 추적하므로 `database`, `redis` 같은 공유 저장소를 사용하세요.

<a name="inside-a-job"></a>

## Inside a job


잡의 `handle` 메서드는 현재 실행을 확인하기 위해 `&Attempt`를 받을 수 있습니다. `number()`는 1부터 시작하는 시도 횟수, `id()`는 잡의 `JobId`를 반환합니다.

```rust
use laravel::queue::{Attempt, job};

#[job(tries = 3)]
impl ProcessPodcast {
    async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
        tracing::info!(id = %attempt.id(), run = attempt.number(), "processing podcast");

        // ...

        Ok(())
    }
}
```


`name()`, `connection()`, `queue()`로 현재 잡의 메타데이터도 확인할 수 있습니다.

<a name="releasing-deleting-and-failing"></a>

### Releasing, deleting, and failing


`Attempt`를 사용하면 잡이 자신의 수명 주기를 제어할 수도 있습니다. 예를 들어 다음 잡은 팟캐스트가 보관 처리되면 자신을 삭제하고, 오디오 업로드가 진행 중이면 큐로 돌아갑니다.

```rust
use laravel::prelude::*;
use laravel::queue::{Attempt, job};

#[job(retry_for = 1.hours())]
impl ProcessPodcast {
    async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
        if self.podcast.archived {
            attempt.delete();
            return Ok(());
        }

        if !self.podcast.uploaded {
            attempt.release(30.seconds());
            return Ok(());
        }

        // Process the uploaded podcast...

        Ok(())
    }
}
```


- `release(delay)`는 주어진 지연 후 다시 실행하도록 잡을 큐로 돌려보냅니다. 큐로 반환하는 경우도 `tries`에 포함되므로 자주 반환되는 잡은 [Limiting errors](#limiting-errors)처럼 `retry_for`를 사용해야 합니다.
- `delete()`는 재시도 없이 큐에서 잡을 제거합니다.
- `fail(error)`는 추가 재시도 없이 잡을 영구 실패시킵니다.


이 지시는 `handle`이 `Ok(())`를 반환할 때 적용됩니다. `handle`이 오류를 반환하면 `release`를 호출했어도 실패합니다. 유일한 예외는 [rate limit](/rust/docs/rate-limiting#outside-a-request) 오류입니다. `TooManyAttempts`를 반환하면 요청 제한이 실행을 허용할 때까지 자동으로 잡을 큐로 돌려보냅니다.

<a name="handling-failures"></a>

### Handling failures


잡이 영구 실패했을 때 사용자에게 알리거나 일부 처리 결과를 정리하고 싶을 수 있습니다. `handle` 옆에 `&laravel::Error`와 `handle`이 받는 것과 같은 주입 인수를 받는 비동기 `failed` 메서드를 추가하세요.

```rust
use laravel::model::update;
use laravel::queue::job;

#[job(tries = 3)]
impl ProcessPodcast {
    async fn handle(self) -> laravel::Result<()> {
        // Process the uploaded podcast...

        Ok(())
    }

    async fn failed(self, error: &laravel::Error) -> laravel::Result<()> {
        let mut podcast = self.podcast;

        update!(podcast { failure: Some(error.to_string()) }).await?;

        Ok(())
    }
}
```


`failed`는 저장된 페이로드를 역직렬화하고 모델 필드를 다시 불러온 새 인스턴스를 받으므로 `handle` 중 메모리에서 변경한 내용은 이어지지 않습니다.

<a name="job-middleware"></a>

## Job middleware


메일 프로바이더의 전송 한도를 지키거나 미인증 사용자를 건너뛰는 것처럼 여러 잡이 같은 가드나 요청 제한 로직을 공유한다면 매번 `handle`에 반복하지 않고 잡 미들웨어로 추출하세요. 같은 잡의 중복 실행을 막으려면 [cache lock](/rust/docs/cache#atomic-locks)을 사용하는 미들웨어를 만드세요.

<a name="defining-middleware"></a>

### Defining middleware


잡 미들웨어는 `laravel::queue`의 `#[middleware]`를 붙인 비동기 함수입니다. 나머지 파이프라인을 나타내는 `next`를 받고 `laravel::Result<()>`를 반환합니다. 다음 예제는 모든 워커에서 메일 잡을 초당 14개로 [rate limits](/rust/docs/rate-limiting#outside-a-request)하고 한도를 넘는 잡은 여유가 생길 때까지 큐로 돌려보냅니다.

```rust
use laravel::queue::{Next, middleware};
use laravel::rate_limit::{self, Limit};

#[middleware]
pub async fn mail_rate_limit(next: Next) -> laravel::Result<()> {
    rate_limit::attempt("mail", Limit::per_second(14)).await??;

    next.run().await
}
```


`next.run()`은 나머지 파이프라인을 실행해 결과를 반환하므로 미들웨어는 `handle` 전후에 코드를 실행하거나 아예 건너뛸 수 있습니다. 미들웨어 함수는 `next` 앞에서 `handle`과 같은 주입 파라미터를 받으며, 잡 반환·삭제·실패에 사용할 `&Attempt`도 받을 수 있습니다.


사용자 ID 같은 잡 데이터를 미들웨어에 전달하려면 `next` 뒤에 파라미터를 선언하세요. `next` 앞은 Laravel이 주입하고 `next` 뒤는 [assigning the middleware to a job](#assigning-middleware-to-jobs) 시 `skip_unverified_users(self.user_id)`처럼 전달하는 인수입니다. 다음 미들웨어는 사용자가 이메일 주소를 인증하지 않았다면 잡을 삭제합니다.

```rust
use laravel::queue::{Attempt, Next, middleware};

use crate::models::User;

#[middleware]
pub async fn skip_unverified_users(
    attempt: &Attempt,
    next: Next,
    user_id: i64,
) -> laravel::Result<()> {
    let verified = User::find(user_id)
        .await?
        .is_some_and(|user| user.email_verified_at.is_some());

    if !verified {
        attempt.delete();
        return Ok(());
    }

    next.run().await
}
```


미들웨어는 잡이 반환한 오류를 가로챌 수도 있습니다. 예를 들어 다음 미들웨어는 `handle` 실패 시 시도를 실패시키지 않고 잡을 큐로 돌려보냅니다.

```rust
#[middleware]
pub async fn release_on_error(attempt: &Attempt, next: Next) -> laravel::Result<()> {
    if let Err(error) = next.run().await {
        tracing::warn!(%error, "releasing the job after an error");
        attempt.release(1.minutes());
    }

    Ok(())
}
```

<a name="assigning-middleware-to-jobs"></a>

### Assigning middleware to jobs


잡에 미들웨어를 붙이려면 `#[job]` impl에 `&self`를 받고 단일 미들웨어나 튜플을 반환하는 `middleware` 메서드를 추가하세요. 잡별 파라미터는 순서대로 전달합니다.

```rust
use laravel::queue::{IntoMiddleware, job};

#[job(retry_for = 1.hours())]
impl SendNewsletter {
    fn middleware(&self) -> impl IntoMiddleware {
        (skip_unverified_users(self.user_id), mail_rate_limit)
    }

    async fn handle(self) -> laravel::Result<()> {
        // Send the newsletter...

        Ok(())
    }
}
```


잡 미들웨어는 나열한 순서대로 실행하므로 여기서는 `skip_unverified_users`가 먼저 실행되어 `mail_rate_limit`을 감싸고, 그 안에서 `handle`을 실행합니다.


조건을 만족할 때만 미들웨어를 적용하려면 `Option`으로 감싸세요. Laravel은 `None` 항목을 건너뜁니다.

```rust
fn middleware(&self) -> impl IntoMiddleware {
    (
        skip_unverified_users(self.user_id),
        self.retry_errors.then_some(release_on_error),
    )
}
```


여러 잡에서 미들웨어 묶음을 공유하려면 헬퍼 함수가 `MiddlewareGroup`을 반환하도록 하고 각 잡의 `middleware` 메서드에서 반환하세요.

```rust
use laravel::queue::{IntoMiddleware, MiddlewareGroup, job};

pub fn mail() -> MiddlewareGroup {
    MiddlewareGroup::new().with(mail_rate_limit).with(release_on_error)
}

#[job]
impl SendNewsletter {
    fn middleware(&self) -> impl IntoMiddleware {
        mail()
    }

    async fn handle(self) -> laravel::Result<()> {
        // Send the newsletter...

        Ok(())
    }
}
```


잡의 [`timeout`](#job-options)은 미들웨어와 `handle` 메서드를 합친 전체에 적용됩니다. 미들웨어는 `sync` 연결이나 [test attempts](#testing-a-job)를 포함하여 잡이 실행되는 모든 곳에서 실행됩니다.

<a name="job-chains"></a>

## Job chains


잡 체이닝은 하나씩 차례로 실행할 잡 순서를 지정합니다. 각 잡은 이전 잡이 성공한 후에만 디스패치하며 하나라도 실패하면 나머지 잡은 실행하지 않습니다. `queue::chain`에 튜플로 전달하고 await하세요.

```rust
use laravel::prelude::*;
use laravel::queue;

use crate::models::Podcast;

pub async fn publish(podcast: Podcast) -> laravel::Result<Redirect> {
    queue::chain((
        ProcessPodcast { podcast: podcast.clone() },
        OptimizePodcast { podcast_id: podcast.id },
        ReleasePodcast { podcast_id: podcast.id },
    ))
    .await?;

    Ok(Redirect::back())
}
```


`queue::chain`은 단일 잡이나 같은 타입 잡의 이터레이터도 받습니다. 체인을 동적으로 구성할 때 `then`으로 잡을 추가할 수 있습니다.

```rust
let mut chain = queue::chain(ProcessPodcast { podcast: podcast.clone() });

if !podcast.transcribed {
    chain = chain.then(TranscribePodcast { podcast_id: podcast.id });
}

chain.then(ReleasePodcast { podcast_id: podcast.id }).await?;
```


각 잡은 설정된 [options](#job-options)를 유지하므로 체인이 진행되기 전에 자체적으로 재시도합니다. [releases itself](#releasing-deleting-and-failing)하는 잡은 성공할 때까지 체인을 멈추며 자신을 삭제하는 잡은 계속 진행하게 합니다. [a model's row is gone](#models-in-jobs)으로 삭제한 잡은 이후 잡을 실행하지 않고 체인을 끝냅니다.


기본적으로 체인의 각 잡은 자신의 연결과 큐를 사용합니다. 모두 같은 연결이나 큐로 보내려면 `on_connection`과 `on_queue`를 호출하세요. `delay`를 호출하면 체인의 첫 잡이 지연됩니다.

```rust
queue::chain((
    ProcessPodcast { podcast: podcast.clone() },
    OptimizePodcast { podcast_id: podcast.id },
))
.on_connection("redis")
.on_queue("podcasts")
.await?;
```

> [!NOTE]
> 체인의 각 잡은 멱등성을 갖도록 설계하세요. 잡은 성공했지만 다음 잡을 큐에 넣는 데 실패하면 워커는 완료된 잡을 재시도합니다.

<a name="adding-jobs-to-the-chain"></a>

### Adding jobs to the chain


실행 중인 잡은 [`&Attempt`](#inside-a-job)를 통해 자신의 체인에 잡을 추가할 수 있습니다. `prepend_to_chain`은 바로 다음에 실행할 잡을 하나 이상 삽입하고 `append_to_chain`은 끝에 추가합니다.

```rust
use laravel::queue::{Attempt, job};

#[job]
impl ProcessPodcast {
    async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
        // ...

        // Run next...
        attempt.prepend_to_chain(TranscribePodcast { podcast_id: self.podcast.id });

        // Run at the end of the chain...
        attempt.append_to_chain((
            NotifyHosts { podcast_id: self.podcast.id },
            UpdatePodcastFeed { podcast_id: self.podcast.id },
        ));

        Ok(())
    }
}
```


두 메서드는 단일 잡, 다른 타입 잡의 튜플, 같은 타입 잡의 이터레이터를 받습니다. `prepend_to_chain`에 여러 잡을 전달하면 체인의 남은 잡보다 먼저 나열된 순서대로 실행합니다. 추가한 잡은 현재 잡이 성공하거나 자신을 삭제해야 큐에 들어갑니다. 현재 잡이 체인에 속하지 않았다면 새 체인이 시작됩니다.

<a name="chain-failures"></a>

### Chain failures


체인의 잡이 영구 실패하면 나머지는 실행되지 않습니다. 실패에 대응하려면 `catch`로 콜백을 등록하세요.

```rust
queue::chain((
    ProcessPodcast { podcast: podcast.clone() },
    OptimizePodcast { podcast_id: podcast.id },
))
.catch(PodcastFailed { podcast_id: podcast.id })
.await?;
```


콜백도 잡처럼 Laravel이 체인과 함께 저장하도록 `Queueable`을 파생한 구조체입니다. `impl`에 `#[callback]`을 붙이고 실패 오류를 받는 비동기 `catch` 메서드를 구현하세요.

```rust
use laravel::model::update;
use laravel::queue::{Queueable, callback};

use crate::models::Podcast;

#[derive(Queueable)]
pub struct PodcastFailed {
    pub podcast_id: i64,
}

#[callback]
impl PodcastFailed {
    async fn catch(self, error: &laravel::Error) -> laravel::Result<()> {
        let mut podcast = Podcast::find_or_fail(self.podcast_id).await?;

        update!(podcast { failure: Some(error.to_string()) }).await?;

        Ok(())
    }
}
```


워커는 실패한 잡의 [`failed` hook](#handling-failures) 전에 `catch`를 즉시 호출합니다. 콜백은 큐 잡이 아니라 인라인으로 실행하므로 재시도하지 않으며 오류는 오류 핸들러에 보고합니다. 콜백의 모델 행이 삭제되면 건너뜁니다. 대신 `MissingModels` 오류를 보고하려면 `#[callback]`에 `fail_when_missing_models`를 추가하세요. 오래 걸리거나 재시도 가능한 정리는 콜백에서 잡을 디스패치하세요.


나중에 [retry the failed job](#failed-jobs)으로 실패한 잡을 재시도해 성공하면 나머지 잡부터 체인을 재개합니다.

<a name="job-batches"></a>

## Job batches


Laravel의 잡 배치는 잡 그룹을 병렬 실행하고 전체 배치 완료 후 콜백을 실행합니다. 예를 들어 사용자가 연락처 300개의 CSV를 올리면 100행씩 세 잡으로 나눠 워커에서 동시에 처리한 후 모두 끝나면 가져오기를 완료 처리할 수 있습니다.


잡을 `queue::batch`에 전달하고 await하세요. 여기서 `ImportCsv`는 일부 행을 가져오는 잡입니다.

```rust
use laravel::prelude::*;
use laravel::queue;

pub async fn start(Params(import_id): Params<i64>) -> laravel::Result<Redirect> {
    let batch_id = queue::batch([
        ImportCsv { import_id, rows: 1..=100 },
        ImportCsv { import_id, rows: 101..=200 },
        ImportCsv { import_id, rows: 201..=300 },
    ])
    .name("Import CSV")
    .then(ImportFinished { import_id })
    .catch(ImportFinished { import_id })
    .await?;

    Ok(Redirect::to(format!("/imports/{import_id}/batches/{batch_id}")))
}
```


`queue::batch`는 같은 타입 잡의 이터레이터나 다른 타입 잡의 튜플을 받습니다. await하면 모든 잡을 디스패치하고 [inspect its progress](#inspecting-batches)에 사용할 `BatchId`를 반환합니다. 배치 잡은 어떤 순서로든 완료될 수 있습니다. 모두 특정 연결과 큐로 보내려면 `on_connection`과 `on_queue`를 호출하세요.

<a name="the-batches-tables"></a>

### The batches tables


Laravel은 `job_batches`와 `job_batch_jobs` 두 테이블로 배치 진행 상황을 추적합니다. `create_jobs_table` 마이그레이션이 [jobs table](#the-jobs-table)과 함께 생성하므로 첫 배치를 디스패치하기 전에 마이그레이션을 실행하세요.


배치 레코드는 잡을 실행하는 큐 드라이버와 관계없이 기본 데이터베이스 연결에 저장됩니다.

<a name="batch-callbacks"></a>

### Batch callbacks


배치 수명 주기의 세 시점에 [callbacks](#chain-failures)를 등록할 수 있습니다. 워커가 콜백의 해당 메서드를 호출합니다.

| 메서드 | 호출 시점 | 선택 인수 |
| --- | --- | --- |
| `then` | 배치의 모든 잡이 성공했을 때 | `&Batch` |
| `catch` | 배치에서 첫 잡이 영구 실패했을 때 | `&Batch`와 `&laravel::Error` |
| `finally` | 성공, 실패, 건너뜀 여부와 관계없이 모든 잡이 끝났을 때 | `&Batch` |


예를 들어 다음 콜백은 `Import` 모델을 완료 처리하거나 실패 이유를 기록합니다.

```rust
use laravel::model::update;
use laravel::queue::{Queueable, callback};

use crate::models::Import;

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

#[callback]
impl ImportFinished {
    async fn then(self) -> laravel::Result<()> {
        let mut import = Import::find_or_fail(self.import_id).await?;

        update!(import { completed: true }).await?;

        Ok(())
    }

    async fn catch(self, error: &laravel::Error) -> laravel::Result<()> {
        let mut import = Import::find_or_fail(self.import_id).await?;

        update!(import { failure: Some(error.to_string()) }).await?;

        Ok(())
    }
}
```


`&Batch` 파라미터는 콜백 실행 시점의 상태를 반영합니다. `then`, `catch`, `finally`를 여러 번 호출해 콜백을 추가할 수 있습니다.


목적이 하나인 콜백은 비동기 함수에 `#[callback]`을 붙여도 됩니다. `import_id` 같은 소유 파라미터는 배치와 함께 저장하고 `&Batch` 같은 프레임워크 파라미터는 실행 시 주입합니다.

```rust
use laravel::queue::Batch;

#[callback]
async fn log_import(import_id: i64, batch: &Batch) {
    tracing::info!(
        import_id,
        jobs = batch.total_jobs(),
        failed = batch.failed_jobs(),
        "import finished",
    );
}

queue::batch(jobs).finally(log_import(import_id)).await?;
```

<a name="chains-and-batches"></a>

### Chains and batches


배치에는 [job chains](#job-chains)가 포함될 수 있습니다. 각 체인은 내부 잡을 순차적으로 실행하면서 배치의 다른 항목과 병렬 실행됩니다.

```rust
queue::batch((
    queue::chain(ReleasePodcast { podcast_id: 1 })
        .then(SendReleaseNotification { podcast_id: 1 }),
    queue::chain(ReleasePodcast { podcast_id: 2 })
        .then(SendReleaseNotification { podcast_id: 2 }),
))
.then(ReleaseFinished)
.await?;
```


배치를 체인의 한 단계로 사용할 수도 있습니다. 배치의 모든 잡이 끝나면 체인이 다음으로 진행합니다.

```rust
queue::chain(FlushPodcastCache)
    .then(queue::batch([ReleasePodcast { podcast_id: 1 }, ReleasePodcast { podcast_id: 2 }]))
    .then(queue::batch([
        SendReleaseNotification { podcast_id: 1 },
        SendReleaseNotification { podcast_id: 2 },
    ]))
    .await?;
```


잡 하나가 실패하는 등 배치가 취소되면 바깥 체인도 멈춥니다.

<a name="adding-jobs-and-cancelling-batches"></a>

### Adding jobs and cancelling batches


배치 안의 잡은 [`&Attempt`](#inside-a-job)로 자신의 배치에 잡을 동적으로 추가할 수 있습니다. 큰 파일을 가져올 때는 HTTP 요청 중 잡 수천 개를 만드는 대신 파일을 백그라운드에서 나누는 시작 잡 하나를 디스패치할 수 있습니다.

```rust
use laravel::queue::{Attempt, Queueable, job};

#[derive(Queueable)]
pub struct SplitImport {
    pub import_id: i64,
}

#[job]
impl SplitImport {
    async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
        let import = Import::find_or_fail(self.import_id).await?;

        let jobs = (0..import.total_rows)
            .step_by(100)
            .map(|start| ImportCsv { import_id: import.id, rows: start + 1..=start + 100 });

        attempt.add_to_batch(jobs);

        Ok(())
    }
}
```


추가한 잡까지 모두 끝날 때까지 배치는 열린 상태를 유지합니다. 잡 안에서 취소하려면 `attempt.cancel_batch()`를 호출하세요. 워커는 남은 대기 잡을 건너뛰며 배치의 `then` 콜백도 실행하지 않습니다. 잡 밖에서는 `queue::cancel_batch(batch_id).await?`로 취소합니다.

<a name="inspecting-batches"></a>

### Inspecting batches


`queue::find_batch`로 ID에 해당하는 배치를 찾아 진행 상황을 보고할 수 있습니다. 일치하는 배치가 없으면 `None`을 반환합니다.

```rust
use laravel::prelude::*;
use laravel::queue::{self, Batch, BatchId};

pub async fn show(Params(batch_id): Params<BatchId>) -> laravel::Result<Json<Batch>> {
    let batch = queue::find_batch(batch_id).await?.or_abort(404)?;

    Ok(Json(batch))
}
```


`Batch`는 `Serialize`를 구현하므로 JSON으로 바로 반환할 수 있습니다. `progress`는 0~100 백분율이며 `total_jobs`, `pending_jobs`, `failed_jobs`, `is_finished`, `is_cancelled`도 제공합니다.

<a name="batch-failures"></a>

### Batch failures


기본적으로 배치의 어느 잡이든 영구 실패하면 Laravel은 배치를 취소하고 `catch` 콜백을 호출하며 남은 잡을 건너뜁니다. 일부가 실패해도 계속 처리하려면 `allow_failures`를 호출하세요.

```rust
queue::batch(jobs).allow_failures().catch(ImportFinished { import_id }).await?;
```


`allow_failures`를 사용하면 첫 실패에서 `catch`를 실행하고, 실패한 모든 잡을 재시도해 성공한 뒤에만 `then`을 실행합니다. `queue:retry-batch`로 배치의 모든 실패 잡을 재시도할 수 있습니다. `allow_failures`가 없는 배치는 첫 실패에 취소되므로 이 방법으로 재시도할 수 없습니다.

```shell
laravel queue:retry-batch 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f53
```


재시도한 잡은 완료된 배치에 새 잡을 추가하거나 자신의 체인을 재개할 수 있습니다. 그러면 추가 잡이 끝날 때까지 배치가 열린 상태로 남고 `finally`를 다시 실행하므로 `finally` 콜백에 멱등성이 있어야 합니다.

<a name="pruning-batches"></a>

### Pruning batches


완료된 배치 레코드는 정리할 때까지 데이터베이스에 남습니다. `queue:prune-batches`는 완료 후 24시간이 지난 배치를 제거합니다. 더 오래 유지하려면 `--hours`를 전달하고 `src/console/mod.rs`에서 매일 [schedule](/rust/docs/scheduling)하세요.

```rust
use laravel::schedule::{self, Schedule};

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.command("queue:prune-batches --hours=48").daily();
}
```


`--unfinished=N`을 전달하면 `N`시간보다 오래된 미완료 배치도 제거하며 취소된 배치는 `--cancelled=N`으로 제거합니다. 삭제하면 콜백이 실행되지 않으므로 미완료 배치는 더 이상 재시도할 계획이 없는 것만 정리하세요.

<a name="running-the-worker"></a>

## Running the worker


`queue:work` 명령어로 큐 워커를 시작하면 대기 중인 잡을 처리합니다.

```shell
laravel queue:work
```


워커는 중지할 때까지 계속 실행하면서 `app::` 접두사를 뺀 잡 이름, 결과, 실행 시간을 출력합니다.

```text
◆ jobs::ProcessPodcast  412.4ms
▲ jobs::SendInvoice retrying  18.2ms
  the payment service timed out
```


워커는 장기 실행 프로세스이므로 재시작할 때까지 시작 시 사용한 바이너리를 계속 실행합니다. 로컬 개발에서는 별도 워커 터미널 대신 `npm run dev`를 사용할 수 있습니다. 웹 서버, 큐 워커, Vite 개발 서버를 함께 시작하며 Rust 코드나 `.env`가 바뀌면 서버와 워커를 자동으로 다시 빌드하고 시작합니다.

```shell
npm run dev
```

<a name="worker-options"></a>

### Worker options


기본적으로 워커는 기본 연결의 기본 큐를 처리합니다. 특정 연결 이름이나 우선순위별 큐 목록을 전달할 수 있습니다. 여러 큐를 나열하면 높은 우선순위 큐를 모두 처리한 뒤 낮은 우선순위 큐에서 가져옵니다.

```shell
laravel queue:work redis
laravel queue:work --queue=high,default
```

| 옵션 | 설명 | 기본값 |
| --- | --- | --- |
| `[connection]` | 처리할 큐 연결 | 기본 연결 |
| `--queue=high,default` | 우선순위별 처리 큐 | 연결의 기본 큐 |
| `--concurrency=4` | 동시에 처리할 잡 수 | `1` |
| `--sleep=3` | 실행할 잡이 없을 때 다음 폴링까지 대기할 초 | `3` |
| `--max-jobs=1000` | 지정한 수의 잡 처리 후 종료 | 제한 없음 |
| `--max-time=3600` | 지정한 초만큼 실행 후 종료 | 제한 없음 |
| `--stop-when-empty` | 감시하는 모든 큐가 비면 종료 | 비활성화 |


워커는 종료 전에 진행 중인 잡을 마칩니다.


큐 워커도 HTTP 서버와 함께 애플리케이션의 [ticks](/rust/docs/tasks#ticks)를 실행합니다. HTTP 핸들러에서 버퍼링한 카운터를 비우는 등 웹 요청에만 해당하는 틱은 `.when(|host| host.is_server())`로 제한하세요.

<a name="worker-concurrency"></a>

### Worker concurrency


단일 워커 프로세스에서 여러 잡을 동시에 처리하려면 `--concurrency`를 전달하세요.

```shell
laravel queue:work --concurrency=8
```


동시 잡은 워커 프로세스 하나를 공유하므로 네트워크나 데이터베이스를 기다리는 I/O 중심 잡에 가장 적합합니다. 이미지 처리 같은 CPU 중심 또는 블로킹 작업은 [`task::spawn_blocking`](/rust/docs/tasks#blocking-work)으로 넘겨 다른 잡이 멈추지 않게 하세요. 하나 이상의 서버에 여러 워커 프로세스를 실행할 수도 있으며 각 잡은 워커 하나만 가져갑니다.

<a name="running-workers-in-production"></a>

### Running workers in production


프로덕션에서는 systemd나 Supervisor 같은 프로세스 관리자로 큐 워커를 실행해 종료 시 자동으로 재시작되게 하세요.

```ini
# /etc/systemd/system/app-worker.service
[Unit]
Description=Queue worker
After=network.target

[Service]
WorkingDirectory=/srv/app
ExecStart=/srv/app/app queue:work --concurrency=4
Restart=always
KillSignal=SIGTERM
TimeoutStopSec=150

[Install]
WantedBy=multi-user.target
```


워커가 `SIGTERM`을 받으면 새 잡을 가져오지 않고 진행 중인 잡의 완료를 기다립니다. 마지막 시도에서 타임아웃된 잡도 `failed` 훅을 실행할 시간이 있도록 관리자의 중지 타임아웃을 가장 긴 잡의 `timeout` 두 배보다 길게 설정하세요.


워커가 갑자기 종료되거나 서버가 충돌하면 약 1분 후 다른 워커가 진행 중이던 잡을 다시 가져갑니다. 중단된 실행은 한 번의 시도로 계산합니다.

<a name="laravel-cloud-workers"></a>

### Running workers on Laravel Cloud


[Laravel Cloud](https://cloud.laravel.com)에 [managed queues](#laravel-cloud)로 배포하면 systemd, Supervisor 설정이나 워커 클러스터 용량 산정이 필요하지 않습니다. Laravel Cloud가 큐를 지속적으로 감시하고 큐 깊이, 잡 지연, 처리량에 따라 워커 동시성을 자동으로 조절합니다.


트래픽 급증 시 Cloud는 워커를 추가하여 대기 시간이 쌓이기 전에 적체를 처리합니다. 큐가 유휴 상태면 워커를 0개로 줄일 수 있어 급증 사이의 유휴 컴퓨팅 비용을 내지 않습니다. 배포할 때마다 워커를 자동 교체하며 대시보드에서 큐 깊이, 처리량, 실패한 잡을 실시간으로 확인할 수 있습니다.

<a name="restarting-workers"></a>

### Restarting workers


워커는 시작한 바이너리를 계속 사용하므로 배포마다 재시작하세요. `queue:restart`는 실행 중인 모든 워커에 현재 잡을 마치고 정상 종료하도록 신호를 보내 프로세스 관리자가 새 릴리스로 시작하게 합니다.

```shell
laravel queue:restart
```


재시작 신호는 기본 [cache](/rust/docs/cache) 저장소로 조정하므로 `database`, `redis` 같은 공유 저장소를 사용하세요.

<a name="pausing-queues"></a>

### Pausing queues


유지보수 중처럼 워커를 종료하지 않고 특정 큐에서 잡을 가져오지 못하게 하려면 큐를 일시 중지하세요. `connection:queue`를 지정하거나 기본 연결에는 큐 이름만 전달합니다.

```shell
laravel queue:pause database:emails
laravel queue:pause emails
```


워커는 실행 중인 잡을 마치고 `queue:continue`로 재개할 때까지 일시 중지된 큐의 새 잡은 그대로 둡니다.

```shell
laravel queue:continue database:emails
```


모든 연결의 모든 큐를 일시 중지하거나 재개하려면 `queue:pause` 또는 `queue:continue`에 `--all`을 전달하세요. `queue:restart`처럼 일시 중지 상태도 기본 캐시 저장소로 공유합니다.

<a name="counting-jobs"></a>

### Counting jobs


큐 깊이를 감시하려면 큐 관리자의 `sizes`를 호출하세요. 예를 들어 적체 시 알림을 보내는 예약 상태 검사에서 사용할 수 있습니다.

```rust
use laravel::queue;

if let Some(sizes) = queue::manager().sizes("database", "emails").await? {
    tracing::info!(
        pending = sizes.pending,
        running = sizes.reserved,
        total = sizes.total(),
        "emails",
    );
}
```


`pending`은 실행 준비된 잡, `delayed`는 지연 대기 중인 잡, `reserved`는 처리 중인 잡을 보고합니다. 큐 깊이 조회를 지원하지 않는 드라이버에서 `sizes`는 `None`을 반환하며 SQS 개수는 근삿값입니다.

<a name="failed-jobs"></a>

## Failed jobs


모든 일이 계획대로 되지는 않습니다. 잡이 영구 실패하면 Laravel은 `failed_jobs` 테이블에 기록합니다. `queue:failed`를 실행하면 최근 실패부터 순서대로 확인할 수 있습니다.

```shell
laravel queue:failed
```


실패한 잡을 재시도하려면 `queue:retry`에 ID를 전달하거나 `all`로 모두 재시도하세요. 재시도한 잡은 시도 횟수를 초기화하고 원래 연결과 큐에 다시 넣습니다.

```shell
laravel queue:retry 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f53
laravel queue:retry all
```


실패한 잡 하나를 삭제하려면 `queue:forget`에 ID를 전달합니다. 전체 테이블을 비우려면 `queue:flush`를 실행하고, 48시간이 지난 실패 잡만 삭제하려면 `--hours=48`을 전달하세요. 테이블 관리가 용이하도록 `queue:flush`를 예약할 수 있습니다.

```shell
laravel queue:forget 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f53
laravel queue:flush --hours=48
```


큐의 모든 대기 잡을 삭제하려면 `queue:clear`를 실행하세요.

```shell
laravel queue:clear redis --queue=emails
```

> [!NOTE]
> [Laravel Cloud managed queues](#laravel-cloud)를 사용하면 영구 실패한 잡은 데이터베이스의 `failed_jobs` 테이블 대신 Laravel Cloud 대시보드에서 추적합니다. 서버에서 CLI 명령어를 실행하지 않고 대시보드에서 오류 상세와 페이로드 확인, 실패 잡의 개별·일괄 재시도, 실패 기록 삭제를 할 수 있습니다.

<a name="events"></a>

## Events


워커는 잡을 처리하면서 `laravel::queue::events`의 [events](/rust/docs/events)를 디스패치합니다. 리스너는 잡 컨텍스트에서 실행하며 디스패치 시 또는 실행 중 추가된 [context values](/rust/docs/context)를 상속합니다.


`JobProcessed`와 `JobFailed` 모두 `JobInfo` 타입의 `event.job` 필드를 포함합니다. `id`, `name`, `connection`, `queue`, 1부터 시작하는 `attempt` 번호로 잡을 설명합니다.


`JobProcessed`는 매 시도 후 `event.duration`과 `event.outcome`을 포함해 발생합니다. 결과는 `Succeeded`, `Released`, `Deleted`, `Debounced`, `MissingModels`, `Retrying`, `Failed` 중 하나입니다. [a model's row was deleted](#models-in-jobs)로 워커가 삭제한 잡은 `MissingModels`를 보고하므로 실패 처리 없이 집계하거나 알림을 보낼 수 있습니다. 다음 리스너는 30초보다 오래 걸리는 잡에 경고를 기록합니다.

```rust
use laravel::event::{Event, listener};
use laravel::prelude::*;
use laravel::queue::events::JobProcessed;

#[listener]
pub async fn warn_about_slow_jobs(event: Event<JobProcessed>) -> laravel::Result<()> {
    if event.duration > 30.seconds() {
        tracing::warn!(
            job = %event.job.name,
            queue = %event.job.queue,
            duration = %event.duration,
            "slow job",
        );
    }

    Ok(())
}
```


`JobFailed`는 영구 실패 후 `failed` 훅이 실행된 다음 발생합니다. 실패 잡은 이미 [error handler](/rust/docs/errors#reporting-errors)에 보고하므로 사용자 지정 알림이나 지표가 필요할 때 `JobFailed`를 수신하세요. `event.job` 외에 `is::<E>()`, `downcast_ref::<E>()`로 확인할 수 있는 `event.error`도 제공합니다.

```rust
use laravel::event::{Event, listener};
use laravel::queue::events::JobFailed;
use laravel::queue::{JobTimedOut, MissingModels};

#[listener]
pub async fn notify_on_job_failure(event: Event<JobFailed>) -> laravel::Result<()> {
    let reason = if event.error.is::<JobTimedOut>() {
        "timed out"
    } else if event.error.is::<MissingModels>() {
        "lost its models"
    } else {
        "failed"
    };

    tracing::error!(
        id = %event.job.id,
        job = %event.job.name,
        queue = %event.job.queue,
        attempt = event.job.attempt,
        error = %event.error,
        "job {reason}",
    );

    Ok(())
}
```


`event.error`에서 확인할 수 있는 일반적인 오류 타입은 다음과 같습니다.

| 오류 타입 | 원인 |
| --- | --- |
| `laravel::queue::JobTimedOut` | 시도가 설정된 `timeout`을 초과함 |
| `laravel::queue::MissingModels` | `fail_when_missing_models` 잡 실행 전에 모델 필드의 레코드가 삭제됨 |
| `laravel::rate_limit::TooManyAttempts` | 요청 제한으로 `retry_for` 만료 전 잡을 실행할 수 없었음 |
| 애플리케이션 오류 | `handle`에서 반환하거나 `attempt.fail(error)`에 전달한 모든 오류 타입 |


`sync` 연결과 `dispatch_sync`는 이러한 이벤트를 디스패치하지 않습니다.

<a name="writing-a-driver"></a>

## Writing a driver


패키지는 사용자 지정 드라이버를 등록해 Cloudflare Queues 같은 큐 백엔드를 지원할 수 있습니다. `Driver`로 잡 추가·예약·삭제를, `ReservedJob`으로 예약된 잡의 임대와 완료를 구현하세요. Laravel 워커는 재시도, 타임아웃, 실패 기록을 자동 처리하고 `LEASE` 기간에 대해 `HEARTBEAT`마다 활성 예약을 갱신하므로 드라이버는 저장과 예약만 관리하면 됩니다.


다음은 Laravel [HTTP client](/rust/docs/http-client)를 사용하는 Cloudflare Queues HTTP pull API 드라이버 예제입니다.

```rust
use std::time::Duration;

use laravel::http::client::{self, PendingRequest};
use laravel::queue::{Driver, LEASE, Reservation, ReservedJob};
use serde::Deserialize;
use serde_json::json;

#[derive(Debug, Clone)]
pub struct CloudflareSettings {
    pub account_id: String,
    pub token: String,
}

#[derive(Clone)]
pub struct CloudflareDriver {
    settings: CloudflareSettings,
}

impl CloudflareDriver {
    fn queue_api(&self, queue: &str) -> PendingRequest {
        client::base_url(format!(
            "https://api.cloudflare.com/client/v4/accounts/{}/queues/{queue}",
            self.settings.account_id
        ))
        .token(&self.settings.token)
        .accept_json()
        .ensure_successful()
    }
}

pub struct CloudflareJob {
    driver: CloudflareDriver,
    queue: String,
    payload: String,
    attempts: u32,
    lease_id: String,
}

#[derive(Deserialize)]
struct Envelope<T> {
    result: T,
}

#[derive(Deserialize)]
struct PullResult {
    messages: Vec<PulledMessage>,
}

#[derive(Deserialize)]
struct PulledMessage {
    body: String,
    attempts: u32,
    lease_id: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AckResult {
    #[serde(default)]
    ack_count: u64,
    #[serde(default)]
    retry_count: u64,
}

impl Driver for CloudflareDriver {
    type Job = CloudflareJob;

    async fn push(
        &self,
        queue: &str,
        payload: String,
        delay: Duration,
    ) -> laravel::Result<()> {
        self.queue_api(queue)
            .post("/messages")
            .json(json!({
                "body": payload,
                "content_type": "text",
                "delay_seconds": delay.as_secs(),
            }))
            .await?;

        Ok(())
    }

    async fn reserve(&self, queues: &[String]) -> laravel::Result<Option<CloudflareJob>> {
        for queue in queues {
            let response: Envelope<PullResult> = self
                .queue_api(queue)
                .post("/messages/pull")
                .json(json!({
                    "batch_size": 1,
                    "visibility_timeout_ms": LEASE.as_millis(),
                }))
                .await?
                .json()?;

            if let Some(message) = response.result.messages.into_iter().next() {
                return Ok(Some(CloudflareJob {
                    driver: self.clone(),
                    queue: queue.clone(),
                    payload: message.body,
                    attempts: message.attempts,
                    lease_id: message.lease_id,
                }));
            }
        }

        Ok(None)
    }

    async fn clear(&self, queue: &str) -> laravel::Result<u64> {
        self.queue_api(queue)
            .post("/purge")
            .json(json!({ "delete_messages_permanently": true }))
            .await?;

        Ok(0)
    }
}

impl ReservedJob for CloudflareJob {
    fn queue(&self) -> &str {
        &self.queue
    }

    fn payload(&self) -> &str {
        &self.payload
    }

    fn attempts(&self) -> u32 {
        self.attempts
    }

    async fn renew(&self) -> laravel::Result<Reservation> {
        // Cloudflare Queues sets the visibility window on pull rather than renewing per lease...
        Ok(Reservation::Held)
    }

    async fn delete(&self) -> laravel::Result<Reservation> {
        let response: Envelope<AckResult> = self
            .driver
            .queue_api(&self.queue)
            .post("/messages/ack")
            .json(json!({ "acks": [{ "lease_id": self.lease_id }] }))
            .await?
            .json()?;

        if response.result.ack_count > 0 {
            Ok(Reservation::Held)
        } else {
            Ok(Reservation::Lost)
        }
    }

    async fn release(&self, delay: Duration) -> laravel::Result<Reservation> {
        let response: Envelope<AckResult> = self
            .driver
            .queue_api(&self.queue)
            .post("/messages/ack")
            .json(json!({
                "retries": [{
                    "lease_id": self.lease_id,
                    "delay_seconds": delay.as_secs(),
                }],
            }))
            .await?
            .json()?;

        if response.result.retry_count > 0 {
            Ok(Reservation::Held)
        } else {
            Ok(Reservation::Lost)
        }
    }
}
```


예약이 만료되어 다른 워커가 잡을 가져갔다면 `renew`, `delete`, `release`에서 `Reservation::Lost`를 반환해 현재 워커가 해당 잡에 접근하지 않도록 하세요. 일괄 추가를 위한 `Driver::bulk`, `QueueSizes` 보고용 `Driver::sizes`, 백엔드가 실패 잡을 직접 기록할 때의 `ReservedJob::fail`도 재정의할 수 있습니다.


서비스 프로바이더의 `register` 메서드에서 이름으로 드라이버를 등록하세요.

```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

impl ServiceProvider for CloudflareQueueServiceProvider {
    fn register(&self, app: &mut Registrar) {
        app.queue().extend("cloudflare", async |_app, definition| {
            let settings = definition.settings::<CloudflareSettings>()?.clone();

            Ok(CloudflareDriver { settings })
        });
    }
}
```


그런 다음 드라이버에 필요한 설정을 전달하고 해당 드라이버를 참조하는 [custom connection](#defining-your-own-connections)을 구성하세요.

```rust
use laravel::config::queue::ConnectionConfig;

queue.add_connection(
    "cloudflare",
    ConnectionConfig::custom("cloudflare")
        .queue("emails-queue-id")
        .settings(CloudflareSettings {
            account_id: env.get("CLOUDFLARE_ACCOUNT_ID").unwrap_or_default(),
            token: env.get("CLOUDFLARE_API_TOKEN").unwrap_or_default(),
        }),
);
```

> [!NOTE]
> Laravel은 설정된 연결마다 최초 사용 시 드라이버 팩토리를 한 번 호출하고 애플리케이션 수명 동안 인스턴스를 캐시하여 동시 요청과 워커가 공유합니다. TCP 기반 드라이버는 내부에 연결 풀이나 재연결 클라이언트를 유지해야 하며 `laravel::http::client` 기반 드라이버는 Laravel의 풀링 HTTP 클라이언트를 자동 공유합니다.

<a name="testing"></a>

## Testing


잡 디스패치 코드 테스트에서는 실행하지 않고 올바른 잡이 큐에 들어갔는지 검증한 뒤 잡 로직을 따로 테스트하는 것이 일반적입니다.


테스트에서 Laravel은 잡, 체인, 배치, 큐 알림이 다른 연결을 지정해도 기본적으로 모든 잡을 `sync` 연결로 보냅니다. 큐를 페이크하지 않으면 디스패치한 잡이 즉시 실행됩니다. 실제 백엔드로 테스트하려면 테스트 설정에서 `QUEUE_CONNECTION`을 변경하세요.

<a name="faking-the-queue"></a>

### Faking the queue


`queue::fake()`를 호출하면 잡을 추가하거나 실행하지 않고 디스패치를 가로챕니다. 반환된 페이크에 대해 단언하세요.

```rust
use laravel::queue;
use laravel::testing::prelude::*;

#[laravel::test]
async fn uploading_a_podcast_queues_it_for_processing(app: Application) {
    let queue = queue::fake();

    app.post("/podcasts").json(json!({ "title": "Episode 1" })).await.assert_redirect();

    queue.assert_pushed::<ProcessPodcast>();
    queue.assert_pushed_times::<ProcessPodcast>(1);

    queue.assert_pushed_where::<ProcessPodcast>(|job| {
        job.podcast.title == "Episode 1" && job.queue() == "default"
    });
}
```


조건자는 역직렬화된 잡과 `id()`, `connection()`, `queue()`, `delay()`를 받습니다. `connection()`은 디스패치에서 요청한 연결을 반영하며 `delay()`는 `job.delay() == 10.minutes()`처럼 기간과 직접 비교할 수 있습니다. `assert_not_pushed::<T>()`, `assert_not_pushed_where`, `assert_nothing_pushed()`도 사용할 수 있습니다.


페이크는 트랜잭션을 따르며 커밋 후에만 잡을 기록합니다. 직렬화 후 역직렬화를 수행하므로 직렬화 버그는 즉시 테스트를 실패시킵니다. `job.user` 같은 모델 필드는 연관관계 없이 보존되며 조건자 내부에서 데이터베이스에 접근할 필요가 없습니다.


특정 잡 타입만 페이크하거나 특정 잡을 제외하려면 `only`나 `except`를 체이닝하세요. 페이크되지 않은 잡은 정상 디스패치됩니다.

```rust
let queue = queue::fake().only::<ProcessPodcast>();
let queue = queue::fake().except::<SendInvoice>();
```


페이크는 핸들을 드롭할 때까지 활성 상태입니다.

<a name="testing-a-job"></a>

### Testing a job


잡의 `handle`을 직접 테스트하려면 `app.job(..)`로 한 번의 시도를 실행하고 결과를 단언하세요. 다음 테스트는 업로드가 끝나지 않았을 때 `ProcessPodcast`가 큐로 돌아가는지 검증합니다.

```rust
use laravel::model::create;
use laravel::testing::prelude::*;

#[laravel::test]
async fn uploading_podcasts_are_released(app: Application) -> laravel::Result<()> {
    let podcast = create!(Podcast { title: "Episode 1", uploaded: false }).await?;

    app.job(ProcessPodcast { podcast })
        .await
        .assert_released_after(30.seconds());

    Ok(())
}
```


잡은 워커에서처럼 [middleware](#job-middleware)를 통과합니다. `attempt(n)`을 호출하면 `attempt.number()`에 특정 재시도 횟수를 설정합니다. `assert_succeeded`, `assert_released`, `assert_released_after`, `assert_deleted`, `assert_failed`, `assert_failed_with::<E>()`로 결과를 검증할 수 있습니다. 테스트 시도는 재시도하거나 `failed`를 호출하지 않고 한 번만 실행합니다.

<a name="testing-chains"></a>

### Testing chains


[queue fake](#faking-the-queue)는 첫 잡과 함께 각 체인을 기록합니다. 잡 타입 튜플과 `assert_chained`를 사용해 순서를 검증하세요.

```rust
let queue = queue::fake();

app.post("/orders/42/ship").await.assert_redirect();

queue.assert_chained::<(ShipOrder, RecordShipment, UpdateInventory)>();
```


후속 잡의 페이로드를 확인하려면 `assert_pushed_where` 안에서 `chain().get::<T>(index)`를 호출하세요.

```rust
queue.assert_pushed_where::<ShipOrder>(|job| {
    job.chain().get::<RecordShipment>(0).is_some_and(|next| next.order_id == 42)
});
```


[dynamically modifies its chain](#adding-jobs-to-the-chain)하는 잡을 테스트하려면 [`app.job(..)`](#testing-a-job)으로 실행하고 잡 타입이나 타입 튜플을 전달해 `assert_chained`를 호출하세요.

```rust
app.job(ProcessPodcast { podcast })
    .await
    .assert_succeeded()
    .assert_chained::<TranscribePodcast>();
```

<a name="testing-batches"></a>

### Testing batches


[queue fake](#faking-the-queue)는 배치 테이블에 쓰거나 잡을 실행하지 않고 디스패치된 배치를 가로챕니다. `assert_batched`로 검증하세요.

```rust
let queue = queue::fake();

app.post("/imports").json(json!({ "file": "contacts.csv" })).await.assert_redirect();

queue.assert_batched(|batch| {
    batch.name() == Some("Import CSV")
        && batch.jobs().len() == 3
        && batch.jobs().get::<ImportCsv>(0).is_some_and(|job| job.rows == (1..=100))
});
```


조건자 안에서 `then()`, `catch()`, `finally()`, `allows_failures()`도 확인할 수 있습니다. 배치가 디스패치되지 않았는지 확인하려면 `queue.assert_nothing_batched()`를 호출하세요.


페이크는 배치 콜백을 실행하지 않으므로 `app.callback`으로 직접 테스트할 수 있습니다. 기본적으로 콜백은 잡 하나짜리 합성 배치를 받으며 `total_jobs`, `failed_jobs` 및 관련 빌더로 바꿀 수 있습니다.

```rust
app.callback(ImportFinished { import_id: 7 }).total_jobs(3).then().await?;
```


배치에 잡을 추가하거나 취소하는 잡을 테스트하려면 `app.job(..).in_batch()`로 실행하고 `added_to_batch()` 또는 `assert_batch_cancelled()`로 검증하세요.

```rust
let result = app.job(ImportCsv { rows: 1..=100 }).in_batch().await;

result.assert_succeeded();

assert_eq!(result.added_to_batch().len(), 1);
assert!(
    result
        .added_to_batch()
        .get::<ImportCsv>(0)
        .is_some_and(|job| job.rows == (101..=200))
);

app.job(ImportCsv { rows: 1..=0 })
    .in_batch()
    .await
    .assert_batch_cancelled();
```