From 85ce6bfd41c5fbbef0cd8c9b2ab4f40302f8f12f Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Sun, 27 Feb 2022 21:33:24 +0000 Subject: [PATCH] [CORE][Cache] Add getListPartialCache, which allows for fetching a list and backing only a portion of it in the cache (useful for feeds and replies to notes, for instance) --- src/Core/Cache.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/Core/Cache.php b/src/Core/Cache.php index c17cb92907..d9d2be7cb7 100644 --- a/src/Core/Cache.php +++ b/src/Core/Cache.php @@ -317,6 +317,42 @@ abstract class Cache } } + /** + * Get a list partially from cache, partially from the DB + * + * Uses two fetches in the worst case, but the first is likely cached + * + * @param callable(int $limit, int $offset): (array) $calculate + */ + public static function getListPartialCache(string $key, callable $calculate, int $max_cache_count, int $left, ?int $right = null, string $pool = 'default', float $beta = 1.0): array + { + if ($left < $max_cache_count) { + $middle = $max_cache_count; + $cached_portion = self::getList( + $key, + fn () => $calculate(limit: $max_cache_count, offset: 0), + pool: $pool, + max_count: $max_cache_count, + left: $left, + right: $right, + beta: $beta, + ); + } else { + $middle = $left; + $cached_portion = []; + } + + $right ??= \PHP_INT_MAX; + $limit = $right - $middle; + if ($right > $max_cache_count) { + $non_cached_portion = $calculate(limit: $limit, offset: $middle); + } else { + $non_cached_portion = []; + } + + return [...$cached_portion, ...$non_cached_portion]; + } + /** * Push a value to the list */