본문으로 건너뛰기
cccskills
무료GitHub에 공개

acc-create-saga-pattern

Generates Saga pattern components for PHP 8.5. Creates Saga interfaces, steps, orchestrator, state management, and compensation logic with unit tests.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md6.7 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Saga Pattern Generator

Creates Saga pattern infrastructure for distributed transaction coordination.

When to Use

  • Distributed transactions across multiple services
  • Long-running business processes
  • Operations requiring compensation on failure
  • Multi-step workflows with rollback capability

Component Characteristics

SagaState Enum

  • Domain layer enum
  • Defines saga lifecycle states: Pending, Running, Compensating, Completed, Failed, CompensationFailed
  • Includes state transition validation
  • Terminal states detection

SagaStep Interface

  • Domain layer interface
  • Execute and compensate methods
  • Idempotency declaration
  • Timeout configuration

SagaContext

  • Carries saga execution data
  • Serializable for persistence
  • Supports data accumulation across steps

SagaOrchestrator

  • Application layer coordinator
  • Manages step execution
  • Handles compensation flow (reverse order)
  • Persists state after each step

SagaPersistence

  • Stores saga state for recovery
  • Supports finding incomplete sagas
  • Dead letter handling

Generation Process

Step 1: Analyze Request

Determine:

  • Context name (Order, Payment, Shipping)
  • Required saga steps
  • Compensation logic for each step

Step 2: Generate Core Components

Create in this order:

  1. Domain Layer (src/Domain/Shared/Saga/)

    • SagaState.php — State enum with transitions
    • StepResult.php — Step result value object
    • SagaStepInterface.php — Step contract
    • SagaContext.php — Execution context
    • SagaResult.php — Saga result
    • Exception classes
  2. Application Layer (src/Application/Shared/Saga/)

    • SagaPersistenceInterface.php — Persistence port
    • SagaRecord.php — Persisted record
    • AbstractSagaStep.php — Base step class
    • SagaOrchestrator.php — Orchestrator
  3. Infrastructure Layer

    • DoctrineSagaPersistence.php — Doctrine implementation
    • Database migration
  4. Tests

    • SagaStateTest.php
    • SagaOrchestratorTest.php

Step 3: Generate Context-Specific Steps

For each saga step (e.g., Order saga):

src/Application/{Context}/Saga/Step/
├── ReserveInventoryStep.php
├── ChargePaymentStep.php
└── CreateShipmentStep.php

src/Application/{Context}/Saga/
└── {Context}SagaFactory.php

File Placement

LayerPath
Domain Typessrc/Domain/Shared/Saga/
Application Sagasrc/Application/Shared/Saga/
Context Stepssrc/Application/{Context}/Saga/Step/
Saga Factorysrc/Application/{Context}/Saga/
Infrastructuresrc/Infrastructure/Persistence/Doctrine/Repository/
Unit Teststests/Unit/{Layer}/{Path}/

Key Principles

Compensation Rules

  1. Compensate in reverse order of execution
  2. Compensations must be idempotent
  3. Handle "already compensated" gracefully
  4. Log all compensation attempts

Idempotency

  1. Use idempotency keys for each step
  2. Check for existing results before executing
  3. Return existing result if found

State Transitions

Pending → Running → Completed
              ↓
         Compensating → Failed
              ↓
         CompensationFailed

Naming Conventions

ComponentPatternExample
State EnumSagaStateSagaState
Step InterfaceSagaStepInterfaceSagaStepInterface
Abstract StepAbstractSagaStepAbstractSagaStep
Concrete Step{Action}StepReserveInventoryStep
OrchestratorSagaOrchestratorSagaOrchestrator
Factory{Name}SagaFactoryOrderSagaFactory
Test{ClassName}TestSagaOrchestratorTest

Quick Template Reference

SagaStepInterface

interface SagaStepInterface
{
    public function name(): string;
    public function execute(SagaContext $context): StepResult;
    public function compensate(SagaContext $context): StepResult;
    public function isIdempotent(): bool;
    public function timeout(): int;
}

StepResult

final readonly class StepResult
{
    public static function success(array $data = []): self;
    public static function failure(string $error): self;
    public function isSuccess(): bool;
    public function isFailure(): bool;
}

Concrete Step Pattern

final readonly class {Action}Step extends AbstractSagaStep
{
    public function name(): string
    {
        return '{action_name}';
    }

    public function execute(SagaContext $context): StepResult
    {
        $idempotencyKey = $this->idempotencyKey($context);

        // Check for existing result (idempotency)
        // Execute action
        // Return StepResult::success([...data...]) or failure
    }

    public function compensate(SagaContext $context): StepResult
    {
        // Get data from context
        // Undo action
        // Handle "already undone" gracefully
        return StepResult::success();
    }
}

Usage Example

// Create saga
$saga = $orderSagaFactory->create($command);

// Execute
$result = $saga->execute();

if ($result->isCompleted()) {
    // Success
} elseif ($result->isFailed()) {
    // Failed but compensated
    $error = $result->error;
} elseif ($result->isCompensationFailed()) {
    // Needs manual intervention
    $originalError = $result->error;
    $compensationError = $result->compensationError;
}

DI Configuration

# Symfony services.yaml
Domain\Shared\Saga\SagaStepInterface:
    tags: ['saga.step']

Application\Shared\Saga\SagaPersistenceInterface:
    alias: Infrastructure\Persistence\Doctrine\Repository\DoctrineSagaPersistence

Application\Order\Saga\OrderSagaFactory:
    arguments:
        $reserveStep: '@Application\Order\Saga\Step\ReserveInventoryStep'
        $chargeStep: '@Application\Order\Saga\Step\ChargePaymentStep'
        $shipStep: '@Application\Order\Saga\Step\CreateShipmentStep'

Database Schema

CREATE TABLE sagas (
    id VARCHAR(255) PRIMARY KEY,
    type VARCHAR(255) NOT NULL,
    state VARCHAR(50) NOT NULL,
    completed_steps JSONB NOT NULL DEFAULT '[]',
    context JSONB NOT NULL,
    error TEXT,
    created_at TIMESTAMP(6) NOT NULL,
    updated_at TIMESTAMP(6) NOT NULL,
    completed_at TIMESTAMP(6)
);

CREATE INDEX idx_sagas_state ON sagas (state);
CREATE INDEX idx_sagas_type_state ON sagas (type, state);

References

For complete PHP templates and test examples, see:

  • references/templates.md — All component templates
  • references/examples.md — Order saga example and unit tests

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Master backend architectures, REST API design, microservices, and server-side development across multiple languages. Use this as a central index to access specialized sub-skills.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

MikeCheng1208/BattleTree22026년 7월 22일 업데이트

在每次回复中使用固定前缀并列出本次实际参考的指令/文件,便于校验是否遵循上下文与规则。

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

MikeCheng1208/BattleTree22026년 7월 22일 업데이트

Automate 21risk tasks via Rube MCP (Composio). Always search tools first for current schemas.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

MikeCheng1208/BattleTree22026년 7월 22일 업데이트

Automate 2chat tasks via Rube MCP (Composio). Always search tools first for current schemas.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

MikeCheng1208/BattleTree22026년 7월 22일 업데이트

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

MikeCheng1208/BattleTree22026년 7월 22일 업데이트

[00] META. Orchestrate skills into dynamic chains for complex tasks. Analyzes the task, discovers available skills, builds an optimal chain, explains why each skill is needed, and executes step-by-step with user confirmation. Use for any complex task requiring multiple thinking/research/analysis steps. Triggers on "plan this", "how to approach", "what's the strategy", "build a plan", or any multi-step problem requiring skill orchestration.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

MikeCheng1208/BattleTree22026년 7월 22일 업데이트

MikeCheng1208의 스킬 모두 보기

이 스킬의 문제 신고