[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)

This commit is contained in:
Hugo Sales 2022-02-27 21:33:24 +00:00
parent 46c4bd9099
commit 85ce6bfd41
No known key found for this signature in database
GPG Key ID: 7D0C7EAFC9D835A0

View File

@ -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<int,mixed>) $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 * Push a value to the list
*/ */