create-saga-pattern

Generate Saga-pattern components for PHP 8.4: includes a Saga interface, step definitions, a coordinator, state management, and compensation logic, with accompanying unit tests, for implementing transactional workflow-like behavior in projects.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "create-saga-pattern" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-c2407fbe9e304d81f1347c1b5cd34eb1de7746652042fd189ff339733485721b. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Generate Saga-pattern components for PHP 8.4: includes a Saga interface, step definitions, a coordinator, state management, and compensation logic, with accompanying unit tests, for implementing transactional workflow-like behavior in projects.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Generates Saga pattern components for PHP 8.4. Creates Saga interfaces, steps, orchestrator, state management, and compensation logic with unit tests.
Audience
Distributed transactions across multiple services Long-running business processes Operations requiring compensation on failure Multi-step workflows with rollback capability
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: create-saga-pattern
description: Generates Saga pattern components for PHP 8.4. Creates Saga interfaces, steps, orchestrator, state management, and compensation logic with unit tests.

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

Layer Path
Domain Types src/Domain/Shared/Saga/
Application Saga src/Application/Shared/Saga/
Context Steps src/Application/{Context}/Saga/Step/
Saga Factory src/Application/{Context}/Saga/
Infrastructure src/Infrastructure/Persistence/Doctrine/Repository/
Unit Tests tests/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

Component Pattern Example
State Enum SagaState SagaState
Step Interface SagaStepInterface SagaStepInterface
Abstract Step AbstractSagaStep AbstractSagaStep
Concrete Step {Action}Step ReserveInventoryStep
Orchestrator SagaOrchestrator SagaOrchestrator
Factory {Name}SagaFactory OrderSagaFactory
Test {ClassName}Test SagaOrchestratorTest

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

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value92/100

Highlights

  • 解决分布式事务协调这一微服务架构下的核心痛点
  • 提供从接口定义到单元测试的完整 Saga 模式实现闭环
  • 适用于长流程业务场景,具备明确的实用价值
Trigger Precision95/100

Highlights

  • description 清晰界定为 PHP 8.4 生成 Saga 模式组件
  • When to Use 章节精准描述适用场景边界
  • 触发词覆盖分布式事务、补偿逻辑等关键特征
Structure and Standards95/100

Highlights

  • 生成流程分步骤清晰(分析→生成→上下文步骤)
  • 包含完整的使用示例和 DI 配置
  • 文件结构、命名规范、数据库 schema 完整规范
Execution Reliability93/100

Highlights

  • 技术栈明确(PHP 8.4 + Symfony + Doctrine)
  • 状态机转换验证和补偿失败处理机制完善
  • 幂等性设计和异常处理覆盖全面
Evidence Verifiability (mean of the first four)94/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.