check-idempotency

分析 PHP 代码中的幂等性问题:检测 POST/PUT 端点缺失幂等性键、非幂等命令处理器、重复写入风险以及重试不安全的操作。

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

安装方式

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

用 AI 助手安装

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

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

来源与配置

github.com

配置方式待核实

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

安装实测待补充

分析 PHP 代码中的幂等性问题:检测 POST/PUT 端点缺失幂等性键、非幂等命令处理器、重复写入风险以及重试不安全的操作。

0 下载

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

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
减记
限制与区别
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: check-idempotency
description: Analyzes PHP code for idempotency issues. Detects missing idempotency keys on POST/PUT endpoints, non-idempotent command handlers, duplicate write risks, and retry-unsafe operations.

Idempotency Check

Analyze PHP code for idempotency violations that can cause duplicate writes, double charges, or inconsistent state on retries.

Detection Patterns

1. Missing Idempotency Key on POST/PUT Endpoints

<?php

declare(strict_types=1);

// BAD: POST endpoint creates resource without deduplication
final class CreateOrderAction
{
    public function __invoke(Request $request): Response
    {
        $order = $this->orderService->create($request->validated());

        return new JsonResponse($order, 201);
        // Retry from client = duplicate order!
    }
}

// GOOD: POST endpoint requires idempotency key
final class CreateOrderAction
{
    public function __invoke(Request $request): Response
    {
        $idempotencyKey = $request->headers->get('Idempotency-Key');
        if ($idempotencyKey === null) {
            return new JsonResponse(['error' => 'Idempotency-Key header required'], 422);
        }

        $existing = $this->idempotencyStore->find($idempotencyKey);
        if ($existing !== null) {
            return new JsonResponse($existing->payload(), $existing->statusCode());
        }

        $order = $this->orderService->create($request->validated());

        $this->idempotencyStore->save($idempotencyKey, $order, 201);

        return new JsonResponse($order, 201);
    }
}

2. Non-Idempotent Command Handlers

<?php

declare(strict_types=1);

// BAD: Handler executes without checking previous execution
final readonly class ChargePaymentHandler
{
    public function __construct(
        private PaymentGateway $gateway,
    ) {}

    public function __invoke(ChargePaymentCommand $command): void
    {
        // If message is redelivered, payment is charged twice!
        $this->gateway->charge($command->amount, $command->cardToken);
    }
}

// GOOD: Handler checks for previous execution
final readonly class ChargePaymentHandler
{
    public function __construct(
        private PaymentGateway $gateway,
        private ProcessedCommandStore $processedStore,
    ) {}

    public function __invoke(ChargePaymentCommand $command): void
    {
        if ($this->processedStore->wasProcessed($command->commandId)) {
            return; // Already executed, skip
        }

        $this->gateway->charge($command->amount, $command->cardToken);
        $this->processedStore->markProcessed($command->commandId);
    }
}

3. Duplicate Write Risk in Critical Operations

<?php

declare(strict_types=1);

// BAD: Payment without dedup guard
final readonly class PaymentService
{
    public function charge(UserId $userId, Money $amount): PaymentResult
    {
        // No guard against duplicate charges
        $result = $this->gateway->charge($userId->toString(), $amount->cents());
        $this->repository->save(new Payment($userId, $amount, $result->transactionId()));

        return $result;
    }
}

// GOOD: Payment with unique constraint and idempotency
final readonly class PaymentService
{
    public function charge(UserId $userId, Money $amount, string $requestId): PaymentResult
    {
        $existing = $this->repository->findByRequestId($requestId);
        if ($existing !== null) {
            return PaymentResult::fromExisting($existing);
        }

        $result = $this->gateway->charge(
            $userId->toString(),
            $amount->cents(),
            idempotencyKey: $requestId,
        );

        $this->repository->save(
            new Payment($userId, $amount, $result->transactionId(), $requestId),
        );

        return $result;
    }
}

4. Retry-Unsafe Operations in Retry Loops

<?php

declare(strict_types=1);

// BAD: Email send in retry loop without idempotency guard
final readonly class NotificationService
{
    public function sendWithRetry(Notification $notification): void
    {
        $attempts = 0;
        while ($attempts < 3) {
            try {
                $this->mailer->send($notification->toEmail());
                $this->smsService->send($notification->toSms());
                return;
            } catch (TransportException $e) {
                $attempts++;
                // Email might have been sent, SMS failed
                // Retry sends email AGAIN!
            }
        }
    }
}

// GOOD: Track each step independently with idempotency
final readonly class NotificationService
{
    public function sendWithRetry(Notification $notification): void
    {
        $this->sendStep(
            stepId: $notification->id() . ':email',
            action: fn () => $this->mailer->send($notification->toEmail()),
        );

        $this->sendStep(
            stepId: $notification->id() . ':sms',
            action: fn () => $this->smsService->send($notification->toSms()),
        );
    }

    private function sendStep(string $stepId, callable $action): void
    {
        if ($this->stepStore->isCompleted($stepId)) {
            return;
        }

        $action();
        $this->stepStore->markCompleted($stepId);
    }
}

Grep Patterns

# POST/PUT actions without idempotency key check
Grep: "class.*Action|class.*Controller" --glob "**/*Action*.php"
Grep: "Idempotency-Key|idempotency_key|idempotencyKey" --glob "**/*.php"

# Command handlers without dedup check
Grep: "class.*Handler.*\{" --glob "**/*Handler*.php"
Grep: "wasProcessed|isProcessed|alreadyHandled" --glob "**/*Handler*.php"

# Payment/charge operations without idempotency
Grep: "->charge\(|->pay\(|->refund\(|->transfer\(" --glob "**/*.php"
Grep: "findByRequestId|findByIdempotencyKey" --glob "**/*.php"

# Retry loops with side effects
Grep: "while.*retry|for.*attempt|catch.*retry" --glob "**/*.php"

# Email/SMS in retry blocks
Grep: "->send\(.*Email|->send\(.*Sms|mailer->send" --glob "**/*.php"

# Missing unique constraints on write operations
Grep: "->save\(|->persist\(|->insert\(" --glob "**/*Handler*.php"

Severity Classification

Pattern Severity
Payment/charge without idempotency key 🔴 Critical
Command handler without dedup check 🔴 Critical
POST endpoint without Idempotency-Key 🟠 Major
Email send in retry loop without guard 🟠 Major
Write operation without unique constraint 🟠 Major
Missing idempotency on non-critical updates 🟡 Minor

Output Format

### Idempotency Issue: [Brief Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Type:** [Missing Key|Non-Idempotent Handler|Duplicate Write|Retry-Unsafe]

**Issue:**
[Description of the idempotency violation]

**Risk:**
- Duplicate charges/payments on retry
- Double email/SMS delivery
- Inconsistent state after network failure

**Code:**
```php
// Problematic pattern

Fix:

// With idempotency guard


## When This Is Acceptable

- **GET/DELETE requests** -- GET is inherently idempotent, DELETE on same resource is safe (returns 404 on retry)
- **Internal synchronous calls** -- Direct method calls within a single transaction boundary don't need idempotency keys
- **Upsert operations** -- INSERT ON CONFLICT UPDATE is inherently idempotent by design
- **Read-only commands** -- Query handlers that only read data don't need dedup checks

### False Positive Indicators
- Operation is wrapped in a database transaction with unique constraint
- Gateway already enforces idempotency (e.g., Stripe idempotency key at SDK level)
- Operation is naturally idempotent (setting a value, not incrementing)

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

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

场景价值85/100

亮点

  • 解决 PHP 开发中幂等性这一关键架构问题,避免资金损失和数据不一致
  • 提供具体检测模式和修复示例,实用性强
触发精准90/100

亮点

  • 触发描述清晰完整,覆盖 POST/PUT 端点、命令处理器、支付操作等核心场景
  • 明确列出可接受场景和误报指示器,边界清晰
结构规范95/100

待提升项

  • 缺少 When to Use 显式章节 原报告严重程度:轻微

    已有 When This Is Acceptable 内容,但未使用标准章节名且位置靠后

    改进建议:将 When This Is Acceptable 移至 Detection Patterns 前并改为 When to Use 章节

亮点

  • Detection Patterns 分 4 类,每类含 BAD/GOOD 代码对比,结构清晰
  • 提供完整 grep 命令和 Severity Classification,执行指导性强
执行可靠88/100

亮点

  • 基于 grep 模式匹配,无需外部依赖,执行简单可靠
  • Severity Classification 明确风险等级,帮助用户优先处理关键问题
证据可验 (前四项均值)90/100

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

正文静态检测

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

正文未命中当前规则。

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

权限与使用前检查

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

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

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

安全评级与访问范围

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

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