Skip to content

Instantly share code, notes, and snippets.

@mmoreram
Created August 21, 2019 08:44
Show Gist options
  • Save mmoreram/752380f204638f49f137986dcd867165 to your computer and use it in GitHub Desktop.
Save mmoreram/752380f204638f49f137986dcd867165 to your computer and use it in GitHub Desktop.
/**
* Enqueue
*
* @param Locker $locker
* @param string $resourceID
* @param float $timeout
*
* @return PromiseInterface
*/
public function enqueue(
Locker $locker,
string $resourceID,
float $timeout
) : PromiseInterface
{
return $this
->client
->eval('
local resource = ARGV[1];
local locker = ARGV[2];
local hash = resource .. ".hash";
local channel = resource .. ".channel";
local len = redis.call("hlen", hash);
redis.call(hset, hash, locker, true);
if (len == 0) then
redis.call("lpush", channel, '.');
end
', 1, $resourceID, $locker->ID())
->then(function() use ($resourceID, $timeout) {
var_dump('SI');
return $this
->client
->blpop($resourceID . '.channel', $timeout);
});
}
/**
* Release
*
* @param Locker $locker
* @param string $resourceID
*
* @return PromiseInterface
*/
public function release(
Locker $locker,
string $resourceID
) : PromiseInterface
{
$promise = new FulfilledPromise();
if ($locker->owns()) {
$promise->then(function() use ($resourceID, $locker) {
return $this
->client
->eval('
local resource = ARGV[1];
local locker = ARGV[2];
local hash = resource .. ".hash";
local channel = resource .. ".channel";
local len = redis.call("hlen", hash);
redis.call(hdel, hash, locker);
if (len > 0) then
redis.call("lpush", channel, ".");
end
', 1, $resourceID, $locker->ID());
});
}
return $promise;
}
$promise = $locker
->enqueue()
->then(function(Locker $locker) use (&$finished, &$current, $loop, $client) {
$this->assertEquals($current, 0);
$current++;
$finished++;
return $client
->get('http://google.es')
->then(function() use (&$current, $locker) {
$this->assertEquals($current, 1);
$current--;
return $locker;
});
})
->then(function(Locker $locker) {
return $locker->release();
});
$loop->run();
Block\await($promise, $loop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment