check-distributed-locks
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "check-distributed-locks":https://skillpi.com/zh/skills/deepskill-fcb2e1fafde61bafe078684b1af1f926e43402d612cc2096f6e6456bae511f84。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
分析 PHP 代码中的分布式锁问题。检测缺少 TTL 的锁、未用 try/finally 的锁、不安全的 Redis SETNX 使用模式、未释放的锁以及可能的死锁风险。
介绍来源: third_party · dykyi-roman · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 输入和输出
- 减记
- 实测状态
- 未测试
文件浏览
Frontmatter
name: check-distributed-locks
description: Analyzes PHP code for distributed lock issues. Detects missing TTL on locks, lock without try/finally, unsafe Redis SETNX patterns, missing lock release, and deadlock risks.Distributed Lock Check
Analyze PHP code for distributed locking anti-patterns that cause deadlocks, race conditions, and resource starvation in multi-instance deployments.
Detection Patterns
1. Missing TTL on Locks
<?php
declare(strict_types=1);
// BAD: Lock without expiration -- if process dies, lock is held forever
final readonly class CacheRefreshService
{
public function refresh(string $key): void
{
$this->redis->set('lock:' . $key, '1');
// No TTL! If process crashes here, lock is orphaned forever
try {
$data = $this->expensiveQuery();
$this->cache->set($key, $data);
} finally {
$this->redis->del('lock:' . $key);
}
}
}
// GOOD: Lock with TTL
final readonly class CacheRefreshService
{
public function refresh(string $key): void
{
$acquired = $this->redis->set('lock:' . $key, uniqid(), ['NX', 'EX' => 30]);
if (!$acquired) {
return; // Another process holds the lock
}
try {
$data = $this->expensiveQuery();
$this->cache->set($key, $data);
} finally {
$this->redis->del('lock:' . $key);
}
}
}
2. Lock Without try/finally
<?php
declare(strict_types=1);
// BAD: Lock acquired but not released on exception
final readonly class ImportService
{
public function importBatch(array $items): void
{
$lock = $this->lockFactory->createLock('import', 300);
$lock->acquire(true);
$this->processItems($items);
// If processItems() throws, lock is never released!
$lock->release();
}
}
// GOOD: Lock release guaranteed in finally block
final readonly class ImportService
{
public function importBatch(array $items): void
{
$lock = $this->lockFactory->createLock('import', 300);
$lock->acquire(true);
try {
$this->processItems($items);
} finally {
$lock->release();
}
}
}
3. Unsafe Redis SETNX Pattern
<?php
declare(strict_types=1);
// BAD: SETNX without EXPIRE -- race condition between two commands
final readonly class RedisLock
{
public function acquire(string $key): bool
{
$acquired = $this->redis->setnx('lock:' . $key, '1');
if ($acquired) {
$this->redis->expire('lock:' . $key, 30);
// Race condition: if process dies between SETNX and EXPIRE,
// lock has no TTL and is held forever
}
return $acquired;
}
}
// BAD: SET without NX -- overwrites existing lock
$this->redis->set('lock:' . $key, '1', 30);
// This always succeeds, even if another process holds the lock!
// GOOD: Atomic SET NX EX (single command, no race)
final readonly class RedisLock
{
public function acquire(string $key, int $ttl = 30): bool
{
$token = bin2hex(random_bytes(16));
$acquired = $this->redis->set(
'lock:' . $key,
$token,
['NX', 'EX' => $ttl],
);
if ($acquired) {
$this->tokens[$key] = $token;
}
return (bool) $acquired;
}
public function release(string $key): void
{
// Lua script: only delete if token matches (owner check)
$script = <<<'LUA'
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
LUA;
$this->redis->eval($script, ['lock:' . $key, $this->tokens[$key]], 1);
}
}
4. Missing Symfony Lock Component
<?php
declare(strict_types=1);
// BAD: Custom lock implementation when framework provides one
final class CustomFileLock
{
private $fileHandle;
public function acquire(string $name): bool
{
$this->fileHandle = fopen('/tmp/' . $name . '.lock', 'c');
return flock($this->fileHandle, LOCK_EX | LOCK_NB);
}
public function release(): void
{
flock($this->fileHandle, LOCK_UN);
fclose($this->fileHandle);
}
}
// GOOD: Use Symfony Lock component with Redis store
// config/packages/lock.yaml:
// framework:
// lock: '%env(REDIS_URL)%'
final readonly class OrderProcessingService
{
public function __construct(
private LockFactory $lockFactory,
) {}
public function processOrder(OrderId $orderId): void
{
$lock = $this->lockFactory->createLock(
resource: 'order-processing:' . $orderId->toString(),
ttl: 60,
);
if (!$lock->acquire(false)) {
throw new OrderAlreadyBeingProcessedException($orderId);
}
try {
$this->doProcessOrder($orderId);
} finally {
$lock->release();
}
}
}
5. Deadlock Patterns -- Inconsistent Lock Ordering
<?php
declare(strict_types=1);
// BAD: Acquiring multiple locks in inconsistent order
final readonly class TransferService
{
public function transfer(AccountId $from, AccountId $to, Money $amount): void
{
// Thread A: locks account-1, then account-2
// Thread B: locks account-2, then account-1
// DEADLOCK!
$lockFrom = $this->lockFactory->createLock('account:' . $from->toString(), 30);
$lockTo = $this->lockFactory->createLock('account:' . $to->toString(), 30);
$lockFrom->acquire(true);
$lockTo->acquire(true); // May deadlock if another transfer is from $to to $from
try {
$this->debit($from, $amount);
$this->credit($to, $amount);
} finally {
$lockTo->release();
$lockFrom->release();
}
}
}
// GOOD: Consistent lock ordering (alphabetical/numerical)
final readonly class TransferService
{
public function transfer(AccountId $from, AccountId $to, Money $amount): void
{
// Always lock in consistent order (lower ID first)
$ids = [$from->toString(), $to->toString()];
sort($ids);
$lockFirst = $this->lockFactory->createLock('account:' . $ids[0], 30);
$lockSecond = $this->lockFactory->createLock('account:' . $ids[1], 30);
$lockFirst->acquire(true);
try {
$lockSecond->acquire(true);
try {
$this->debit($from, $amount);
$this->credit($to, $amount);
} finally {
$lockSecond->release();
}
} finally {
$lockFirst->release();
}
}
}
Grep Patterns
# Locks without TTL
Grep: "->set\(['\"]lock:|->setnx\(" --glob "**/*.php"
Grep: "createLock\([^)]*\)" --glob "**/*.php"
# SETNX without atomic EXPIRE
Grep: "setnx\(" --glob "**/*.php"
# Lock without try/finally
Grep: "->acquire\(|->lock\(" --glob "**/*.php"
# flock usage (local file lock)
Grep: "flock\(" --glob "**/src/**/*.php"
# Custom lock implementations
Grep: "class.*Lock|class.*Mutex|class.*Semaphore" --glob "**/*.php"
# Symfony Lock component usage
Grep: "LockFactory|LockInterface|use Symfony\\\\Component\\\\Lock" --glob "**/*.php"
# Multiple lock acquisitions in same method (deadlock risk)
Grep: "createLock.*\n.*createLock|acquire.*\n.*acquire" --glob "**/*.php"
# Lock release patterns
Grep: "->release\(\)" --glob "**/*.php"
Grep: "finally" --glob "**/*.php"
Severity Classification
| Pattern | Severity |
|---|---|
| Lock without TTL | 🔴 Critical |
| SETNX without atomic EXPIRE | 🔴 Critical |
| Deadlock from inconsistent lock ordering | 🔴 Critical |
| Lock without try/finally | 🟠 Major |
| Custom file-based lock (flock) | 🟠 Major |
| Missing lock ownership verification | 🟠 Major |
| Lock release without owner check | 🟡 Minor |
| Custom lock when framework provides one | 🟡 Minor |
Output Format
### Distributed Lock Issue: [Brief Description]
**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Type:** [No TTL|No Finally|Unsafe SETNX|Deadlock|File Lock]
**Issue:**
[Description of the distributed lock problem]
**Risk:**
- Permanent lock hold on process crash
- Deadlock between concurrent processes
- Race condition on lock acquisition
**Code:**
```php
// Problematic locking pattern
Fix:
// Safe distributed locking
## When This Is Acceptable
- **Single-instance deployment** -- File-based locking is fine when only one process runs
- **Short-lived CLI scripts** -- One-shot scripts with no concurrency don't need distributed locks
- **In-memory locks for thread safety** -- PHP-FPM worker process isolation makes in-memory locks irrelevant (each request is isolated)
- **Database advisory locks** -- Using `pg_advisory_lock()` or `GET_LOCK()` is valid for single-database setups
### False Positive Indicators
- Lock is in test code or a test double
- flock is used for log file rotation (not coordination)
- Custom lock class wraps Symfony Lock component internally
- SETNX is immediately followed by EXPIRE in a Lua script (atomic)当前收录版本
0.0.1
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 针对PHP分布式锁这一高频刚需场景,提供完整的检测模式与修复方案
- 覆盖5大核心问题:TTL缺失、try/finally缺失、Redis SETNX不安全模式、锁释放缺失、死锁风险
- 提供grep模式便于集成到CI/CD流程
亮点
- 触发词精准完整,覆盖多种变体,边界清晰
- description明确说明检测的5类问题,便于用户理解适用场景
亮点
- Phase/步骤清晰,有出口条件,含端到端示例
- frontmatter完整,单文件≤500行
- 提供完整的代码示例和修复方案
亮点
- 工具来源明确,参数正确,覆盖主要异常
- 不可逆操作有确认机制
- 提供严重性分类和输出格式规范
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。