1
0
mirror of https://github.com/danog/dns.git synced 2024-11-30 04:29:06 +01:00

Make caching API asynchronous

Closes #5
This commit is contained in:
Chris Wright 2014-07-18 01:07:01 +01:00
parent 361e207d1f
commit d74f8c9a10
3 changed files with 30 additions and 15 deletions

View File

@ -14,9 +14,9 @@ interface Cache
*
* @param string $name Name to query
* @param int $type AddressModes::INET4_ADDR or AddressModes::INET6_ADDR
* @return string|null Mapped IP address or null or no record exists
* @param callable $callback Function to receive the result
*/
public function resolve($name, $type);
public function resolve($name, $type, callable $callback);
/**
* Store an entry in the cache

View File

@ -286,27 +286,42 @@ class Client
}
/**
* Send a request to the server
* Lookup name in cache and send request to server on failure
*
* @param int $id
*/
private function processPendingLookup($id)
{
$lookup = &$this->pendingLookups[$id];
if (!$lookup['requests']) {
if (!$this->pendingLookups[$id]['requests']) {
$this->completePendingLookup($id, null, ResolutionErrors::ERR_NO_RECORD);
return;
}
$name = $lookup['name'];
$type = array_shift($lookup['requests']);
$name = $this->pendingLookups[$id]['name'];
$type = array_shift($this->pendingLookups[$id]['requests']);
if ($this->cache && $addr = $this->cache->resolve($name, $type)) {
$this->completePendingLookup($id, $addr, $type);
return;
if ($this->cache) {
$this->cache->resolve($name, $type, function($addr) use ($id, $name, $type) {
if ($addr !== null) {
$this->completePendingLookup($id, $addr, $type);
} else {
$this->dispatchRequest($id, $name, $type);
}
});
} else {
$this->dispatchRequest($id, $name, $type);
}
}
/**
* Send a request to the server
*
* @param int $id
* @param string $name
* @param int $type
*/
private function dispatchRequest($id, $name, $type)
{
$lookup['last_type'] = $type;
$this->pendingRequestsByNameAndType[$name][$type]['lookups'][$id] = $lookup;

View File

@ -19,19 +19,19 @@ class MemoryCache implements Cache
*
* @param string $name
* @param int $type
* @return string|null
* @param callable $callback
*/
public function resolve($name, $type)
public function resolve($name, $type, callable $callback)
{
if (isset($this->data[$type][$name])) {
if ($this->data[$type][$name][1] >= time()) {
return $this->data[$type][$name][0];
$callback($this->data[$type][$name][0]);
}
unset($this->data[$type][$name]);
}
return null;
$callback($this->data[$type][$name][0]);
}
/**