create-saga-pattern

为 PHP 8.4 生成 Saga 模式组件:包含 Saga 接口、步骤定义、协调器、状态管理与补偿逻辑,并附带单元测试,用于在项目中实现分布式事务式工作流。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "create-saga-pattern":https://skillpi.com/zh/skills/deepskill-c2407fbe9e304d81f1347c1b5cd34eb1de7746652042fd189ff339733485721b。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

为 PHP 8.4 生成 Saga 模式组件:包含 Saga 接口、步骤定义、协调器、状态管理与补偿逻辑,并附带单元测试,用于在项目中实现分布式事务式工作流。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
适合谁
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
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

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

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

亮点

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

亮点

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

亮点

  • 技术栈明确(PHP 8.4 + Symfony + Doctrine)
  • 状态机转换验证和补偿失败处理机制完善
  • 幂等性设计和异常处理覆盖全面
证据可验 (前四项均值)94/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

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

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。