Br optimistic locking

From Lonsdale201/wp-agent-skills · View interactive version

Br optimistic locking is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Configure Better Route 1.1 optimistic locking for REST writes with If-Match or version parameters and an atomic per-resource critical section. Use when preventing stale updates, lost writes, or two cooperating Better Route requests from passing the same version check concurrently.

How to use this skill

Skill file

Better Route optimistic locking

Use optimistic locking on updates or deletes where overwriting a newer state is unsafe. Resolve the current version from storage while the critical section is held.

use BetterRoute\Middleware\Write\CallbackOptimisticLockVersionResolver;
use BetterRoute\Middleware\Write\OptimisticLockMiddleware;
use BetterRoute\Middleware\Write\WpdbOptimisticLockCriticalSection;

$lock = new OptimisticLockMiddleware(
    versionResolver: new CallbackOptimisticLockVersionResolver(
        static function ($context): string|int|null {
            $id = (int) ($context->request->get_url_params()['id'] ?? 0);
            return my_current_record_version($id);
        }
    ),
    required: true,
    headerName: 'if-match',
    paramName: 'version',
    criticalSection: new WpdbOptimisticLockCriticalSection(timeoutSeconds: 2)
);

$router->patch('/records/(?P<id>\d+)', $handler)
    ->middleware([$auth, $lock])
    ->protectedByMiddleware('bearerAuth');

The middleware prefers If-Match, then falls back to the configured request parameter. It accepts quoted or weak ETag-like values by normalizing W/"value" to value; numeric values become strings. * accepts any available current version.

Response contract

Atomicity boundary

The default WpdbOptimisticLockCriticalSection derives a MySQL named lock from route path plus canonicalized URL parameters. It holds that lock around both the current-version read and the downstream handler. Concurrent Better Route writers using the same route identity cannot both pass the same stale check.

This is a cooperative lock, not a database-wide compare-and-swap:

For storage shared with uncontrolled writers, implement a true conditional update such as UPDATE ... WHERE id = ? AND version = ? and verify one affected row, or provide a custom OptimisticLockCriticalSectionInterface aligned with that storage.

Checks

Source references: src/Middleware/Write/OptimisticLockMiddleware.php, src/Middleware/Write/WpdbOptimisticLockCriticalSection.php, src/Middleware/Write/CallbackOptimisticLockVersionResolver.php.

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.