123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153 |
- <?php
- defined('GNUSOCIAL') || die();
- class CachingNoticeStream extends NoticeStream
- {
- const CACHE_WINDOW = 200;
- public $stream = null;
- public $cachekey = null;
- public $useLast = true;
- public $alwaysCheck = true;
- public function __construct(
- NoticeStream $stream,
- string $cachekey,
- bool $useLast = true,
- bool $alwaysCheck = false
- ) {
- $this->stream = $stream;
- $this->cachekey = $cachekey;
- $this->useLast = $useLast;
- $this->alwaysCheck = $alwaysCheck;
- }
- private function getCacheNoticeIds(
- Cache $cache,
- string $idkey,
- bool $check = false
- ): ?array {
- $id_str = $cache->get($idkey);
- if ($id_str === false) {
- return null;
- }
- $ids = explode(',', $id_str);
- if ($check) {
- $latest_id = $ids[0];
- $new_ids = $this->stream->getNoticeIds(
- 0,
- self::CACHE_WINDOW,
- $latest_id,
- null
- );
- $ids = array_merge($new_ids, $ids);
- $ids = array_slice($ids, 0, self::CACHE_WINDOW);
- $new_id_str = implode(',', $ids);
- if ($id_str !== $new_id_str) {
- $cache->set($idkey, $new_id_str);
- }
- }
- return $ids;
- }
- public function getNoticeIds($offset, $limit, $sinceId, $maxId)
- {
- $cache = Cache::instance();
-
-
- if (empty($cache) ||
- $sinceId != 0 || $maxId != 0 ||
- is_null($limit) ||
- ($offset + $limit) > self::CACHE_WINDOW) {
- return $this->stream->getNoticeIds($offset, $limit, $sinceId, $maxId);
- }
-
- $idkey = Cache::key($this->cachekey);
- $ids = $this->getCacheNoticeIds($cache, $idkey, $this->alwaysCheck);
- if (!is_null($ids)) {
-
- return array_slice($ids, $offset, $limit);
- }
- if ($this->useLast) {
-
-
-
-
-
- $ids = $this->getCacheNoticeIds($cache, $idkey . ';last', true);
- if (!is_null($ids)) {
-
- $id_str = implode(',', $ids);
- $cache->set($idkey, $id_str);
- return array_slice($ids, $offset, $limit);
- }
- }
-
-
- $window = $this->stream->getNoticeIds(0, self::CACHE_WINDOW, null, null);
- $windowstr = implode(',', $window);
- $cache->set($idkey, $windowstr);
- if ($this->useLast) {
- $cache->set($idkey . ';last', $windowstr);
- }
-
- return array_slice($window, $offset, $limit);
- }
- }
|