MadelineProto/src/danog/MadelineProto/Db/ArrayCacheTrait.php

104 lines
2.2 KiB
PHP
Raw Normal View History

2020-05-02 19:36:59 +02:00
<?php
namespace danog\MadelineProto\Db;
2020-06-09 00:47:54 +02:00
use Amp\Loop;
use danog\MadelineProto\Logger;
2020-10-03 12:36:08 +02:00
/**
2020-10-03 15:04:35 +02:00
* Array caching trait.
2020-10-03 12:36:08 +02:00
*/
2020-05-02 19:36:59 +02:00
trait ArrayCacheTrait
{
/**
* @var array<mixed>
2020-05-02 19:36:59 +02:00
*/
protected array $cache = [];
/**
* @var array<int>
*/
protected array $ttlValues = [];
/**
* TTL interval.
*/
protected int $ttl = 5 * 60;
/**
* TTL cleanup interval.
*/
private int $ttlCheckInterval = 60;
/**
* Cache cleanup watcher ID.
*/
private ?string $cacheCleanupId = null;
2020-05-02 19:36:59 +02:00
protected function getCache(string $key, $default = null)
{
if (!isset($this->ttlValues[$key])) {
return $default;
2020-05-02 19:36:59 +02:00
}
2020-10-07 23:45:10 +02:00
$this->ttlValues[$key] = time() + $this->ttl;
return $this->cache[$key];
2020-05-02 19:36:59 +02:00
}
/**
2020-06-16 17:52:55 +02:00
* Save item in cache.
2020-05-02 19:36:59 +02:00
*
* @param string $key
* @param $value
*/
protected function setCache(string $key, $value): void
{
$this->cache[$key] = $value;
2020-10-07 23:45:10 +02:00
$this->ttlValues[$key] = time() + $this->ttl;
2020-05-02 19:36:59 +02:00
}
/**
2020-06-16 17:52:55 +02:00
* Remove key from cache.
2020-05-02 19:36:59 +02:00
*
* @param string $key
*/
protected function unsetCache(string $key): void
{
unset($this->cache[$key], $this->ttlValues[$key]);
2020-05-02 19:36:59 +02:00
}
2020-06-09 00:47:54 +02:00
protected function startCacheCleanupLoop(): void
2020-05-02 19:36:59 +02:00
{
$this->cacheCleanupId = Loop::repeat($this->ttlCheckInterval * 1000, fn () => $this->cleanupCache());
}
protected function stopCacheCleanupLoop(): void
{
if ($this->cacheCleanupId) {
Loop::cancel($this->cacheCleanupId);
$this->cacheCleanupId = null;
}
2020-05-02 19:36:59 +02:00
}
/**
2020-06-16 17:52:55 +02:00
* Remove all keys from cache.
*/
protected function cleanupCache(): void
{
2020-06-16 17:52:55 +02:00
$now = \time();
$oldCount = 0;
foreach ($this->ttlValues as $cacheKey => $ttl) {
if ($ttl < $now) {
$this->unsetCache($cacheKey);
$oldCount++;
}
}
2020-06-09 00:47:54 +02:00
Logger::log(
2020-06-16 17:52:55 +02:00
\sprintf(
"cache for table: %s; keys left: %s; keys removed: %s",
(string) $this,
2020-06-16 17:52:55 +02:00
\count($this->cache),
$oldCount
2020-06-09 00:47:54 +02:00
),
Logger::VERBOSE
);
}
2020-06-16 17:52:55 +02:00
}