Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Illuminate/Cache/CacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,11 @@ protected function createDatabaseDriver(array $config)

return $this->repository(
new DatabaseStore(
$connection, $config['table'], $this->getPrefix($config)
$connection,
$config['table'],
$this->getPrefix($config),
$config['lock_table'] ?? 'cache_locks',
$config['lock_lottery'] ?? [2, 100]
)
);
}
Expand Down
138 changes: 138 additions & 0 deletions src/Illuminate/Cache/DatabaseLock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?php

namespace Illuminate\Cache;

use Illuminate\Database\Connection;
use Illuminate\Database\QueryException;

class DatabaseLock extends Lock
{
/**
* The database connection instance.
*
* @var \Illuminate\Database\Connection
*/
protected $connection;

/**
* The database table name.
*
* @var string
*/
protected $table;

/**
* The prune probability odds.
*
* @var array
*/
protected $lottery;

/**
* Create a new lock instance.
*
* @param \Illuminate\Database\Connection $connection
* @param string $table
* @param string $name
* @param int $seconds
* @param string|null $owner
* @param array $lottery
* @return void
*/
public function __construct(Connection $connection, $table, $name, $seconds, $owner = null, $lottery = [2, 100])
{
parent::__construct($name, $seconds, $owner);

$this->connection = $connection;
$this->table = $table;
$this->lottery = $lottery;
}

/**
* Attempt to acquire the lock.
*
* @return bool
*/
public function acquire()
{
$acquired = false;

try {
$this->connection->table($this->table)->insert([
'id' => $this->name,
'owner' => $this->owner,
'expires_at' => $this->expiresAt(),
]);

$acquired = true;
} catch (QueryException $e) {
$updated = $this->connection->table($this->table)
->where('id', $this->name)
->where(function ($query) {
return $query->where('owner', $this->owner)->orWhere('expires_at', '<=', time());
})->update([
'owner' => $this->owner,
'expires_at' => $this->expiresAt(),
]);

$acquired = $updated >= 1;
}

if (random_int(1, $this->lottery[1]) <= $this->lottery[0]) {
$this->connection->table($this->table)->where('expires_at', '<=', time())->delete();
}

return $acquired;
}

/**
* Get the UNIX timestamp indicating when the lock should expire.
*
* @return int
*/
protected function expiresAt()
{
return $this->seconds > 0 ? time() + $this->seconds : now()->addDays(1)->getTimestamp();
}

/**
* Release the lock.
*
* @return bool
*/
public function release()
{
if ($this->isOwnedByCurrentProcess()) {
$this->connection->table($this->table)
->where('id', $this->name)
->where('owner', $this->owner)
->delete();

return true;
}

return false;
}

/**
* Releases this lock in disregard of ownership.
*
* @return void
*/
public function forceRelease()
{
$this->connection->table($this->table)
->where('id', $this->name)
->delete();
}

/**
* Returns the owner value written into the driver for this lock.
*
* @return string
*/
protected function getCurrentOwner()
{
return optional($this->connection->table($this->table)->where('id', $this->name)->first())->owner;
}
}
56 changes: 55 additions & 1 deletion src/Illuminate/Cache/DatabaseStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,41 @@ class DatabaseStore implements Store
*/
protected $prefix;

/**
* The name of the cache locks table.
*
* @var string
*/
protected $lockTable;

/**
* A array representation of the lock lottery odds.
*
* @var array
*/
protected $lockLottery;

/**
* Create a new database store.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param string $table
* @param string $prefix
* @param string $lockTable
* @param array $lockLottery
* @return void
*/
public function __construct(ConnectionInterface $connection, $table, $prefix = '')
public function __construct(ConnectionInterface $connection,
$table,
$prefix = '',
$lockTable = 'cache_locks',
$lockLottery = [2, 100])
{
$this->table = $table;
$this->prefix = $prefix;
$this->connection = $connection;
$this->lockTable = $lockTable;
$this->lockLottery = $lockLottery;
}

/**
Expand Down Expand Up @@ -205,6 +227,38 @@ public function forever($key, $value)
return $this->put($key, $value, 315360000);
}

/**
* Get a lock instance.
*
* @param string $name
* @param int $seconds
* @param string|null $owner
* @return \Illuminate\Contracts\Cache\Lock
*/
public function lock($name, $seconds = 0, $owner = null)
{
return new DatabaseLock(
$this->connection,
$this->lockTable,
$this->prefix.$name,
$seconds,
$owner,
$this->lockLottery
);
}

/**
* Restore a lock instance using the owner identifier.
*
* @param string $name
* @param string $owner
* @return \Illuminate\Contracts\Cache\Lock
*/
public function restoreLock($name, $owner)
{
return $this->lock($name, 0, $owner);
}

/**
* Remove an item from the cache.
*
Expand Down
65 changes: 65 additions & 0 deletions tests/Integration/Database/DatabaseLockTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace Illuminate\Tests\Integration\Database;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
* @group integration
*/
class DatabaseLockTest extends DatabaseTestCase
{
protected function setUp(): void
{
parent::setUp();

Schema::create('cache_locks', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('owner');
$table->integer('expires_at');
});
}

public function testLockCanBeAcquired()
{
$lock = Cache::driver('database')->lock('foo');
$this->assertTrue($lock->get());

$otherLock = Cache::driver('database')->lock('foo');
$this->assertFalse($otherLock->get());

$lock->release();

$otherLock = Cache::driver('database')->lock('foo');
$this->assertTrue($otherLock->get());

$otherLock->release();
}

public function testLockCanBeForceReleased()
{
$lock = Cache::driver('database')->lock('foo');
$this->assertTrue($lock->get());

$otherLock = Cache::driver('database')->lock('foo');
$otherLock->forceRelease();
$this->assertTrue($otherLock->get());

$otherLock->release();
}

public function testExpiredLockCanBeRetrieved()
{
$lock = Cache::driver('database')->lock('foo');
$this->assertTrue($lock->get());
DB::table('cache_locks')->update(['expires_at' => now()->subDays(1)->getTimestamp()]);

$otherLock = Cache::driver('database')->lock('foo');
$this->assertTrue($otherLock->get());

$otherLock->release();
}
}