Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
nikuscs committed Nov 21, 2024
1 parent 722dfae commit e70807a
Showing 1 changed file with 52 additions and 2 deletions.
54 changes: 52 additions & 2 deletions src/Helpers/Locker/Locker.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,11 @@ public function getIdFromModel(): string
$key = $this->model->getKeyName();

return Str::snake(sprintf(
'%s_%s_%s',
'%s_%s_%s_%s',
'locks',
strtolower($this->getModelName()),
$this->model->{$key}
$this->model->{$key},
$this->model?->created_at?->timestamp ?? '-',
));
}

Expand Down Expand Up @@ -232,6 +233,28 @@ public function restore(): Lock
return Cache::restoreLock($this->getId(), (string) $this->owner);
}

/**
* Clear all locks for the current model
*/
public function clearAll(): void
{
/** @var RedisStore $store */
$store = Cache::store('redis');
/** @var \Illuminate\Redis\Connections\Connection $redis */
$redis = $store->lockConnection();

// Get all locks for this model - match the correct pattern
$pattern = sprintf('%slocks_%s*', Cache::getPrefix(), strtolower($this->getModelName()));
$keys = $redis->keys($pattern);

if (! empty($keys)) {
foreach ($keys as $key) {
$lock_key = str_replace([Cache::getPrefix(), 'database_'], '', $key);
Cache::lock($lock_key)->forceRelease();
}
}
}

/**
* Get the model name formatted.
*/
Expand All @@ -245,4 +268,31 @@ protected function getModelName(): string
return substr($result !== false ? $result : '', 1);
}
}

/**
* Get all active locks in the system
*
* @return array<string, mixed> Array of lock information
*/
public static function getAllLocks(): array
{
/** @var RedisStore $store */
$store = Cache::store('redis');
/** @var \Illuminate\Redis\Connections\Connection $redis */
$redis = $store->lockConnection();

// Get all locks with pattern locks_*
$pattern = sprintf('%s%s_*', Cache::getPrefix(), 'locks');
$keys = $redis->keys($pattern);

$locks = [];
foreach ($keys as $key) {
$locks[$key] = [
'owner' => $redis->get($key),
'ttl' => $redis->ttl($key),
];
}

return $locks;
}
}

0 comments on commit e70807a

Please sign in to comment.