From ca03bc662a87727a8388b65a132b82c06d4ea58b Mon Sep 17 00:00:00 2001 From: Alexander Pankratov Date: Tue, 9 Jun 2020 01:47:54 +0300 Subject: [PATCH] New mysql cache cleanup --- .../MadelineProto/Db/ArrayCacheTrait.php | 28 +++++++++---------- src/danog/MadelineProto/Db/MysqlArray.php | 2 ++ 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/danog/MadelineProto/Db/ArrayCacheTrait.php b/src/danog/MadelineProto/Db/ArrayCacheTrait.php index f94a90eb..20abdb9c 100644 --- a/src/danog/MadelineProto/Db/ArrayCacheTrait.php +++ b/src/danog/MadelineProto/Db/ArrayCacheTrait.php @@ -2,6 +2,9 @@ namespace danog\MadelineProto\Db; +use Amp\Loop; +use danog\MadelineProto\Logger; + trait ArrayCacheTrait { /** @@ -18,7 +21,6 @@ trait ArrayCacheTrait protected array $cache = []; protected string $ttl = '+5 minutes'; private string $ttlCheckInterval = '+1 minute'; - private int $nextTtlCheckTs = 0; protected function getCache(string $key, $default = null) { @@ -30,8 +32,6 @@ trait ArrayCacheTrait $this->cache[$key]['ttl'] = strtotime($this->ttl); } - $this->cleanupCache(); - return $result; } @@ -47,8 +47,6 @@ trait ArrayCacheTrait 'value' => $value, 'ttl' => strtotime($this->ttl), ]; - - $this->cleanupCache(); } /** @@ -61,12 +59,9 @@ trait ArrayCacheTrait unset($this->cache[$key]); } - /** - * Remove all keys from cache - */ - protected function clearCache(): void + protected function startCacheCleanupLoop(): void { - $this->cache = []; + Loop::repeat(strtotime($this->ttlCheckInterval, 0) * 1000, fn() => $this->cleanupCache()); } /** @@ -75,11 +70,6 @@ trait ArrayCacheTrait protected function cleanupCache(): void { $now = time(); - if ($this->nextTtlCheckTs > $now) { - return; - } - - $this->nextTtlCheckTs = strtotime($this->ttlCheckInterval, $now); $oldKeys = []; foreach ($this->cache as $cacheKey => $cacheValue) { if ($cacheValue['ttl'] < $now) { @@ -89,6 +79,14 @@ trait ArrayCacheTrait foreach ($oldKeys as $oldKey) { $this->unsetCache($oldKey); } + + Logger::log( + sprintf( + "cache for table:%s; keys left: %s; keys removed: %s", + $this->table, \count($this->cache), \count($oldKeys) + ), + Logger::VERBOSE + ); } } \ No newline at end of file diff --git a/src/danog/MadelineProto/Db/MysqlArray.php b/src/danog/MadelineProto/Db/MysqlArray.php index 8c842a7a..143e84b2 100644 --- a/src/danog/MadelineProto/Db/MysqlArray.php +++ b/src/danog/MadelineProto/Db/MysqlArray.php @@ -57,6 +57,8 @@ class MysqlArray implements DbArray $instance->db = static::getDbConnection($settings); $instance->ttl = $settings['cache_ttl'] ?? $instance->ttl; + $instance->startCacheCleanupLoop(); + return call(static function() use($instance, $value) { yield from static::renameTmpTable($instance, $value); yield from $instance->prepareTable();