Logo von Check Distributed Locks

Check Distributed Locks

Community
dykyi-roman
check-distributed-locks

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.

Übersicht

Herausgeberdykyi-roman
Repositoryawesome-claude-code
Skill-Namecheck-distributed-locks
Sterne
98
Forks
25
Mitgelieferte Dateien
Nur Anweisungen
LizenzMIT
Links
  • Anweisungen in Markdown

    Eine SKILL.md-Datei, die das Modell bei Bedarf lädt. So werden nur dann Token verbraucht, wenn eine Anfrage tatsächlich dazu passt.

  • Funktioniert mit jedem LLM

    KI-Skills bestehen aus reinem Markdown, nicht aus anbieterspezifischem Code. Daher funktionieren sie mit GPT, Claude, Gemini, Grok oder einem lokalen Modell.

  • In sich abgeschlossen

    Alles, was das Modell braucht, steht in den Anweisungen — keine zusätzlichen Dateien zum Synchronisieren.

  • Open Source

    Von dykyi-roman auf GitHub veröffentlicht. Prüfen Sie vor der Installation die Quelldateien.

Installation

Installieren Sie den KI-Skill Check Distributed Locks in TypingMind, um ihn mit jedem LLM zu nutzen, oder fügen Sie ihn einem anderen Agenten hinzu, der SKILL.md lesen kann.

1

In TypingMind installieren

TypingMind installiert einen Skill direkt aus seinem GitHub-Ordner. Dabei liest die App SKILL.md, bündelt die Ressourcendateien und speichert das Ergebnis lokal.

  1. Öffnen Sie die App und gehen Sie zu Plugins → Skills.
  2. Wählen Sie „Von GitHub installieren“.
  3. Fügen Sie die unten angegebene URL des Skill-Ordners ein und bestätigen Sie.
    https://github.com/dykyi-roman/awesome-claude-code/tree/master/skills/check-distributed-locks
  4. Aktivieren Sie den Skill in jedem Chat, in dem er verfügbar sein soll.
Plugins → Skills → Skill hinzufügen → Über GitHub-URL. Fügen Sie dann die Ordner-URL ein und klicken Sie auf „Weiter“.
2

In einem anderen Agenten installieren

Jeder Agent, der das Agent-Skills-Format unterstützt, kann diesen Skill nutzen. Kopieren Sie den Ordner in das Skill-Verzeichnis des jeweiligen Agenten.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/dykyi-roman/awesome-claude-code.git /tmp/awesome-claude-code
mkdir -p .claude/skills
cp -r /tmp/awesome-claude-code/skills/check-distributed-locks .claude/skills/check-distributed-locks
Starten Sie Claude Code nach dem Kopieren neu, damit der neue Skill erkannt wird.

In TypingMind verwenden

Aktivieren Sie Check Distributed Locks in einem beliebigen Chat in TypingMind. Den Rest übernimmt das Modell. Name und Beschreibung des Skills stehen im System-Prompt. Sobald eine Anfrage passt, lädt das Modell selbstständig die vollständigen Anweisungen — Sie müssen den Skill nie manuell aufrufen, und er verbraucht erst Token, wenn er tatsächlich genutzt wird.

Das Modell lädt Check Distributed Locks automatisch, sobald eine passende Anfrage gestellt wird.

Funktioniert mit jedem KI-Modell

KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher ist Check Distributed Locks nicht an das Modell gebunden, für das der Skill geschrieben wurde. Installieren Sie ihn einmal in TypingMind und nutzen Sie ihn mit GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder einem selbst betriebenen lokalen Modell — alles mit Ihren eigenen API-Schlüsseln.

  • Wird nur bei Bedarf geladen

    Der System-Prompt enthält nur den Namen und die Beschreibung. Die Anweisungen werden bei der ersten passenden Anfrage geladen. Ein ungenutzter Skill verursacht daher keine Kosten.

  • Modell im laufenden Chat wechseln

    Da der Skill aus Anweisungen statt aus Code besteht, funktioniert er auch nach einem Modellwechsel — das nächste Modell liest dieselbe SKILL.md-Datei.

Skill-Anweisungen

Dies ist der Inhalt von SKILL.md, den das Modell lädt. Lesen Sie ihn vor der Installation — ein Skill besteht aus Anweisungen, denen Ihr Modell folgt.

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
<?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
<?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
<?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
<?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
<?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

bash
# 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

PatternSeverity
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

markdown
### 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:

php
// 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)

Häufig gestellte Fragen

Was macht der KI-Skill Check Distributed Locks?

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.

Warum Check Distributed Locks in TypingMind nutzen?

Weil Sie den Skill einmal installieren und mit jedem Modell verwenden können. Check Distributed Locks besteht aus reinem Markdown statt aus anbieterspezifischem Code. So funktioniert derselbe Skill mit GPT-5, Claude, Gemini, Grok oder einem lokalen Modell – und Sie können das Modell mitten im Chat wechseln, ohne dass der Skill seine Funktion verliert. TypingMind verwendet Ihre eigenen API-Schlüssel. Sie bezahlen die Anbieter daher direkt statt über ein Abonnement pro Nutzerplatz, und Ihre Skills und Chats bleiben in Ihrem eigenen Speicher.

Wie installiere ich Check Distributed Locks in TypingMind?

Öffnen Sie in TypingMind Plugins → Skills → Von GitHub installieren und fügen Sie https://github.com/dykyi-roman/awesome-claude-code/tree/master/skills/check-distributed-locks ein. TypingMind liest die Datei SKILL.md und installiert den Skill, den Sie für jeden Chat einzeln aktivieren können.

Welche KI-Modelle können Check Distributed Locks nutzen?

Jedes Modell, das Sie mit TypingMind verbinden. KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher können GPT, Claude, Gemini, Grok und lokale Modelle diesen Skill laden, wenn eine Anfrage dazu passt.

Wie viele KI-Modelle kann ich mit Check Distributed Locks verwenden?

So viele Sie möchten. In TypingMind können Sie Check Distributed Locks mit jedem Modell verwenden, das Skills unterstützt, etwa mit GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama. Dabei nutzen Sie Ihre eigenen API-Schlüssel.

Ist der KI-Skill Check Distributed Locks kostenlos?

Ja. Der Skill wird von dykyi-roman auf GitHub unter der Lizenz MIT veröffentlicht. Sie bezahlen nur Ihren eigenen KI-Anbieter für die verwendeten Token.

Was sind KI-Skills?

Ein KI-Skill ist ein wiederverwendbares Anweisungspaket, das einem KI-Modell vermittelt, wie es eine bestimmte Aufgabe erledigt. Es folgt dem offenen Format Agent Skills: Die Datei SKILL.md enthält den Namen und die Beschreibung des Skills. Hinzu kommen bei Bedarf Skripte, Vorlagen oder Referenzdateien für das Modell. Das Modell liest die Anweisungen nur, wenn Ihre Anfrage zum Skill passt. Ein installierter Skill verursacht daher erst Kosten, wenn er verwendet wird.

Wie unterscheiden sich KI-Skills von Plugins oder MCP-Servern?

Ein Plugin oder MCP-Server stellt einem Modell neue aufrufbare Tools bereit – Code, der auf einem System ausgeführt wird und ein Ergebnis zurückgibt. Ein KI-Skill vermittelt dem Modell stattdessen Wissen und Vorgehensweisen: wie es eine Aufgabe angeht, welche Schritte es befolgt und wie eine gute Ausgabe aussieht. Skills bestehen aus reinem Markdown und kommen daher ohne Server, API-Schlüssel und Laufzeitumgebung aus. Sie funktionieren mit jedem Modell.

Alle anzeigen

Jetzt eigenen KI-Arbeitsbereich einrichten

Abonnieren Sie unseren Newsletter und erfahren Sie mehr über neue Funktionen und kommende Gewinnspiele 👇