Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature key prefixes #56

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
"latte/latte": "~2.3@dev",
"tracy/tracy": "~2.3@dev",

"nette/tester": "~1.3@rc"
"nette/tester": "~1.3@rc",
"mockery/mockery": "~0.9"
},
"autoload": {
"psr-0": {
Expand Down
38 changes: 38 additions & 0 deletions docs/en/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,41 @@ You can disable the native driver by this option (and the emulated will take con
redis:
session: {native: off}
```

## Key namespace

Key namespace gives you availability to create prefixed keys in Redis storage.

You can define namespace for: journal, session, storage.

To use key prefixed with namespace, add `namespace` option in configuration, for example:

Instance 1
```yml
redis:
host: 127.0.0.1
port: 6379
journal:
namespace: "instance1"
session: on
storage: on
debugger: off
```

Instance 2
```yml
redis:
host: 127.0.0.1
port: 6379
journal:
namespace: "instance2"
session: on
storage: on
debugger: off
```

After configuration all keys will be prefixed "namespace:key"

Example use case:
When you use two instances of one application with one Redis server, it is possible, that your data can be overwritten by second application instance.
To avoid this problem you can define key namespaces in configuration.
43 changes: 32 additions & 11 deletions src/Kdyby/Redis/DI/RedisExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
use Nette\DI\Config;



/**
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not neccesary

* @author Filip Procházka <filip@prochazka.su>
*/
Expand Down Expand Up @@ -52,6 +51,7 @@ class RedisExtension extends Nette\DI\CompilerExtension
'lockAcquireTimeout' => FALSE,
'debugger' => '%debugMode%',
'versionCheck' => TRUE,
'namespace' => NULL,
);

/**
Expand Down Expand Up @@ -155,8 +155,17 @@ protected function loadJournal(array $config)

$builder = $this->getContainerBuilder();

$journalConfig = Nette\DI\Config\Helpers::merge(is_array($config['journal']) ? $config['journal'] : array(), array(
'namespace' => NULL,
));

$constructParams = array(
$this->prefix('@client'),
$journalConfig['namespace'],
);

$builder->addDefinition($this->prefix('cacheJournal'))
->setClass('Kdyby\Redis\RedisLuaJournal');
->setClass('Kdyby\Redis\RedisLuaJournal', $constructParams);

// overwrite
$journalService = $builder->getByType('Nette\Caching\Storages\IJournal') ?: 'nette.cacheJournal';
Expand All @@ -176,10 +185,17 @@ protected function loadStorage(array $config)

$storageConfig = Nette\DI\Config\Helpers::merge(is_array($config['storage']) ? $config['storage'] : array(), array(
'locks' => TRUE,
'namespace' => NULL,
));

$constructParams = array(
$this->prefix('@client'),
$this->prefix('@cacheJournal'),
$storageConfig['namespace'],
);

$cacheStorage = $builder->addDefinition($this->prefix('cacheStorage'))
->setClass('Kdyby\Redis\RedisStorage');
->setClass('Kdyby\Redis\RedisStorage', $constructParams);

if (!$storageConfig['locks']) {
$cacheStorage->addSetup('disableLocking');
Expand All @@ -206,7 +222,7 @@ protected function loadSession(array $config)
'weight' => 1,
'timeout' => $config['timeout'],
'database' => $config['database'],
'prefix' => self::DEFAULT_SESSION_PREFIX,
'prefix' => isset($config['namespace']) ? $config['namespace'] : self::DEFAULT_SESSION_PREFIX,
'auth' => $config['auth'],
'native' => TRUE,
'lockDuration' => $config['lockDuration'],
Expand All @@ -220,15 +236,20 @@ protected function loadSession(array $config)

if ($sessionConfig['native']) {
$this->loadNativeSessionHandler($sessionConfig);
return;
}

} else {
$builder->addDefinition($this->prefix('sessionHandler'))
->setClass('Kdyby\Redis\RedisSessionHandler', array($this->prefix('@sessionHandler_client')));
$constructParams = array(
$this->prefix('@sessionHandler_client'),
$sessionConfig['namespace'],
);

$sessionService = $builder->getByType('Nette\Http\Session') ?: 'session';
$builder->getDefinition($sessionService)
->addSetup('?->bind(?)', array($this->prefix('@sessionHandler'), '@self'));
}
$builder->addDefinition($this->prefix('sessionHandler'))
->setClass('Kdyby\Redis\RedisSessionHandler', $constructParams);

$sessionService = $builder->getByType('Nette\Http\Session') ?: 'session';
$builder->getDefinition($sessionService)
->addSetup('?->bind(?)', array($this->prefix('@sessionHandler'), '@self'));
}


Expand Down
1 change: 0 additions & 1 deletion src/Kdyby/Redis/ExclusiveLock.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ class ExclusiveLock extends Nette\Object
public $acquireTimeout = FALSE;



/**
* @param RedisClient $redisClient
*/
Expand Down
13 changes: 10 additions & 3 deletions src/Kdyby/Redis/RedisJournal.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use Nette\Caching\Cache;



/**
* Redis journal for tags and priorities of cached values.
*
Expand All @@ -36,14 +35,22 @@ class RedisJournal extends Nette\Object implements Nette\Caching\Storages\IJourn
*/
protected $client;

/**
* @var string
*/
protected $namespace = '';


/**
* @param RedisClient $client
* @param string|NULL $namespace
*/
public function __construct(RedisClient $client)
public function __construct(RedisClient $client, $namespace = NULL)
{
$this->client = $client;
if (!empty($namespace)) {
$this->namespace = $namespace . ':';
}
}


Expand Down Expand Up @@ -183,7 +190,7 @@ private function tagEntries($tag)
*/
protected function formatKey($key, $suffix = NULL)
{
return self::NS_NETTE . ':' . $key . ($suffix ? ':' . $suffix : NULL);
return self::NS_NETTE . ':' . $this->namespace . $key . ($suffix ? ':' . $suffix : NULL);
}

}
2 changes: 1 addition & 1 deletion src/Kdyby/Redis/RedisLuaJournal.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function clean(array $conds, Nette\Caching\IStorage $storage = NULL)

$args = self::flattenDp($conds);

$result = $this->client->evalScript($this->getScript('clean'), array(), array($args));
$result = $this->client->evalScript($this->getScript('clean'), array(), array($args, $this->namespace));
if (!is_array($result) && $result !== TRUE) {
throw new RedisClientException("Failed to successfully execute lua script journal.clean(): " . $this->client->getDriver()->getLastError());
}
Expand Down
15 changes: 12 additions & 3 deletions src/Kdyby/Redis/RedisSessionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ class RedisSessionHandler extends Nette\Object implements \SessionHandlerInterfa
*/
private $client;

/**
* @var string
*/
private $namespace = '';

/**
* @var Nette\Http\Session
*/
Expand All @@ -51,13 +56,16 @@ class RedisSessionHandler extends Nette\Object implements \SessionHandlerInterfa
private $ttl;



/**
* @param RedisClient $redisClient
* @param string|NULL $namespace
*/
public function __construct(RedisClient $redisClient)
public function __construct(RedisClient $redisClient, $namespace = NULL)
{
$this->client = $redisClient;
if (!empty($namespace)) {
$this->namespace = $namespace . ':';
}
}


Expand Down Expand Up @@ -228,7 +236,8 @@ protected function lock($id)
*/
private function formatKey($id)
{
return self::NS_NETTE . $id;
$key = $this->namespace . self::NS_NETTE . $id;
return $key;
}

}
16 changes: 12 additions & 4 deletions src/Kdyby/Redis/RedisStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,29 @@ class RedisStorage extends Nette\Object implements IMultiReadStorage
*/
private $journal;

/**
* @var string
*/
private $namespace = '';

/**
* @var bool
*/
private $useLocks = TRUE;



/**
* @param RedisClient $client
* @param \Nette\Caching\Storages\IJournal $journal
* @param string|NULL $namespace
*/
public function __construct(RedisClient $client, IJournal $journal = NULL)
public function __construct(RedisClient $client, IJournal $journal = NULL, $namespace = NULL)
{
$this->client = $client;
$this->journal = $journal;
if (!empty($namespace)) {
$this->namespace = $namespace . ':';
}
}


Expand Down Expand Up @@ -275,7 +283,7 @@ public function clean(array $conds)
{
// cleaning using file iterator
if (!empty($conds[Cache::ALL])) {
if ($keys = $this->client->send('keys', array(self::NS_NETTE . ':*'))) {
if ($keys = $this->client->send('keys', array(self::NS_NETTE . ':' . $this->namespace . '*'))) {
$this->client->send('del', $keys);
}

Expand All @@ -301,7 +309,7 @@ public function clean(array $conds)
*/
protected function formatEntryKey($key)
{
return self::NS_NETTE . ':' . str_replace(Cache::NAMESPACE_SEPARATOR, ':', $key);
return self::NS_NETTE . ':' . $this->namespace . str_replace(Cache::NAMESPACE_SEPARATOR, ':', $key);
}


Expand Down
12 changes: 10 additions & 2 deletions src/Kdyby/Redis/scripts/common.lua
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@

local namespace = ARGV[2]
if namespace == nil then
namespace = ""
end

rawset(_G, "namespace", namespace)

local formatKey = function (key, suffix)
local res = "Nette.Journal:" .. key
local res = "Nette.Journal:" .. namespace .. key
if suffix ~= nil then
res = res .. ":" .. suffix
end
Expand All @@ -9,7 +16,7 @@ local formatKey = function (key, suffix)
end

local formatStorageKey = function(key, suffix)
local res = "Nette.Storage:" .. key
local res = "Nette.Storage:" .. namespace .. key
if suffix ~= nil then
res = res .. ":" .. suffix
end
Expand Down Expand Up @@ -45,3 +52,4 @@ local cleanEntry = function (keys)
-- redis.call('exec')
end
end

2 changes: 1 addition & 1 deletion src/Kdyby/Redis/scripts/journal.clean.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ local conds = cjson.decode(ARGV[1])

if conds["all"] ~= nil then
-- redis.call('multi')
for i, value in pairs(redis.call('keys', "Nette.Journal:*")) do
for i, value in pairs(redis.call('keys', "Nette.Journal:".. namespace .."*")) do
redis.call('del', value)
end
-- redis.call('exec')
Expand Down
Loading