
# 逐次チェーン

最も一般的なワークフローパターンは、ステップを直線的につなぐ方法です。各ステップは前のステップの完了後に実行され、蓄積された状態が次へ渡されます。

## `->then()`メソッド

`->then()`を使って、ワークフローに順次実行するステップを追加します。

```php
use Queuety\Queuety;

Queuety::workflow( 'onboarding' )
    ->then( CreateAccountHandler::class )
    ->then( SendWelcomeEmailHandler::class )
    ->then( NotifyAdminHandler::class )
    ->dispatch( [ 'email' => 'user@example.com' ] );
```

ステップは追加された順に実行されます。現在のステップが正常に完了した場合にのみ、ワークフローは次へ進みます。

## Stepインターフェース

ワークフローのステップハンドラーは`Queuety\Step`インターフェースを実装します。

```php
use Queuety\Step;

class CreateAccountHandler implements Step {
    public function handle( array $state ): array {
        $user_id = wp_create_user( $state['email'], wp_generate_password() );
        return [ 'user_id' => $user_id ];
    }

    public function config(): array {
        return [
            'max_attempts' => 3,
        ];
    }
}
```

`Handler`インターフェースとの主な違いは次のとおりです。

| | `Handler`（ジョブ） | `Step`（ワークフロー） |
|---|---|---|
| メソッドシグネチャ | `handle(array $payload): void` | `handle(array $state): array` |
| 入力 | ジョブのペイロード | 蓄積されたワークフロー状態 |
| 出力 | なし（void） | 状態にマージするデータ |

## 状態の流れ

各ステップは蓄積された状態全体を受け取り、新しいキーと値のペアの配列を返します。返されたデータは状態にマージされ、後続のステップに渡されます。

```php
class FetchUserHandler implements Step {
    public function handle( array $state ): array {
        // $state contains: ['user_id' => 42]
        $user = get_user_by( 'ID', $state['user_id'] );
        return [ 'user_name' => $user->display_name, 'user_email' => $user->user_email ];
    }

    public function config(): array {
        return [];
    }
}

class GenerateReportHandler implements Step {
    public function handle( array $state ): array {
        // $state contains: ['user_id' => 42, 'user_name' => 'Alice', 'user_email' => 'alice@example.com']
        $report = build_report( $state['user_name'] );
        return [ 'report_url' => $report->url ];
    }

    public function config(): array {
        return [];
    }
}
```

## ステップの設定

`config()`メソッドは次のキーに対応しています。

| キー | 型 | デフォルト | 説明 |
|---|---|---|---|
| `max_attempts` | `int` | `3` | このステップの最大再試行回数 |
| `backoff` | `string` | `exponential` | 再試行のバックオフ方式 |

## LLMパイプラインの例

よくある用途の1つは、LLMのAPI呼び出しとデータ処理を連結することです。

```php
use Queuety\Step;

class BuildPromptHandler implements Step {
    public function handle( array $state ): array {
        $user = get_user_by( 'ID', $state['user_id'] );
        $posts = get_posts( [ 'author' => $user->ID, 'numberposts' => 10 ] );
        $context = implode( "\n", array_map( fn( $p ) => $p->post_content, $posts ) );

        return [
            'prompt' => "Summarize this author's recent work:\n\n{$context}",
        ];
    }

    public function config(): array {
        return [];
    }
}

class CallOpenAIHandler implements Step {
    public function handle( array $state ): array {
        $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', [
            'timeout' => 120,
            'headers' => [
                'Authorization' => 'Bearer ' . OPENAI_API_KEY,
                'Content-Type'  => 'application/json',
            ],
            'body' => json_encode( [
                'model'    => 'gpt-4',
                'messages' => [ [ 'role' => 'user', 'content' => $state['prompt'] ] ],
            ] ),
        ] );

        $body = json_decode( wp_remote_retrieve_body( $response ), true );
        return [ 'summary' => $body['choices'][0]['message']['content'] ];
    }

    public function config(): array {
        return [ 'max_attempts' => 5 ];
    }
}

class SaveSummaryHandler implements Step {
    public function handle( array $state ): array {
        $post_id = wp_insert_post( [
            'post_title'   => "Summary for user #{$state['user_id']}",
            'post_content' => $state['summary'],
            'post_status'  => 'publish',
        ] );
        return [ 'summary_post_id' => $post_id ];
    }

    public function config(): array {
        return [];
    }
}
```

パイプラインをディスパッチします。

```php
Queuety::workflow( 'summarize_author' )
    ->then( BuildPromptHandler::class )
    ->then( CallOpenAIHandler::class )
    ->then( SaveSummaryHandler::class )
    ->on_queue( 'llm' )
    ->max_attempts( 5 )
    ->dispatch( [ 'user_id' => 42 ] );
```

OpenAIへの呼び出しがタイムアウトした場合、ワーカーはそのステップだけを再試行します。ステップ0で作成したプロンプトは、すでにワークフローの状態に安全に保存されています。
